问:
[Atollic Truestudio][STM32] "Load Failed" while GDB download/debug using CMSIS-pack/Components
I am trying to use CMSIS-pack with my new F103 project. Until now, I was using auto-generated project structure, just moving some files elsewhere and everything worked fine. Now with CMSIS-pack, although the code is successfully compiled, I get some "Load Failed" error during downloading the .elf into the MCU. I run auto-generated debug configuration, same as for all of my previous projects. I am using ST-link and with GDB-server. Here's the error:

```<code>Failure at line:13 in 'Target Software Startup Scripts'. Please edit the debug configuration settings.

Load Failed
</code>```

Debug logs:

```<code>[0.000] init():  Atollic TrueSTUDIO gdbserver for ST-Link. Version 4.2.2 (WIN32 2018-02-26 16:20:21 15675)
[1.229] reset_hw_wtchpt_module():  Hardware watchpoint supported by the target
[1.233] createFlashParams():  STM32 device: Flash size =1024
[1.335] STM32_AppReset():  Enter STM32_AppReset() function
[1.440] STM32_AppReset():  NVIC_DFSR_REG = 0x00000009
[1.441] STM32_AppReset():  NVIC_CFGFSR_REG = 0x00000000
[1.442] STM32_AppReset():  XPSR = 0x01000000
[1.442] Device_Initialise():  ST_LINK Major version =2 Jtag version =27
[1.442] Device_Initialise():  ST_LINK VID=1155 PID=14155
[1.442] Device_Initialise():  ST_LINK device status: HALT_MODE
[1.442] Device_Initialise():  ST_LINK detects target voltage =3.26 Volt
[1.443] initServerContext():  ST-Link device initialization OK
[1.445] WaitConnection():  Waiting for connection on port 61234...
[2.028] WaitConnection():  Accepted connection on port 61234...
[2.028] Device_GetStatus():  ST_LINK device status: HALT_MODE
[2.045] handlePacket():  Reading 0x4 bytes of memory from addr 0x8006b54
[2.045] handlePacket():  Reading 0x2 bytes of memory from addr 0x8006b54
[2.069] handlePacket():  Reading 0x20 bytes of memory from addr 0xe00fffd0
[2.071] handlePacket():  Reading 0x2 bytes of memory from addr 0x807a
[2.071] handlePacket():  Reading 0x2 bytes of memory from addr 0x807e
[2.084] STM32_AppReset():  Enter STM32_AppReset() function
[2.189] STM32_AppReset():  NVIC_DFSR_REG = 0x00000009
[2.190] STM32_AppReset():  NVIC_CFGFSR_REG = 0x00000000
[2.191] STM32_AppReset():  XPSR = 0x01000000
[2.755] handlePacket():  Reading 0x4 bytes of memory from addr 0xffffffff
[2.755] handlePacket():  Reading 0x4 bytes of memory from addr 0xffffffff
[2.930] handlePacket():  Reading 0x40 bytes of memory from addr 0x8006b40
[2.932] handlePacket():  Reading 0x40 bytes of memory from addr 0x8006b80
[6.065] STM32_AppReset():  Enter STM32_AppReset() function
[6.170] STM32_AppReset():  NVIC_DFSR_REG = 0x00000009
[6.171] STM32_AppReset():  NVIC_CFGFSR_REG = 0x00000000
[6.172] STM32_AppReset():  XPSR = 0x01000000
</code>```

Any ideas why can't it download the code, while the same configurations work for all my projects without Components/CMSIS-pack?

Regards, Patryk

答:
Looking at the differences in the build generated files of a CMSIS auto-generated project file and a CubeMx generated project I noticed that there are differences in the .list file. The isr_vector is not listed.

If you check this section
You will notice that there is something that is missing in the new auto-generated project. It is the startup files for your device.

In the RTEconfig object within your project tree there is a way to include the device startup files by ticking:

Device>Startup

After adding this to the RTE Components selector and saving the changes, you will find in your project tree the files

the "CMSIS system and clock configuration file" RTE>Device>STM32F103C8>system_stm32f10x.c

the "CMSIS Device Peripheral Access header" stm32f10x.h will be included

and so the "CMSIS System and clock configuration header" file startup_stm32f10x.h

I am afraid that in the initial and the only available version nowadays, v1.0.0, the "CMSIS Device Startup Interrupt Vectors" file startup_stm32f10x.s is not added in any way to the project.

The way I fixed it was by adding the startup_stm32f10x.s and STM32F103C8_FLASH.ld files from a CubeMx Generated project.

The STM32F103C8_FLASH.ld location has to be added to project>C/C++ Build>Settings>C Linker>General>Linker script

I copied the startup_stm32f10x.s file to the RTE>Device>STM32F103C8 folder

Doing so, recompiling the code and starting a debug session you will get as expected a normal debugging session. This is only a provisional solution but I hope that I may help someone.

Body:
I am trying to use CMSIS-pack with my new F103 project. Until now, I was using auto-generated project structure, just moving some files elsewhere and everything worked fine. Now with CMSIS-pack, although the code is successfully compiled, I get some "Load Failed" error during downloading the .elf into the MCU. I run auto-generated debug configuration, same as for all of my previous projects. I am using ST-link and with GDB-server. Here's the error:

Failure at line:13 in 'Target Software Startup Scripts'. Please edit the debug configuration settings.

Load Failed

Debug logs:

[0.000] init():  Atollic TrueSTUDIO gdbserver for ST-Link. Version 4.2.2 (WIN32 2018-02-26 16:20:21 15675)
[1.229] reset_hw_wtchpt_module():  Hardware watchpoint supported by the target
[1.233] createFlashParams():  STM32 device: Flash size =1024
[1.335] STM32_AppReset():  Enter STM32_AppReset() function
[1.440] STM32_AppReset():  NVIC_DFSR_REG = 0x00000009
[1.441] STM32_AppReset():  NVIC_CFGFSR_REG = 0x00000000
[1.442] STM32_AppReset():  XPSR = 0x01000000
[1.442] Device_Initialise():  ST_LINK Major version =2 Jtag version =27
[1.442] Device_Initialise():  ST_LINK VID=1155 PID=14155
[1.442] Device_Initialise():  ST_LINK device status: HALT_MODE
[1.442] Device_Initialise():  ST_LINK detects target voltage =3.26 Volt
[1.443] initServerContext():  ST-Link device initialization OK
[1.445] WaitConnection():  Waiting for connection on port 61234...
[2.028] WaitConnection():  Accepted connection on port 61234...
[2.028] Device_GetStatus():  ST_LINK device status: HALT_MODE
[2.045] handlePacket():  Reading 0x4 bytes of memory from addr 0x8006b54
[2.045] handlePacket():  Reading 0x2 bytes of memory from addr 0x8006b54
[2.069] handlePacket():  Reading 0x20 bytes of memory from addr 0xe00fffd0
[2.071] handlePacket():  Reading 0x2 bytes of memory from addr 0x807a
[2.071] handlePacket():  Reading 0x2 bytes of memory from addr 0x807e
[2.084] STM32_AppReset():  Enter STM32_AppReset() function
[2.189] STM32_AppReset():  NVIC_DFSR_REG = 0x00000009
[2.190] STM32_AppReset():  NVIC_CFGFSR_REG = 0x00000000
[2.191] STM32_AppReset():  XPSR = 0x01000000
[2.755] handlePacket():  Reading 0x4 bytes of memory from addr 0xffffffff
[2.755] handlePacket():  Reading 0x4 bytes of memory from addr 0xffffffff
[2.930] handlePacket():  Reading 0x40 bytes of memory from addr 0x8006b40
[2.932] handlePacket():  Reading 0x40 bytes of memory from addr 0x8006b80
[6.065] STM32_AppReset():  Enter STM32_AppReset() function
[6.170] STM32_AppReset():  NVIC_DFSR_REG = 0x00000009
[6.171] STM32_AppReset():  NVIC_CFGFSR_REG = 0x00000000
[6.172] STM32_AppReset():  XPSR = 0x01000000

Any ideas why can't it download the code, while the same configurations work for all my projects without Components/CMSIS-pack?

Regards, Patryk


来源: stackexchange

问:
Problem with plugin in zend framework
I have created one plugin that is reside in application/controllers/plugin/view.php and below is its content

```
class Application_Controller_Plugin_View extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $frontController = Zend_Controller_Front::getInstance();
        $view = $frontController->getParam('bootstrap')->getResource('view');
        echo 'erace';
        exit;
        $view->doctype('XHTML1_STRICT');

        $baseUrl = $request->getBaseUrl();
        if (defined('RUNNING_FROM_ROOT')) {
            $baseUrl .= '/public';
            $frontController->setBaseUrl($baseUrl);
        }
      /*  $view->headLink()->appendStylesheet($baseUrl . '/css/main.css');
        $view->headLink()->appendStylesheet($baseUrl . '/css/screen.css', 'screen');
        $view->headLink()->appendStylesheet($baseUrl . '/css/print.css', 'print');*/
    }
}

```

Then I have registered this plugin in bootstrap as follow :

```
protected function _initLayoutHelper()
    {

        $front = Zend_Controller_Front::getInstance();
        $front->registerPlugin(new Application_Controller_Plugin_View());

    }
```

but its give me an error like

```
( ! ) Fatal error: Class 'Application_Controller_Plugin_View' not found in C:\wamp\www\saet_new\application\Bootstrap.php on line 42
```

Please help me.

答:
I think it's caused because you are calling Default_Application_Controller_Plugin_View and you're plugin is Application_Controller_Plugin_View.

Are you using modules at all? that would explain why the Default_ would be there, although I believe the prefix isn't required unlesss prefixDefaultModule is set.

ContentLicense: CC BY-SA 3.0

Title: Problem with plugin in zend framework

Body:
I have created one plugin that is reside in application/controllers/plugin/view.php and below is its content

class Application_Controller_Plugin_View extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $frontController = Zend_Controller_Front::getInstance();
        $view = $frontController->getParam('bootstrap')->getResource('view');
        echo 'erace';
        exit;
        $view->doctype('XHTML1_STRICT');

        $baseUrl = $request->getBaseUrl();
        if (defined('RUNNING_FROM_ROOT')) {
            $baseUrl .= '/public';
            $frontController->setBaseUrl($baseUrl);
        }
      /*  $view->headLink()->appendStylesheet($baseUrl . '/css/main.css');
        $view->headLink()->appendStylesheet($baseUrl . '/css/screen.css', 'screen');
        $view->headLink()->appendStylesheet($baseUrl . '/css/print.css', 'print');*/
    }
}

Then I have registered this plugin in bootstrap as follow :

protected function _initLayoutHelper()
    {

        $front = Zend_Controller_Front::getInstance();
        $front->registerPlugin(new Application_Controller_Plugin_View());

    }

but its give me an error like

( ! ) Fatal error: Class 'Application_Controller_Plugin_View' not found in C:\wamp\www\saet_new\application\Bootstrap.php on line 42

Please help me.


问:
How to configure redis client in node js
I tried install redis client in system and run node js code its working fine. but I tried to redis client configure to set host and port in node js.but its not connected its throwing connection refused error.how to resolve it any one give suggestion.

cache.js

```<code>//Import redis
const redis = require('redis');

const { promisify } = require('util');

const host = "127.0.0.1"

const port = 6379

//Connecting redis client
const client = redis.createClient(port,host,redis)

client.on('connect', function () {
    console.log("Redis Connected")
});

client.on('error', function (err) {
    console.log(err)
});
</code>```

{ Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
      at Object._errnoException (util.js:1022:11)
      at _exceptionWithHostPort (util.js:1044:20)
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
    code: 'ECONNREFUSED',
    errno: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 6379 }

答:
The code for connecting to redis seems to work fine. You can check if redis is running on your system:

```<code>sudo service redis status
</code>```

If the status is not active try to restart the service.
You can refer to this code for creating a better wrapper for redis: https://github.com/kumaranshu72/node_ts_boilerplate/blob/github/src/utils/redis.ts

ContentLicense: CC BY-SA 4.0

Body:
I tried install redis client in system and run node js code its working fine. but I tried to redis client configure to set host and port in node js.but its not connected its throwing connection refused error.how to resolve it any one give suggestion.

cache.js

//Import redis
const redis = require('redis');

const { promisify } = require('util');

const host = "127.0.0.1"

const port = 6379

//Connecting redis client
const client = redis.createClient(port,host,redis)

client.on('connect', function () {
    console.log("Redis Connected")
});

client.on('error', function (err) {
    console.log(err)
});

{ Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
      at Object._errnoException (util.js:1022:11)
      at _exceptionWithHostPort (util.js:1044:20)
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
    code: 'ECONNREFUSED',
    errno: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 6379 }

Body:
The code for connecting to redis seems to work fine. You can check if redis is running on your system:

sudo service redis status

If the status is not active try to restart the service.
You can refer to this code for creating a better wrapper for redis: https://github.com/kumaranshu72/node_ts_boilerplate/blob/github/src/utils/redis.ts


问:
How do I add information to an exception message in Ruby?
How do I add information to an exception message without changing its class in ruby?

The approach I'm currently using is

```<code>strings.each_with_index do |string, i|
  begin
    do_risky_operation(string)
  rescue
    raise $!.class, "Problem with string number #{i}: #{$!}"
  end
end
</code>```

Ideally, I would also like to preserve the backtrace.

Is there a better way?

答:
I realize I'm 6 years late to this party, but...I thought I understood Ruby error handling until this week and ran across this question.  While the answers are useful, there is non-obvious (and undocumented) behavior that may be useful to future readers of this thread.  All code was run under ruby v2.3.1.

@Andrew Grimm asks

How do I add information to an exception message without changing its class in ruby?

and then provides sample code:

raise $!.class, "Problem with string number #{i}: #{$!}"
```
<p>I think it is <em>critical</em> to point out that this does NOT add information <strong>to the original error instance object</strong>, but instead raises a NEW error object with the same class.</p>
<p>@BoosterStage says</p>
<blockquote>
<p>To reraise the exception and modify the message...</p>
</blockquote>
<p>but again, the provided code</p>
<pre class="lang-rb prettyprint-override"><code>raise $!, "Problem with string number #{i}: #{$!}", $!.backtrace
</code>```

will raise a new instance of whatever error class is referenced by $!, but it will not be the exact same instance as $!.

The difference between @Andrew Grimm's code and @BoosterStage's example is the fact that the first argument to #raise in the first case is a Class, whereas in the second case it is an instance of some (presumably) StandardError.  The difference matters because the documentation for Kernel#raise says:

With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message).

If only one argument is given and it is an error object instance, that object will be raised IF that object's #exception method inherits or implements the default behavior defined in Exception#exception(string):

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

As many would guess:

catch StandardError => e
  raise $!
```
<p>raises the same error referenced by $!, the same as simply calling:</p>
<pre class="lang-rb prettyprint-override"><code>catch StandardError => e
  raise
</code>```

but probably not for the reasons one might think.  In this case, the call to raise is NOT just raising the object in $!...it raises the result of $!.exception(nil), which in this case happens to be $!.

To clarify this behavior, consider this toy code:

class TestError < StandardError
    def initialize(message=nil)
        puts 'initialize'
        super
    end
    def exception(message=nil)
        puts 'exception'
        return self if message.nil? || message == self
        super
    end
end
```
<p>Running it (this is the same as @Andrew Grimm's sample which I quoted above):</p>
<pre class="lang-rb prettyprint-override"><code>2.3.1 :071 > begin ; raise TestError, 'message' ; rescue => e ; puts e ; end
</code>```

results in:

```<code>initialize
message
</code>```

So a TestError was initialized, rescued, and had its message printed.  So far so good.  A second test (analogous to @BoosterStage's sample quoted above):

2.3.1 :073 > begin ; raise TestError.new('foo'), 'bar' ; rescue => e ; puts e ; end
```
<p>The somewhat surprising results:</p>
```initialize
exception
bar
```
<p>So a <code>TestError</code> was initialized with 'foo', but then <code>#raise</code> has called <code>#exception</code> on the first argument (an instance of <code>TestError</code>) and passed in the message of 'bar' <em>to create a second instance of <code>TestError</code>, which is what ultimately gets raised</em>.</p>
<p>TIL.</p>
<p>Also, like @Sim, I am <em>very</em> concerned about preserving any original backtrace context, but instead of implementing a custom error handler like his <code>raise_with_new_message</code>, Ruby's <code>Exception#cause</code> has my back: whenever I want to catch an error, wrap it in a domain-specific error and then raise <em>that</em> error, I still have the original backtrace available via <code>#cause</code> on the domain-specific error being raised.</p>
<p>The point of all this is that--like @Andrew Grimm--I want to raise errors with more context; specifically, I want to only raise domain-specific errors from certain points in my app that can have many network-related failure modes.  Then my error reporting can be made to handle the domain errors at the top level of my app and I have all the context I need for logging/reporting by calling <code>#cause</code> recursively until I get to the "root cause".</p>
<p>I use something like this:</p>
<pre class="lang-rb prettyprint-override"><code>class BaseDomainError < StandardError
  attr_reader :extra
  def initialize(message = nil, extra = nil)
    super(message)
    @extra = extra
  end
end
class ServerDomainError < BaseDomainError; end
</code>```

Then if I am using something like Faraday to make calls to a remote REST service, I can wrap all possible errors into a domain-specific error and pass in extra info (which I believe is the original question of this thread):

class ServiceX
  def initialize(foo)
    @foo = foo
  end
  def get_data(args)
    begin
      # This method is not defined and calling it will raise an error
      make_network_call_to_service_x(args)
    rescue StandardError => e
      raise ServerDomainError.new('error calling service x', binding)
    end
  end
end
```
<p>Yeah, that's right: I literally just realized I can set the <code>extra</code> info to the current <code>binding</code> to grab all local vars defined at the time the <code>ServerDomainError</code> is instantiated/raised.  This test code:</p>
<pre class="lang-rb prettyprint-override"><code>begin
  ServiceX.new(:bar).get_data(a: 1, b: 2)
rescue
  puts $!.extra.receiver
  puts $!.extra.local_variables.join(', ')
  puts $!.extra.local_variable_get(:args)
  puts $!.extra.local_variable_get(:e)
  puts eval('self.instance_variables', $!.extra)
  puts eval('self.instance_variable_get(:@foo)', $!.extra)
end
</code>```

will output:

```<code>#<ServiceX:0x00007f9b10c9ef48>
args, e
{:a=>1, :b=>2}
undefined method `make_network_call_to_service_x' for #<ServiceX:0x00007f9b10c9ef48 @foo=:bar>
@foo
bar
</code>```

Now a Rails controller calling ServiceX doesn't particularly need to know that ServiceX is using Faraday (or gRPC, or anything else), it just makes the call and handles BaseDomainError.  Again: for logging purposes, a single handler at the top level can recursively log all the #causes of any caught errors, and for any BaseDomainError instances in the error chain it can also log the extra values, potentially including the local variables pulled from the encapsulated binding(s).

I hope this tour has been as useful for others as it was for me.  I learned a lot.

UPDATE: Skiptrace looks like it adds the bindings to Ruby errors.

Also, see this other post for info about how the implementation of  Exception#exception will clone the object (copying instance variables).

Body:
How do I add information to an exception message without changing its class in ruby?

The approach I'm currently using is

strings.each_with_index do |string, i|
  begin
    do_risky_operation(string)
  rescue
    raise $!.class, "Problem with string number #{i}: #{$!}"
  end
end

Ideally, I would also like to preserve the backtrace.

Is there a better way?

Body:
I realize I'm 6 years late to this party, but...I thought I understood Ruby error handling until this week and ran across this question.  While the answers are useful, there is non-obvious (and undocumented) behavior that may be useful to future readers of this thread.  All code was run under ruby v2.3.1.

@Andrew Grimm asks

How do I add information to an exception message without changing its class in ruby?

and then provides sample code:

raise $!.class, "Problem with string number #{i}: #{$!}"

I think it is critical to point out that this does NOT add information to the original error instance object, but instead raises a NEW error object with the same class.

@BoosterStage says

To reraise the exception and modify the message...

but again, the provided code

raise $!, "Problem with string number #{i}: #{$!}", $!.backtrace

will raise a new instance of whatever error class is referenced by $!, but it will not be the exact same instance as $!.

The difference between @Andrew Grimm's code and @BoosterStage's example is the fact that the first argument to #raise in the first case is a Class, whereas in the second case it is an instance of some (presumably) StandardError.  The difference matters because the documentation for Kernel#raise says:

With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message).

If only one argument is given and it is an error object instance, that object will be raised IF that object's #exception method inherits or implements the default behavior defined in Exception#exception(string):

With no argument, or if the argument is the same as the receiver, return the receiver. Otherwise, create a new exception object of the same class as the receiver, but with a message equal to string.to_str.

As many would guess:

catch StandardError => e
  raise $!

raises the same error referenced by $!, the same as simply calling:

catch StandardError => e
  raise

but probably not for the reasons one might think.  In this case, the call to raise is NOT just raising the object in $!...it raises the result of $!.exception(nil), which in this case happens to be $!.

To clarify this behavior, consider this toy code:

class TestError < StandardError
    def initialize(message=nil)
        puts 'initialize'
        super
    end
    def exception(message=nil)
        puts 'exception'
        return self if message.nil? || message == self
        super
    end
end

Running it (this is the same as @Andrew Grimm's sample which I quoted above):

2.3.1 :071 > begin ; raise TestError, 'message' ; rescue => e ; puts e ; end

results in:

initialize
message

So a TestError was initialized, rescued, and had its message printed.  So far so good.  A second test (analogous to @BoosterStage's sample quoted above):

2.3.1 :073 > begin ; raise TestError.new('foo'), 'bar' ; rescue => e ; puts e ; end

The somewhat surprising results:

initialize
exception
bar

So a TestError was initialized with 'foo', but then #raise has called #exception on the first argument (an instance of TestError) and passed in the message of 'bar' to create a second instance of TestError, which is what ultimately gets raised.

TIL.

Also, like @Sim, I am very concerned about preserving any original backtrace context, but instead of implementing a custom error handler like his raise_with_new_message, Ruby's Exception#cause has my back: whenever I want to catch an error, wrap it in a domain-specific error and then raise that error, I still have the original backtrace available via #cause on the domain-specific error being raised.

The point of all this is that--like @Andrew Grimm--I want to raise errors with more context; specifically, I want to only raise domain-specific errors from certain points in my app that can have many network-related failure modes.  Then my error reporting can be made to handle the domain errors at the top level of my app and I have all the context I need for logging/reporting by calling #cause recursively until I get to the "root cause".

I use something like this:

class BaseDomainError < StandardError
  attr_reader :extra
  def initialize(message = nil, extra = nil)
    super(message)
    @extra = extra
  end
end
class ServerDomainError < BaseDomainError; end

Then if I am using something like Faraday to make calls to a remote REST service, I can wrap all possible errors into a domain-specific error and pass in extra info (which I believe is the original question of this thread):

class ServiceX
  def initialize(foo)
    @foo = foo
  end
  def get_data(args)
    begin
      # This method is not defined and calling it will raise an error
      make_network_call_to_service_x(args)
    rescue StandardError => e
      raise ServerDomainError.new('error calling service x', binding)
    end
  end
end

Yeah, that's right: I literally just realized I can set the extra info to the current binding to grab all local vars defined at the time the ServerDomainError is instantiated/raised.  This test code:

begin
  ServiceX.new(:bar).get_data(a: 1, b: 2)
rescue
  puts $!.extra.receiver
  puts $!.extra.local_variables.join(', ')
  puts $!.extra.local_variable_get(:args)
  puts $!.extra.local_variable_get(:e)
  puts eval('self.instance_variables', $!.extra)
  puts eval('self.instance_variable_get(:@foo)', $!.extra)
end

will output:

#<ServiceX:0x00007f9b10c9ef48>
args, e
{:a=>1, :b=>2}
undefined method `make_network_call_to_service_x' for #<ServiceX:0x00007f9b10c9ef48 @foo=:bar>
@foo
bar

Now a Rails controller calling ServiceX doesn't particularly need to know that ServiceX is using Faraday (or gRPC, or anything else), it just makes the call and handles BaseDomainError.  Again: for logging purposes, a single handler at the top level can recursively log all the #causes of any caught errors, and for any BaseDomainError instances in the error chain it can also log the extra values, potentially including the local variables pulled from the encapsulated binding(s).

I hope this tour has been as useful for others as it was for me.  I learned a lot.

UPDATE: Skiptrace looks like it adds the bindings to Ruby errors.

Also, see this other post for info about how the implementation of  Exception#exception will clone the object (copying instance variables).


问:
Cannot read property 'unselectable' of null for CKEditor ASP.NET
I have a basic HTML form in (create.cshtml), and I called the CKEditor.js in the main layout (_layout.cshtml)
When I use the same code in a seperate project, it works fine, but in my ASP.NET project I get this error:
   Uncaught TypeError: Cannot read property 'unselectable' of null

Create.cshtml :

```<code><form>
    <textarea id="prop_editor" name="prop_editor">
         <h2>WYSIWYG Editor</h2>
         <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ullamcorper sapien non nisl facilisis bibendum in quis tellus. Duis in urna bibendum turpis pretium fringilla. Aenean neque velit, porta eget mattis ac, imperdiet quis nisi. Donec non dui et tortor vulputate luctus. Praesent consequat rhoncus velit, ut molestie arcu venenatis sodales.</p>
         <h3>Lacinia</h3>
         <ul>
              <li>Suspendisse tincidunt urna ut velit ullamcorper fermentum.</li>
              <li>Nullam mattis sodales lacus, in gravida sem auctor at.</li>
              <li>Praesent non lacinia mi.</li>
              <li>Mauris a ante neque.</li>
              <li>Aenean ut magna lobortis nunc feugiat sagittis.</li>
         </ul>
         <h3>Pellentesque adipiscing</h3>
         <p>Maecenas quis ante ante. Nunc adipiscing rhoncus rutrum. Pellentesque adipiscing urna mi, ut tempus lacus ultrices ac. Pellentesque sodales, libero et mollis interdum, dui odio vestibulum dolor, eu pellentesque nisl nibh quis nunc. Sed porttitor leo adipiscing venenatis vehicula. Aenean quis viverra enim. Praesent porttitor ut ipsum id ornare.</p>

     </textarea>
</form>
</code>```

_layout.cshtml

```<code><script type="text/javascript">
     CKEDITOR.replace('prop_editor');
</script>
</code>```

答:
Try to destroy previously opened CK editors before new CK-Editor load

for (name in CKEDITOR.instances) {
        CKEDITOR.instances[name].destroy()
 }```

Body:
I have a basic HTML form in (create.cshtml), and I called the CKEditor.js in the main layout (_layout.cshtml)
When I use the same code in a seperate project, it works fine, but in my ASP.NET project I get this error:
   Uncaught TypeError: Cannot read property 'unselectable' of null

Create.cshtml :

<form>
    <textarea id="prop_editor" name="prop_editor">

WYSIWYG Editor

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ullamcorper sapien non nisl facilisis bibendum in quis tellus. Duis in urna bibendum turpis pretium fringilla. Aenean neque velit, porta eget mattis ac, imperdiet quis nisi. Donec non dui et tortor vulputate luctus. Praesent consequat rhoncus velit, ut molestie arcu venenatis sodales.

Lacinia

Suspendisse tincidunt urna ut velit ullamcorper fermentum.

Nullam mattis sodales lacus, in gravida sem auctor at.

Praesent non lacinia mi.

Mauris a ante neque.

Aenean ut magna lobortis nunc feugiat sagittis.

Pellentesque adipiscing

Maecenas quis ante ante. Nunc adipiscing rhoncus rutrum. Pellentesque adipiscing urna mi, ut tempus lacus ultrices ac. Pellentesque sodales, libero et mollis interdum, dui odio vestibulum dolor, eu pellentesque nisl nibh quis nunc. Sed porttitor leo adipiscing venenatis vehicula. Aenean quis viverra enim. Praesent porttitor ut ipsum id ornare.

     </textarea>
</form>

_layout.cshtml


问:
Append the next line to previous line
I have file of 5GB in this format:

```<code>dn: cn
changetype: add
objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2
givenname: surya2
cn: surya2
</code>```

```<code>dn: cn
changetype: add
objectclass: inetOrgPerson
surname: sa
sddsds
givenname: s
cn: sur
</code>```

as you can see the Object class and surname are getting to the next line.
I want then in same line.
And below code achieves it, but it throws memory error for large files,
can you change this code so that it works efficiently for large files.

```<code>import re

pattern = re.compile(r"(\w+):(.*)")

with open("uservolvo2.ldif", "r") as f:
    new_lines = []

    for line in f:

        if line.endswith('\n'):
            line = line[:-1]

        if line == "":
            new_lines.append(line)
            continue

        l = pattern.search(line)

        if l:
            new_lines.append(line)
        else:
            new_lines[-1] += line

with open("user_modified.ldif", "a") as f:
    f.write("\n".join(new_lines))
    f.write("\n\n")
</code>```

答:
Perhaps instead of writing a big string, when you join new_lines, which might be causing the memory error, you can iterate over the list and write each line one by one

```<code>with open("file_modified.txt", "a") as f:
    for line in new_lines:
        f.write(line+'\n')
</code>```

Title: Append the next line to previous line

Body:
I have file of 5GB in this format:

dn: cn
changetype: add
objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2
givenname: surya2
cn: surya2

dn: cn
changetype: add
objectclass: inetOrgPerson
surname: sa
sddsds
givenname: s
cn: sur

as you can see the Object class and surname are getting to the next line.
I want then in same line.
And below code achieves it, but it throws memory error for large files,
can you change this code so that it works efficiently for large files.

import re

pattern = re.compile(r"(\w+):(.*)")

with open("uservolvo2.ldif", "r") as f:
    new_lines = []

    for line in f:

        if line.endswith('\n'):
            line = line[:-1]

        if line == "":
            new_lines.append(line)
            continue

        l = pattern.search(line)

        if l:
            new_lines.append(line)
        else:
            new_lines[-1] += line

with open("user_modified.ldif", "a") as f:
    f.write("\n".join(new_lines))
    f.write("\n\n")

Body:
Perhaps instead of writing a big string, when you join new_lines, which might be causing the memory error, you can iterate over the list and write each line one by one

with open("file_modified.txt", "a") as f:
    for line in new_lines:
        f.write(line+'\n')


问:
Not able to show foreign key value
I am trying to create a Post and Comments sections, I managed to show all the posts in one page, now I'm trying to show the comments under each post. In my model, I have connected both tables and in my function I am able to view the post and comments when I use dd(); this is my result:

I am not sure if I'm calling the comment part correctly in my Views because I am getting error :

Property [activity_post_comments] does not exist on this collection instance.
  (View: C:\xampp\xampp\htdocs\rsapp\resources\views\pages\timeline.blade.php)

My function:

```<code>public function timeline()
{
    $activityposts = ActivityPost::with('activity_post_comment')
                                ->orderBy('created_at','desc')
                                ->paginate(100);

    $posts = Post::orderBy('created_at','desc')->paginate(100);

    // dd($activityposts);

    return view('pages.timeline')
            ->with('posts', $posts)
            ->with('activityposts', $activityposts);
}
</code>```

View:

```<code>@if(count($activityposts) > 0)
    @foreach($activityposts as $activitypost)
    <div class="panel panel-default">
        <!--
        <div class="panel-heading"><a href="#" class="pull-right">View all</a>
        <h4>Bootply Editor & Code Library</h4></div>
        -->
        <div class="panel-body">
            <p>
                <img src="../storage/user_image/{{ $activitypost->user->user_image }}" width="28px" height="28px">
                <b>{{ $activitypost->user->firstname }} {{ $activitypost->user->lastname }}</b>
                <span class="pull-right">{{ $activitypost->created_at->format('d-m-Y') }}</span>
            </p>
            <!--
                <div class="clearfix"></div>
                <hr>
            -->
            {{ $activitypost->status_update }}
            <hr>
            <div class="well">
                {{ $activitypost->activity_post_comments->activity_post_comments }};
            </div>
            <hr>
            <form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" action="{{ action('PagesController@storecomments', $activitypost->id) }}">
                {{ csrf_field() }}
                <div class="form-group{{ $errors->has('activity_post_comments') ? ' has-error' : '' }}">
                    <!-- <label for="activity_post_comments" class="col-md-4 control-label">First Name</label> -->
                    <div class="col-md-12">
                        <input id="activity_post_comments" type="text" class="form-control" name="activity_post_comments" required autofocus>
                        @if ($errors->has('activity_post_comments'))
                        <span class="help-block">
                        <strong>{{ $errors->first('activity_post_comments') }}</strong>
                        </span>
                        @endif
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">Post</button>
            </form>
        </div>
    </div>
    @endforeach
{{$activityposts->links()}}
@else
<p>No new activity from users</p>
@endif
</code>```

Here is where I'm not sure :

```<code>{{ $activitypost->activity_post_comment->activity_post_comments }};
</code>```

答:
as linktoahref pointed out, the thing you're not sure is correct.
The relationship between $activitypost and $activity_post_comment is 1-n,
or $activitypost will has a collection of $activity_post_comment,
so when working with collection you could use for-loop or other convenient helper method.
for-loop could be

```<code>@foreach ($activitypost->activity_post_comment as $comment)
<p>{{ $comment->activity_post_comments }}</p>
@endforeach
</code>```

or if you just want an array of activity_post_comments

```<code>$activitypost->activity_post_comment->pluck('activity_post_comments')
</code>```

Title: Not able to show foreign key value

Body:
I am trying to create a Post and Comments sections, I managed to show all the posts in one page, now I'm trying to show the comments under each post. In my model, I have connected both tables and in my function I am able to view the post and comments when I use dd(); this is my result:

I am not sure if I'm calling the comment part correctly in my Views because I am getting error :

Property [activity_post_comments] does not exist on this collection instance.
  (View: C:\xampp\xampp\htdocs\rsapp\resources\views\pages\timeline.blade.php)

My function:

public function timeline()
{
    $activityposts = ActivityPost::with('activity_post_comment')
                                ->orderBy('created_at','desc')
                                ->paginate(100);

    $posts = Post::orderBy('created_at','desc')->paginate(100);

    // dd($activityposts);

    return view('pages.timeline')
            ->with('posts', $posts)
            ->with('activityposts', $activityposts);
}

View:

@if(count($activityposts) > 0)
    @foreach($activityposts as $activitypost)

                user->user_image }}" width="28px" height="28px">
                {{ $activitypost->user->firstname }} {{ $activitypost->user->lastname }}
                {{ $activitypost->created_at->format('d-m-Y') }}

            {{ $activitypost->status_update }}

                {{ $activitypost->activity_post_comments->activity_post_comments }};

            <form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" action="{{ action('PagesController@storecomments', $activitypost->id) }}">
                {{ csrf_field() }}

has('activity_post_comments') ? ' has-error' : '' }}">

                        <input id="activity_post_comments" type="text" class="form-control" name="activity_post_comments" required autofocus>
                        @if ($errors->has('activity_post_comments'))

                        {{ $errors->first('activity_post_comments') }}

                        @endif

                <button type="submit" class="btn btn-primary">Post</button>
            </form>

    @endforeach
{{$activityposts->links()}}
@else

No new activity from users

@endif

Here is where I'm not sure :

{{ $activitypost->activity_post_comment->activity_post_comments }};

Body:
as linktoahref pointed out, the thing you're not sure is correct.
The relationship between $activitypost and $activity_post_comment is 1-n,
or $activitypost will has a collection of $activity_post_comment,
so when working with collection you could use for-loop or other convenient helper method.
for-loop could be

@foreach ($activitypost->activity_post_comment as $comment)
<p>{{ $comment->activity_post_comments }}</p>
@endforeach

or if you just want an array of activity_post_comments

$activitypost->activity_post_comment->pluck('activity_post_comments')


问:
What does ::numeric and ::text mean in mysql
While I am practicing mysql in codewars, this query confused me because I can't find the meaning of ::numeric and ::text in this query.

Query: in baseball, the batting average is a simple and most common way to measure a hitter's performace. Batting average is calculated by taking all the players hits and dividing it by their number of at_bats, and it is usually displayed as a 3 digit decimal (i.e. 0.300).

Given a yankees table with the following schema,

player_id STRING

player_name STRING

primary_position STRING

games INTEGER

at_bats INTEGER

hits INTEGER

return a table with player_name, games, and batting_average.

We want batting_average to be rounded to the nearest thousandth, since that is how baseball fans are used to seeing it. Format it as text and make sure it has 3 digits to the right of the decimal (pad with zeroes if neccesary).

Next, order our resulting table by batting_average, with the highest average in the first row.

Finally, since batting_average is a rate statistic, a small number of at_bats can change the average dramatically. To correct for this, exclude any player who doesn't have at least 100 at bats.

Expected result as output:

player_name STRING

games INTEGER

batting_average STRING

Solution by codewars:-

```<code>select player_name,
       games,
       round(hits::numeric / at_bats, 3)::text as batting_average
from yankees
where at_bats > 100
order by 3 desc
</code>```

答:
```<code>round(hits::numeric / at_bats, 3)::text
</code>```

-->

```<code>RIGHT(ROUND(hits / at_bats, 3), 3)
</code>```

Mostly, numeric values and string values are interchangeable.  So, you can usually get away with not casting from one to the other.

Samples:

```<code>mysql> SELECT RIGHT(ROUND(7 / 120, 3), 3);
+-----------------------------+
| RIGHT(ROUND(7 / 120, 3), 3) |
+-----------------------------+
| 058                         |  -- leading zero works
+-----------------------------+
1 row in set (0.00 sec)

mysql> SELECT RIGHT(ROUND(120 / 120, 3), 3);
+-------------------------------+
| RIGHT(ROUND(120 / 120, 3), 3) |
+-------------------------------+
| 000                           |   -- Oops, "batting a thousande" fails
+-------------------------------+
1 row in set (0.00 sec)
</code>```

So:

```<code>SELECT IF(hits = at_bats, '1000', RIGHT(ROUND(hits / at_bats, 3), 3))
</code>```

Oops; that is not quite correct.  But who ever gets a batting average of 999.7?

Body:
While I am practicing mysql in codewars, this query confused me because I can't find the meaning of ::numeric and ::text in this query.

Query: in baseball, the batting average is a simple and most common way to measure a hitter's performace. Batting average is calculated by taking all the players hits and dividing it by their number of at_bats, and it is usually displayed as a 3 digit decimal (i.e. 0.300).

Given a yankees table with the following schema,

player_id STRING

player_name STRING

primary_position STRING

games INTEGER

at_bats INTEGER

hits INTEGER

return a table with player_name, games, and batting_average.

We want batting_average to be rounded to the nearest thousandth, since that is how baseball fans are used to seeing it. Format it as text and make sure it has 3 digits to the right of the decimal (pad with zeroes if neccesary).

Next, order our resulting table by batting_average, with the highest average in the first row.

Finally, since batting_average is a rate statistic, a small number of at_bats can change the average dramatically. To correct for this, exclude any player who doesn't have at least 100 at bats.

Expected result as output:

player_name STRING

games INTEGER

batting_average STRING

Solution by codewars:-

select player_name,
       games,
       round(hits::numeric / at_bats, 3)::text as batting_average
from yankees
where at_bats > 100
order by 3 desc

Body:
round(hits::numeric / at_bats, 3)::text

-->

RIGHT(ROUND(hits / at_bats, 3), 3)

Mostly, numeric values and string values are interchangeable.  So, you can usually get away with not casting from one to the other.

Samples:

mysql> SELECT RIGHT(ROUND(7 / 120, 3), 3);
+-----------------------------+
| RIGHT(ROUND(7 / 120, 3), 3) |
+-----------------------------+
| 058                         |  -- leading zero works
+-----------------------------+
1 row in set (0.00 sec)

mysql> SELECT RIGHT(ROUND(120 / 120, 3), 3);
+-------------------------------+
| RIGHT(ROUND(120 / 120, 3), 3) |
+-------------------------------+
| 000                           |   -- Oops, "batting a thousande" fails
+-------------------------------+
1 row in set (0.00 sec)

So:

SELECT IF(hits = at_bats, '1000', RIGHT(ROUND(hits / at_bats, 3), 3))

Oops; that is not quite correct.  But who ever gets a batting average of 999.7?


问:
oom invoked even though enough memory available
I use Android P-OS. and kernel version is msm-4.14

oom invoked and killing process since booting up. However, memory is abundant.
My memory size is 8GByte, Swap is 1GByte.
I'm not even using a swap.

```<code>[   59.901334] Killing 'ndroid.keychain' (2011), adj 906,\x0a   to free 87268kB on behalf of 'Binder:883_2' (938)\x0a   Free CMA is 246200kB\x0a   Total reserve is 242332kB\x0a   Total free pages is 5100764kB\x0a   Total file cache is 978224kB
[   59.903948] Killing 'Jit thread pool' (2016), adj 906,\x0a   to free 88676kB on behalf of 'ActivityManager' (960)\x0a   Free CMA is 246200kB\x0a   Total reserve is 242332kB\x0a   Total free pages is 5100764kB\x0a   Total file cache is 978224kB
[   60.007328] oom_reaper: reaped process 2011 (ndroid.keychain), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB
</code>```

$ free

```<code>        total        used        free      shared     buffers
Mem:       7842377728  3144630272  4697747456     2084864    14852096
-/+ buffers/cache:     3129778176  4712599552
Swap:      1073737728           0  1073737728
</code>```

$ meminfo

```<code>MemTotal:        7658572 kB
MemFree:         4589120 kB
MemAvailable:    5800580 kB
Buffers:           14416 kB
Cached:          1415944 kB
SwapCached:            0 kB
Active:           630232 kB
Inactive:        1299508 kB
Active(anon):     501820 kB
Inactive(anon):     1876 kB
Active(file):     128412 kB
Inactive(file):  1297632 kB
Unevictable:        2888 kB
Mlocked:            2888 kB
SwapTotal:       1048572 kB
SwapFree:        1048572 kB
Dirty:                92 kB
Writeback:             0 kB
AnonPages:        502148 kB
Mapped:           745728 kB
Shmem:              2036 kB
Slab:             520776 kB
SReclaimable:     130688 kB
SUnreclaim:       390088 kB
KernelStack:       28336 kB
PageTables:        40972 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     4877856 kB
Committed_AS:   95986336 kB
VmallocTotal:   263061440 kB
VmallocUsed:           0 kB
VmallocChunk:          0 kB
CmaTotal:         303104 kB
CmaFree:          246200 kB
</code>```

I don't understand this situation.
Why does this happen? Is there a way to avoid it?

答:
Answer Myself

It is not Out Of Memory.
Just oom_reaper is working by sigkill signal.
Memory is enough

Thanks

Body:
I use Android P-OS. and kernel version is msm-4.14

oom invoked and killing process since booting up. However, memory is abundant.
My memory size is 8GByte, Swap is 1GByte.
I'm not even using a swap.

[   59.901334] Killing 'ndroid.keychain' (2011), adj 906,\x0a   to free 87268kB on behalf of 'Binder:883_2' (938)\x0a   Free CMA is 246200kB\x0a   Total reserve is 242332kB\x0a   Total free pages is 5100764kB\x0a   Total file cache is 978224kB
[   59.903948] Killing 'Jit thread pool' (2016), adj 906,\x0a   to free 88676kB on behalf of 'ActivityManager' (960)\x0a   Free CMA is 246200kB\x0a   Total reserve is 242332kB\x0a   Total free pages is 5100764kB\x0a   Total file cache is 978224kB
[   60.007328] oom_reaper: reaped process 2011 (ndroid.keychain), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

$ free

        total        used        free      shared     buffers
Mem:       7842377728  3144630272  4697747456     2084864    14852096
-/+ buffers/cache:     3129778176  4712599552
Swap:      1073737728           0  1073737728

$ meminfo

MemTotal:        7658572 kB
MemFree:         4589120 kB
MemAvailable:    5800580 kB
Buffers:           14416 kB
Cached:          1415944 kB
SwapCached:            0 kB
Active:           630232 kB
Inactive:        1299508 kB
Active(anon):     501820 kB
Inactive(anon):     1876 kB
Active(file):     128412 kB
Inactive(file):  1297632 kB
Unevictable:        2888 kB
Mlocked:            2888 kB
SwapTotal:       1048572 kB
SwapFree:        1048572 kB
Dirty:                92 kB
Writeback:             0 kB
AnonPages:        502148 kB
Mapped:           745728 kB
Shmem:              2036 kB
Slab:             520776 kB
SReclaimable:     130688 kB
SUnreclaim:       390088 kB
KernelStack:       28336 kB
PageTables:        40972 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     4877856 kB
Committed_AS:   95986336 kB
VmallocTotal:   263061440 kB
VmallocUsed:           0 kB
VmallocChunk:          0 kB
CmaTotal:         303104 kB
CmaFree:          246200 kB

I don't understand this situation.
Why does this happen? Is there a way to avoid it?


问:
Why isn't router.currentRoute.path reactive?
I have an app which is contained in this div:

```<code><div id="app" v-bind:style='{backgroundColor: backgroundColor}'>
  ... the app ...
</div>
</code>```

The routing is done following the example in the documentation (this is a webpack project):

```<code>import Vue from 'vue/dist/vue.js'
import VueRouter from 'vue-router'
import ComponentOne from './component1.vue'
import ComponentTwo from './component2.vue'

Vue.use(VueRouter)

const routes = [{
        path: '/foo',
        component: ComponentOne
    },
    {
        path: '/bar',
        component: ComponentTwo
    }
]

const router = new VueRouter({
    routes // short for `routes: routes`
})

const app = new Vue({
    router,
    data: {
        day: "Monday"
    },
    computed: {
        backgroundColor: function () {
            console.log(JSON.stringify(router.currentRoute))
            if (router.currentRoute.path == "/foo") {
                return "green"
            } else {
                return "blue"
            }
        }
    }
}).$mount('#app')
</code>```

I wanted the background to be dependent on the current route (router.currentRoute.path).

But, the solution above does not work, because router.currentRoute.path is not detected by the Vue instance as having changed (is not reactive).

What is the correct way to access the dynamic router data from within the Vue instance?

答:
I found on Vue's documentation page that tracks the router using watch for transition animations. Not sure if this is a best practice but you can use to.path or from.path to grab the path instead.</p>
```<code>// then, in the parent component,
// watch the `$route` to determine the transition to use
watch: {
  '$route': (to, from) => {
    const toDepth = to.path.split('/').length
    const fromDepth = from.path.split('/').length
    this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
  }
}
</code>```

Body:
I have an app which is contained in this div:

  ... the app ...

The routing is done following the example in the documentation (this is a webpack project):

import Vue from 'vue/dist/vue.js'
import VueRouter from 'vue-router'
import ComponentOne from './component1.vue'
import ComponentTwo from './component2.vue'

Vue.use(VueRouter)

const routes = [{
        path: '/foo',
        component: ComponentOne
    },
    {
        path: '/bar',
        component: ComponentTwo
    }
]

const router = new VueRouter({
    routes // short for `routes: routes`
})

const app = new Vue({
    router,
    data: {
        day: "Monday"
    },
    computed: {
        backgroundColor: function () {
            console.log(JSON.stringify(router.currentRoute))
            if (router.currentRoute.path == "/foo") {
                return "green"
            } else {
                return "blue"
            }
        }
    }
}).$mount('#app')

I wanted the background to be dependent on the current route (router.currentRoute.path).

But, the solution above does not work, because router.currentRoute.path is not detected by the Vue instance as having changed (is not reactive).

What is the correct way to access the dynamic router data from within the Vue instance?

Body:
I found on Vue's documentation page that tracks the router using watch for transition animations. Not sure if this is a best practice but you can use to.path or from.path to grab the path instead.

// then, in the parent component,
// watch the `$route` to determine the transition to use
watch: {
  '$route': (to, from) => {
    const toDepth = to.path.split('/').length
    const fromDepth = from.path.split('/').length
    this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
  }
}


问:
ContextVars across modules
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

```<code>from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)
</code>```

then I try to import number.py

```<code>(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200
</code>```

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?

答: You have assigned the value for the number again. Which is why it shows 200 from the latest update.</p>

Title: ContextVars across modules

Body:
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)

then I try to import number.py

(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?


问:
Django's html email's inline css not working
I am trying to send a mail through HTML email. Everything is working perfectly, but the inline css of html file is not getting rendered in actual email.
views.py

```<code>        subject = 'Activate Your Account.'
        htmly     = get_template('account_activation_email.html')

        d = { 'user': user, 'domain':current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user)}
        text_content = ""
        html_content = htmly.render(d)
        msg = EmailMultiAlternatives(subject, text_content, '', [user.email])
        msg.attach_alternative(html_content, "text/html")
        try:
            msg.send()
        except BadHeaderError:
            print("Error while sending email!")
</code>```

Here my html file :

```<code><html>
<head>
</head>
<body>
    <div style="backgound-color:red;position:relative;width:100%;text-align:center;">Email Verification</div>
    Hi {{ user.username }},
</body>
</code>```

Please help!

答:
The red background is being skipped because of the spelling: backgound-color vs background-color.

Also did you try different email clients - HTML email is very much it's own art.

Body:
I am trying to send a mail through HTML email. Everything is working perfectly, but the inline css of html file is not getting rendered in actual email.
views.py

        subject = 'Activate Your Account.'
        htmly     = get_template('account_activation_email.html')

        d = { 'user': user, 'domain':current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user)}
        text_content = ""
        html_content = htmly.render(d)
        msg = EmailMultiAlternatives(subject, text_content, '', [user.email])
        msg.attach_alternative(html_content, "text/html")
        try:
            msg.send()
        except BadHeaderError:
            print("Error while sending email!")

Here my html file :

Email Verification

    Hi {{ user.username }},

Please help!


问:
AWS AppSync - How to query data by date range(Today to 30 days before)?
This is how my schema.graphql looks like.

```<code>type Post
  @model
  @auth(
    rules: [
      { allow: owner }
    ]
  ) {
  id: ID!
  author: User! @connection(name: "UserPosts")
  content: AWSJSON!
  createdAt: AWSDateTime
  updatedAt: AWSDateTime
}
</code>```

Which generated GraphQL query showing below

```<code>export const listPosts = `query listPosts(
  $filter: ModelPostFilterInput
  $limit: Int
  $nextToken: String
) {
  listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {
    items {
      id
      author {
        id
        uuid
      }
      content
      createdAt
      updatedAt
    }
    nextToken
  }
}
`;
</code>```

I'm calling listPosts to query list of Posts but not sure how to implement date range into below query that I'm using to get data.

await API.graphql(graphqlOperation(queries.listPosts, {limit: 10, nextToken: nextToken}))

Is it possible to add two strings start: TODAY and end: 30 DAYS BEFORE TODAY to the query above and get it returns 30 latest posts?

答:
I did not try the new @key directive mentioned by Richard.

The solution I was using so far is to pass the parameter to the resolver and implement the query expression at resolver level.

For example, to query all bookings in the future (when booking start date is > today), I used

```<code>#set( $todayString = $util.time.nowISO8601().substring(0, 10) )
{
  "version": "2017-02-28",
  "operation": "Query",
  "query": {
    "expression": "guestId = :gId AND startDate > :startDate",
    "expressionValues": {
      ":gId": $util.dynamodb.toDynamoDBJson($ctx.args.guestId),
      ":startDate": $util.dynamodb.toDynamoDBJson($todayString)
    }
  },
  "index": "guestId-startDate-index"
}
</code>```

Body:
This is how my schema.graphql looks like.

type Post
  @model
  @auth(
    rules: [
      { allow: owner }
    ]
  ) {
  id: ID!
  author: User! @connection(name: "UserPosts")
  content: AWSJSON!
  createdAt: AWSDateTime
  updatedAt: AWSDateTime
}

Which generated GraphQL query showing below

export const listPosts = `query listPosts(
  $filter: ModelPostFilterInput
  $limit: Int
  $nextToken: String
) {
  listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {
    items {
      id
      author {
        id
        uuid
      }
      content
      createdAt
      updatedAt
    }
    nextToken
  }
}
`;

I'm calling listPosts to query list of Posts but not sure how to implement date range into below query that I'm using to get data.

await API.graphql(graphqlOperation(queries.listPosts, {limit: 10, nextToken: nextToken}))

Is it possible to add two strings start: TODAY and end: 30 DAYS BEFORE TODAY to the query above and get it returns 30 latest posts?

Body:
I did not try the new @key directive mentioned by Richard.

The solution I was using so far is to pass the parameter to the resolver and implement the query expression at resolver level.

For example, to query all bookings in the future (when booking start date is > today), I used

#set( $todayString = $util.time.nowISO8601().substring(0, 10) )
{
  "version": "2017-02-28",
  "operation": "Query",
  "query": {
    "expression": "guestId = :gId AND startDate > :startDate",
    "expressionValues": {
      ":gId": $util.dynamodb.toDynamoDBJson($ctx.args.guestId),
      ":startDate": $util.dynamodb.toDynamoDBJson($todayString)
    }
  },
  "index": "guestId-startDate-index"
}


问:
Delete to end of line in IntelliJ IDEA editor
Does IntelliJ IDEA support this feature?

Eclipse supports this with Ctrl + Shift + Del, vi with d$, so on...

答:
For Windows Users,

```<code>Ctrl + x
</code>```

it deletes the whole line, except when you highlighted parts of the line

Body:
For Windows Users,

Ctrl + x

it deletes the whole line, except when you highlighted parts of the line


问:
how to manage torch.Tensor with variable length in some dimenson?
I am programming a custom optimizer now, and the legth of bias in first dimension is not certain because last batch have no enough data to bulid a batch. So the initialization of weights with fixed batch_size do not satisfy  for torch.add between the last batch and the fixed length weights.

bias = torch.randn(batch_size,units)
batch_data = generator(path)
# for example
weights.shape # is (128,256)
# but the last batch has only 50 samples.
out = sigmoid(x*weights+bias) # where the length of first dimension is not mathed.
```

So, I wonder whether I can create a tensor where the lenght of some dimension could be variable, like variable length list.

答:
Why do you want bias to depend on batch size? In test time, would you always test your net with batches of exactly the same size? If so, what is the meaning of a smaller batch?

If you still insist on using smaller batch, you can ignore the "un-used" entries of bias:

```<code>out = sigmoid(x * weights[:x.size(0), ...] + bias[:x.size(0), ...])
</code>```

Body:
I am programming a custom optimizer now, and the legth of bias in first dimension is not certain because last batch have no enough data to bulid a batch. So the initialization of weights with fixed batch_size do not satisfy  for torch.add between the last batch and the fixed length weights.

bias = torch.randn(batch_size,units)
batch_data = generator(path)
# for example
weights.shape # is (128,256)
# but the last batch has only 50 samples.
out = sigmoid(x*weights+bias) # where the length of first dimension is not mathed.

So, I wonder whether I can create a tensor where the lenght of some dimension could be variable, like variable length list.

Body:
Why do you want bias to depend on batch size? In test time, would you always test your net with batches of exactly the same size? If so, what is the meaning of a smaller batch?

If you still insist on using smaller batch, you can ignore the "un-used" entries of bias:

out = sigmoid(x * weights[:x.size(0), ...] + bias[:x.size(0), ...])


问:
How to save an image using SQLite to then use it in a RecycleView
I have a problem saving and displaying an image using SQLite ,then display the data with a RecyclerView. My intention is to get the information of the user, within it its genre  through RadioButton, to finally show the data and an image distinguishing between man and woman. All was OK trying to do it without image, just text, but when I added the necessary to the image, the app failed.

I pointed with "/ * ??HERE * /" where I suppose there is a problem.

I really hope you can help me. Thanks.

```<code>public class MainActivity extends AppCompatActivity {

    EditText edtNames, edtLastNames, edtId;
    Button btnRegister, btnShow;
    RadioButton rdbtnMale, rdbtnFemale;
    int imgStudent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtNames= (EditText) findViewById(R.id.edtNames);
        edtLastNames= (EditText) findViewById(R.id.edtLastNames);
        //...etc, etc ->linkinkgs

        final SQLiteDb sqLiteDb =new SQLiteDb(getApplicationContext());

        // ??HERE
        if(rdbtnMale.isChecked()){
            imgStudent = R.drawable.boy;
        }else if(rdbtnFemale.isChecked()){
            imgStudent = R.drawable.girl;
        }

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sqLiteDb.AddStudents(edtNames.getText().toString(),
    edtLastNames.getText().toString(), edtId.getText().toString(),imgStudent /* ??HERE*/);
                Toast.makeText(getApplicationContext(),"Was added correctly",
     Toast.LENGTH_SHORT).show();
            }
        });

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent showStudents = new Intent(getApplicationContext(),StudentsActivity.class);
                startActivity(showStudents);
            }
        });
    }
}
</code>```

The Student class

```<code>public class Student {

    private String Names, LastNames, Id;
    private int Image;

    public Student(String names, String lastnames, String id, int imageStudent) {
        //...parameters
    }
    // + Getters and Setters
}
</code>```

The Database Helper class

```<code>public class SQLiteDb extends SQLiteOpenHelper {

        private static final String TABLE_STUDENTS = "CREATE TABLE STUDENTS(NAMES TEXT,
    LASTNAMES TEXT,ID TEXT, IMAGEN INT)";

    public SQLiteDb(Context context) {
        super(context, "db_students", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(TABLE_STUDENTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS TABLE_STUDENTS");
        onCreate(sqLiteDatabase);
    }

    public void AddStudents(String names, String lastnames, String id,/*??HERE*/ int img) {
        SQLiteDatabase bd = getWritableDatabase();
        if (bd != null) {
            bd.execSQL("INSERT INTO STUDENTS VALUES('" + names + "','"
    + lastnames + "','" + id + "','" + img + "')");
            bd.close();
        }
    }

    public List<Student> ShowStudents() {
        SQLiteDatabase bd = getReadableDatabase();
        Cursor cursor = bd.rawQuery("SELECT * FROM STUDENTS", null);
        List<Student> students = new ArrayList<>();

        if (cursor.moveToFirst()) {
            do {
                students.add(new Student(cursor.getString(0), cursor.getString(1)
    , cursor.getString(2),/*??HERE*/ cursor.getInt(3)));
            } while (cursor.moveToNext());
        }
        return students;
    }
}
</code>```

And the adapter :-

```<code>public class AdapterStudentList extends RecyclerView.Adapter<AdapterStudentList.ViewHolder> {

    public static  class  ViewHolder extends RecyclerView.ViewHolder{

        private TextView CompleteName;
        ImageView ImageStudent;

        public ViewHolder(View itemView) {
            super(itemView);
            CompleteName =(TextView)itemView.findViewById(R.id.tvCompleteName);
            ImageStudent = (ImageView)itemView.findViewById(R.id.imgStudent);
        }
    }

    public List<Student> studentsList;
    public AdapterStudentList(List<Student>studentsList){
        this.studentsList = studentsList;
    }

    //@NonNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_student,parent,false);
        ViewHolder  viewHolder= new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.CompleteName.setText(studentsList.get(position).getNames()+" "+ studentsList.get(position).getLastNames());
        holder.ImageStudent.setImageResource(studentsList.get(position).getImagen());
    }

    @Override
</code>```

答:
Considering the comment :-

Yeah you were right. The message is: "E/SQLiteLog: (1) table STUDENTS
  has 3 columns but 4 values were supplied". it is not assumed that the
  table had 4 columns in the part: private final static String
  TABLE_ALUMNOS = "CREATE TABLE STUDENTS (NAMES TEXT, LAST NAME TEXT, ID
  TEXT, IMAGE TEXT)"; ??

The most likely cause is that although you have changed the schema (added the IMAGE column at a guess) the onCreate only runs when the database is created. The database persists (only gets created once and the data is stored as part of the App).

When developing an App and if the data is expendable then the quickest fix is to either delete the App's data or to uninstall the App (both delete the database) and then rerun the App.

As the onUpgrade methed drops the table and calls the onCreate, you have the additional option of increasing the database version number e.g. change super(context, "db_students", null, 1); to super(context, "db_students", null, 2); (the 4th parameter is the database version)

With regard to the radio button selection then you could use something like :-

```<code>public class MainActivity extends AppCompatActivity {

    RadioButton rdbtnMale, rdbtnFemale;
    RadioGroup rgrpGender; //<<<<<<<<<<< ADDED
    Button btnRegister;
    int imgStudent; //<<<<<<<<<< Not needed

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rdbtnMale = this.findViewById(R.id.rdbtnMale);
        rdbtnFemale = this.findViewById(R.id.rdbtnFemale);
        btnRegister = this.findViewById(R.id.btnRegister);
        rgrpGender = this.findViewById(R.id.rgrpGender); //<<<<<<<<<< ADDED

        // ??HERE - NOTHING COMMENTED OUT
        /**
        if(rdbtnMale.isChecked()){
            imgStudent = R.drawable.boy;
        }else if(rdbtnFemale.isChecked()){
            imgStudent = R.drawable.girl;
        }
        **/
        //............ other code

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int studentGender;
                switch(rgrpGender.getCheckedRadioButtonId()) {
                    case R.id.rdbtnMale:
                        studentGender = 0;
                        break;
                    case R.id.rdbtnFemale:
                        studentGender = 1;
                        break;
                    default:
                        studentGender = -1;
                        break;
                }
                Log.d("SAVING","Student is gender " + String.valueOf(studentGender) + "\t(1 = Male 0= Female)"); //TODO Remove before publishing
                //<<<<<<<<<< COMMENTED OUT FOR DEMO >>>>>>>>>>
                //sqLiteDb.AddStudents(edtNames.getText().toString(),edtLastNames.getText().toString(), edtId.getText().toString(),studentGender);
            }
        });
    }
}
</code>```

The above allows additional RadioButtons for other genders just add the appropriate case(s)

The above can be run on it's own with an appropriate layout.

In essence you aren't saving the image but an indicator of the gender.

Body:
I have a problem saving and displaying an image using SQLite ,then display the data with a RecyclerView. My intention is to get the information of the user, within it its genre  through RadioButton, to finally show the data and an image distinguishing between man and woman. All was OK trying to do it without image, just text, but when I added the necessary to the image, the app failed.

I pointed with "/ * ??HERE * /" where I suppose there is a problem.

I really hope you can help me. Thanks.

public class MainActivity extends AppCompatActivity {

    EditText edtNames, edtLastNames, edtId;
    Button btnRegister, btnShow;
    RadioButton rdbtnMale, rdbtnFemale;
    int imgStudent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtNames= (EditText) findViewById(R.id.edtNames);
        edtLastNames= (EditText) findViewById(R.id.edtLastNames);
        //...etc, etc ->linkinkgs

        final SQLiteDb sqLiteDb =new SQLiteDb(getApplicationContext());

        // ??HERE
        if(rdbtnMale.isChecked()){
            imgStudent = R.drawable.boy;
        }else if(rdbtnFemale.isChecked()){
            imgStudent = R.drawable.girl;
        }

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sqLiteDb.AddStudents(edtNames.getText().toString(),
    edtLastNames.getText().toString(), edtId.getText().toString(),imgStudent /* ??HERE*/);
                Toast.makeText(getApplicationContext(),"Was added correctly",
     Toast.LENGTH_SHORT).show();
            }
        });

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent showStudents = new Intent(getApplicationContext(),StudentsActivity.class);
                startActivity(showStudents);
            }
        });
    }
}

The Student class

public class Student {

    private String Names, LastNames, Id;
    private int Image;

    public Student(String names, String lastnames, String id, int imageStudent) {
        //...parameters
    }
    // + Getters and Setters
}

The Database Helper class

public class SQLiteDb extends SQLiteOpenHelper {

        private static final String TABLE_STUDENTS = "CREATE TABLE STUDENTS(NAMES TEXT,
    LASTNAMES TEXT,ID TEXT, IMAGEN INT)";

    public SQLiteDb(Context context) {
        super(context, "db_students", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(TABLE_STUDENTS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS TABLE_STUDENTS");
        onCreate(sqLiteDatabase);
    }

    public void AddStudents(String names, String lastnames, String id,/*??HERE*/ int img) {
        SQLiteDatabase bd = getWritableDatabase();
        if (bd != null) {
            bd.execSQL("INSERT INTO STUDENTS VALUES('" + names + "','"
    + lastnames + "','" + id + "','" + img + "')");
            bd.close();
        }
    }

    public List<Student> ShowStudents() {
        SQLiteDatabase bd = getReadableDatabase();
        Cursor cursor = bd.rawQuery("SELECT * FROM STUDENTS", null);
        List<Student> students = new ArrayList<>();

        if (cursor.moveToFirst()) {
            do {
                students.add(new Student(cursor.getString(0), cursor.getString(1)
    , cursor.getString(2),/*??HERE*/ cursor.getInt(3)));
            } while (cursor.moveToNext());
        }
        return students;
    }
}

And the adapter :-

public class AdapterStudentList extends RecyclerView.Adapter<AdapterStudentList.ViewHolder> {

    public static  class  ViewHolder extends RecyclerView.ViewHolder{

        private TextView CompleteName;
        ImageView ImageStudent;

        public ViewHolder(View itemView) {
            super(itemView);
            CompleteName =(TextView)itemView.findViewById(R.id.tvCompleteName);
            ImageStudent = (ImageView)itemView.findViewById(R.id.imgStudent);
        }
    }

    public List<Student> studentsList;
    public AdapterStudentList(List<Student>studentsList){
        this.studentsList = studentsList;
    }

    //@NonNull
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_student,parent,false);
        ViewHolder  viewHolder= new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.CompleteName.setText(studentsList.get(position).getNames()+" "+ studentsList.get(position).getLastNames());
        holder.ImageStudent.setImageResource(studentsList.get(position).getImagen());
    }

    @Override

Body:
Considering the comment :-

Yeah you were right. The message is: "E/SQLiteLog: (1) table STUDENTS
  has 3 columns but 4 values were supplied". it is not assumed that the
  table had 4 columns in the part: private final static String
  TABLE_ALUMNOS = "CREATE TABLE STUDENTS (NAMES TEXT, LAST NAME TEXT, ID
  TEXT, IMAGE TEXT)"; ??

The most likely cause is that although you have changed the schema (added the IMAGE column at a guess) the onCreate only runs when the database is created. The database persists (only gets created once and the data is stored as part of the App).

When developing an App and if the data is expendable then the quickest fix is to either delete the App's data or to uninstall the App (both delete the database) and then rerun the App.

As the onUpgrade methed drops the table and calls the onCreate, you have the additional option of increasing the database version number e.g. change super(context, "db_students", null, 1); to super(context, "db_students", null, 2); (the 4th parameter is the database version)

With regard to the radio button selection then you could use something like :-

public class MainActivity extends AppCompatActivity {

    RadioButton rdbtnMale, rdbtnFemale;
    RadioGroup rgrpGender; //<<<<<<<<<<< ADDED
    Button btnRegister;
    int imgStudent; //<<<<<<<<<< Not needed

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rdbtnMale = this.findViewById(R.id.rdbtnMale);
        rdbtnFemale = this.findViewById(R.id.rdbtnFemale);
        btnRegister = this.findViewById(R.id.btnRegister);
        rgrpGender = this.findViewById(R.id.rgrpGender); //<<<<<<<<<< ADDED

        // ??HERE - NOTHING COMMENTED OUT
        /**
        if(rdbtnMale.isChecked()){
            imgStudent = R.drawable.boy;
        }else if(rdbtnFemale.isChecked()){
            imgStudent = R.drawable.girl;
        }
        **/
        //............ other code

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int studentGender;
                switch(rgrpGender.getCheckedRadioButtonId()) {
                    case R.id.rdbtnMale:
                        studentGender = 0;
                        break;
                    case R.id.rdbtnFemale:
                        studentGender = 1;
                        break;
                    default:
                        studentGender = -1;
                        break;
                }
                Log.d("SAVING","Student is gender " + String.valueOf(studentGender) + "\t(1 = Male 0= Female)"); //TODO Remove before publishing
                //<<<<<<<<<< COMMENTED OUT FOR DEMO >>>>>>>>>>
                //sqLiteDb.AddStudents(edtNames.getText().toString(),edtLastNames.getText().toString(), edtId.getText().toString(),studentGender);
            }
        });
    }
}

The above allows additional RadioButtons for other genders just add the appropriate case(s)

The above can be run on it's own with an appropriate layout.

In essence you aren't saving the image but an indicator of the gender.


问:
Check for value changes in variable
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

```<code>  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

  <div class="col-5 right">
    <div>
      <span *ngIf="offerExpiry">{{offerExpiry?.data}} days left to respond</span>
      <img src="../../../../assets/icons/calendar(old).png">
    </div>
  </div>
</code>```

Component B

```<code>offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }
</code>```

service file

```<code>  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }
</code>```

答:
Create one shared Observable service in your module and once your values are set from component B update the value and subscibe that observable variable in component A. so you will be received you updated value

steps are as follows

step 1 : create shared observable service

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable({
  providedIn: 'root'
})
export class ObservablesService {

constructor(
) { }

public updatedValue = new BehaviorSubject<object>([]);
 changeInUpdatedValue(value = {}) {
    this.updatedValue.next(value);
 }
}
</code>```

step 2 : Import that service in constructor and from Component B calls method changeInUpdatedValue function onces you receive the value

```<code> constructor(
    private _observablesService: ObservablesService,
) {
   //in data you can send your updated value whatever it is array,object or string
  this._observablesService.changeInUpdatedValue({ status: true, data: {} });
}
</code>```

step 3 : Import that service in constructor and from Component A subscribe method updatedValue function onces you receive the value

```<code>  constructor(
    private _observablesService: ObservablesService,
) {
  this._observablesService.updatedValue.subscribe((result: any) => {
     //you will receive your value here
  })
}
</code>```

Thanks

Title: Check for value changes in variable

Body:
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

      {{offerExpiry?.data}} days left to respond

Component B

offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }

service file

  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }

Body:
Create one shared Observable service in your module and once your values are set from component B update the value and subscibe that observable variable in component A. so you will be received you updated value

steps are as follows

step 1 : create shared observable service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable({
  providedIn: 'root'
})
export class ObservablesService {

constructor(
) { }

public updatedValue = new BehaviorSubject<object>([]);
 changeInUpdatedValue(value = {}) {
    this.updatedValue.next(value);
 }
}

step 2 : Import that service in constructor and from Component B calls method changeInUpdatedValue function onces you receive the value

 constructor(
    private _observablesService: ObservablesService,
) {
   //in data you can send your updated value whatever it is array,object or string
  this._observablesService.changeInUpdatedValue({ status: true, data: {} });
}

step 3 : Import that service in constructor and from Component A subscribe method updatedValue function onces you receive the value

  constructor(
    private _observablesService: ObservablesService,
) {
  this._observablesService.updatedValue.subscribe((result: any) => {
     //you will receive your value here
  })
}

Thanks


问:
Display different colored content detail for each option from the dropdown in Angular Material
I wanted to display the content with different color when user selected an option. For example on the dropdown list, there's three option for the items. If user selects on Confirmed in Status placeholder, the content will display "Confirmed" in green and when user selects Not Confirmed, the item will display the wording "Not Confirmed" in Red. If user select "Confirmed and Shipped", the color will show Yellow. How do I get it to work? I'm new to Angular. I have tried so many ways but it won't work. </p>

```<code><mat-form-field>
  <mat-select placeholder="Status" [formControl]="statusTypeFilter">
    <mat-option value="1">Confirmed</mat-option>
    <mat-option value="2">Not Confirmed</mat-option>
    <mat-option value="3">Confirmed and Shipped</mat-option>
</mat-form-field>

<div class="table-container mat-elevation-z8">
  <table mat-table [dataSource]="ItemConfirmationList" multiTemplateDataRows matSort matSortActive="no">
    <ng-container matColumnDef="StatusName">
      <th mat-header-cell *matHeaderCellDef mat-sort- header>Status</th>
      <td mat-cell *matCellDef="let element">{{element.StatusName }}</td>
    </ng-container>
</div>
</code>```

答:
A few things that i did:

we stored the value selected from the dropdown in a variable

for each row in our table, we checked the status against this variable and in
case of a match, we set the appropriate class

appropriate html:

```<code><mat-form-field>
    <mat-label>Status</mat-label>
    <mat-select [(value)]="selected">
        <mat-option *ngFor="let food of foods" [value]="food.value">
            {{food.viewValue}}
        </mat-option>
    </mat-select>
</mat-form-field>
<!-- <p>You selected: {{selected}}</p> -->
<hr/>
    <table>
        <thead>
            <tr>
                <td> Item </td>
                <td> Status </td>
            </tr>
        </thead>
        <tbody>
            <ng-container *ngFor='let pickedItem of sampleItems; let idx = index'>
                <tr [ngClass]="setColor(pickedItem.status, idx)">
                    <td> {{pickedItem.item}}</td>
                    <td>
                        <span *ngIf='pickedItem.status == 1'> Confirmed </span>
            <span *ngIf='pickedItem.status == 2'> Not Confirmed </span>
            <span *ngIf='pickedItem.status == 3'> Confirmed and Shipped </span>
                    </td>
                </tr>
            </ng-container>
        </tbody>
    </table>
</code>```

appropriate ts:

```<code>setColor(statusVal, idx){
  let returnedClass:string ='defaultClass';
  (statusVal == this.selected && statusVal ===1) ? returnedClass = 'confirmedClass' : 'defaultClass';
  (statusVal == this.selected && statusVal ===2) ? returnedClass = 'notConfirmedClass' : 'defaultClass';
  (statusVal == this.selected && statusVal ===3) ? returnedClass = 'shippedClass' : 'defaultClass';
  return returnedClass;
}
</code>```

appropriate css:

```<code>.confirmedClass { color:green;}
.notConfirmedClass { color:red;}
.shippedClass { color:orange;}
.defaultClass { color:#000;}
</code>```

complete working stackblitz here

Body:
I wanted to display the content with different color when user selected an option. For example on the dropdown list, there's three option for the items. If user selects on Confirmed in Status placeholder, the content will display "Confirmed" in green and when user selects Not Confirmed, the item will display the wording "Not Confirmed" in Red. If user select "Confirmed and Shipped", the color will show Yellow. How do I get it to work? I'm new to Angular. I have tried so many ways but it won't work.

<mat-form-field>
  <mat-select placeholder="Status" [formControl]="statusTypeFilter">
    <mat-option value="1">Confirmed</mat-option>
    <mat-option value="2">Not Confirmed</mat-option>
    <mat-option value="3">Confirmed and Shipped</mat-option>
</mat-form-field>

    <ng-container matColumnDef="StatusName">
      Status
      {{element.StatusName }}
    </ng-container>

Body:
A few things that i did:

we stored the value selected from the dropdown in a variable

for each row in our table, we checked the status against this variable and in
case of a match, we set the appropriate class

appropriate html:

<mat-form-field>
    <mat-label>Status</mat-label>
    <mat-select [(value)]="selected">
        <mat-option *ngFor="let food of foods" [value]="food.value">
            {{food.viewValue}}
        </mat-option>
    </mat-select>
</mat-form-field>
<!-- <p>You selected: {{selected}}</p> -->
<hr/>
    <table>
        <thead>
            <tr>
                <td> Item </td>
                <td> Status </td>
            </tr>
        </thead>
        <tbody>
            <ng-container *ngFor='let pickedItem of sampleItems; let idx = index'>
                <tr [ngClass]="setColor(pickedItem.status, idx)">
                    <td> {{pickedItem.item}}</td>
                    <td>
                        <span *ngIf='pickedItem.status == 1'> Confirmed </span>
            <span *ngIf='pickedItem.status == 2'> Not Confirmed </span>
            <span *ngIf='pickedItem.status == 3'> Confirmed and Shipped </span>
                    </td>
                </tr>
            </ng-container>
        </tbody>
    </table>

appropriate ts:

setColor(statusVal, idx){
  let returnedClass:string ='defaultClass';
  (statusVal == this.selected && statusVal ===1) ? returnedClass = 'confirmedClass' : 'defaultClass';
  (statusVal == this.selected && statusVal ===2) ? returnedClass = 'notConfirmedClass' : 'defaultClass';
  (statusVal == this.selected && statusVal ===3) ? returnedClass = 'shippedClass' : 'defaultClass';
  return returnedClass;
}

appropriate css:

.confirmedClass { color:green;}
.notConfirmedClass { color:red;}
.shippedClass { color:orange;}
.defaultClass { color:#000;}

complete working stackblitz here


问:
What is an idiomatic Scala way to "remove" one element from an immutable List?
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

```<code>def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}
</code>```

答:
As one possible solutions you can find index of the first suitable element and then remove element at this index:</p>

```<code>def removeOne(l: List[Card], c: Card) = l indexOf c match {
    case -1 => l
    case n => (l take n) ++ (l drop (n + 1))
}
</code>```

Body:
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}

Body:
As one possible solutions you can find index of the first suitable element and then remove element at this index:

def removeOne(l: List[Card], c: Card) = l indexOf c match {
    case -1 => l
    case n => (l take n) ++ (l drop (n + 1))
}


问:
Removing the drop shadow from a Scaffold AppBar in Flutter?
Is there a way to remove the drop shadow under the app bar (AppBar class) when using a Scaffold widget in Flutter?</p>

答:
If you want to remove the shadow of all app bars without repeating code, just add a AppBarTheme property with elevation: 0 to your app theme (ThemeData), inside your MaterialApp widget:

```<code>// This code should be located inside your "MyApp" class, or equivalent (in main.dart by default)
return MaterialApp(
  // App Theme:
  theme: ThemeData(
    // ••• ADD THIS: App Bar Theme: •••
    appBarTheme: AppBarTheme(
      elevation: 0, // This removes the shadow from all App Bars.
    )
  ),
);
</code>```

Body:
If you want to remove the shadow of all app bars without repeating code, just add a AppBarTheme property with elevation: 0 to your app theme (ThemeData), inside your MaterialApp widget:

// This code should be located inside your "MyApp" class, or equivalent (in main.dart by default)
return MaterialApp(
  // App Theme:
  theme: ThemeData(
    // ••• ADD THIS: App Bar Theme: •••
    appBarTheme: AppBarTheme(
      elevation: 0, // This removes the shadow from all App Bars.
    )
  ),
);