问:
How to get error messages from python Gst.Bus
I have a program that is expected to fail with an error.  I am writing the logic to handle those errors.

The program fails while doing, pipeline.set_state(Gst.State.READY).  The return code confirms that.  What I am looking for is a means of identifying the error source.

I am trying to register callback function via, bus.connect('message::error', on_error).  The callback never gets called.

I am getting the impression that debug errors, GST_ERROR_OBJECT(), are different than messages of type Gst.MessageType.ERROR.  There are also a wide variety of messaging schemes and signals that are making my investigation difficult.

./foo.py --gst-debug=3 produces lots of output.  Including droppings from unclean library code.

```<code>0:00:00.020176932 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: Cannot connect to server socket err = No such file or directory
0:00:00.020225574 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: Cannot connect to server request channel
0:00:00.022293832 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: jack server is not running or cannot be started
0:00:00.022422501 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
0:00:00.022435733 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
0:00:00.022444680 20284      0x2d49390 WARN              jackclient gstjackaudioclient.c:379:gst_jack_audio_get_connection: could not create connection
0:00:00.022562482 20284      0x2d49390 WARN                jacksink gstjackaudiosink.c:357:gst_jack_ring_buffer_open_device:<sink-actual-sink-jackaudio> error: Jack server not found
0:00:00.022573131 20284      0x2d49390 WARN                jacksink gstjackaudiosink.c:357:gst_jack_ring_buffer_open_device:<sink-actual-sink-jackaudio> error: Cannot connect to the Jack server (status 17)
0:00:00.023123730 20284      0x2d49390 WARN                 default oss4-property-probe.c:303:gst_oss4_property_probe_get_values:<sink-actual-sink-oss4> Can't open file descriptor to probe available devices: No such file or directory
0:00:00.023150887 20284      0x2d49390 WARN                oss4sink oss4-sink.c:514:gst_oss4_sink_open:<sink-actual-sink-oss4> error: Could not open audio device for playback.
0:00:00.023160358 20284      0x2d49390 WARN                oss4sink oss4-sink.c:514:gst_oss4_sink_open:<sink-actual-sink-oss4> error: system error: No such file or directory
AL lib: (WW) alc_initconfig: Failed to initialize backend "pulse"
ALSA lib confmisc.c:768:(parse_card) cannot find card '0'
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1251:(snd_func_refer) error evaluating name
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:4771:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM default
AL lib: (EE) ALCplaybackAlsa_open: Could not open playback device 'default': No such file or directory
0:00:00.048076943 20284      0x2d49390 WARN                  openal gstopenalsink.c:635:gst_openal_sink_open:<sink-actual-sink-openal> error: Could not open device.
0:00:00.048195277 20284      0x2d49390 WARN                  openal gstopenalsink.c:635:gst_openal_sink_open:<sink-actual-sink-openal> error: ALC error: Out of Memory
0:00:00.048822468 20284      0x2d49390 WARN                     oss gstosssink.c:399:gst_oss_sink_open:<sink-actual-sink-oss> error: Could not open audio device for playback.
0:00:00.048945169 20284      0x2d49390 WARN                     oss gstosssink.c:399:gst_oss_sink_open:<sink-actual-sink-oss> error: system error: No such file or directory
0:00:00.055983656 20284      0x2d49390 ERROR       decklinkaudiosrc gstdecklinkaudiosrc.cpp:670:gst_decklink_audio_src_open:<audio> Failed to acquire input
Traceback (most recent call last):
  File "./tim.py", line 40, in <module>
    raise Exception('state change failed')
Exception: state change failed
</code>```

Here is the code.

```<code>#!/usr/bin/env python3

import sys
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstBase', '1.0')
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gst, GstBase, Gtk, GObject

def on_error(bus, msg):
    print('Error {}: {}, {}'.format(msg.src.name, *msg.parse_error()))

if __name__ == '__main__':
    # exits on error
    sys.argv = Gst.init(sys.argv)

    pipeline = Gst.Pipeline.new("mypipeline")
    assert(pipeline)
    bus = pipeline.get_bus()
    assert(bus)
    bus.add_signal_watch()
    bus.connect('message::error', on_error)
    # bus.add_watch(GLib.PRIORITY_DEFAULT, on_error)

    #audio = Gst.ElementFactory.make("audiotestsrc", "audio")
    audio = Gst.ElementFactory.make('decklinkaudiosrc', "audio")
    assert(audio)
    ret = pipeline.add(audio)
    assert(ret)
    sink = Gst.ElementFactory.make("autoaudiosink", "sink")
    assert(sink)
    ret = pipeline.add(sink)
    assert(ret)
    ret = audio.link(sink)
    assert(ret)

    ret = pipeline.set_state(Gst.State.READY)
    if ret == Gst.StateChangeReturn.FAILURE:
        msg = bus.pop_filtered(Gst.MessageType.ERROR)
        while msg:
            on_error(bus, msg)
            msg = bus.pop_filtered(Gst.MessageType.ERROR)
        raise Exception('state change failed')
</code>```

Updating, Mar 14 2018

I am able to get output on par with gst-launch-1.0 --gst-debug=2 -m decklinkaudiosrc ! autoaudiosink with the following code.  Also interesting to get a glimpse of the state changed messages.

To me, that is strong evidence that the debugging infrastructure is independent of the messaging system observed on the bus.  I am going to search for a hook into the debug code and attempt to observe those messages.

```<code>    msg = bus.pop()
    while msg:
        if msg.type == Gst.MessageType.ERROR:
            on_error(bus, msg)
        else:
            print('{} {}: {}'.format(
                Gst.MessageType.get_name(msg.type), msg.src.name,
                msg.get_structure().to_string()))
        msg = bus.pop()
</code>```

答:
Looks like an order is important:

```<code>Gst.debug_remove_log_function(None)
Gst.debug_add_log_function(on_debug,None)
Gst.debug_set_default_threshold(Gst.DebugLevel.WARNING)
Gst.debug_set_active(True)
</code>```

This allowed me to control GStreamer logs.

Body:
I have a program that is expected to fail with an error.  I am writing the logic to handle those errors.

The program fails while doing, pipeline.set_state(Gst.State.READY).  The return code confirms that.  What I am looking for is a means of identifying the error source.

I am trying to register callback function via, bus.connect('message::error', on_error).  The callback never gets called.

I am getting the impression that debug errors, GST_ERROR_OBJECT(), are different than messages of type Gst.MessageType.ERROR.  There are also a wide variety of messaging schemes and signals that are making my investigation difficult.

./foo.py --gst-debug=3 produces lots of output.  Including droppings from unclean library code.

0:00:00.020176932 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: Cannot connect to server socket err = No such file or directory
0:00:00.020225574 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: Cannot connect to server request channel
0:00:00.022293832 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: jack server is not running or cannot be started
0:00:00.022422501 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
0:00:00.022435733 20284      0x2d49390 ERROR             jackclient gstjackaudioclient.c:35:jack_log_error: JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
0:00:00.022444680 20284      0x2d49390 WARN              jackclient gstjackaudioclient.c:379:gst_jack_audio_get_connection: could not create connection
0:00:00.022562482 20284      0x2d49390 WARN                jacksink gstjackaudiosink.c:357:gst_jack_ring_buffer_open_device:<sink-actual-sink-jackaudio> error: Jack server not found
0:00:00.022573131 20284      0x2d49390 WARN                jacksink gstjackaudiosink.c:357:gst_jack_ring_buffer_open_device:<sink-actual-sink-jackaudio> error: Cannot connect to the Jack server (status 17)
0:00:00.023123730 20284      0x2d49390 WARN                 default oss4-property-probe.c:303:gst_oss4_property_probe_get_values:<sink-actual-sink-oss4> Can't open file descriptor to probe available devices: No such file or directory
0:00:00.023150887 20284      0x2d49390 WARN                oss4sink oss4-sink.c:514:gst_oss4_sink_open:<sink-actual-sink-oss4> error: Could not open audio device for playback.
0:00:00.023160358 20284      0x2d49390 WARN                oss4sink oss4-sink.c:514:gst_oss4_sink_open:<sink-actual-sink-oss4> error: system error: No such file or directory
AL lib: (WW) alc_initconfig: Failed to initialize backend "pulse"
ALSA lib confmisc.c:768:(parse_card) cannot find card '0'
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1251:(snd_func_refer) error evaluating name
ALSA lib conf.c:4292:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:4771:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM default
AL lib: (EE) ALCplaybackAlsa_open: Could not open playback device 'default': No such file or directory
0:00:00.048076943 20284      0x2d49390 WARN                  openal gstopenalsink.c:635:gst_openal_sink_open:<sink-actual-sink-openal> error: Could not open device.
0:00:00.048195277 20284      0x2d49390 WARN                  openal gstopenalsink.c:635:gst_openal_sink_open:<sink-actual-sink-openal> error: ALC error: Out of Memory
0:00:00.048822468 20284      0x2d49390 WARN                     oss gstosssink.c:399:gst_oss_sink_open:<sink-actual-sink-oss> error: Could not open audio device for playback.
0:00:00.048945169 20284      0x2d49390 WARN                     oss gstosssink.c:399:gst_oss_sink_open:<sink-actual-sink-oss> error: system error: No such file or directory
0:00:00.055983656 20284      0x2d49390 ERROR       decklinkaudiosrc gstdecklinkaudiosrc.cpp:670:gst_decklink_audio_src_open:<audio> Failed to acquire input
Traceback (most recent call last):
  File "./tim.py", line 40, in <module>
    raise Exception('state change failed')
Exception: state change failed

Here is the code.

#!/usr/bin/env python3

import sys
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstBase', '1.0')
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gst, GstBase, Gtk, GObject

def on_error(bus, msg):
    print('Error {}: {}, {}'.format(msg.src.name, *msg.parse_error()))

if __name__ == '__main__':
    # exits on error
    sys.argv = Gst.init(sys.argv)

    pipeline = Gst.Pipeline.new("mypipeline")
    assert(pipeline)
    bus = pipeline.get_bus()
    assert(bus)
    bus.add_signal_watch()
    bus.connect('message::error', on_error)
    # bus.add_watch(GLib.PRIORITY_DEFAULT, on_error)

    #audio = Gst.ElementFactory.make("audiotestsrc", "audio")
    audio = Gst.ElementFactory.make('decklinkaudiosrc', "audio")
    assert(audio)
    ret = pipeline.add(audio)
    assert(ret)
    sink = Gst.ElementFactory.make("autoaudiosink", "sink")
    assert(sink)
    ret = pipeline.add(sink)
    assert(ret)
    ret = audio.link(sink)
    assert(ret)

    ret = pipeline.set_state(Gst.State.READY)
    if ret == Gst.StateChangeReturn.FAILURE:
        msg = bus.pop_filtered(Gst.MessageType.ERROR)
        while msg:
            on_error(bus, msg)
            msg = bus.pop_filtered(Gst.MessageType.ERROR)
        raise Exception('state change failed')

Updating, Mar 14 2018

I am able to get output on par with gst-launch-1.0 --gst-debug=2 -m decklinkaudiosrc ! autoaudiosink with the following code.  Also interesting to get a glimpse of the state changed messages.

To me, that is strong evidence that the debugging infrastructure is independent of the messaging system observed on the bus.  I am going to search for a hook into the debug code and attempt to observe those messages.

    msg = bus.pop()
    while msg:
        if msg.type == Gst.MessageType.ERROR:
            on_error(bus, msg)
        else:
            print('{} {}: {}'.format(
                Gst.MessageType.get_name(msg.type), msg.src.name,
                msg.get_structure().to_string()))
        msg = bus.pop()

Body:
Looks like an order is important:

Gst.debug_remove_log_function(None)
Gst.debug_add_log_function(on_debug,None)
Gst.debug_set_default_threshold(Gst.DebugLevel.WARNING)
Gst.debug_set_active(True)

This allowed me to control GStreamer logs.


来源: stackexchange

问:
Writing both intermediates and results to file using Dask
I have a data script application that uses dask to go trough a database and produce some intermediates, it than combines these intermediates to produce the result. Now I would like to both write out the intermediates and the result efficiently but as you can see below I have only found a very inefficient way where you compute the intermediates more than ones.

```<code>import dask.bag as db
from other_functions import *

input = db.read_text(file1)
processing_parameter = parse_mapping_parameters(file2)

intermediates = []
for p in mapping_parameter:
    intermediate = input.map(lambda x: process(x, p))
    intermediates.append(intermediate)

products = intermediates.pop(0)

for intermediate in intermediates:
    products = product.products(i)

result = products.map(calc_result)

for i, intermediate in enumerate(intermediates):
    intermediate.to_textfiles(f'./data/intermediate_{i}.*.txt')

result.to_textfiles(f'./data/result.*.txt')
</code>```

The alternative I see is to write the intermediates to file and then use a separate script to read them into memory again and generate the results but IO wise that also feels inefficient. Is there a better way to do this in dask?

答:
Ended up solving it this way:

```<code>import dask.bag as db
from other_functions import *

input = db.read_text(file1)
processing_parameter = parse_mapping_parameters(file2)

to_compute = []
intermediates = []
for i, p in enumerate(mapping_parameter):
    intermediate = input.map(lambda x: process(x, p))
    to_compute.append(
        intermediate.to_textfiles(f'./data/intermediate_{i}.*.txt', compute=False)
    intermediates.append(intermediate)

products = intermediates.pop(0)
for intermediate in intermediates:
    products = product.products(i)

result = products.map(calc_result)

to_compute.append(result.to_textfiles(f'./data/result.*.txt', compute=False))
dask.compute(*to_compute)
</code>```

Didn't realize the to_text method had a parameter that allows you to get a lazy writer. Once I saw that it was kind of obvious. Not sure about how efficient this is though.

ContentLicense: CC BY-SA 4.0

Body:
I have a data script application that uses dask to go trough a database and produce some intermediates, it than combines these intermediates to produce the result. Now I would like to both write out the intermediates and the result efficiently but as you can see below I have only found a very inefficient way where you compute the intermediates more than ones.

import dask.bag as db
from other_functions import *

input = db.read_text(file1)
processing_parameter = parse_mapping_parameters(file2)

intermediates = []
for p in mapping_parameter:
    intermediate = input.map(lambda x: process(x, p))
    intermediates.append(intermediate)

products = intermediates.pop(0)

for intermediate in intermediates:
    products = product.products(i)

result = products.map(calc_result)

for i, intermediate in enumerate(intermediates):
    intermediate.to_textfiles(f'./data/intermediate_{i}.*.txt')

result.to_textfiles(f'./data/result.*.txt')

The alternative I see is to write the intermediates to file and then use a separate script to read them into memory again and generate the results but IO wise that also feels inefficient. Is there a better way to do this in dask?

Body:
Ended up solving it this way:

import dask.bag as db
from other_functions import *

input = db.read_text(file1)
processing_parameter = parse_mapping_parameters(file2)

to_compute = []
intermediates = []
for i, p in enumerate(mapping_parameter):
    intermediate = input.map(lambda x: process(x, p))
    to_compute.append(
        intermediate.to_textfiles(f'./data/intermediate_{i}.*.txt', compute=False)
    intermediates.append(intermediate)

products = intermediates.pop(0)
for intermediate in intermediates:
    products = product.products(i)

result = products.map(calc_result)

to_compute.append(result.to_textfiles(f'./data/result.*.txt', compute=False))
dask.compute(*to_compute)

Didn't realize the to_text method had a parameter that allows you to get a lazy writer. Once I saw that it was kind of obvious. Not sure about how efficient this is though.


问:
Google Cloud Resource created with user that is not in IAM
Situation:

I have a GCP project (owner) that is under a organization I do not have access to, so I see it in No Organization

a user (xyz@domain.com) has created a subscription for an existing pubsub topic, I see that under activity and the audit logs

this user is not visible for me in IAM (e.g. as editor, or with some pubsub specific role)

neither can I see this user in any pub/sub related topic/subscription, with a role, specifically not in the topic he created the subscription in

Summary:

xyz@domain.com created a subs.

I don't know where he got the role from (inherited?)

Question:

Is it possible that this person has e.g. editor on the organization (or some folder above the project) but I don't see that role in my IAM section of the project?

If not, where could the role be inherited from?

答:
Creating a Subscribtion

To subscribe to a Pub/Sub topic a user should be able to create a Subscription object. To do that, a permission pubsub.subscriptions.create on a Topic is needed. It could be assigned explicitly onto a Topic or inherited from the parent levels (Project, Folder, Org) via:

a Custom Role inherited from the Project level or above;

a Predefined Role pubsub.editor or pubsub.admin assigned at the Pub/Sub Topic level or inherited from a parent level;

a Primitive Role Editor or Owner inherited from the Project or Service Resource level or above; for example, the Compute Engine default service account freshly created VM Instances are working on behalf of has an Editor Role on the Project it is part of.

Viewing role assignments

To trace where effective rights are inherited from, one would need at list the following Permssions:

resourcemanager.organizations.getIamPolicy

resourcemanager.folders.getIamPolicy

resourcemanager.projects.getIamPolicy

IAM Predefined Roles that contain that permissions are:

resourcemanager.organizationAdmin

iam.securityAdmin

iam.securityReviewer

IAM Predefined Roles that can trace up to the Folder level are:

resourcemanager.folderAdmin

resourcemanager.folderEditor

resourcemanager.folderIamAdmin

IAM Primitive Roles:

Viewer

Editor

Owner

To obtain the comprehensive view of resulting permissions you should be granted the Roles listed above assigned as high as possible in the IAM hierarchy (ideally at the Org level) to get enough administrative scope for investigation.

You can't see bindings that are located outside of the administrative scope you've got. Therefore you can't see the level where permissions are inherited from as well as security subject the permissions are granted for.

Back to the questions

Is it possible that this person has e.g. editor on the organization (or some folder above the project) but I don't see that role in my IAM section of the project?

Yes

If not, where could the role be inherited from?

An Org level and all Folder levels (those could be nested) above your Project.

Vendor documentation

IAM Roles

Cloud Pub/Sub | Access Control | Roles

Support level for permissions in custom roles


问:
PHP Symfony Attempted to load class "SonataIntlBundle" from namespace "Sonata\IntlBundle"
I am new to Symfony and PHP in general, I just want to set up a project from GitHub and instruction says that I have to run composer update. So after this command an error logs:

```<code> Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the symfony-scripts event terminated with an exception

  [RuntimeException]
  An error occurred when executing the "'cache:clear --no-warmup'" command:

  Fatal error: Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "SonataIntlBundle" from namespace "Sonata\IntlBundle".
  Did you forget a "use" statement for another namespace? in /Users/xxx/Documents/project/app/AppKernel.php:28
  Stack trace:
  #0 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(427): AppKernel->registerBundles()
  #1 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(128): Symfony\Component\HttpKernel\Kernel->initializeBundles()
  #2 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(62): Symfony\Component\HttpKernel\Kernel->boot()
  #3 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php(117): Symfony\Bundle\FrameworkBundle\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Obj
  ect(Symfony\Component\Console\Output\ConsoleOutput))
  #4 /U in /Users/xxx/Documents/project/app/AppKernel.php on line 28

  PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "SonataIntlBundle" from namespace "Sonata\IntlBundle".
  Did you forget a "use" statement for another namespace? in /Users/xxx/Documents/project/app/AppKernel.php:28
  Stack trace:
  #0 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(427): AppKernel->registerBundles()
  #1 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(128): Symfony\Component\HttpKernel\Kernel->initializeBundles()
  #2 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(62): Symfony\Component\HttpKernel\Kernel->boot()
  #3 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php(117): Symfony\Bundle\FrameworkBundle\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Obj
  ect(Symfony\Component\Console\Output\ConsoleOutput))
  #4 /U in /Users/xxx/Documents/project/app/AppKernel.php on line 28
</code>```

Can anyone help me with this one? I'm kinda lost.

答: As @Cid mentioned, I re-cloned the repo and this time used composer install instead of update and it works just fine!</p>

Body:
I am new to Symfony and PHP in general, I just want to set up a project from GitHub and instruction says that I have to run composer update. So after this command an error logs:

 Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the symfony-scripts event terminated with an exception

  [RuntimeException]
  An error occurred when executing the "'cache:clear --no-warmup'" command:

  Fatal error: Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "SonataIntlBundle" from namespace "Sonata\IntlBundle".
  Did you forget a "use" statement for another namespace? in /Users/xxx/Documents/project/app/AppKernel.php:28
  Stack trace:
  #0 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(427): AppKernel->registerBundles()
  #1 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(128): Symfony\Component\HttpKernel\Kernel->initializeBundles()
  #2 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(62): Symfony\Component\HttpKernel\Kernel->boot()
  #3 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php(117): Symfony\Bundle\FrameworkBundle\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Obj
  ect(Symfony\Component\Console\Output\ConsoleOutput))
  #4 /U in /Users/xxx/Documents/project/app/AppKernel.php on line 28

  PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "SonataIntlBundle" from namespace "Sonata\IntlBundle".
  Did you forget a "use" statement for another namespace? in /Users/xxx/Documents/project/app/AppKernel.php:28
  Stack trace:
  #0 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(427): AppKernel->registerBundles()
  #1 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php(128): Symfony\Component\HttpKernel\Kernel->initializeBundles()
  #2 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php(62): Symfony\Component\HttpKernel\Kernel->boot()
  #3 /Users/xxx/Documents/project/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php(117): Symfony\Bundle\FrameworkBundle\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Obj
  ect(Symfony\Component\Console\Output\ConsoleOutput))
  #4 /U in /Users/xxx/Documents/project/app/AppKernel.php on line 28

Can anyone help me with this one? I'm kinda lost.


问:
SQL : Calculating Percentage by joining a sub table to another

I've the above dataset, I need to report for each year the percentage of movies in that year with only female actors, and the total number of movies made that year. For example, one answer will be: 1990 31.81 13522 meaning that in 1990 there were 13,522 movies, and 31.81%

In order to get the moves with only female actors, wrote the following code:

```<code>SELECT a.year as Year, COUNT(a.title) AS Female_Movies, a.title
FROM Movie a
WHERE a.title NOT IN (

  SELECT b.title from Movie b
  Inner Join M_cast c
  on TRIM(c.MID) = b.MID
  Inner Join Person d
  on TRIM(c.PID) = d.PID
  WHERE d.Gender='Male'
  GROUP BY b.title
  )
GROUP BY a.year,a.title
Order By a.year asc
</code>```

The total movies in each year , can be found using the following:

```<code>SELECT a.year, count(a.title) AS Total_Movies
FROM Movie a
GROUP BY a.year
ORDER BY COUNT(a.title) DESC
</code>```

Combinig the both I wrote, the following code:

```<code>SELECT z.year as Year, count(z.title) AS Total_Movies, count(x.title) as Female_movies, count(z.title)/ count(x.title) As percentage
FROM Movie z
Inner Join (
SELECT a.year as Year, COUNT(a.title) AS Female_Movies, a.title
FROM Movie a
WHERE a.title NOT IN (

  SELECT b.title from Movie b
  Inner Join M_cast c
  on TRIM(c.MID) = b.MID
  Inner Join Person d
  on TRIM(c.PID) = d.PID
  WHERE d.Gender='Male'
  GROUP BY b.title
  )
GROUP BY a.year,a.title
Order By a.year asc
)x
on x.year = z.year
GROUP BY z.year
ORDER BY COUNT(z.title) DESC
</code>```

However, in th output I'm seeing the years with only female movies correctly, but the count of total movies is equal to female_movies so I'm getting 1%, I tried debugging the code, but not sure where this is going wrong. Any insights would be appreciated.

答:
```<code>              SELECT m.Year,COUNT(m.Year),x.t,
              (COUNT(m.Year)*1.0/x.t*1.0)*100
             FROM Movie m LEFT  JOIN
             (SELECT Year,COUNT(Year) AS t FROM Movie GROUP BY year) AS x

             ON  m.Year=x.Year
             WHERE m.MID IN
             (SELECT MID FROM M_Cast WHERE PID in
             (SELECT PID FROM Person WHERE Gender='Female')
              AND m.MID NOT IN
             (SELECT MID FROM M_Cast WHERE PID in
             (SELECT PID FROM Person WHERE Gender='Male'))) GROUP BY m.year
</code>```

Body:
I've the above dataset, I need to report for each year the percentage of movies in that year with only female actors, and the total number of movies made that year. For example, one answer will be: 1990 31.81 13522 meaning that in 1990 there were 13,522 movies, and 31.81%

In order to get the moves with only female actors, wrote the following code:

SELECT a.year as Year, COUNT(a.title) AS Female_Movies, a.title
FROM Movie a
WHERE a.title NOT IN (

  SELECT b.title from Movie b
  Inner Join M_cast c
  on TRIM(c.MID) = b.MID
  Inner Join Person d
  on TRIM(c.PID) = d.PID
  WHERE d.Gender='Male'
  GROUP BY b.title
  )
GROUP BY a.year,a.title
Order By a.year asc

The total movies in each year , can be found using the following:

SELECT a.year, count(a.title) AS Total_Movies
FROM Movie a
GROUP BY a.year
ORDER BY COUNT(a.title) DESC

Combinig the both I wrote, the following code:

SELECT z.year as Year, count(z.title) AS Total_Movies, count(x.title) as Female_movies, count(z.title)/ count(x.title) As percentage
FROM Movie z
Inner Join (
SELECT a.year as Year, COUNT(a.title) AS Female_Movies, a.title
FROM Movie a
WHERE a.title NOT IN (

  SELECT b.title from Movie b
  Inner Join M_cast c
  on TRIM(c.MID) = b.MID
  Inner Join Person d
  on TRIM(c.PID) = d.PID
  WHERE d.Gender='Male'
  GROUP BY b.title
  )
GROUP BY a.year,a.title
Order By a.year asc
)x
on x.year = z.year
GROUP BY z.year
ORDER BY COUNT(z.title) DESC

However, in th output I'm seeing the years with only female movies correctly, but the count of total movies is equal to female_movies so I'm getting 1%, I tried debugging the code, but not sure where this is going wrong. Any insights would be appreciated.


问:
data- attribute not working to grab dynamic id from foreach
I am using JS in a razor page to grab a dynamic ID from a col in a foreach.

In the past, I have used this and it worked fine. However, it seems that it is currently only grabbing the ID from the first col no matter which one I click.

Can someone please tell me if I am still doing this right? Or if I am missing something. Thank you.

View:

```<code>            <div class="list-group container" id="JobRequestMonitorTable">
            <div class="row list-group-item list-group-item-heading container divTableHeading" style="margin-bottom:0px;">
                <div class="col-md-4"> Job Code </div>
                <div class="col-md-4"> Description </div>
                <div class="col-md-2"> Schedule </div>
                <div class="col-md-1"> Running </div>
                <div class="col-md-1"></div>
            </div>
            @if (!string.IsNullOrEmpty(ViewBag.ErrorMessage))
            {
                <div class="row list-group-item-danger">
                    <div class="col-md-1 text-center">@ViewBag.ErrorMessage</div>
                </div>
            }
            @foreach (var item in Model.JobRequests)
            {
                <div class="row list-group-item container">
                    <div class="hidden" data-id="@item.JobRequestId" id="requestId">@item.JobRequestId</div>
                    <div class="col-md-4">@item.JobCode</div>
                    <div class="col-md-4">@item.Description</div>
                    <div class="col-md-2">@item.Schedule</div>
                    @if (@item.IsRunning == true)
                    {
                        <div class="col-md-1" style="margin-left:25px;"><span class="glyphicon glyphicon-ok"></span></div>
                        <div class="col-md-1"></div>
                    }
                    else
                    {
                        <div class="col-md-1"></div>
                        <div class="col-md-1">
                            <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn"></button>
                        </div>
                    }
                </div>
            }
        </div>
</code>```

JS:

```<code>        $("button").click(function () {

            var col = $('#requestId');
            var jobRequestId = col.data('Id');

             $.ajax({
                url: '@Url.Action("JobPollerParameters", "Tools")',
                 data: { "jobRequestId": jobRequestId},
                 success: function (results) {

                    $modal = $('#paramsModal');
                    $modal.modal("show");

                     var arr = results;
                     //loop through arr created from dictionary to grab key(s)
                     for (var key in arr) {
                         if (arr.hasOwnProperty(key)) {
                             var myKey = key;
                         }
                     }

                     var name = myKey;
                     var value = results[myKey];

                    $('#modalName').text(name);
                     $('#modalMessage').text(value);

                }
            });
        });
</code>```

Really the only important part to see in the JS is var col = $('#requestId');
            var jobRequestId = col.data('Id');

But I suppose I will include the whole script just in case people ask.

答:
All of your items inside the loop are getting the same id attribute, it is hard-codded

```<code>id="requestId"
</code>```

the jQuery selector $('#requestId') is getting back the first one, this is by design.

I would add a data-id to each button and select the relevant col with that id.

For example the button will get:

```<code><button data-col-id="@item.JobRequestId" class="glyphicon glyphicon-list-alt btn btn-primary"></button>
</code>```

And then, its easy to grab that info on click:

```<code>$("button").click(function () {

            var jobRequestId = $(this).data('col-id');

             $.ajax({
                url: '@Url.Action("JobPollerParameters", "Tools")',
                 data: { "jobRequestId": jobRequestId},
                 success: function (results) {

                    $modal = $('#paramsModal');
                    $modal.modal("show");

                     var arr = results;
                     //loop through arr created from dictionary to grab key(s)
                     for (var key in arr) {
                         if (arr.hasOwnProperty(key)) {
                             var myKey = key;
                         }
                     }

                     var name = myKey;
                     var value = results[myKey];

                    $('#modalName').text(name);
                     $('#modalMessage').text(value);

                }
            });
        });
</code>```

I like this solution as you are not depended on your HTML structure and hierarchy thus selectors won't break often.

Body:
I am using JS in a razor page to grab a dynamic ID from a col in a foreach.

In the past, I have used this and it worked fine. However, it seems that it is currently only grabbing the ID from the first col no matter which one I click.

Can someone please tell me if I am still doing this right? Or if I am missing something. Thank you.

View:

 Job Code

 Description

 Schedule

 Running

            @if (!string.IsNullOrEmpty(ViewBag.ErrorMessage))
            {

@ViewBag.ErrorMessage

            }
            @foreach (var item in Model.JobRequests)
            {

@item.JobRequestId

@item.JobCode

@item.Description

@item.Schedule

                    @if (@item.IsRunning == true)
                    {

                    }
                    else
                    {

                            <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn"></button>

                    }

            }

JS:

        $("button").click(function () {

            var col = $('#requestId');
            var jobRequestId = col.data('Id');

             $.ajax({
                url: '@Url.Action("JobPollerParameters", "Tools")',
                 data: { "jobRequestId": jobRequestId},
                 success: function (results) {

                    $modal = $('#paramsModal');
                    $modal.modal("show");

                     var arr = results;
                     //loop through arr created from dictionary to grab key(s)
                     for (var key in arr) {
                         if (arr.hasOwnProperty(key)) {
                             var myKey = key;
                         }
                     }

                     var name = myKey;
                     var value = results[myKey];

                    $('#modalName').text(name);
                     $('#modalMessage').text(value);

                }
            });
        });

Really the only important part to see in the JS is var col = $('#requestId');
            var jobRequestId = col.data('Id');

But I suppose I will include the whole script just in case people ask.

Body:
All of your items inside the loop are getting the same id attribute, it is hard-codded

id="requestId"

the jQuery selector $('#requestId') is getting back the first one, this is by design.

I would add a data-id to each button and select the relevant col with that id.

For example the button will get:

<button data-col-id="@item.JobRequestId" class="glyphicon glyphicon-list-alt btn btn-primary"></button>

And then, its easy to grab that info on click:

$("button").click(function () {

            var jobRequestId = $(this).data('col-id');

             $.ajax({
                url: '@Url.Action("JobPollerParameters", "Tools")',
                 data: { "jobRequestId": jobRequestId},
                 success: function (results) {

                    $modal = $('#paramsModal');
                    $modal.modal("show");

                     var arr = results;
                     //loop through arr created from dictionary to grab key(s)
                     for (var key in arr) {
                         if (arr.hasOwnProperty(key)) {
                             var myKey = key;
                         }
                     }

                     var name = myKey;
                     var value = results[myKey];

                    $('#modalName').text(name);
                     $('#modalMessage').text(value);

                }
            });
        });

I like this solution as you are not depended on your HTML structure and hierarchy thus selectors won't break often.


问:
Need to move files to specific directory based on last two characters of filename in Linux
Please forgive my ignorance. I'm sure this is very basic, but I am so new to Bash. Any help you can provide is greatly appreciated.

I have a series of files (within a source directory) that I need to organize into other specific directories based on the last two charcters of their name. e.g. K1F2P4T1, needs to go to one directory while K1F2P4R1 needs to go to another. What I need it to do is check all files for the last two characters and if it ends with, e.g T1, E1, or B1 it goes to one directory and if it ends in C1, M1, or Z1 it gets moved to another.

How can I do this?

答:
You can use</p>

```<code>mv *{T1,E1,B1} one_dir
mv *{C1,M1,Z1} another_dir
</code>```

Body:
You can use

mv *{T1,E1,B1} one_dir
mv *{C1,M1,Z1} another_dir


问:
dns01 validation: Certificate issuance in progress. Temporary certificate issued
Following this

Setup:

```<code>Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-19T22:12:47Z", GoVersion:"go1.12.4", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"12+", GitVersion:"v1.12.7-gke.10", GitCommit:"8d9b8641e72cf7c96efa61421e87f96387242ba1", GitTreeState:"clean", BuildDate:"2019-04-12T22:59:24Z", GoVersion:"go1.10.8b4", Compiler:"gc", Platform:"linux/amd64"}

knative-serve & Istio is v0.5.2
cert-manager is v0.7 applyed with --validate=false as k8s is 1.12.7
</code>```

Cert-manager ClusterIssuer status:

```<code>│  status:                                                                                │
│    conditions:                                                                                │
│    - lastTransitionTime: "2019-04-29T21:29:40Z"                                                                                │
│      message: Certificate issuance in progress. Temporary certificate issued.                                                                                │
│      reason: TemporaryCertificate                                                                                │
│      status: "False"                                                                                │
│      type: Ready
</code>```

I have done as in the documentation, but setting up Google DNS not described

I have manually created a DNS in Google DNS consule.

My domain is pointing at the nameservers and I can ping the right server ip address,

When creating the DNS I added a record set:

```<code>*.mydomain.com. A   300 x.x.x.x
</code>```

Note: also tried without " * "

I have seen here, that they talk abaout setting TXT?

Do you know how to make this(cert-manager & TLS) it work?

答:
First, look at the logs being issued by the cert manager pod kubectl logs -n <namespace> pod/podname.

Cert manager will tell you why the challenge is failing.

One common reason is the rate limiting by Letsencrypt and you have to wait for 7 days.

You can also view this same issue on github https://github.com/jetstack/cert-manager/issues/1745

Body:
Following this

Setup:

Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-19T22:12:47Z", GoVersion:"go1.12.4", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"12+", GitVersion:"v1.12.7-gke.10", GitCommit:"8d9b8641e72cf7c96efa61421e87f96387242ba1", GitTreeState:"clean", BuildDate:"2019-04-12T22:59:24Z", GoVersion:"go1.10.8b4", Compiler:"gc", Platform:"linux/amd64"}

knative-serve & Istio is v0.5.2
cert-manager is v0.7 applyed with --validate=false as k8s is 1.12.7

Cert-manager ClusterIssuer status:

│  status:                                                                                │
│    conditions:                                                                                │
│    - lastTransitionTime: "2019-04-29T21:29:40Z"                                                                                │
│      message: Certificate issuance in progress. Temporary certificate issued.                                                                                │
│      reason: TemporaryCertificate                                                                                │
│      status: "False"                                                                                │
│      type: Ready

I have done as in the documentation, but setting up Google DNS not described

I have manually created a DNS in Google DNS consule.

My domain is pointing at the nameservers and I can ping the right server ip address,

When creating the DNS I added a record set:

*.mydomain.com. A   300 x.x.x.x

Note: also tried without " * "

I have seen here, that they talk abaout setting TXT?

Do you know how to make this(cert-manager & TLS) it work?


问:
sort from information from a text file Python 3
I'm currently trying to open text file with a 100 random numbers. Then reading them and sorting this numbers from lowest to highest.

I've created the file and written the 100 random numbers through this function.

```<code>def hundred_values():
    import random
    numbers_list = []
    for _ in range(100):
        numbers_list.append(random.randint(1, 100))
    with open('numbers.txt', 'w') as file:
        file.write(str(numbers_list))
</code>```

after this I'm trying to get Python to read the file, changing the string into int to then sorting them from lowest to highest. But I can't get it to work. Any input would be greatly appreciated

```<code>def find_smallest_number():
    lines = []
    with open('numbers.txt', 'r') as file:
        line = file.read().splitlines() # for processing
        lines.append(line) # storing everything in memory
        lines.sort(lines)
        print(lines)
</code>```

答:
There's a couple of issues here. The first, and most important, is that you're writing the string representation of a list to the file. This is going to cause you pain right from the start. Second, you'll want to read in integers and not strings so that your ordering is correct (if they are strings, you'll get lexicographical ordering). So, it needs to be corrected at the source.

This is how to generate the file:

```<code>import random # get the import out of the function and in the global scope

def hundred_values():

    numbers_list = []

    for _ in range(100):
        numbers_list.append(random.randint(1, 100))
    with open('numbers.txt', 'w') as file:
        file.write('\n'.join([str(item) for item in numbers_list])) # use join with a newline character to get an actual list

hundred_values()
</code>```

Then you can read and sort it like so:

```<code>with open('numbers.txt') as infile:
    data = infile.readlines()

data = [int(item) for item in data] # make sure that we have ints so we can have numerical ordering
data.sort() # Sort the list in-place
print(data)
</code>```

Body:
I'm currently trying to open text file with a 100 random numbers. Then reading them and sorting this numbers from lowest to highest.

I've created the file and written the 100 random numbers through this function.

def hundred_values():
    import random
    numbers_list = []
    for _ in range(100):
        numbers_list.append(random.randint(1, 100))
    with open('numbers.txt', 'w') as file:
        file.write(str(numbers_list))

after this I'm trying to get Python to read the file, changing the string into int to then sorting them from lowest to highest. But I can't get it to work. Any input would be greatly appreciated

def find_smallest_number():
    lines = []
    with open('numbers.txt', 'r') as file:
        line = file.read().splitlines() # for processing
        lines.append(line) # storing everything in memory
        lines.sort(lines)
        print(lines)

Body:
There's a couple of issues here. The first, and most important, is that you're writing the string representation of a list to the file. This is going to cause you pain right from the start. Second, you'll want to read in integers and not strings so that your ordering is correct (if they are strings, you'll get lexicographical ordering). So, it needs to be corrected at the source.

This is how to generate the file:

import random # get the import out of the function and in the global scope

def hundred_values():

    numbers_list = []

    for _ in range(100):
        numbers_list.append(random.randint(1, 100))
    with open('numbers.txt', 'w') as file:
        file.write('\n'.join([str(item) for item in numbers_list])) # use join with a newline character to get an actual list

hundred_values()

Then you can read and sort it like so:

with open('numbers.txt') as infile:
    data = infile.readlines()

data = [int(item) for item in data] # make sure that we have ints so we can have numerical ordering
data.sort() # Sort the list in-place
print(data)


问:
When using the GET chromeosdevices method, are custom fields returned in the resource returned?
I'm not optimistic because I don't see any reference to custom fields in the resource page here: https://developers.google.com/admin-sdk/directory/v1/reference/chromeosdevices#resource

but I'm wondering if anyone has experience with this.

In the Google Admin console (Device management->Chrome->Devices-><) there is a section for custom fields. Is there any way to retrieve that using the API?

Thanks!

答:
Though not explicitly documented, when I raised an enhancement request, the Google team let me know it is already possible. Response from Google:

Please note that retrieving custom fields for Chromeosdevices: get is already possible.

You can verify it by testing with the Try this API of Chromeosdevices: get, selecting the option Show standard parameters and specifying fields.

Indeed, they are there!


问:
How to check for records that are older than today in PHP?
I've set up a timestamp field with extra set to ON UPDATE CURRENT_TIMESTAMP.
It works but I have a question:

I'd like to check for all records which are older than today - how would I do that?

答:
I am assuming that, by "older than today", you mean anything inserted before last night at midnight. If you mean older than 24 hours ago let me know (and edit your question).

Here's what you do:

Get yesterday's timestamp: $timestamp = strtotime('24.00 yesterday');

Convert it in the mysql datetime format: $mysql_datetime = date('Y-m-d H:i:s', $timestamp);

Do the query: SELECT foo FROM bar WERE baz < $timestamp.


问:
jQuery: Performing synchronous AJAX request followed by a chain of other ajax requests
I have an ASP.NET MVC app and I am trying to make a chain of operations, one after another using jQuery inside a javascript function. The function consists of three parts.

What I am trying to do is: If some condition is satisfied then I want to execute syncrhonous jQuery ajax call CheckData. Dependending on the result returned:

It returns ok -> I want to continue executing part2 and finally part3 in this order.

It returns Nok -> then it finishes and returns. It does not continue executing part2 and part3.

So I have set async: false but it is not working, program continues executing part2 and part3.
I know async:false is deprecated so how can I achieve this?

```<code>function onCheckValidData()
{
    // do something....

    // PART 1 STARTS HERE

    if (some_condition_is_satified)
    {
        $.ajax({
            url: '@Url.Action("CheckData", "MyController")',
            async: false,
            type: "POST",
            dataType: "JSON",
            beforeSend: function () {
                showLoading();
            },
            success: function (result) {
                if (!result.isOk) {
                    return;
                }
            },
            complete: function(){
                hideLoading();
            }
        });
    }

    // PART 2 STARTS HERE

    // do something.....
    // continue doing more thing.....
    // more things.....

    // PART 3 STARTS HERE

    $.ajax({
        url: '@Url.Action("MyActionMethod1", "MyController")?' + paramsStr,
        type: "POST",
        dataType: "html",
        beforeSend: function () {
            showLoading();
        },
        success: function (result) {
            if (result == 'True') {
                jsMethod2();  // jsMethod2 is another javascript method which contains another $.ajax block
            }
            else if (result == 'False') {
                jsMethod3(); // jsMethod3 is another javascript method which contains another $.ajax block
            }
            else {
                alert(result);
            }
        },
        complete: function(){
            hideLoading();
        }
    });
}
</code>```

My actions in the controller:

```<code>    private JsonResult CheckData()
    {
        MyBoolResult res = new MyBoolResult();

        // do something....

        return Json(new { isOk = res.isOk });
    }

    public String MyActionMethod1(String param1, String param2, bool param3, string param4, string param5)
    {

       // do something

       return condition ? "True" : "False";
    }
</code>```

答:
No need to make that synchornuous. If u want the "PART 2" and "PART 3" to wait for the ajax-request to finish just put them into a function and call them on success:

function onCheckValidData()
{
    // do something....

    // PART 1 STARTS HERE
    if (some_condition_is_satified)
    {
        $.ajax({
            url: '@Url.Action("CheckData", "MyController")',
            type: "POST",
            dataType: "JSON",
            beforeSend: function () {
                showLoading();
            },
            //Success will execute only if the ajax-request is finised
            success: function (result) {
                if (!result.isOk) {
                    return;
                }
                part2();
                part3();
            },
            complete: function(){
                hideLoading();
            }
        });
    }

    // PART 2 STARTS HERE
    function part2 () {/*do something.....*/}

    // PART 3 STARTS HERE
    function part3 () {/*$.ajax({...})*/}
}
```

Body:
I have an ASP.NET MVC app and I am trying to make a chain of operations, one after another using jQuery inside a javascript function. The function consists of three parts.

What I am trying to do is: If some condition is satisfied then I want to execute syncrhonous jQuery ajax call CheckData. Dependending on the result returned:

It returns ok -> I want to continue executing part2 and finally part3 in this order.

It returns Nok -> then it finishes and returns. It does not continue executing part2 and part3.

So I have set async: false but it is not working, program continues executing part2 and part3.
I know async:false is deprecated so how can I achieve this?

function onCheckValidData()
{
    // do something....

    // PART 1 STARTS HERE

    if (some_condition_is_satified)
    {
        $.ajax({
            url: '@Url.Action("CheckData", "MyController")',
            async: false,
            type: "POST",
            dataType: "JSON",
            beforeSend: function () {
                showLoading();
            },
            success: function (result) {
                if (!result.isOk) {
                    return;
                }
            },
            complete: function(){
                hideLoading();
            }
        });
    }

    // PART 2 STARTS HERE

    // do something.....
    // continue doing more thing.....
    // more things.....

    // PART 3 STARTS HERE

    $.ajax({
        url: '@Url.Action("MyActionMethod1", "MyController")?' + paramsStr,
        type: "POST",
        dataType: "html",
        beforeSend: function () {
            showLoading();
        },
        success: function (result) {
            if (result == 'True') {
                jsMethod2();  // jsMethod2 is another javascript method which contains another $.ajax block
            }
            else if (result == 'False') {
                jsMethod3(); // jsMethod3 is another javascript method which contains another $.ajax block
            }
            else {
                alert(result);
            }
        },
        complete: function(){
            hideLoading();
        }
    });
}

My actions in the controller:

    private JsonResult CheckData()
    {
        MyBoolResult res = new MyBoolResult();

        // do something....

        return Json(new { isOk = res.isOk });
    }

    public String MyActionMethod1(String param1, String param2, bool param3, string param4, string param5)
    {

       // do something

       return condition ? "True" : "False";
    }


问:
How to implement free plans in Stripe
To implement a free plan for a subscription, I have created a plan with a monthly charge of $0.

Is this the correct way to subscribe users to a free plan so that they don't have to pay?

Will users still get invoices when they are subscribed to a free plan? If so, how can I avoid sending invoices to those subscribed to the free plan?

答:
Stripe Subscriptions are designed to manage billing and payments, rather than "tracking who is using a product". An "active" Subscription in Stripe is one that is being paid for, rather than one that is "being actively used".

You could conceivably set up a Subscription with an indefinite free trial, but really, you're doing a bunch of work to keep updating it to "remain free". I'd suggest taking a look at what you are actually trying to accomplish, because you're probably trying to track a user of your services, rather than track that a user doesn't pay you anything.

Title: How to implement free plans in Stripe


问:
Serilog - how to customize date in rolling file name?
In Serilog, you can easily enable rolling log files:

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("log-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();
```

This will create a new log file every day in the following format:

log-20200214.txt

log-20200215.txt

log-20200216.txt

My question: is it possible to customize where the date is placed in the file name, and to customize how the date is formatted?

e.g. I want the file names to look like this:

2020-02-14-log.txt

2020-02-15-log.txt

2020-02-16-log.txt

I was hoping replacing "log-.txt" with "{Date:yyyy-MM-dd}-log.txt" would work, but it doesn't.

答:
This is not currently supported by the Serilog.Sinks.File sink. If you really want this feature, you can try to send a pull-request, or fork the repository and use your own custom implementation.

Links you might be interested in:

Support {Date} for log path

Serilog {Date} format when using RollingFile

Ability to use DateTime format strings in Rolling File Sinks file names

Support for path by date

Body:
In Serilog, you can easily enable rolling log files:

Log.Logger = new LoggerConfiguration()
    .WriteTo.File("log-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

This will create a new log file every day in the following format:

log-20200214.txt

log-20200215.txt

log-20200216.txt

My question: is it possible to customize where the date is placed in the file name, and to customize how the date is formatted?

e.g. I want the file names to look like this:

2020-02-14-log.txt

2020-02-15-log.txt

2020-02-16-log.txt

I was hoping replacing "log-.txt" with "{Date:yyyy-MM-dd}-log.txt" would work, but it doesn't.


问:
How to overrwite directory using kubectl cp
I am copying a local directory into Kubernetes pod using kubectl cp command

```<code>kubectl cp test $POD:/tmp
</code>```

It copies the test directory into Kubernetes pod /tmp directory.

Now I want to overwrite the test directory in the pod.  I did not find any option to overwrite directory while copying using kubectl cp command.

Currently, I am deleting the test directory from the pod and then copy the directory.

```<code>kubectl exec $POD -- sh -c 'rm -rf /tmp/test'
kubectl cp test $POD:/tmp
</code>```

This is working fine, but in case any error comes while copying, existing directory from pod will also be deleted.

How can I overwrite the pod directory with a local directory without deleting the pod directory first?

Thanks in advance.

答:
Currently there is unfortunatelly no way to achieve your desired state with kubectl cp command.

If there are some undocumented features, please feel free to edit this answer and provide the solution, but currently there is no single place in documentation that could suggest the opposite.

Neither here nor in the context help of the kubectl command, available by running kubectl cp --help, there is no option mentioned that would modify the default operation of the kubectl cp command, which is basically a merge of the content of the already existing directory and copied one.

```<code>$ kubectl cp --help
</code>```
```<code>Copy files and directories to and from containers.

Examples:
  # !!!Important Note!!!
  # Requires that the 'tar' binary is present in your container
  # image.  If 'tar' is not present, 'kubectl cp' will fail.
  #
  # For advanced use cases, such as symlinks, wildcard expansion or
  # file mode preservation, consider using 'kubectl exec'.

  # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
  tar cf - /tmp/foo | kubectl exec -i -n <some-namespace> <some-pod> -- tar xf - -C /tmp/bar

  # Copy /tmp/foo from a remote pod to /tmp/bar locally
  kubectl exec -n <some-namespace> <some-pod> -- tar cf - /tmp/foo | tar xf - -C /tmp/bar

  # Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
  kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir

  # Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
  kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>

  # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
  kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar

  # Copy /tmp/foo from a remote pod to /tmp/bar locally
  kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar

Options:
    -c, --container='':
    Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the
    container to be attached or the first container in the pod will be chosen

    --no-preserve=false:
    The copied file/directory's ownership and permissions will not be preserved in the container

    --retries=0:
    Set number of retries to complete a copy operation from a container. Specify 0 to disable or any negative
    value for infinite retrying. The default is 0 (no retry).

Usage:
  kubectl cp <file-spec-src> <file-spec-dest> [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
</code>```

Basically the default behavior of kubectl cp command is a merge of the content of source and destination directory. Let's say we have local directory /tmp/test containing:

```<code>/tmp/test$ ls
different_file.txt
</code>```

with single line of text "some content". If we copy our local /tmp/test directory to /tmp directory on our Pod, which already contains test folder with a different file, let's say testfile.txt, the content of both directories will be merged, so our destination /tmp/test will contain eventually:

```<code>/tmp/test# ls
different_file.txt  testfile.txt
</code>```

If we change the content of our local different_file.txt to "yet another content" and run again the command:

```<code>kubectl cp /tmp/test pod-name:/tmp
</code>```

it will only override the destination different_file.txt which is already present in the destination /tmp/test directory.

Currently there is no way to override this default behavior.

Body:
I am copying a local directory into Kubernetes pod using kubectl cp command

kubectl cp test $POD:/tmp

It copies the test directory into Kubernetes pod /tmp directory.

Now I want to overwrite the test directory in the pod.  I did not find any option to overwrite directory while copying using kubectl cp command.

Currently, I am deleting the test directory from the pod and then copy the directory.

kubectl exec $POD -- sh -c 'rm -rf /tmp/test'
kubectl cp test $POD:/tmp

This is working fine, but in case any error comes while copying, existing directory from pod will also be deleted.

How can I overwrite the pod directory with a local directory without deleting the pod directory first?

Thanks in advance.

Body:
Currently there is unfortunatelly no way to achieve your desired state with kubectl cp command.

If there are some undocumented features, please feel free to edit this answer and provide the solution, but currently there is no single place in documentation that could suggest the opposite.

Neither here nor in the context help of the kubectl command, available by running kubectl cp --help, there is no option mentioned that would modify the default operation of the kubectl cp command, which is basically a merge of the content of the already existing directory and copied one.

$ kubectl cp --help

Copy files and directories to and from containers.

Examples:
  # !!!Important Note!!!
  # Requires that the 'tar' binary is present in your container
  # image.  If 'tar' is not present, 'kubectl cp' will fail.
  #
  # For advanced use cases, such as symlinks, wildcard expansion or
  # file mode preservation, consider using 'kubectl exec'.

  # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
  tar cf - /tmp/foo | kubectl exec -i -n <some-namespace> <some-pod> -- tar xf - -C /tmp/bar

  # Copy /tmp/foo from a remote pod to /tmp/bar locally
  kubectl exec -n <some-namespace> <some-pod> -- tar cf - /tmp/foo | tar xf - -C /tmp/bar

  # Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
  kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir

  # Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
  kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>

  # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
  kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar

  # Copy /tmp/foo from a remote pod to /tmp/bar locally
  kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar

Options:
    -c, --container='':
    Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the
    container to be attached or the first container in the pod will be chosen

    --no-preserve=false:
    The copied file/directory's ownership and permissions will not be preserved in the container

    --retries=0:
    Set number of retries to complete a copy operation from a container. Specify 0 to disable or any negative
    value for infinite retrying. The default is 0 (no retry).

Usage:
  kubectl cp <file-spec-src> <file-spec-dest> [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

Basically the default behavior of kubectl cp command is a merge of the content of source and destination directory. Let's say we have local directory /tmp/test containing:

/tmp/test$ ls
different_file.txt

with single line of text "some content". If we copy our local /tmp/test directory to /tmp directory on our Pod, which already contains test folder with a different file, let's say testfile.txt, the content of both directories will be merged, so our destination /tmp/test will contain eventually:

/tmp/test# ls
different_file.txt  testfile.txt

If we change the content of our local different_file.txt to "yet another content" and run again the command:

kubectl cp /tmp/test pod-name:/tmp

it will only override the destination different_file.txt which is already present in the destination /tmp/test directory.

Currently there is no way to override this default behavior.


问:
Update ASP.NET panel asynchronously
I need some help with this problem:

Situation:
I've got a usercontrol (in SharePoint) that reads query string and processes it with an asynchronous event. While it's busy, a spinner is shown. After the event is finished, the updatepanel inside the usercontrol should update and show the message (+ hide the spinner)

Code: I've got a function that's called asynchronously on the UserControl_Unload event.

```<code>private delegate void AsyncFunction(string activation);

void UserControl_Unload(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        AsyncFunction dlgt = new AsyncFunction(this.CheckUrl);
        AsyncCallback callback = new AsyncCallback(FunctionCallBack);
        IAsyncResult ar = dlgt.BeginInvoke(activationcode, callback, null);
    }
}
private void CheckUrl(string lalala)
{
   // Some code
}
</code>```

User control markup:

```<code><asp:UpdatePanel runat="server" id="pnlContent" updatemode="Conditional"      ChildrenAsTriggers="true">
    <ContentTemplate>
         <asp:UpdatePanel runat="server" id="pnlStatus" UpdateMode="Conditional"  ChildrenAsTriggers="false">
            <ContentTemplate>
                <asp:Label runat="server" ID="lblMessage" />
                <asp:LinkButton runat="server" ID="btnHome" Text="Terug naar welkom-pagina" PostBackUrl="<% $SPUrl:~sitecollection %>"  />
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdatePanel runat="server" id="pnlGegevens" UpdateMode="Conditional" ChildrenAsTriggers="false">
            <ContentTemplate>
                <div><asp:Image runat="server" ID="imgLoading" AlternateText="Loading..." CssClass="gb_pl_loadingImage" ImageUrl="<% $SPUrl:~sitecollection/Style Library/GB-VW Styles/Images/ajax-loader.gif %>"/></div>
                <div class="gb_pl_loading">Even geduld aub. De gebruiker wordt geactiveerd...</div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

This all works great, but when I need to update the panel, it doesn't work.

```<code>private void FunctionCallBack(IAsyncResult test)
{
    pnlContent.Update()
}
</code>```

Anyone who knows how to solve this? (if it's possible only use asp, c# or javascript)

答:
Is it possible to fire off the asynchronous operation from the client? That is, display your page but include javascript that makes a webservice call? That way you at least have something to wait for, and your client will get notified becuase it initiated the request.

Otherwise I don't see how the page, which is already gone to the client, could be updated by the server once the async op finishes.

ContentLicense: CC BY-SA 3.0

Title: Update ASP.NET panel asynchronously

Body:
I need some help with this problem:

Situation:
I've got a usercontrol (in SharePoint) that reads query string and processes it with an asynchronous event. While it's busy, a spinner is shown. After the event is finished, the updatepanel inside the usercontrol should update and show the message (+ hide the spinner)

Code: I've got a function that's called asynchronously on the UserControl_Unload event.

private delegate void AsyncFunction(string activation);

void UserControl_Unload(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        AsyncFunction dlgt = new AsyncFunction(this.CheckUrl);
        AsyncCallback callback = new AsyncCallback(FunctionCallBack);
        IAsyncResult ar = dlgt.BeginInvoke(activationcode, callback, null);
    }
}
private void CheckUrl(string lalala)
{
   // Some code
}

User control markup:

<asp:UpdatePanel runat="server" id="pnlContent" updatemode="Conditional"      ChildrenAsTriggers="true">
    <ContentTemplate>
         <asp:UpdatePanel runat="server" id="pnlStatus" UpdateMode="Conditional"  ChildrenAsTriggers="false">
            <ContentTemplate>
                <asp:Label runat="server" ID="lblMessage" />
                <asp:LinkButton runat="server" ID="btnHome" Text="Terug naar welkom-pagina" PostBackUrl="<% $SPUrl:~sitecollection %>"  />
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdatePanel runat="server" id="pnlGegevens" UpdateMode="Conditional" ChildrenAsTriggers="false">
            <ContentTemplate>

<asp:Image runat="server" ID="imgLoading" AlternateText="Loading..." CssClass="gb_pl_loadingImage" ImageUrl="<% $SPUrl:~sitecollection/Style Library/GB-VW Styles/Images/ajax-loader.gif %>"/>

Even geduld aub. De gebruiker wordt geactiveerd...

            </ContentTemplate>
        </asp:UpdatePanel>
    </ContentTemplate>
</asp:UpdatePanel>

This all works great, but when I need to update the panel, it doesn't work.

private void FunctionCallBack(IAsyncResult test)
{
    pnlContent.Update()
}

Anyone who knows how to solve this? (if it's possible only use asp, c# or javascript)


问:
Asynchronous server messages with python flask
I'm trying to get server messages pushed out to the end user that's logged into our flask website.

I've done some research and it seems that the best solution is to use socket-io.

My attempts at this don't seem to be working, I must also indicate that my knowledge of javascript is very basic.

Any assistance / guidance will be highly appreciated.

See my code below:

python - app.py

```<code>from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, request
from time import sleep

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

# turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if request.form['submit_button'] == 'Do Stuff':
            # server doing things....
            # the below method will make calls to emit socket messages
            # based on actions / outcome of actions.
            serverActions()
    return render_template('index.html')

@socketio.on('connect')
def connect():
    print('Client connected')

@socketio.on('display_message')
def displayMessage(message):
    socketio.emit('newmessage', {'message': message})
    socketio.sleep(2)

def serverActions():
    # get connection to DB
    message = "connecting to DB"
    # show message to user on flask page
    displayMessage(message)

    # test successful connection to DB
    message = "successfully connected to DB"
    displayMessage(message)

    # query the DB
    message = "querying the DB"
    displayMessage(message)

    # update DB
    message = "updating the DB"
    displayMessage(message)

    # etc......

if __name__ == '__main__':
    socketio.run(app)
</code>```

HTML - templates/index.html

```<code><!DOCTYPE html>
<html>
<head>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
    <script src="static/js/application.js"></script>
</head>
<body>
  <form method="POST">
  <div>
    <div>
      <h1>Asynchronous Flask Communication</h1>
      <p>Messages generated by the Flask server should appear below, asynchronously.</p>
    </div>
  </div>

  <div>
      <p>Asynchronous page updates will appear here:</p>
      <div>
        <input type="submit" value="Do Stuff" name="submit_button">
      </div>
      <div>
        <h3>Server Messages:</h3>
        <div id="message">
        </div>
      </div>
  </div>

  </form>
</body>
</html>
</code>```

javascript - static/js/application.js

```<code>$(document).ready(function(){
    //connect to the socket server.
    var socket = io.connect('http://' + document.domain + ':' + location.port);

    //receive message details from server
    socket.on('display_message', function(msg) {
        console.log("Received message" + msg.message);
        message_string = '<p>' + msg.message + '</p>';
        $('#message').html(message_string);
    });

});
</code>```

答:
The problem from the example that you have given appears to be that the client, i.e. your JS in the browser, is listening for the event display_message. However your server is not emitting that event by the looks of it. Every call to the displayMethod is emitting a newmessage event. Update your client to add an event listener for that event.

```<code>    socket.on('newmessage', function(msg) {
        console.log("Received message" + msg.message);
        message_string = '<p>' + msg.message + '</p>';
        $('#message').html(message_string);
    });

</code>```

Body:
I'm trying to get server messages pushed out to the end user that's logged into our flask website.

I've done some research and it seems that the best solution is to use socket-io.

My attempts at this don't seem to be working, I must also indicate that my knowledge of javascript is very basic.

Any assistance / guidance will be highly appreciated.

See my code below:

python - app.py

from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, request
from time import sleep

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

# turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if request.form['submit_button'] == 'Do Stuff':
            # server doing things....
            # the below method will make calls to emit socket messages
            # based on actions / outcome of actions.
            serverActions()
    return render_template('index.html')

@socketio.on('connect')
def connect():
    print('Client connected')

@socketio.on('display_message')
def displayMessage(message):
    socketio.emit('newmessage', {'message': message})
    socketio.sleep(2)

def serverActions():
    # get connection to DB
    message = "connecting to DB"
    # show message to user on flask page
    displayMessage(message)

    # test successful connection to DB
    message = "successfully connected to DB"
    displayMessage(message)

    # query the DB
    message = "querying the DB"
    displayMessage(message)

    # update DB
    message = "updating the DB"
    displayMessage(message)

    # etc......

if __name__ == '__main__':
    socketio.run(app)

HTML - templates/index.html

<!DOCTYPE html>

  <form method="POST">

Asynchronous Flask Communication

Messages generated by the Flask server should appear below, asynchronously.

Asynchronous page updates will appear here:

        <input type="submit" value="Do Stuff" name="submit_button">

Server Messages:

  </form>

javascript - static/js/application.js

$(document).ready(function(){
    //connect to the socket server.
    var socket = io.connect('http://' + document.domain + ':' + location.port);

    //receive message details from server
    socket.on('display_message', function(msg) {
        console.log("Received message" + msg.message);
        message_string = '
' + msg.message + '
';
        $('#message').html(message_string);
    });

});

Body:
The problem from the example that you have given appears to be that the client, i.e. your JS in the browser, is listening for the event display_message. However your server is not emitting that event by the looks of it. Every call to the displayMethod is emitting a newmessage event. Update your client to add an event listener for that event.

    socket.on('newmessage', function(msg) {
        console.log("Received message" + msg.message);
        message_string = '<p>' + msg.message + '</p>';
        $('#message').html(message_string);
    });


问:
What does Apple mean by @ObjectBinding should be passed over through view?
I've been newly studying SwiftUI.
And since I've seen Data flow over SwiftUI video from Apple explaining difference between @ObjectBinding and @EnvironmentObject, a question has come to my mind.
What does apple mean by :

You have to pass around the model from hop to hop in @ObjectBinding ? (29':00")

Do we have to pass the object using @binding in another views for using them ?

What if we don't use @binding and reference to it using another @ObjectBinding ?

Does that make an inconvenience or make SwiftUI not to work correctly or views not being sync with each other ?

答:
[Edit: note that @ObjectBinding is no longer around; instead you can use @State to mark an instance variable as requiring a view refresh when it changes.]

When a view declares an @State or @Binding variable, its value must be explicitly passed from the view's parent. So if you have a long hierarchy of views with some piece of data from the top being used in the bottom, you must code every level of that hierarchy to know about and pass down the data.

In his comment at 29:00, he is contrasting this to using @EnvironmentVariable in a child view, which searches the whole hierarchy for that piece of data. This means any views that do not explicitly need the data can effectively ignore it. Registering a variable needs only be done once (via .environmentObject(_) on a view).

Here is a contrived example. Given some data type conforming to ObservableObject,

```<code>class SampleData: ObservableObject {
    @Published var contents: String

    init(_ contents: String) {
        self.contents = contents
    }
}
</code>```

Consider this view hierarchy:

```<code>struct ContentView: View {
    @State private var data = SampleData("sample content")

    var body: some View {
        VStack {
            StateViewA(data: self.data)

            EnvironmentViewA()
                .environmentObject(self.data)
        }
    }
}

struct StateViewA: View {
    @State var data: SampleData

    var body: some View {
        StateViewB(data: self.data)
    }
}

struct StateViewB: View {
    @State var data: SampleData

    var body: some View {
        Text(self.data.contents)
    }
}

struct EnvironmentViewA: View {
    var body: some View {
        EnvironmentViewB()
    }
}

struct EnvironmentViewB: View {
    @EnvironmentObject var data: SampleData

    var body: some View {
        Text(self.data.contents)
    }
}
</code>```

The result in ContentView will be two views that display the same piece of text. In the first, StateViewA must pass the data on to its child (i.e. the model is passed from "hop to hop"), whereas in the second, EnvironmentViewA does not have to be aware of the data at all.

Body:
[Edit: note that @ObjectBinding is no longer around; instead you can use @State to mark an instance variable as requiring a view refresh when it changes.]

When a view declares an @State or @Binding variable, its value must be explicitly passed from the view's parent. So if you have a long hierarchy of views with some piece of data from the top being used in the bottom, you must code every level of that hierarchy to know about and pass down the data.

In his comment at 29:00, he is contrasting this to using @EnvironmentVariable in a child view, which searches the whole hierarchy for that piece of data. This means any views that do not explicitly need the data can effectively ignore it. Registering a variable needs only be done once (via .environmentObject(_) on a view).

Here is a contrived example. Given some data type conforming to ObservableObject,

class SampleData: ObservableObject {
    @Published var contents: String

    init(_ contents: String) {
        self.contents = contents
    }
}

Consider this view hierarchy:

struct ContentView: View {
    @State private var data = SampleData("sample content")

    var body: some View {
        VStack {
            StateViewA(data: self.data)

            EnvironmentViewA()
                .environmentObject(self.data)
        }
    }
}

struct StateViewA: View {
    @State var data: SampleData

    var body: some View {
        StateViewB(data: self.data)
    }
}

struct StateViewB: View {
    @State var data: SampleData

    var body: some View {
        Text(self.data.contents)
    }
}

struct EnvironmentViewA: View {
    var body: some View {
        EnvironmentViewB()
    }
}

struct EnvironmentViewB: View {
    @EnvironmentObject var data: SampleData

    var body: some View {
        Text(self.data.contents)
    }
}

The result in ContentView will be two views that display the same piece of text. In the first, StateViewA must pass the data on to its child (i.e. the model is passed from "hop to hop"), whereas in the second, EnvironmentViewA does not have to be aware of the data at all.


答:
Your loop is creating multiple #requestId and #paramModalBtn elements when id attributes have to be unique within the DOM. Change the logic to use common classes instead. Then you can traverse the DOM to find the elements related to the button which was clicked. Try this:

$("button").click(function() {
  var $col = $(this).closest('.row').find('.requestId');
  var jobRequestId = $col.data('id');
  console.log(jobRequestId);

  // AJAX request...
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

<div class="row list-group-item container">
  <div class="hidden requestId" data-id="foo-bar">Job #1</div>
  <!-- other content... -->
  <div class="col-md-1">
    <button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
  </div>
</div>

<div class="row list-group-item container">
  <div class="hidden requestId" data-id="lorem-ipsum">#Job #2</div>
  <!-- other content... -->
  <div class="col-md-1">
    <button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
  </div>
</div></code>```

Title: data- attribute not working to grab dynamic id from foreach

Body:
Your loop is creating multiple #requestId and #paramModalBtn elements when id attributes have to be unique within the DOM. Change the logic to use common classes instead. Then you can traverse the DOM to find the elements related to the button which was clicked. Try this:

$("button").click(function() {
  var $col = $(this).closest('.row').find('.requestId');
  var jobRequestId = $col.data('id');
  console.log(jobRequestId);

  // AJAX request...
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

<div class="row list-group-item container">
  <div class="hidden requestId" data-id="foo-bar">Job #1</div>
  <!-- other content... -->
  <div class="col-md-1">
    <button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
  </div>
</div>

<div class="row list-group-item container">
  <div class="hidden requestId" data-id="lorem-ipsum">#Job #2</div>
  <!-- other content... -->
  <div class="col-md-1">
    <button class="glyphicon glyphicon-list-alt btn btn-primary" name="paramsBtn"></button>
  </div>
</div>


问:
specify GitHub's Package Repository in buildspec.yml
I have an AWS CodeBuild process kicking off whenever I check code into master branch of my GitHub repo.  My codebase is a dotnet core serverless application.  I have a dependency on a private nuget package residing in GitHub Package Repository.  My CodeBuild process is failing when trying to find the package:

```<code>error NU1101: Unable to find package datastop.io.data-dictionary.
No packages exist with this id in source(s): nuget.org
</code>```

datastop.io.data-dictionary is a private nuget package residing in GitHub Package Repository, not in nuget.org.  It appears from the error message the CodeBuild process is attempting to find 'datastop.io.data-dictionary' in nuget.

Here's my current buildspec.yml file:

```<code>version: 0.2
phases:
    install:
        runtime-versions:
            dotnet: 2.1
        commands:
            - echo Entered the install phase...
            - export PATH="$PATH:/root/.dotnet/tools"
            - dotnet tool install -g Amazon.Lambda.Tools
    pre_build:
        commands:
            - echo Entered the pre_build phase...
            - dotnet restore
    build:
        commands:
            - echo Entered the build phase...
            - echo Build started on `date`
            - cd $FOLDER
            - dotnet lambda package --configuration release --framework netcoreapp2.1 -o ./$ZIPPED_APPLICATION
            - aws cloudformation package --template-file infrastructure.yml --s3-bucket $S3_DEPLOYMENT_BUCKET --output-template-file packaged-infrastructure.yml --region us-east-2
            - aws cloudformation deploy --template-file packaged-infrastructure.yml --stack-name $CLOUDFORMATION_STACK_NAME --capabilities CAPABILITY_IAM --region us-east-2
</code>```

The build process is failing while running dotnet restore.

I'm assuming I need to modify my buildspec.yml file somehow to let the build process know to look at the correct package repository (our private GitHub Package Repository).  How do I modify my buildspec.yml file to point to the appropriate GitHub Package Repository when trying to find datastop.io.data-dictionary package?

答:
If you add a nuget.config file to your project, and add your GitHub repo to that config it will know where to look. From there it's a question of permissions, which is what I'm struggling with.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <clear />
        <add key="github" value="https://nuget.pkg.github.com/YOUR_ACCOUNT_NAME/index.json" />
    </packageSources>
</configuration>
```

Body:
I have an AWS CodeBuild process kicking off whenever I check code into master branch of my GitHub repo.  My codebase is a dotnet core serverless application.  I have a dependency on a private nuget package residing in GitHub Package Repository.  My CodeBuild process is failing when trying to find the package:

error NU1101: Unable to find package datastop.io.data-dictionary.
No packages exist with this id in source(s): nuget.org

datastop.io.data-dictionary is a private nuget package residing in GitHub Package Repository, not in nuget.org.  It appears from the error message the CodeBuild process is attempting to find 'datastop.io.data-dictionary' in nuget.

Here's my current buildspec.yml file:

version: 0.2
phases:
    install:
        runtime-versions:
            dotnet: 2.1
        commands:
            - echo Entered the install phase...
            - export PATH="$PATH:/root/.dotnet/tools"
            - dotnet tool install -g Amazon.Lambda.Tools
    pre_build:
        commands:
            - echo Entered the pre_build phase...
            - dotnet restore
    build:
        commands:
            - echo Entered the build phase...
            - echo Build started on `date`
            - cd $FOLDER
            - dotnet lambda package --configuration release --framework netcoreapp2.1 -o ./$ZIPPED_APPLICATION
            - aws cloudformation package --template-file infrastructure.yml --s3-bucket $S3_DEPLOYMENT_BUCKET --output-template-file packaged-infrastructure.yml --region us-east-2
            - aws cloudformation deploy --template-file packaged-infrastructure.yml --stack-name $CLOUDFORMATION_STACK_NAME --capabilities CAPABILITY_IAM --region us-east-2

The build process is failing while running dotnet restore.

I'm assuming I need to modify my buildspec.yml file somehow to let the build process know to look at the correct package repository (our private GitHub Package Repository).  How do I modify my buildspec.yml file to point to the appropriate GitHub Package Repository when trying to find datastop.io.data-dictionary package?


问:
Informatica: How to pick the sorted record from multiple rows or take the max on two columns together in Informatica
I have a requirement as below.

source:

```<code>   prod_id          DATE              Price      Count(Price)

   1          01-02-2017              100             1

   1          01-02-2017              10             4

   2          02-02-2017              50             1

   2          02-02-2017              60             1
</code>```

I have data like this. Now I need to pick records with max(count(Price)) for every unique prod_id and date combination, but if Count(price) is same then it should take max(price) or sort the columns on the basis of Count(price) and price and pick the top record. I'm achieving this data by using an aggregator doing group by prod_id, date column and taking count on price and not a direct table. How can I achieve this? Any suggestions?

Thanks,
Priyanka

答:
As you tagged Teradata, you can get it directly by adding

```<code>select .....
qualify
   row_number()
   over(partition by prod_id
        order by Count(Price) desc, Price desc) = 1
</code>```

to your current query.

Body:
I have a requirement as below.

source:

   prod_id          DATE              Price      Count(Price)

   1          01-02-2017              100             1

   1          01-02-2017              10             4

   2          02-02-2017              50             1

   2          02-02-2017              60             1

I have data like this. Now I need to pick records with max(count(Price)) for every unique prod_id and date combination, but if Count(price) is same then it should take max(price) or sort the columns on the basis of Count(price) and price and pick the top record. I'm achieving this data by using an aggregator doing group by prod_id, date column and taking count on price and not a direct table. How can I achieve this? Any suggestions?

Thanks,
Priyanka

Body:
As you tagged Teradata, you can get it directly by adding

select .....
qualify
   row_number()
   over(partition by prod_id
        order by Count(Price) desc, Price desc) = 1

to your current query.


问:
Running multiple instances of an application with different arguments using eclipse
I'm trying to build client server program.
So I should run my program simultaneously with diffrent ports.
The program gets the port through the arguments.

What is the way to do that?
Thank you

答: If you pull down the menu under the Run toolbar button, you will see "Run Configurations...". This will open a dialog to let you define any number of launch configurations. Then use this pull-down menu to launch your app with different parameters using different launch configurations.</p>


问:
Get IServiceCollection in Service?
Is there a way to get the IServiceCollection we use at Startup in a Service?
I want to get a list of all current services.
Taking a dependency on it does not work, as the servicecollection is not registered in the DI</p>

```<code>public class Test
{
    public Test(IServiceCollection collection)
    {
        this.services=collection;
    }
}
</code>```

答: As long as you add the Dependency Injection using statement you should get a list of all the services. Is that what you're not seeing ?</p>

Title: Get IServiceCollection in Service?

Body:
Is there a way to get the IServiceCollection we use at Startup in a Service?
I want to get a list of all current services.
Taking a dependency on it does not work, as the servicecollection is not registered in the DI

public class Test
{
    public Test(IServiceCollection collection)
    {
        this.services=collection;
    }
}