问:
Avoid writing too many getters and setters in Go
I am implementing a message passing system in Go. So I have a general interface called Msg. The Msg interface defines many common fields such as source, destination, send time, receive time, etc. I cannot define a full list of Msgs since I want the library users to define the concrete type of Msgs.

To provide a concrete type of Msg, a user would need to implement a large list of getters and setters, which is very annoying.

One solution I tried is to provide a simple base class like MsgBase and defines all the common properties and getters and setters. And for each concrete type of Msg, I embed a pointer to the MsgBase. This solution works.

But then, I want to embed a value version of the MsgBase in the concrete Msg types. This is because such Msgs are created too many times in the execution and dynamically allocating a MsgBase would increase the garbage collection overhead. I really want all the Msgs are allocated statically since they are passed by the components and should never be shared. If I use the value version of the MsgBase, I cannot use the setters defined in the MsgBase.

I wonder if there is any simple solution to this problem?

EDIT: Adding sample code

type Msg interface {
    // Agent is another interface
    Src() Agent
    SetSrc(a Agent)
    Dst() Agent
    SetDst(a Agent)

    ... // A large number of properties
}

type MsgBase struct {
    src, dst Agent
    ... // Properties as private fields.
}

func (m MsgBase) Src() Agent {
    return m.src
}

func (m *MsgBase) SetSrc(a Agent) {
    m.src = a
}

... // Many other setters and getters for MsgBase

type SampleMsg struct {
    MsgBase // option1
    *MsgBase // option2
}

```

答:
Remember that Go doesn't have object-oriented inheritance in the same way Java does.  This sounds like you're trying to write an abstract base class that encapsulates all of the parts of a "message"; that's not really typical Go style.

The fields you're describing are typical message metadata.  You can encapsulate this metadata in a pure-data structure.  It doesn't necessarily need any behavior, and it doesn't necessarily need getter and setter methods.

```<code>type MessageMeta struct {
  Source Agent
  Destination Agent
}
</code>```

The more object-oriented approach is to say a message has a (mutable) metadata block and a (immutable, encoded) payload.

```<code>import "encoding"

type Message interface {
  encoding.BinaryMarshaler // requires MarshalBinary()
  Meta() *MessageMeta
}

type SomeMessage struct {
  MessageMeta
  Greeting string
}

func (m *SomeMessage) Meta() *MessageMeta {
  return &m.MessageMeta
}

func (m *SomeMessage) MarshalBinary() ([]byte, error) {
  return []byte(m.Greeting), nil
}
</code>```

A more procedural approach that passes these two things separately is also reasonable.  In this case there's no interface for what's a "message", you just pass on the encoded payload; standard-library interfaces like encoding.BinaryMarshaler could make sense here.  You might include this in a lower-level interface that's part of your library.

```<code>func Deliver(meta *MessageMeta, payload []byte) error { ... }
</code>```

Translating one to the other is easy

```<code>func DeliverMessage(m Message) error {
  payload, err := m.Payload()
  if err != nil {
    return err
  }
  meta := m.Meta()
  return Deliver(meta, payload)
}
</code>```

If one of the metadata fields is "delivered at", making sure to pass a pointer to the metadata object all the way through the chain lets you update that field in the original object.

I would not worry about garbage collection as a first-class consideration, except to avoid being overtly wasteful, and to check up on object allocation if GC starts showing up in profiles.  Creating two objects instead of one probably isn't going to be a huge problem here.

Body:
Remember that Go doesn't have object-oriented inheritance in the same way Java does.  This sounds like you're trying to write an abstract base class that encapsulates all of the parts of a "message"; that's not really typical Go style.

The fields you're describing are typical message metadata.  You can encapsulate this metadata in a pure-data structure.  It doesn't necessarily need any behavior, and it doesn't necessarily need getter and setter methods.

type MessageMeta struct {
  Source Agent
  Destination Agent
}

The more object-oriented approach is to say a message has a (mutable) metadata block and a (immutable, encoded) payload.

import "encoding"

type Message interface {
  encoding.BinaryMarshaler // requires MarshalBinary()
  Meta() *MessageMeta
}

type SomeMessage struct {
  MessageMeta
  Greeting string
}

func (m *SomeMessage) Meta() *MessageMeta {
  return &m.MessageMeta
}

func (m *SomeMessage) MarshalBinary() ([]byte, error) {
  return []byte(m.Greeting), nil
}

A more procedural approach that passes these two things separately is also reasonable.  In this case there's no interface for what's a "message", you just pass on the encoded payload; standard-library interfaces like encoding.BinaryMarshaler could make sense here.  You might include this in a lower-level interface that's part of your library.

func Deliver(meta *MessageMeta, payload []byte) error { ... }

Translating one to the other is easy

func DeliverMessage(m Message) error {
  payload, err := m.Payload()
  if err != nil {
    return err
  }
  meta := m.Meta()
  return Deliver(meta, payload)
}

If one of the metadata fields is "delivered at", making sure to pass a pointer to the metadata object all the way through the chain lets you update that field in the original object.

I would not worry about garbage collection as a first-class consideration, except to avoid being overtly wasteful, and to check up on object allocation if GC starts showing up in profiles.  Creating two objects instead of one probably isn't going to be a huge problem here.


来源: stackexchange

问:
Whats app (web.whatsapp.com/send) send not working
https://web.whatsapp.com/send?phone=&text=
is redirecting to web but not opening the right mobilenumber with text message.
Anything changed ?</p>

答: Received From WhatsApp Support-We are aware of the issue and we are working on fixing it in a future update of WhatsApp. Unfortunately, we can't comment on any future release dates at this time.</p>

ContentLicense: CC BY-SA 4.0


问:
How to customize validation error message to display on tooltip in Yii2?
I am using ActiveForm of yii2 and I want to customize the validation errors. I want to display errors on tooltip.

This is my form

```<code><?= $form = ActiveForm::begin(['id' => 'login-form','method'=>'post']); ?>
    <?=
        $form->field($model, 'email')
            ->textInput([
                'class'=>'form-control login_email',
                'placeholder'=>'Email'
                /*'onfocus'=>"this.value = '';",
                "onblur"=>"if (this.value == '') {
                    this.value = 'Email';
                }"*/
            ])
            ->label(false);
    ?>
    <?=
        $form->field($model, 'password')
            ->passwordInput([
                'class'=>'form-control',
                'placeholder'=>'Password'
            ])
            ->label(false);
    ?>
    <input type="text" name="hidden" value="login" hidden="true">
    <p class="forgot">
        <a href="<?= Yii::$app->urlManager->createUrl(['site/request-password-reset']); ?>">
            Forgot Password?
        </a>
    </p>

    <div class="form-group">
        <?= Html::submitButton('Log In', ['class' => 'sign-in','name' => 'login-button']) ?>
    </div>
<?php ActiveForm::end(); ?>
</code>```

Please tell me if anyone has idea about this.

答:
Update error message in form template like below</p>

```<code>  $form = ActiveForm::begin([
  'id' => 'login-form',
  'options' => ['enctype' => 'multipart/form-data'],
   'fieldConfig' => ['template' => "<div class=\"input-cover\"><div class=\"tooltip\">{error}</div>\n{label}\n{input}</div>",
  'inputOptions' => ['class' => 'input-control'],
                    ],
          ]);
</code>```

Body:
I am using ActiveForm of yii2 and I want to customize the validation errors. I want to display errors on tooltip.

This is my form

<?= $form = ActiveForm::begin(['id' => 'login-form','method'=>'post']); ?>
    <?=
        $form->field($model, 'email')
            ->textInput([
                'class'=>'form-control login_email',
                'placeholder'=>'Email'
                /*'onfocus'=>"this.value = '';",
                "onblur"=>"if (this.value == '') {
                    this.value = 'Email';
                }"*/
            ])
            ->label(false);
    ?>
    <?=
        $form->field($model, 'password')
            ->passwordInput([
                'class'=>'form-control',
                'placeholder'=>'Password'
            ])
            ->label(false);
    ?>
    <input type="text" name="hidden" value="login" hidden="true">

        <a href="<?= Yii::$app->urlManager->createUrl(['site/request-password-reset']); ?>">
            Forgot Password?

        <?= Html::submitButton('Log In', ['class' => 'sign-in','name' => 'login-button']) ?>

<?php ActiveForm::end(); ?>

Please tell me if anyone has idea about this.

Body:
Update error message in form template like below

  $form = ActiveForm::begin([
  'id' => 'login-form',
  'options' => ['enctype' => 'multipart/form-data'],
   'fieldConfig' => ['template' => "<div class=\"input-cover\"><div class=\"tooltip\">{error}</div>\n{label}\n{input}</div>",
  'inputOptions' => ['class' => 'input-control'],
                    ],
          ]);


问:
Error while use custom class when implement IProfileService. The type 'IProfileService' is defined in an assembly that is not referenced
I'm updating IdentityServer from 2.2 to 2.4. I have two projects one its entry point and another for services.
I updated both projects to 2.4 and facing an issue with:

The type 'IProfileService' is defined in an assembly that is not
  referenced.

Also, I have another error:

The type 'ClaimsProfileService' cannot be used as type parameter 'T'
  in the generic type or method
  'IdentityServerBuilderExtensionsAdditional.AddProfileService(IIdentityServerBuilder)'.
  There is no implicit reference conversion from 'ClaimsProfileService'
  to 'IdentityServer4.Services.IProfileService'.

The class ClaimsProfileService implemented the interface IProfileService.  It looks weird, 'cause when I downgrade IdentityServer to 2.2 it's work properly.

Actually, there present strange behavior, when I created a nested class in my Startup.cs than implemented IProfileService I got no errors.

This is my identity server confiration.

var identityServer = services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseSuccessEvents = true;
                    options.Authentication.CookieLifetime = TimeSpan.FromSeconds(7200);
                })
                // this adds the config data from DB (clients, resources, CORS)
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                })
                // this adds the operational data from DB (codes, tokens, consents)
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));

                    // this enables automatic token cleanup. this is optional.
                    options.EnableTokenCleanup = true;
                    // options.TokenCleanupInterval = 15; // interval in seconds. 15 seconds useful for debugging
                })
                .AddAspNetIdentity<ApplicationUser>()
                .AddProfileService<ClaimsProfileService>()
                .AddExtensionGrantValidator<DelegationGrantValidator>();
```

<p>This is PackageReferences for main app project.</p>

```  <ItemGroup>
    <PackageReference Include="IdentityServer4" Version="2.4.0" />
    <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.7.0" />
    <PackageReference Include="IdentityServer4.AspNetIdentity" Version="2.4.0" />
    <PackageReference Include="IdentityServer4.EntityFramework" Version="2.4.0" />
    <PackageReference Include="jQuery" Version="3.3.1" />
    <PackageReference Include="jQuery.Validation" Version="1.17.0" />
    <PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.2" />
    <PackageReference Include="Microsoft.jQuery.Unobtrusive.Validation" Version="3.2.11" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.2" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
  </ItemGroup>
```

<p>This is PackageReferences for Services project.</p>

```  <ItemGroup>
    <PackageReference Include="IdentityServer4" Version="2.4.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.2" />
  </ItemGroup>
```

Thank for any help with this issue.

答: Already fixed. Just deleted from NuGet folder version 2.2 manually. Then I reinstalled IdentityServer and all work properly.</p>

Body:
I'm updating IdentityServer from 2.2 to 2.4. I have two projects one its entry point and another for services.
I updated both projects to 2.4 and facing an issue with:

The type 'IProfileService' is defined in an assembly that is not
  referenced.

Also, I have another error:

The type 'ClaimsProfileService' cannot be used as type parameter 'T'
  in the generic type or method
  'IdentityServerBuilderExtensionsAdditional.AddProfileService(IIdentityServerBuilder)'.
  There is no implicit reference conversion from 'ClaimsProfileService'
  to 'IdentityServer4.Services.IProfileService'.

The class ClaimsProfileService implemented the interface IProfileService.  It looks weird, 'cause when I downgrade IdentityServer to 2.2 it's work properly.

Actually, there present strange behavior, when I created a nested class in my Startup.cs than implemented IProfileService I got no errors.

This is my identity server confiration.

var identityServer = services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseSuccessEvents = true;
                    options.Authentication.CookieLifetime = TimeSpan.FromSeconds(7200);
                })
                // this adds the config data from DB (clients, resources, CORS)
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                })
                // this adds the operational data from DB (codes, tokens, consents)
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));

                    // this enables automatic token cleanup. this is optional.
                    options.EnableTokenCleanup = true;
                    // options.TokenCleanupInterval = 15; // interval in seconds. 15 seconds useful for debugging
                })
                .AddAspNetIdentity<ApplicationUser>()
                .AddProfileService<ClaimsProfileService>()
                .AddExtensionGrantValidator<DelegationGrantValidator>();

This is PackageReferences for main app project.

  <ItemGroup>
    <PackageReference Include="IdentityServer4" Version="2.4.0" />
    <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.7.0" />
    <PackageReference Include="IdentityServer4.AspNetIdentity" Version="2.4.0" />
    <PackageReference Include="IdentityServer4.EntityFramework" Version="2.4.0" />
    <PackageReference Include="jQuery" Version="3.3.1" />
    <PackageReference Include="jQuery.Validation" Version="1.17.0" />
    <PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.2" />
    <PackageReference Include="Microsoft.jQuery.Unobtrusive.Validation" Version="3.2.11" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.2" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
  </ItemGroup>

This is PackageReferences for Services project.

  <ItemGroup>
    <PackageReference Include="IdentityServer4" Version="2.4.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.2" />
  </ItemGroup>

Thank for any help with this issue.


问:
How to produce a running sequence in Oracle based on report column values
I have the following sample Oracle APEX report by where the Origin ID and Origin Name are retrieved from the origin_tab(id,origin_id,origin_name)

Based on these two column values, I need to generate the Temporary Origin ID value on the fly as part of the selection retrieval from the origin_tab.

The rule behind this is - where the Origin Name is the same against the Origin ID, take the Origin ID value before the dash and append a 3-digit sequence for each Orgin ID as per example below.

Since the origin name (AAA) is the same for the first two records, '001' is appended to the origin id 1111. The same for BBB, '002' is appended to those three records and so forth.

Please note that the Temporary Origin ID here is a string.

```<code>Origin ID         Origin Name        Temporary Origin ID
----------------- ------------------ --------------------
1111-1            AAA                1111001
1111-2            AAA                1111001
1111-3            BBB                1111002
1111-4            BBB                1111002
1111-5            BBB                1111002
1111-6            CCC                1111003
1111-7            DDD                1111004
1111-8            DDD                1111004
</code>```

What approach should I take in my query to achieve the above result, for the Temporary Origin ID?

答:
Use dense_rank():

```<code>select t.*,
       (substr(origin_id, 1, 4) ||
        lpad(dense_rank() over (order by origin_name), 4, '0')
       ) as temp_origin_id
from t;
</code>```

Here is a db<>fiddle.

Body:
I have the following sample Oracle APEX report by where the Origin ID and Origin Name are retrieved from the origin_tab(id,origin_id,origin_name)

Based on these two column values, I need to generate the Temporary Origin ID value on the fly as part of the selection retrieval from the origin_tab.

The rule behind this is - where the Origin Name is the same against the Origin ID, take the Origin ID value before the dash and append a 3-digit sequence for each Orgin ID as per example below.

Since the origin name (AAA) is the same for the first two records, '001' is appended to the origin id 1111. The same for BBB, '002' is appended to those three records and so forth.

Please note that the Temporary Origin ID here is a string.

Origin ID         Origin Name        Temporary Origin ID
----------------- ------------------ --------------------
1111-1            AAA                1111001
1111-2            AAA                1111001
1111-3            BBB                1111002
1111-4            BBB                1111002
1111-5            BBB                1111002
1111-6            CCC                1111003
1111-7            DDD                1111004
1111-8            DDD                1111004

What approach should I take in my query to achieve the above result, for the Temporary Origin ID?

Body:
Use dense_rank():

select t.*,
       (substr(origin_id, 1, 4) ||
        lpad(dense_rank() over (order by origin_name), 4, '0')
       ) as temp_origin_id
from t;

Here is a db<>fiddle.


问:
PyCharm issue with runserver command
I have a script, part of a Django app, that makes thumbnails from pdfs. I'm using the excellent wand package to do it: Here are the Wand docs

It runs fine if I do ./manage.py runserver from the command line, but if I run from PyCharm, it breaks.

When I step through the code, the problem is that the code used to open the blob always returns an empty wand.image object. It's the right class (wand.image) but it's an empty one. The object I pass it is a pdf, but the blob conversion, which produces no error at all, is empty.

The error occurs in the next line (single_image = all_pages.sequence[0]) because all_pages is empty, so the index is out of range.

Again, if I launch the server from the command line, it works, but if I launch from PyCharm, it breaks.

I'm using virtualenv.

Here's the code I'm running:

```<code>from wand.image import Image as WandImage
from wand.color import Color

def convert_to_thumb(pdf_path, slug):
    with open(pdf_path) as f:
        image_binary = f.read()
    all_pages = WandImage(blob=image_binary) #<-- Here image_binary is a pdf
    single_image = all_pages.sequence[0]     #<-- BOOM! all_pages is a wand.image, but it's empty. Gives an Index error
    with WandImage(single_image) as i:
        i.format = 'png'
        i.background_color = Color('white')
        i.alpha_channel = 'remove'
        i.transform(resize='x100')
        save_name = slug + '_pdf_preview.png'
        i.save(filename='/foo/bar/' + save_name)

        return i
</code>```

EDIT: Here's some Debug info

When I run from CLI and use pdb.set_trace() to check the value of all_pages I get this

```<code>(Pdb) p all_pages
<wand.image.Image: 3da0549 'PDF' (612x792)>
</code>```

But when I do the same thing from the PyCharm console, I get:

```<code>(Pdb) >? p all_pages
<wand.image.Image: (empty)>
</code>```

The value of image_binary appears to be identical in both cases. I diffed them.

Furthermore, the value of libmagick (the ImageMagick install) is /usr/local/lib/libMagickWand.dylib in both cases.

EDIT: This is interesting. If I launch PyCharm from the system Terminal, it works fine.

EDIT: Added relevant run configuration settings

```<code><configuration default="false" name="foo_bar_app" type="Python.DjangoServer" factoryName="Django server">
  <option name="INTERPRETER_OPTIONS" value="" />
  <option name="PARENT_ENVS" value="true" />
  <envs>
    <env name="PYTHONUNBUFFERED" value="1" />
    <env name="FOO_USERID" value="foobar" />
    <env name="DJANGO_SETTINGS_MODULE" value="foo_bar.settings" />
  </envs>
  <option name="SDK_HOME" value="$USER_HOME$/venv/foo_bar/bin/python" />
  <option name="WORKING_DIRECTORY" value="" />
  <option name="IS_MODULE_SDK" value="false" />
  <option name="ADD_CONTENT_ROOTS" value="true" />
  <option name="ADD_SOURCE_ROOTS" value="true" />
  <module name="foo_bar_app" />
  <option name="launchJavascriptDebuger" value="false" />
  <option name="port" value="8000" />
  <option name="host" value="" />
  <option name="additionalOptions" value="" />
  <option name="browserUrl" value="" />
  <option name="runTestServer" value="false" />
  <option name="runNoReload" value="false" />
  <option name="useCustomRunCommand" value="false" />
  <option name="customRunCommand" value="" />
  <RunnerSettings RunnerId="PyDebugRunner" />
  <RunnerSettings RunnerId="PythonCover" />
  <RunnerSettings RunnerId="PythonRunner" />
  <ConfigurationWrapper RunnerId="PyDebugRunner" />
  <ConfigurationWrapper RunnerId="PythonCover" />
  <ConfigurationWrapper RunnerId="PythonRunner" />
  <method />
</configuration>
</code>```

答: i got this problem few month ago. The only way i found to fix it was to launch everything in admin mode. It's probably a permissions denied problem from system.</p>

ContentLicense: CC BY-SA 3.0

Title: PyCharm issue with runserver command

Body:
I have a script, part of a Django app, that makes thumbnails from pdfs. I'm using the excellent wand package to do it: Here are the Wand docs

It runs fine if I do ./manage.py runserver from the command line, but if I run from PyCharm, it breaks.

When I step through the code, the problem is that the code used to open the blob always returns an empty wand.image object. It's the right class (wand.image) but it's an empty one. The object I pass it is a pdf, but the blob conversion, which produces no error at all, is empty.

The error occurs in the next line (single_image = all_pages.sequence[0]) because all_pages is empty, so the index is out of range.

Again, if I launch the server from the command line, it works, but if I launch from PyCharm, it breaks.

I'm using virtualenv.

Here's the code I'm running:

from wand.image import Image as WandImage
from wand.color import Color

def convert_to_thumb(pdf_path, slug):
    with open(pdf_path) as f:
        image_binary = f.read()
    all_pages = WandImage(blob=image_binary) #<-- Here image_binary is a pdf
    single_image = all_pages.sequence[0]     #<-- BOOM! all_pages is a wand.image, but it's empty. Gives an Index error
    with WandImage(single_image) as i:
        i.format = 'png'
        i.background_color = Color('white')
        i.alpha_channel = 'remove'
        i.transform(resize='x100')
        save_name = slug + '_pdf_preview.png'
        i.save(filename='/foo/bar/' + save_name)

        return i

EDIT: Here's some Debug info

When I run from CLI and use pdb.set_trace() to check the value of all_pages I get this

(Pdb) p all_pages
<wand.image.Image: 3da0549 'PDF' (612x792)>

But when I do the same thing from the PyCharm console, I get:

(Pdb) >? p all_pages
<wand.image.Image: (empty)>

The value of image_binary appears to be identical in both cases. I diffed them.

Furthermore, the value of libmagick (the ImageMagick install) is /usr/local/lib/libMagickWand.dylib in both cases.

EDIT: This is interesting. If I launch PyCharm from the system Terminal, it works fine.

EDIT: Added relevant run configuration settings

<configuration default="false" name="foo_bar_app" type="Python.DjangoServer" factoryName="Django server">
  <option name="INTERPRETER_OPTIONS" value="" />
  <option name="PARENT_ENVS" value="true" />
  <envs>
    <env name="PYTHONUNBUFFERED" value="1" />
    <env name="FOO_USERID" value="foobar" />
    <env name="DJANGO_SETTINGS_MODULE" value="foo_bar.settings" />
  </envs>
  <option name="SDK_HOME" value="$USER_HOME$/venv/foo_bar/bin/python" />
  <option name="WORKING_DIRECTORY" value="" />
  <option name="IS_MODULE_SDK" value="false" />
  <option name="ADD_CONTENT_ROOTS" value="true" />
  <option name="ADD_SOURCE_ROOTS" value="true" />
  <module name="foo_bar_app" />
  <option name="launchJavascriptDebuger" value="false" />
  <option name="port" value="8000" />
  <option name="host" value="" />
  <option name="additionalOptions" value="" />
  <option name="browserUrl" value="" />
  <option name="runTestServer" value="false" />
  <option name="runNoReload" value="false" />
  <option name="useCustomRunCommand" value="false" />
  <option name="customRunCommand" value="" />
  <RunnerSettings RunnerId="PyDebugRunner" />
  <RunnerSettings RunnerId="PythonCover" />
  <RunnerSettings RunnerId="PythonRunner" />
  <ConfigurationWrapper RunnerId="PyDebugRunner" />
  <ConfigurationWrapper RunnerId="PythonCover" />
  <ConfigurationWrapper RunnerId="PythonRunner" />
  <method />
</configuration>


问:
Copying the values in a column based in their index referencing the value of other DataFrame
I'm having a problem with creating a new column based from value of my df2["index"]. What I want to get is the value inside df1["score"] based from its actual index.

It make it more understandable, here's my two sample dataframes:

```<code>df1= pd.DataFrame({'cluster':[1,2,3,4,5], 'score':[80, 90, 60, 40, 12]})
df2= pd.DataFrame({'word':["hello", "my", "name", "is", "tom"], 'label':["aa", "bb", "cc", "dd", "ee"], 'idx':[1,3,4,4,4]})
</code>```

And here's the result I'm expecting to have where the score is referenced based from the "index" column of df2 and the 'actual index' of df1

```<code>df3= pd.DataFrame({'word':["hello", "my", "name", "is", "tom"], 'label':["aa", "bb", "cc", "dd", "ee"], 'idx':[1,3,4,4,4], 'score':[90, 40, 12, 12, 12]})
</code>```

答:
Use Series.map by Series df1['score'] matched by index values:

```<code>df2['score'] = df2['idx'].map(df1['score'])
print (df1)
    word label  idx  score
0  hello    aa    1     90
1     my    bb    3     40
2   name    cc    4     12
3     is    dd    4     12
4    tom    ee    4     12
</code>```

Body:
I'm having a problem with creating a new column based from value of my df2["index"]. What I want to get is the value inside df1["score"] based from its actual index.

It make it more understandable, here's my two sample dataframes:

df1= pd.DataFrame({'cluster':[1,2,3,4,5], 'score':[80, 90, 60, 40, 12]})
df2= pd.DataFrame({'word':["hello", "my", "name", "is", "tom"], 'label':["aa", "bb", "cc", "dd", "ee"], 'idx':[1,3,4,4,4]})

And here's the result I'm expecting to have where the score is referenced based from the "index" column of df2 and the 'actual index' of df1

df3= pd.DataFrame({'word':["hello", "my", "name", "is", "tom"], 'label':["aa", "bb", "cc", "dd", "ee"], 'idx':[1,3,4,4,4], 'score':[90, 40, 12, 12, 12]})

Body:
Use Series.map by Series df1['score'] matched by index values:

df2['score'] = df2['idx'].map(df1['score'])
print (df1)
    word label  idx  score
0  hello    aa    1     90
1     my    bb    3     40
2   name    cc    4     12
3     is    dd    4     12
4    tom    ee    4     12


问:
How to specify function for stub when using minitest mocha?
Is it possible to specify which find_by! exception is raised in the following example (I want the second one to be raised, not the first):

```<code>def self.test
  Instance.stubs(:find_by!).raises(ActiveRecord::RecordNotFound)

  begin
    function_one
  rescue ActiveRecord::RecordNotFound
    puts 'Failure'
  end

  begin
    function_two
  rescue ActiveRecord::RecordNotFound
    puts 'Success'
  end
end

def self.function_one
  Model.find_by!(id: 1)
end

def self.function_two
  Model.find_by!(id: 1)
end
</code>```

*Assume id: 1 does not exist. As in the example, also assume these will be static class functions, but please mention any differences in the case that add any_instance will not be enough for instance methods.

答:
How about this?

Instance.stubs(:find_by!).returns('result').then.raises(ActiveRecord::RecordNotFound)
```

Body:
Is it possible to specify which find_by! exception is raised in the following example (I want the second one to be raised, not the first):

def self.test
  Instance.stubs(:find_by!).raises(ActiveRecord::RecordNotFound)

  begin
    function_one
  rescue ActiveRecord::RecordNotFound
    puts 'Failure'
  end

  begin
    function_two
  rescue ActiveRecord::RecordNotFound
    puts 'Success'
  end
end

def self.function_one
  Model.find_by!(id: 1)
end

def self.function_two
  Model.find_by!(id: 1)
end

*Assume id: 1 does not exist. As in the example, also assume these will be static class functions, but please mention any differences in the case that add any_instance will not be enough for instance methods.


问:
Select all checkbox not triggering their individual .change functions
I have a table with a checkbox on each row, plus a header checkbox that lets you select them all, that works fine with this code :

var idArray = [];

$(function(event, request, settings){

    //This method is explained later in the post
    //It takes care of storing checked rows into an array
    setupStoreSelected();

    $(function(){
        //Get every checkbox in table body
        var $checkboxes = $("tbody").find(":checkbox");

        //When checkAll is clicked, check/uncheck every enabled checkbox
        $("#checkAll").on("click", function(){
            $($checkboxes).not(":disabled").prop('checked', $(this).prop('checked'));
        });

        //Uncheck global if any individual checkbox is unchecked
        $("tbody").on("change", function () {
            if (!$(this).prop("checked")) {
                $("#checkAll").prop("checked", false);
            }
        });
    });
});

function setupStoreSelected(){

    //This selector listens to every checkbox except for the CheckAll
    $("input:checkbox:not('#checkAll')").change(function(){
        //Get that row's ID value from its column
        var id = $(this).closest("tr").find("td.idColumn").text();

        //If it is checked now, push that ID into a global array
        if($(this).prop("checked")){
            idArray.push(id);
            console.log("Added ID : " + id);
        }

        //Search and delete it from array if it gets unchecked
        else{
            var index = idArray.indexOf(id);
            if(index > -1){
                idArray.splice(index,1);
                console.log("Deleted ID : " + id);
            }
        }
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table{
  border : 1px solid grey;
}

thead{
  background-color : silver;
}

td{
  text-align : center;
}</code>```

    ID
    <input type="checkbox" id="checkAll" value="false">

      001
      <input type="checkbox"/>

      002
      <input type="checkbox"/>

      003
      <input type="checkbox"/>

      004
      <input type="checkbox"/>

```

The problem is that the checkAll checkbox does not trigger the .change(...) function of the individual checkboxes, so it doesnt work at all.

How can i modify my code so both individual and checkAll checkboxes store the ID's??

答:
In the end, this is the way i got it to work :

var idArray = [];

$(document).on('change', '#checkAll', function(e) {
        var checkboxes = $('tbody').find(':checkbox').not(":disabled");
  if($(this).is(':checked')) {
   checkboxes.prop('checked', true);
   checkboxes.each(
    function() {
     checkTerminal($(this).closest("tr").find("td.idColumn").text());
    }
   );
  } else {
   checkboxes.prop('checked', false);
   checkboxes.each(
    function() {
     uncheckTerminal($(this).closest("tr").find("td.idColumn").text());
    }
   );
  }
 });

 $(document).on('change', ':checkbox', function(e) {
  var id = $(this).closest("tr").find("td.idColumn").text();
  if($(this).is(':checked')) {
   checkTerminal(id);
  } else {
   uncheckTerminal(id);
  }

 });

function checkTerminal(id){
    if((idArray.indexOf(id) == -1) && (id!="") && (id!=null)){
        idArray.push(id);
        console.log("Adding ID : " + id);
    }

}

function uncheckTerminal(id){
    var index = idArray.indexOf(id);
 if((index != -1) && (id!="") && (id!=null)){
  idArray.splice(index,1);
  console.log("Deleting ID : " + id);
 }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table{
    border : 1px solid grey;
  }

  thead{
    background-color : silver;
  }

  td{
    text-align : center;
  }

  *{
      font-family: Roboto, sans-serif;
  }</code>```

                    ID
                    <input type="checkbox" id="checkAll" value="false">

          001
          <input type="checkbox"/>

          002
          <input type="checkbox"/>

          003
          <input type="checkbox" disabled/>

          004
          <input type="checkbox"/>

```

Body:
I have a table with a checkbox on each row, plus a header checkbox that lets you select them all, that works fine with this code :

var idArray = [];

$(function(event, request, settings){

    //This method is explained later in the post
    //It takes care of storing checked rows into an array
    setupStoreSelected();

    $(function(){
        //Get every checkbox in table body
        var $checkboxes = $("tbody").find(":checkbox");

        //When checkAll is clicked, check/uncheck every enabled checkbox
        $("#checkAll").on("click", function(){
            $($checkboxes).not(":disabled").prop('checked', $(this).prop('checked'));
        });

        //Uncheck global if any individual checkbox is unchecked
        $("tbody").on("change", function () {
            if (!$(this).prop("checked")) {
                $("#checkAll").prop("checked", false);
            }
        });
    });
});

function setupStoreSelected(){

    //This selector listens to every checkbox except for the CheckAll
    $("input:checkbox:not('#checkAll')").change(function(){
        //Get that row's ID value from its column
        var id = $(this).closest("tr").find("td.idColumn").text();

        //If it is checked now, push that ID into a global array
        if($(this).prop("checked")){
            idArray.push(id);
            console.log("Added ID : " + id);
        }

        //Search and delete it from array if it gets unchecked
        else{
            var index = idArray.indexOf(id);
            if(index > -1){
                idArray.splice(index,1);
                console.log("Deleted ID : " + id);
            }
        }
    });
}

table{
  border : 1px solid grey;
}

thead{
  background-color : silver;
}

td{
  text-align : center;
}

    ID
    <input type="checkbox" id="checkAll" value="false">

      001
      <input type="checkbox"/>

      002
      <input type="checkbox"/>

      003
      <input type="checkbox"/>

      004
      <input type="checkbox"/>

The problem is that the checkAll checkbox does not trigger the .change(...) function of the individual checkboxes, so it doesnt work at all.

How can i modify my code so both individual and checkAll checkboxes store the ID's??

Body:
In the end, this is the way i got it to work :

var idArray = [];

$(document).on('change', '#checkAll', function(e) {
        var checkboxes = $('tbody').find(':checkbox').not(":disabled");
  if($(this).is(':checked')) {
   checkboxes.prop('checked', true);
   checkboxes.each(
    function() {
     checkTerminal($(this).closest("tr").find("td.idColumn").text());
    }
   );
  } else {
   checkboxes.prop('checked', false);
   checkboxes.each(
    function() {
     uncheckTerminal($(this).closest("tr").find("td.idColumn").text());
    }
   );
  }
 });

 $(document).on('change', ':checkbox', function(e) {
  var id = $(this).closest("tr").find("td.idColumn").text();
  if($(this).is(':checked')) {
   checkTerminal(id);
  } else {
   uncheckTerminal(id);
  }

 });

function checkTerminal(id){
    if((idArray.indexOf(id) == -1) && (id!="") && (id!=null)){
        idArray.push(id);
        console.log("Adding ID : " + id);
    }

}

function uncheckTerminal(id){
    var index = idArray.indexOf(id);
 if((index != -1) && (id!="") && (id!=null)){
  idArray.splice(index,1);
  console.log("Deleting ID : " + id);
 }
}

table{
    border : 1px solid grey;
  }

  thead{
    background-color : silver;
  }

  td{
    text-align : center;
  }

  *{
      font-family: Roboto, sans-serif;
  }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" width="20%">
            <thead>
                <tr>
                    <th>ID</th>
                    <th><input type="checkbox" id="checkAll" value="false"></th>

                </tr>
            </thead>
      <tbody>
        <tr>
          <td class="idColumn">001</td>
          <td><input type="checkbox"/></td>
        </tr>
        <tr>
          <td class="idColumn">002</td>
          <td><input type="checkbox"/></td>
        </tr>
        <tr>
          <td class="idColumn">003</td>
          <td><input type="checkbox" disabled/></td>
        </tr>
        <tr>
          <td class="idColumn">004</td>
          <td><input type="checkbox"/></td>
        </tr>
      </tbody>
        </table>


问:
How to convert a list of selected choices into columns of yes/no values for all possible choices
I have used a Google Form to survey 100 people. The last question was a checkbox question where people could choose up to 5 options. Google has output this data as a box with their 5 choices separated by commas. I know how to split this into up to 5 cells with one choice in each. However, I would like to split it into 16 cells (one for each possible option) with a yes or no in each cell depending on whether the person chose it.

I have tried to find this under make columns from cells but with no luck.

答:
I found one way of doing it:
Use the Text to Columns function to split the data into separate cells.
Then create the headings for the extra columns. Assuming the title for the first option is in AA1 and the first cell containing a choice is in M2, use this function in AA2:

=IF(OR($M2=AA$1, $N2=AA$1, $O2=AA$1, $P2=AA$1, $Q2=AA$1, $R2=AA$1), 1, 0)

Then drag it to populate the rest of your table with 1s and 0s.


问:
How to mount jar file to tomcat container
I have a folder in my project, which contains 1 properties file and 1 jar file(db-driver) file.

I need to copy both of these files to /usr/local/tomcat/lib directory on my pod. I am not sure how to achieve this in kubernetes yaml file. Below is my yaml file where I am trying to achieve this using configMap, but pod creation fails with error "configmap references non-existent config key: app.properties"

Target /usr/local/tomcat/lib already has other jar files so I am trying to use configMap to not override entire directory and just add 2 files which are specific to my application.

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcatdeployment
  labels:
    app:  tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app:  tomcat
  template:
    metadata:
      labels:
        app:  tomcat
    spec:
      containers:
        - name: tomcat
          image: tomcat:latest
          imagePullPolicy: IfNotPresent
          volumeMounts:
          - name: appvolume
            mountPath: /usr/local/data
          - name: config
            mountPath: /usr/local/tomcat/lib
            subPath: ./configuration
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
      volumes:
        - name: appvolume
        - name: config
          configMap:
            name: config-map
            items:
              - key: app.properties
                path: app.properties
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: config-map
data:
  key:  app.properties

</code>```

Current Directory structure...

```<code>.
├── configuration
│   ├── app.properties
│   └── mysql-connector-java-5.1.21.jar
├── deployment.yaml
└── service.yaml

</code>```

Please share your valuable feedback on how to achieve this.

Regards.

答:
Please try this:

kubectl create configmap config-map --from-file=app.properties --from-file=mysql-connector-java-5.1.21.jar

```<code>    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: tomcatdeployment
      labels:
        app:  tomcat
    spec:
      replicas: 1
      selector:
        matchLabels:
          app:  tomcat
      template:
        metadata:
          labels:
            app:  tomcat
        spec:
          containers:
            - name: tomcat
              image: tomcat:latest
              imagePullPolicy: IfNotPresent
              volumeMounts:
              - name: config
                mountPath: /usr/local/tomcat/lib/conf
              ports:
                - name: http
                  containerPort: 8080
                  protocol: TCP
          volumes:
            - name: config
              configMap:
                name: config-map
</code>```

or

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcatdeployment
  labels:
    app:  tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app:  tomcat
  template:
    metadata:
      labels:
        app:  tomcat
    spec:
      containers:
        - name: tomcat3
          image: tomcat:latest
          imagePullPolicy: IfNotPresent
          volumeMounts:
          - name: config
            mountPath: /usr/local/tomcat/lib/app.properties
            subPath: app.properties
          - name: config
            mountPath: /usr/local/tomcat/lib/mysql-connector-java-5.1.21.jar
            subPath: mysql-connector-java-5.1.21.jar
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
      volumes:
        - name: config
          configMap:
            name: config-map
            items:
            - key: app.properties
              path: app.properties
            - key: mysql-connector-java-5.1.21.jar
              path: mysql-connector-java-5.1.21.jar
</code>```

Body:
I have a folder in my project, which contains 1 properties file and 1 jar file(db-driver) file.

I need to copy both of these files to /usr/local/tomcat/lib directory on my pod. I am not sure how to achieve this in kubernetes yaml file. Below is my yaml file where I am trying to achieve this using configMap, but pod creation fails with error "configmap references non-existent config key: app.properties"

Target /usr/local/tomcat/lib already has other jar files so I am trying to use configMap to not override entire directory and just add 2 files which are specific to my application.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcatdeployment
  labels:
    app:  tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app:  tomcat
  template:
    metadata:
      labels:
        app:  tomcat
    spec:
      containers:
        - name: tomcat
          image: tomcat:latest
          imagePullPolicy: IfNotPresent
          volumeMounts:
          - name: appvolume
            mountPath: /usr/local/data
          - name: config
            mountPath: /usr/local/tomcat/lib
            subPath: ./configuration
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
      volumes:
        - name: appvolume
        - name: config
          configMap:
            name: config-map
            items:
              - key: app.properties
                path: app.properties
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: config-map
data:
  key:  app.properties

Current Directory structure...

.
├── configuration
│   ├── app.properties
│   └── mysql-connector-java-5.1.21.jar
├── deployment.yaml
└── service.yaml

Please share your valuable feedback on how to achieve this.

Regards.

Body:
Please try this:

kubectl create configmap config-map --from-file=app.properties --from-file=mysql-connector-java-5.1.21.jar

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: tomcatdeployment
      labels:
        app:  tomcat
    spec:
      replicas: 1
      selector:
        matchLabels:
          app:  tomcat
      template:
        metadata:
          labels:
            app:  tomcat
        spec:
          containers:
            - name: tomcat
              image: tomcat:latest
              imagePullPolicy: IfNotPresent
              volumeMounts:
              - name: config
                mountPath: /usr/local/tomcat/lib/conf
              ports:
                - name: http
                  containerPort: 8080
                  protocol: TCP
          volumes:
            - name: config
              configMap:
                name: config-map

or

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcatdeployment
  labels:
    app:  tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app:  tomcat
  template:
    metadata:
      labels:
        app:  tomcat
    spec:
      containers:
        - name: tomcat3
          image: tomcat:latest
          imagePullPolicy: IfNotPresent
          volumeMounts:
          - name: config
            mountPath: /usr/local/tomcat/lib/app.properties
            subPath: app.properties
          - name: config
            mountPath: /usr/local/tomcat/lib/mysql-connector-java-5.1.21.jar
            subPath: mysql-connector-java-5.1.21.jar
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
      volumes:
        - name: config
          configMap:
            name: config-map
            items:
            - key: app.properties
              path: app.properties
            - key: mysql-connector-java-5.1.21.jar
              path: mysql-connector-java-5.1.21.jar


问:
Unable to search character with string input from fgets
I'm writing a program to find the location of a certain character in a string using strchr. When using fgets to input the string from the user, the program does not execute properly.

However when using gets everything works fine.

Code that works using gets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    gets(input);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the letter %c was found at character %d\n", let, ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}
</code>```

Output:

```
what is the string that you would like to check?
what is the character that you would like to find?
in string "why is the world when wondering"...
the letter w was found at character 1
the letter w was found at character 12
the letter w was found at character 18
the letter w was found at character 23
```

Code that does not work usgin fgets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    fgets(input, 16, stdin);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the character is found at %d \n", ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}
</code>```

Output:

```
what is the string that you would like to check?
what is the character that you would like to find?
in string "abcdefghijklmno"...
```

答:
Change

```<code>fgets(input, 16, stdin)
</code>```

to

```<code>fgets(input, sizeof(input), stdin)
</code>```

When you pass an argument of 16 to fgets() you are instructing it to read no more than 15 characters. Why?

From the fgets() manpage:

fgets()  reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.

If you provide more than size -1 characters, the remaining characters are left in the input buffer.

Then when the program subsequently calls

```<code>let = getchar();
</code>```

let is assigned whatever the next character in the input buffer is - without even waiting for you to type anything else. It then searches for this character in the string you provided - but in the example you provided doesn't find it.

Body:
I'm writing a program to find the location of a certain character in a string using strchr. When using fgets to input the string from the user, the program does not execute properly.

However when using gets everything works fine.

Code that works using gets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    gets(input);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the letter %c was found at character %d\n", let, ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}

Output:

what is the string that you would like to check?
what is the character that you would like to find?
in string "why is the world when wondering"...
the letter w was found at character 1
the letter w was found at character 12
the letter w was found at character 18
the letter w was found at character 23

Code that does not work usgin fgets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    fgets(input, 16, stdin);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the character is found at %d \n", ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}

Output:

what is the string that you would like to check?
what is the character that you would like to find?
in string "abcdefghijklmno"...

Body:
Change

fgets(input, 16, stdin)

to

fgets(input, sizeof(input), stdin)

When you pass an argument of 16 to fgets() you are instructing it to read no more than 15 characters. Why?

From the fgets() manpage:

fgets()  reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.

If you provide more than size -1 characters, the remaining characters are left in the input buffer.

Then when the program subsequently calls

let = getchar();

let is assigned whatever the next character in the input buffer is - without even waiting for you to type anything else. It then searches for this character in the string you provided - but in the example you provided doesn't find it.


问:
Namespace issue calling Axis2 web service from Flex4 with client generated by Flex Builder introspection
I have a java-based web service built with Axis2. The WSDL was generated by the Eclipse 3.6 wizard.

I have a Flex 4 client built using introspection via the WSDL in Flash Builder 4.

For calls where the method takes a 'simple' type like String or int, it all seems OK, but for calls where the parameter is (on the Java side) and OMElement, ie XML data, I'm setting the following runtime error on the service:

```<code>org.apache.axis2.engine.AxisEngine  - namespace mismatch require http://server.rsc.geo.othermaps.com found none
</code>```

http://server.rsc.geo.othermaps.com is indeed the target namespace declared in the WSDL.

The same workflow (use autogenerated client built from web service introspection) worked fine against the same service in Flex 3, so I'm not sure where to start hunting. So I really need to manually add the namespace to the XML data I'm submitting?

D

答: If your XML that's coming back doesn't have the namespace declaration at the top, I would definitely add it.</p>

Body:
I have a java-based web service built with Axis2. The WSDL was generated by the Eclipse 3.6 wizard.

I have a Flex 4 client built using introspection via the WSDL in Flash Builder 4.

For calls where the method takes a 'simple' type like String or int, it all seems OK, but for calls where the parameter is (on the Java side) and OMElement, ie XML data, I'm setting the following runtime error on the service:

org.apache.axis2.engine.AxisEngine  - namespace mismatch require http://server.rsc.geo.othermaps.com found none

http://server.rsc.geo.othermaps.com is indeed the target namespace declared in the WSDL.

The same workflow (use autogenerated client built from web service introspection) worked fine against the same service in Flex 3, so I'm not sure where to start hunting. So I really need to manually add the namespace to the XML data I'm submitting?

D


问:
How do I solve fusionauth php client error 'FusionAuthClient' not found?
when I follow https://github.com/FusionAuth/fusionauth-php-client

I can see error:

```<code>PHP Fatal error:  Uncaught Error: Class 'FusionAuthClient' not found ... on line 6
</code>```

My application looks like this:

```<code>  First application
  <?php
  require_once 'FusionAuthClient.php';

  $apiKey = "7W-yBfeXfniDhu8PR_h0dGkSsPDJlpUYuP9rP2xXd_4";
  $client = new FusionAuthClient($apiKey, "http://localhost:9011");
</code>```

line 6 is last.

composer says all is right

```<code>$ composer require fusionauth/fusionauth-client
Using version ^1.6 for fusionauth/fusionauth-client
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing fusionauth/fusionauth-client (1.6.1)
    Downloading: 100%

Writing lock file
Generating autoload files
</code>```

FusionAuthClient.php, ClientResponse.php and RESTClient.php are in the same directory as my test script.

Can you point me into the right direction what is cause of this problem?

答:
Have you looked at the first line of the FusionAuthClient.php file? apparently not.

```<code>namespace FusionAuth;
</code>```

Therefore, the class is not in the global namespace, therefore you need to tell php which namespace it's in:

```<code>$client = new FusionAuth\FusionAuthClient($apiKey, "http://localhost:9011");
</code>```

You're welcome.

Body:
when I follow https://github.com/FusionAuth/fusionauth-php-client

I can see error:

PHP Fatal error:  Uncaught Error: Class 'FusionAuthClient' not found ... on line 6

My application looks like this:

  First application
  <?php
  require_once 'FusionAuthClient.php';

  $apiKey = "7W-yBfeXfniDhu8PR_h0dGkSsPDJlpUYuP9rP2xXd_4";
  $client = new FusionAuthClient($apiKey, "http://localhost:9011");

line 6 is last.

composer says all is right

$ composer require fusionauth/fusionauth-client
Using version ^1.6 for fusionauth/fusionauth-client
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing fusionauth/fusionauth-client (1.6.1)
    Downloading: 100%

Writing lock file
Generating autoload files

FusionAuthClient.php, ClientResponse.php and RESTClient.php are in the same directory as my test script.

Can you point me into the right direction what is cause of this problem?

Body:
Have you looked at the first line of the FusionAuthClient.php file? apparently not.

namespace FusionAuth;

Therefore, the class is not in the global namespace, therefore you need to tell php which namespace it's in:

$client = new FusionAuth\FusionAuthClient($apiKey, "http://localhost:9011");

You're welcome.


问:
Does this RegExp string need some escaping?
I was trying to use a RegExp so that I could insert a string variable at some later point. But even this first attempt without said variable won't work. What is missing?

There's a nice jsbin linked that shows the behavior.

```<code>const DOCS = [
    "My Report – March 2019.pdf",
    "My Report – May 2019.pdf",
    "My Diary - April-May 2019.pdf",
    "My Diary - February-March 2019.pdf"
]

const title_month_year = new RegExp("(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

DOCS.forEach(
    mag = mag.replace(/–/g, "-");
//  if (title_month_year.test(mag)) {   <--- does not match
    if (/(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})/.test(mag)) {
        console.log('we have a match');
    }
</code>```

https://jsbin.com/lomolew/edit?js,console

答:
```<code>const DOCS = [
    "My Report – March 2019.pdf",
    "My Report – May 2019.pdf",
    "My Diary - April-May 2019.pdf",
    "My Diary - February-March 2019.pdf"
]

const months = {
    "January": "01",
    "Jan": "01",
    "February": "02",
    "Feb": "02",
    "March": "03",
    "Mar": "03",
    "April": "04",
    "Apr": "04",
    "May": "05",
    "June": "06",
    "Jun": "06",
    "July": "07",
    "Jul": "07",
    "August": "08",
    "Aug": "08",
    "September": "09",
    "Sep": "09",
    "October": "10",
    "Oct": "10",
    "November": "11",
    "Nov": "11",
    "December": "12",
    "Dec": "12"
}

let docsCopy = DOCS.map(m => {
    var mReplace = m.replace(/^(.+)(?:\s[-–]\s)+(.+)\s(\d+)(.+)/, (match, p1, p2, p3, p4) => {

        var p2C = p2.split('-').map(item=>{
            return months[item]
        }).join('-')
        console.log(p2C)
        return p1 + ' ' + p3 + '-' + p2C + p4

    })

    return mReplace

});

console.log(docsCopy)
</code>```

Body:
I was trying to use a RegExp so that I could insert a string variable at some later point. But even this first attempt without said variable won't work. What is missing?

There's a nice jsbin linked that shows the behavior.

const DOCS = [
    "My Report – March 2019.pdf",
    "My Report – May 2019.pdf",
    "My Diary - April-May 2019.pdf",
    "My Diary - February-March 2019.pdf"
]

const title_month_year = new RegExp("(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")

DOCS.forEach(
    mag = mag.replace(/–/g, "-");
//  if (title_month_year.test(mag)) {   <--- does not match
    if (/(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})/.test(mag)) {
        console.log('we have a match');
    }

https://jsbin.com/lomolew/edit?js,console


问:
retrofit Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
I'm trying to get just string request but it's give error like this

```<code>Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
</code>```

And my API output is like this :

```<code>{
    "status": true,
    "message": "Video uploaded successfully!",
    "data": {
        "video_name": "674631516178278_abc2.mp4",
        "video_thumbnail": "674631516178278_thumb0017.jpg"
    }
}
</code>```

Code for response :

```<code>        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            try {
                if (response.body() != null)
                    Log.e("UploadResponse>>>", response.body());
                layoutUpload.setVisibility(View.GONE);
                if (file.exists()) {
                    file.delete();
                    thumb.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
                layoutUpload.setVisibility(View.GONE);
                if (file.exists()) {
                    file.delete();
                    thumb.delete();
                }
            }
        }
</code>```

Body:
I'm trying to get just string request but it's give error like this

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

And my API output is like this :

{
    "status": true,
    "message": "Video uploaded successfully!",
    "data": {
        "video_name": "674631516178278_abc2.mp4",
        "video_thumbnail": "674631516178278_thumb0017.jpg"
    }
}

Code for response :

        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            try {
                if (response.body() != null)
                    Log.e("UploadResponse>>>", response.body());
                layoutUpload.setVisibility(View.GONE);
                if (file.exists()) {
                    file.delete();
                    thumb.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
                layoutUpload.setVisibility(View.GONE);
                if (file.exists()) {
                    file.delete();
                    thumb.delete();
                }
            }
        }

Body:
.addConverterFactory(ScalarsConverterFactory.create())
.addxxxx


问:
Blinking effect on UILabel
I have a UILabel with background color as grey.

I want a blinking effect on this label like it should become a little white & then become gray and it should keep happen till I turn it off programatically.

Any clue how to achieve this?

答:
For Swift 3+, building on all the great answers here, I ended up with a few tweaks that gave me smooth blinking effect that automatically stops after a given number of cycles.

```<code>extension UIView {
    func blink(duration: Double=0.5, repeatCount: Int=2) {
        self.alpha = 0.0;
        UIView.animate(withDuration: duration,
            delay: 0.0,
            options: [.curveEaseInOut, .autoreverse, .repeat],
            animations: { [weak self] in
                UIView.setAnimationRepeatCount(Float(repeatCount) + 0.5)
                self?.alpha = 1.0
            }
        )
    }
}
</code>```

Title: Blinking effect on UILabel

Body:
For Swift 3+, building on all the great answers here, I ended up with a few tweaks that gave me smooth blinking effect that automatically stops after a given number of cycles.

extension UIView {
    func blink(duration: Double=0.5, repeatCount: Int=2) {
        self.alpha = 0.0;
        UIView.animate(withDuration: duration,
            delay: 0.0,
            options: [.curveEaseInOut, .autoreverse, .repeat],
            animations: { [weak self] in
                UIView.setAnimationRepeatCount(Float(repeatCount) + 0.5)
                self?.alpha = 1.0
            }
        )
    }
}


问:
Changing ansible loop due to v2.11 deprecation
I'm running a playbook which defined several packages to install via apt:

```<code>    - name: Install utility packages common to all hosts
      apt:
        name: "{{ item }}"
        state: present
        autoclean: yes
      with_items:
        - aptitude
        - jq
        - curl
        - git-core
        - at
...
</code>```

A recent ansible update on my system now renders this message concerning the playbook above:

```<code>[DEPRECATION WARNING]: Invoking "apt" only once while using a loop via squash_actions is deprecated. Instead of
 using a loop to supply multiple items and specifying `name: {{ item }}`, please use `name: [u'aptitude',
u'jq', u'curl', u'git-core', u'at', u'heirloom-mailx', u'sudo-ldap', u'sysstat', u'vim', u'at', u'ntp',
u'stunnel', u'sysstat', u'arping', u'net-tools', u'lshw', u'screen', u'tmux', u'lsscsi']` and remove the loop.
</code>```

If I'm understanding this correctly, Ansible now wants this list of packages as an array which leaves this:

```<code>name: [u'aptitude', u'jq', u'curl', u'git-core', u'at','heirloom-mailx', u'sudo-ldap', u'sysstat', u'vim', u'at', u'ntp',u'stunnel', u'sysstat', u'arping', u'net-tools', u'lshw', u'screen', u'tmux', u'lsscsi']
</code>```

Is there a better way? Just seems like I'll be scrolling right forever in VIM trying to maintain this. Either that, or word wrap it and deal with a word-cloud of packages.

答:
I came across this exact same problem , but with a much longer list of apps , held in a vars file. This is the code I implemented to get around that problem. The list of the apps is placed into the "apps" variable and Ansible iterates over that.

```<code>- name: Install default applications
  apt:
    name: "{{item}}"
    state: latest
  loop: "{{ apps }}"
  when: ansible_distribution == 'Ubuntu' or ansible_distribution == 'Debian'
  tags:
     - instapps
</code>```

The file holding the list of apps to install is in the Defaults directory in the role directory for this task - namely the "common" role directory.

```<code>roles
    - common
      - Defaults
        - main.yml
</code>```

Body:
I'm running a playbook which defined several packages to install via apt:

    - name: Install utility packages common to all hosts
      apt:
        name: "{{ item }}"
        state: present
        autoclean: yes
      with_items:
        - aptitude
        - jq
        - curl
        - git-core
        - at
...

A recent ansible update on my system now renders this message concerning the playbook above:

[DEPRECATION WARNING]: Invoking "apt" only once while using a loop via squash_actions is deprecated. Instead of
 using a loop to supply multiple items and specifying `name: {{ item }}`, please use `name: [u'aptitude',
u'jq', u'curl', u'git-core', u'at', u'heirloom-mailx', u'sudo-ldap', u'sysstat', u'vim', u'at', u'ntp',
u'stunnel', u'sysstat', u'arping', u'net-tools', u'lshw', u'screen', u'tmux', u'lsscsi']` and remove the loop.

If I'm understanding this correctly, Ansible now wants this list of packages as an array which leaves this:

name: [u'aptitude', u'jq', u'curl', u'git-core', u'at','heirloom-mailx', u'sudo-ldap', u'sysstat', u'vim', u'at', u'ntp',u'stunnel', u'sysstat', u'arping', u'net-tools', u'lshw', u'screen', u'tmux', u'lsscsi']

Is there a better way? Just seems like I'll be scrolling right forever in VIM trying to maintain this. Either that, or word wrap it and deal with a word-cloud of packages.

Body:
I came across this exact same problem , but with a much longer list of apps , held in a vars file. This is the code I implemented to get around that problem. The list of the apps is placed into the "apps" variable and Ansible iterates over that.

- name: Install default applications
  apt:
    name: "{{item}}"
    state: latest
  loop: "{{ apps }}"
  when: ansible_distribution == 'Ubuntu' or ansible_distribution == 'Debian'
  tags:
     - instapps

The file holding the list of apps to install is in the Defaults directory in the role directory for this task - namely the "common" role directory.

roles
    - common
      - Defaults
        - main.yml


问:
Joining two datasets with different classes
I'm struggling with joining two data sets

```<code> #df1

  id   name1
   1    a
   2    b
   3    c
</code>```

and

```<code>   $df2

  id     name2
  1       c
  2       d
</code>```

I try to join them by their id

```<code>  library(dplyr)

 result <- left_join(df1, df2, by="id")
</code>```

it gives me the following error

Error: cannot join on columns 'id' x 'id':
  Can't join on 'id' x 'id' because of
  incompatible types (factor / integer)

because they have different classes:

```<code> sapply(df1, class)
        id       name1
     "factor"       "factor"

sapply(df2, class)
        id       name2
     "integer"       "factor"
</code>```

I tried to change the classes to make them similar

```<code> df1$id <- as.integer (df1$id)
</code>```

but , it doesn't help to find the common rows in two datasets.
 ( it can not recognize similar "id"s in df2)

答:
I was running into the same problems with just going from characters to numeric and joining tables. I tried to go to numbers and it didn't work, even with the above method.

I had to go to as.integers(levels(df1$id))[df1$id] to make it work.

I tried using as.numeric(levels(df1$id))[df1$id] and it would take all of my values to NA.

Hope this helps!

Body:
I'm struggling with joining two data sets

 #df1

  id   name1
   1    a
   2    b
   3    c

and

   $df2

  id     name2
  1       c
  2       d

I try to join them by their id

  library(dplyr)

 result <- left_join(df1, df2, by="id")

it gives me the following error

Error: cannot join on columns 'id' x 'id':
  Can't join on 'id' x 'id' because of
  incompatible types (factor / integer)

because they have different classes:

 sapply(df1, class)
        id       name1
     "factor"       "factor"

sapply(df2, class)
        id       name2
     "integer"       "factor"

I tried to change the classes to make them similar

 df1$id <- as.integer (df1$id)

but , it doesn't help to find the common rows in two datasets.
 ( it can not recognize similar "id"s in df2)