问:
AsyncLocalStorage in Hapi.js
I trying to add trace id in async storage, onRequest. But in the handler, there is no stored data. Why data is empty in handler? What am I do wrong?

async local storage:

```<code>const {AsyncLocalStorage} = require('async_hooks')
const asyncLocalStorage = new AsyncLocalStorage()
module.exports = {
  asyncLocalStorage
}
</code>```

setup:

```<code>server.ext({
    type: 'onRequest',
    method(request, h) {
      return new Promise(resolve => {
        getLocalStorage().run({meta: {traceId: 'id'}}, () => {
          return resolve(h.continue)
        })
      })
    },
  })
</code>```

handler:

```<code>    {
    path: '/',
    method: 'GET',
    handler: (req) => {
      const data = asyncLocalStorage.getStore()
      //why data is undefined?
      return data;
    },
    options: {
      tags: ['api', 'Test'],
      description: "Test",
      auth: {
        strategy: 'jwt_user',
        scope: ['USER'],
      },
      response: {
        schema: testResponseSchema,
        modify: true,
        options: {
          stripUnknown: true,
          convert: true,
        },
      },
    },
  },
</code>```

答:
I was able to get it to work (note - I am still testing this) using a wrapper over the handler function like below.

Step 1 : Create a file async-local-storage.js

```<code>// async-local-storage.js

const { AsyncLocalStorage } = require('async_hooks')

module.exports = {
  asyncLocalStorage: new AsyncLocalStorage(),
}

</code>```

Step 2 : Create a wrapper for handler function

```<code>// handle-request.js

const asyncLocalStorage = require('./async-local-storage').asyncLocalStorage

function handleRequest(handler) {
  return (req, h) => {
    const correlationId = req.headers['correlationId']
    return asyncLocalStorage.run({ correlationId : correlationId || 'Not set' }, async () => {
      return handler(req, h)
    })
  }
}

module.exports = {
  handleRequest,
}
</code>```

Step 3: In each route, use the handleRequest wrapper.

```<code>// routes.js

const handleRequest = require('./handle-request').handleRequest
const myTestApiHandler = require('./myTestApiHandler').myTestApiHandler

module.exports = [
{
    method: 'GET',
    path: '/api/my-test-api',
    config: {
      handler: handleRequest(myTestApiHandler),
    },
  },
}]
</code>```

Now, in myTestApiHandler we can get correlationId like below.

```<code>// myTestApiHandler

const asyncLocalStorage = require('./async-local-storage').asyncLocalStorage

function myTestApiHandler(req, h) {
  const store = asyncLocalStorage.getStore();
  const correlationId = store.correlationId;
  ..
  ..

}

module.exports = {
  myTestApiHandler
}
</code>```

The correlationId should also be available to any functions getting invoked from the myTestApiHandler function like logger etc.

Please refer official doc for AsyncLocalStorage for more details

Title: AsyncLocalStorage in Hapi.js

Body:
I trying to add trace id in async storage, onRequest. But in the handler, there is no stored data. Why data is empty in handler? What am I do wrong?

async local storage:

const {AsyncLocalStorage} = require('async_hooks')
const asyncLocalStorage = new AsyncLocalStorage()
module.exports = {
  asyncLocalStorage
}

setup:

server.ext({
    type: 'onRequest',
    method(request, h) {
      return new Promise(resolve => {
        getLocalStorage().run({meta: {traceId: 'id'}}, () => {
          return resolve(h.continue)
        })
      })
    },
  })

handler:

    {
    path: '/',
    method: 'GET',
    handler: (req) => {
      const data = asyncLocalStorage.getStore()
      //why data is undefined?
      return data;
    },
    options: {
      tags: ['api', 'Test'],
      description: "Test",
      auth: {
        strategy: 'jwt_user',
        scope: ['USER'],
      },
      response: {
        schema: testResponseSchema,
        modify: true,
        options: {
          stripUnknown: true,
          convert: true,
        },
      },
    },
  },

Body:
I was able to get it to work (note - I am still testing this) using a wrapper over the handler function like below.

Step 1 : Create a file async-local-storage.js

// async-local-storage.js

const { AsyncLocalStorage } = require('async_hooks')

module.exports = {
  asyncLocalStorage: new AsyncLocalStorage(),
}

Step 2 : Create a wrapper for handler function

// handle-request.js

const asyncLocalStorage = require('./async-local-storage').asyncLocalStorage

function handleRequest(handler) {
  return (req, h) => {
    const correlationId = req.headers['correlationId']
    return asyncLocalStorage.run({ correlationId : correlationId || 'Not set' }, async () => {
      return handler(req, h)
    })
  }
}

module.exports = {
  handleRequest,
}

Step 3: In each route, use the handleRequest wrapper.

// routes.js

const handleRequest = require('./handle-request').handleRequest
const myTestApiHandler = require('./myTestApiHandler').myTestApiHandler

module.exports = [
{
    method: 'GET',
    path: '/api/my-test-api',
    config: {
      handler: handleRequest(myTestApiHandler),
    },
  },
}]

Now, in myTestApiHandler we can get correlationId like below.

// myTestApiHandler

const asyncLocalStorage = require('./async-local-storage').asyncLocalStorage

function myTestApiHandler(req, h) {
  const store = asyncLocalStorage.getStore();
  const correlationId = store.correlationId;
  ..
  ..

}

module.exports = {
  myTestApiHandler
}

The correlationId should also be available to any functions getting invoked from the myTestApiHandler function like logger etc.

Please refer official doc for AsyncLocalStorage for more details


来源: stackexchange

问:
changing image in different div on hover
I have a page that contains 6 elements, 3 elements in each row. My goal is to change the image in div with id=b in the second row when hovering div with id=a in the first row. Below is my HTML.

homepage.html

```<code>{% block body %}

<div class="container-fluid">

<!--ROW 1-->
    <div class="row w-100">
        <div class="card col-4 mobile-fly-me-section sidebar-color">
              <div class="text-uppercase home-fly">Lorem Ipsum</div>
          </div>
          <div class="card col-4 hal-section justify-content-between p-3" id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">
              <h5 class="card-title home text-uppercase">header</h5>
              <a href="{% url 'main' %}" class="border-0 text-uppercase home stretched-link text-decoration-none">GO <img class="arrow" src="{% static 'assets/main/arrow.svg' %}"></a>
          </div>
          <div class="col-4 border d-flex flex-column min-vh-25 justify-content-end align-items-bottom p-3 home">Lorem ipsum</div>
    </div>
<!--END ROW 1-->

<!--ROW 2-->
<div class="row w-100">
    <div class="card col-4 mobile-fly-me-section text-uppercase home" id="b">
        <img src="{% static 'assets/graphics/graphic 01.svg' %}" width="75%"> <!-- before hover-->
        <img src="{% static 'assets/graphics/graphic 02.svg' %}" width="75%"> <!-- after hover-->
      </div>
        <div class="col-4 border d-flex flex-column min-vh-25 justify-content-end align-items-bottom p-3 home">Lorem ipsum</div>
        <div class="col-4 border d-flex flex-column min-vh-25 justify-content-between align-items-top p-3 text-uppercase home"><b>Lorem ipsum</b>
        <div> <img class="arrow" src="{% static 'assets/main/arrow.svg' %}">
        </div>
</div>
<!--END ROW 2-->

</div>

{% endblock body %}

{% block js %}
<script async src="//jsfiddle.net/YShs2/embed/"></script>
<script>
  function chbg(color) {
      document.getElementById('b').style.backgroundColor = color;
  }
</script>
{% endblock js %}
</code>```

I found a solution that is changing the background color but I am not sure how to switch images (from graphic 01.svg to graphic 02.svg)

答:
You could do it in a similar way to the way the background is changed. The property you need to update is 'content' and you set it to "url(http://someimage.com)"

So you would have a function like

```<code>  function changeURL(imgURL) {
    document.getElementById('b').style.content = `url(${imgURL})`;
  }
</code>```

And then on the div #a you can have

```<code>onmouseover="changeURL(url1)" onmouseout="changeURL(url2)"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a page that contains 6 elements, 3 elements in each row. My goal is to change the image in div with id=b in the second row when hovering div with id=a in the first row. Below is my HTML.

homepage.html

{% block body %}

Lorem Ipsum

header

              GO

Lorem ipsum

Lorem ipsum

Lorem ipsum

{% endblock body %}

{% block js %}

{% endblock js %}

I found a solution that is changing the background color but I am not sure how to switch images (from graphic 01.svg to graphic 02.svg)

Body:
You could do it in a similar way to the way the background is changed. The property you need to update is 'content' and you set it to "url(http://someimage.com)"

So you would have a function like

  function changeURL(imgURL) {
    document.getElementById('b').style.content = `url(${imgURL})`;
  }

And then on the div #a you can have

onmouseover="changeURL(url1)" onmouseout="changeURL(url2)"


问:
Select nonzero elements from MDF files in MATLAB
I am currently working with MDF file(.mf4) in MATLAB and I don't want to see the ChannelNumsamples that contain no values or lets say zero values so how to do that? I have tried with this code. but it is not helping me to extract nonzeroes elements.

cc = table2array(dd(1,:))
if table2array(A(x,"ChannelGroupNumSamples")) >= 0
    disp('YES');
    A(x,3)
    size(cc);
else disp('nodata')

numel(cc)
Elements = sum(cc ~= 0)
elementscount = nonzeros(Elements)
end
```

答:
To open an MDF file and read the data from it, but remove channel groups that don't contain any samples, you can do something like

```<code>m = mdf('myMDFfile.mf4');
mData = m.read;
for group = 1:numel(m.ChannelGroup)
    if m.ChannelGroup(group).NumSamples == 0
        mData(group) = [];
    end
end
</code>```

Now mData is a cell array of timetables containing only the data from the channel groups that had one or more samples.

Body:
To open an MDF file and read the data from it, but remove channel groups that don't contain any samples, you can do something like

m = mdf('myMDFfile.mf4');
mData = m.read;
for group = 1:numel(m.ChannelGroup)
    if m.ChannelGroup(group).NumSamples == 0
        mData(group) = [];
    end
end

Now mData is a cell array of timetables containing only the data from the channel groups that had one or more samples.


问:
Unable to create an AWS Blockchain instance of type bc.t3.small / bc.t3.medium
I'm trying to use a bc.t3.small or medium for my NFT minting test following this guide but I got a 400 HTTP response code telling it's invalid as size... I've tried on eu-west-1 and eu-west-2, but following this link it should be possible... anyone has a similar issue?

Thanks

答: These sizes are no longer available. The current selection is (the AWS page can be outdated; wouldn't be the first time):


问:
Changing state (visibility) of nested td
I would like to change the visibility of the td with class="tempCLS". The structure is shown in the image below with html code.

In the css file I have tried doing .tempCls {visibility : hidden; }

I have also tried doing: .tbl > thead > tr > .tempCls {... }

Thanks for any help

答:
you can try this</p>
```<code>.tempCls {display:none; }
</code>```

Body:
you can try this

.tempCls {display:none; }


问:
luaj can't import my app's classes: vm error: java.lang.ClassNotFoundException
when trying to import any class from my application, luaj(3.0-beta2) throws an exception that the class cannot be found, when importing built-in classes, there is no such problem

code run function

```<code>public static boolean run(String code){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream printStream = new PrintStream(baos, true, "utf-8");
            Globals globals = JsePlatform.standardGlobals();
            globals.set("logger", CoerceJavaToLua.coerce(new DLogger()));
            globals.set("binder", CoerceJavaToLua.coerce(new EventsBinder()));
            globals.set("entry", CoerceJavaToLua.coerce(new EntryPoints()));
            globals.set("file", CoerceJavaToLua.coerce(new DFile()));
            globals.set("luaj", CoerceJavaToLua.coerce(new LuaRunner()));
            globals.set("firebase", CoerceJavaToLua.coerce(new DFirebase()));
            globals.STDOUT = printStream;
            globals.load(code).call();
            String result =new String(baos.toByteArray());
            if(result != "")
            DLogger.log(result,"Luaj");
            printStream.close();
            return true;
        }catch (Exception e){
            DLogger.log("Luaj error excepted!\n "+e.getMessage(), "LuaRunner");
            return false;
        }

    }
</code>```

class hierarchy in my application https://i.stack.imgur.com/9jbwi.png

calling the classBinder() function in my application https://i.stack.imgur.com/trIQj.png

it doesn't matter that the class is imported as "firebase", I need to take the interface from this class via createProxy, but the problem is the same

UPD:

found the cause of my trouble. the new version of luaj uses a different classloader that does not see the inner classes of my application

quote from the site:
In newer versions, if the class is not found in the Java system libraries, LuaJ seems to check the local application directory. Because the Desktop project is a runnable *.jar and contains the actual class files, the desktop version of the game would run correctly in any version of LuaJ. In contrast, Android bundles everything in the classes.dex file, which is not "searchable" in the sense of a file path. Hence ClassNotFoundException.

also i found some solution but it throws a different error:

```<code>public class LuajFixer extends LuajavaLib {

    public LuajFixer() {
        super();
    }

    @Override
    protected Class classForName(String name) throws ClassNotFoundException{
            return Class.forName(name, true, Thread.currentThread(). getContextClassLoader());

    }
}
</code>```

and new jlua runner

```<code>
public static boolean run(String code){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream printStream = new PrintStream(baos, true, "utf-8");

            Globals globals = JsePlatform.standardGlobals();
            globals.set("logger", CoerceJavaToLua.coerce(new DLogger()));
            globals.set("binder", CoerceJavaToLua.coerce(new EventsBinder()));
            globals.set("entry", CoerceJavaToLua.coerce(new EntryPoints()));
            globals.set("file", CoerceJavaToLua.coerce(new DFile()));
            globals.set("luaj", CoerceJavaToLua.coerce(new LuaRunner()));
            globals.set("firebase", CoerceJavaToLua.coerce(new DFirebase()));
            globals.load(new LuajFixer());
            globals.STDOUT = printStream;

            LoadState.install(globals);
            LuaC.install(globals);
            globals.load(code).call();
            String result =new String(baos.toByteArray());
            if(result != "")
            DLogger.log(result,"Luaj");
            printStream.close();
            return true;
        }catch (Exception e){
            DLogger.log("Luaj error excepted!\n "+e.getMessage(), "LuaRunner");
            return false;
        }
</code>```

new error screenshot

答:
I had to download the library and add it manually so that I could edit this line. This helped and I no longer need the class fixer:

LuaJavaLib.java:202

original return Class.forName(name, true, ClassLoader.getSystemClassLoader());

change to return Class.forName(name, true, Thread.currentThread(). getContextClassLoader());

Body:
when trying to import any class from my application, luaj(3.0-beta2) throws an exception that the class cannot be found, when importing built-in classes, there is no such problem

code run function

public static boolean run(String code){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream printStream = new PrintStream(baos, true, "utf-8");
            Globals globals = JsePlatform.standardGlobals();
            globals.set("logger", CoerceJavaToLua.coerce(new DLogger()));
            globals.set("binder", CoerceJavaToLua.coerce(new EventsBinder()));
            globals.set("entry", CoerceJavaToLua.coerce(new EntryPoints()));
            globals.set("file", CoerceJavaToLua.coerce(new DFile()));
            globals.set("luaj", CoerceJavaToLua.coerce(new LuaRunner()));
            globals.set("firebase", CoerceJavaToLua.coerce(new DFirebase()));
            globals.STDOUT = printStream;
            globals.load(code).call();
            String result =new String(baos.toByteArray());
            if(result != "")
            DLogger.log(result,"Luaj");
            printStream.close();
            return true;
        }catch (Exception e){
            DLogger.log("Luaj error excepted!\n "+e.getMessage(), "LuaRunner");
            return false;
        }

    }

class hierarchy in my application https://i.stack.imgur.com/9jbwi.png

calling the classBinder() function in my application https://i.stack.imgur.com/trIQj.png

it doesn't matter that the class is imported as "firebase", I need to take the interface from this class via createProxy, but the problem is the same

UPD:

found the cause of my trouble. the new version of luaj uses a different classloader that does not see the inner classes of my application

quote from the site:
In newer versions, if the class is not found in the Java system libraries, LuaJ seems to check the local application directory. Because the Desktop project is a runnable *.jar and contains the actual class files, the desktop version of the game would run correctly in any version of LuaJ. In contrast, Android bundles everything in the classes.dex file, which is not "searchable" in the sense of a file path. Hence ClassNotFoundException.

also i found some solution but it throws a different error:

public class LuajFixer extends LuajavaLib {

    public LuajFixer() {
        super();
    }

    @Override
    protected Class classForName(String name) throws ClassNotFoundException{
            return Class.forName(name, true, Thread.currentThread(). getContextClassLoader());

    }
}

and new jlua runner

public static boolean run(String code){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream printStream = new PrintStream(baos, true, "utf-8");

            Globals globals = JsePlatform.standardGlobals();
            globals.set("logger", CoerceJavaToLua.coerce(new DLogger()));
            globals.set("binder", CoerceJavaToLua.coerce(new EventsBinder()));
            globals.set("entry", CoerceJavaToLua.coerce(new EntryPoints()));
            globals.set("file", CoerceJavaToLua.coerce(new DFile()));
            globals.set("luaj", CoerceJavaToLua.coerce(new LuaRunner()));
            globals.set("firebase", CoerceJavaToLua.coerce(new DFirebase()));
            globals.load(new LuajFixer());
            globals.STDOUT = printStream;

            LoadState.install(globals);
            LuaC.install(globals);
            globals.load(code).call();
            String result =new String(baos.toByteArray());
            if(result != "")
            DLogger.log(result,"Luaj");
            printStream.close();
            return true;
        }catch (Exception e){
            DLogger.log("Luaj error excepted!\n "+e.getMessage(), "LuaRunner");
            return false;
        }

new error screenshot


问:
Class doesn't get added on first click
I add a classname with Jquery, and it works, but only starts working AFTER my first click.
The code only addes the 'class' attribute the first time, but without the value.
Can anyone see what I do wrong?
(the class just add's a top margin in CSS)

```<code>(function(){
    $(document).ready(Setup)

    function Setup(){
        $("#navBarBehandeling").on('click',CheckDropDown);
    }
    $("#navBarBehandeling").on('click',CheckDropDown);
    function CheckDropDown(){
        var t = $(this);
        if(t.attr('aria-expanded')=='false'){
           $('main').addClass("mt-9");

        }
        else{
            $('main').removeClass("mt-9");
        }

    }
}()
</code>```

And here's my css:

```<code>.mt-9{
    margin-top: 9rem;
}
</code>```

and here's my html:

```<code><head>
   CDN's for Jquery and bootstrap
</head>
<body>
    <header>
        <div id="navBarBehandeling"> navbar with dropdown here></div>
    </header>
    <main>
        <p> blablabla </p>
    </main>
</body>
</code>```

答:
You can just do !t.attr('aria-expanded') to make it work

$("#navBarBehandeling").on('click',CheckDropDown);
function CheckDropDown() {
    var t = $(this);

    if (!t.attr('aria-expanded')) {
       console.log('addClass');
       $('main').addClass("mt-9");
    } else{
      console.log('removeClass');
      $('main').removeClass("mt-9");
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mt-9{
    margin-top: 9rem;
}</code>```

<!DOCTYPE html>

 navbar with dropdown here>

 blablabla

```

Title: Class doesn't get added on first click

Body:
I add a classname with Jquery, and it works, but only starts working AFTER my first click.
The code only addes the 'class' attribute the first time, but without the value.
Can anyone see what I do wrong?
(the class just add's a top margin in CSS)

(function(){
    $(document).ready(Setup)

    function Setup(){
        $("#navBarBehandeling").on('click',CheckDropDown);
    }
    $("#navBarBehandeling").on('click',CheckDropDown);
    function CheckDropDown(){
        var t = $(this);
        if(t.attr('aria-expanded')=='false'){
           $('main').addClass("mt-9");

        }
        else{
            $('main').removeClass("mt-9");
        }

    }
}()

And here's my css:

.mt-9{
    margin-top: 9rem;
}

and here's my html:

   CDN's for Jquery and bootstrap

 navbar with dropdown here>

 blablabla

Body:
You can just do !t.attr('aria-expanded') to make it work

$("#navBarBehandeling").on('click',CheckDropDown);
function CheckDropDown() {
    var t = $(this);

    if (!t.attr('aria-expanded')) {
       console.log('addClass');
       $('main').addClass("mt-9");
    } else{
      console.log('removeClass');
      $('main').removeClass("mt-9");
    }
}

.mt-9{
    margin-top: 9rem;
}

<!DOCTYPE html>
<html>
  <head>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
      <header>
          <div id="navBarBehandeling"> navbar with dropdown here></div>
      </header>
      <main>
          <p> blablabla </p>
      </main>
  </body>
</html>


问:
How to get a job on a different stage in azure pipeline
i have something like this in my azure pipeline

```<code>pool:
  name: name
  vmImage: Image

stages:
  stage: 1
    jobs:
     job: 1
     job: 2
     job: 3
  stage: 2
    condition: will run if stage 1 on job 2 is successful
  stage: 3
    condition: will run if job 1 or 3 in stage 1 is successful or stage
               2 is successful
</code>```

can I get the job 1 or 3 in stage 1? or can I do a

```<code>  (dependencies.stage3.job1.result,"Succeeded")
</code>```

like code?

答:
How to get a job on a different stage in azure pipeline

You could add a task for job1,job2,job3 to set veriables for each job, like:

```<code>  - task: InlinePowershell@1
    displayName: 'SetVariableInJobA'
    inputs:
      Script: 'Write-Host "##vso[task.setvariable variable=JobA;isOutput=true]true"'
    name: JobAResult
</code>```

Then we could set the condition based on the variables from the job1 to job3 in the stage1 by the syntax stageDependencies.stageName.jobName.outputs['stepName.variableName'].

Please check the document Jobs can access output variables from previous stages for some more details.

So, my final test YAML file looks like:

```<code>stages:
  - stage: A
    jobs:
    - job: jobA
      steps:
      - script: echo "This is JobA"
      - task: InlinePowershell@1
        displayName: 'SetVariableInJobA'
        inputs:
          Script: 'Write-Host "##vso[task.setvariable variable=JobA;isOutput=true]true"'
        name: JobAResult

    - job: jobB
      steps:
      - script: echo "This is JobB"
      - task: InlinePowershell@1
        displayName: 'SetVariableInJobB'
        inputs:
          Script: 'Write-Host "##vso[task.setvariable variable=JobB;isOutput=true]No"'
        name: JobBResult

    - job: jobC
      steps:
      - script: echo "This is JobC"
      - task: InlinePowershell@1
        displayName: 'SetVariableInJobC'
        inputs:
          Script: 'Write-Host "##vso[task.setvariable variable=JobC;isOutput=true]true"'
        name: JobCResult

  - stage: B
    variables:
      testB: $[ stageDependencies.A.jobB.outputs['JobBResult.JobB']]

    jobs:
    - job:
      condition: and(succeeded(), eq(variables.testB, 'Yes'))
      steps:
      - task: InlinePowershell@1
        inputs:
          Script: 'Write-Output ''$(testB)'''

  - stage: C
    variables:
      testA: $[ stageDependencies.A.jobA.outputs['JobAResult.JobA']]
      testB: $[ stageDependencies.A.jobB.outputs['JobBResult.JobB']]
      testC: $[ stageDependencies.A.jobC.outputs['JobCResult.JobC']]
    jobs:
    - job:
      condition: and(succeeded(), or(eq(variables.testA, 'Yes'), or(eq(variables.testB, 'Yes'), eq(variables.testC, 'Yes'))))
      steps:
      - task: InlinePowershell@1
        inputs:
          Script: 'Write-Output ''hello world'''
</code>```

Note:

We could not set the condotion on the stage level directly, that is because the  variable $[ stageDependencies.A.jobA.outputs['JobAResult.JobA']] is compile variable, and the varibale we set by the task is runtime variable.

Body:
i have something like this in my azure pipeline

pool:
  name: name
  vmImage: Image

stages:
  stage: 1
    jobs:
     job: 1
     job: 2
     job: 3
  stage: 2
    condition: will run if stage 1 on job 2 is successful
  stage: 3
    condition: will run if job 1 or 3 in stage 1 is successful or stage
               2 is successful

can I get the job 1 or 3 in stage 1? or can I do a

  (dependencies.stage3.job1.result,"Succeeded")

like code?

Body:
How to get a job on a different stage in azure pipeline

You could add a task for job1,job2,job3 to set veriables for each job, like:

  - task: InlinePowershell@1
    displayName: 'SetVariableInJobA'
    inputs:
      Script: 'Write-Host "##vso[task.setvariable variable=JobA;isOutput=true]true"'
    name: JobAResult

Then we could set the condition based on the variables from the job1 to job3 in the stage1 by the syntax stageDependencies.stageName.jobName.outputs['stepName.variableName'].

Please check the document Jobs can access output variables from previous stages for some more details.

So, my final test YAML file looks like:

stages:
  - stage: A
    jobs:
    - job: jobA
      steps:
      - script: echo "This is JobA"
      - task: InlinePowershell@1
        displayName: 'SetVariableInJobA'
        inputs:
          Script: 'Write-Host "##vso[task.setvariable variable=JobA;isOutput=true]true"'
        name: JobAResult

    - job: jobB
      steps:
      - script: echo "This is JobB"
      - task: InlinePowershell@1
        displayName: 'SetVariableInJobB'
        inputs:
          Script: 'Write-Host "##vso[task.setvariable variable=JobB;isOutput=true]No"'
        name: JobBResult

    - job: jobC
      steps:
      - script: echo "This is JobC"
      - task: InlinePowershell@1
        displayName: 'SetVariableInJobC'
        inputs:
          Script: 'Write-Host "##vso[task.setvariable variable=JobC;isOutput=true]true"'
        name: JobCResult

  - stage: B
    variables:
      testB: $[ stageDependencies.A.jobB.outputs['JobBResult.JobB']]

    jobs:
    - job:
      condition: and(succeeded(), eq(variables.testB, 'Yes'))
      steps:
      - task: InlinePowershell@1
        inputs:
          Script: 'Write-Output ''$(testB)'''

  - stage: C
    variables:
      testA: $[ stageDependencies.A.jobA.outputs['JobAResult.JobA']]
      testB: $[ stageDependencies.A.jobB.outputs['JobBResult.JobB']]
      testC: $[ stageDependencies.A.jobC.outputs['JobCResult.JobC']]
    jobs:
    - job:
      condition: and(succeeded(), or(eq(variables.testA, 'Yes'), or(eq(variables.testB, 'Yes'), eq(variables.testC, 'Yes'))))
      steps:
      - task: InlinePowershell@1
        inputs:
          Script: 'Write-Output ''hello world'''

Note:

We could not set the condotion on the stage level directly, that is because the  variable $[ stageDependencies.A.jobA.outputs['JobAResult.JobA']] is compile variable, and the varibale we set by the task is runtime variable.


问:
How to inject the full request path in Spring @RestController?
How can I inject the complete subpath in a Spring @RestController?

In my example, I want subpaths=/test/sub/path being injected

```<code>@RestController
public class MyController {
    @GetMapping(value = "/v1/{subpaths}", produces = MediaType.APPLICATION_JSON)
    public Object handle(@PathVariable String subpaths) {
        //this is not called for /v1/test/sub/path
    }
}
</code>```

答:
Effectively if the idea is to have a single entry point , we can just capture everything and later just extract subpath.
The following illustrates the same :

```<code>@RestController
public class MyController {
    @GetMapping(value = "/v1/parentPath/**", produces = MediaType.APPLICATION_JSON)
    public Object handle(@RequestParam(name = "myParam") String myParam,HttpServletRequest request) {
        //Get the complete url
        String url=request.getRequestURL();
        String[] paths=url.split("parentPath/");
        //paths[1] is the desired subPath

        //Provides URI
        // example : /context-path/v1/parentPath/subPath
        String uri=request.getRequestURI();

        //Returns query string, ex: test=abc&page=1
        String queryString=request.getQueryString();

        //Returns query parameters as map,Includes both query and ported form data
        Map<String, String[]> parameterMap=request.getParameterMap();

    }
}
</code>```

HttpServletRequest : is injected automatically by Spring.(Will try to find some documentation and add it here)

Just to be safe added parentPath to ensure that we do not capture ALL of the requests under v1

Body:
How can I inject the complete subpath in a Spring @RestController?

In my example, I want subpaths=/test/sub/path being injected

@RestController
public class MyController {
    @GetMapping(value = "/v1/{subpaths}", produces = MediaType.APPLICATION_JSON)
    public Object handle(@PathVariable String subpaths) {
        //this is not called for /v1/test/sub/path
    }
}

Body:
Effectively if the idea is to have a single entry point , we can just capture everything and later just extract subpath.
The following illustrates the same :

@RestController
public class MyController {
    @GetMapping(value = "/v1/parentPath/**", produces = MediaType.APPLICATION_JSON)
    public Object handle(@RequestParam(name = "myParam") String myParam,HttpServletRequest request) {
        //Get the complete url
        String url=request.getRequestURL();
        String[] paths=url.split("parentPath/");
        //paths[1] is the desired subPath

        //Provides URI
        // example : /context-path/v1/parentPath/subPath
        String uri=request.getRequestURI();

        //Returns query string, ex: test=abc&page=1
        String queryString=request.getQueryString();

        //Returns query parameters as map,Includes both query and ported form data
        Map<String, String[]> parameterMap=request.getParameterMap();

    }
}

HttpServletRequest : is injected automatically by Spring.(Will try to find some documentation and add it here)

Just to be safe added parentPath to ensure that we do not capture ALL of the requests under v1


问:
React Native - Allow insecure protocols, android gradle. (EAS BUILD FAILING)
I am trying to build my RN app with eas:build. It is using gradle 7 and gradle 7 does not allow insecure protocol, I have already gone through this link. I understand that I need to add allowInsecureProtocol = true to the insecure maven repository. However, in my build gradle file I don't find any such maven repositories. So I don't know where to add this line to fix this issue. I investigated other packages gradle as well but so far I have not found any repo that has http.

This is my Gradle file,

```<code>buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
        ndkVersion = "21.4.7075529"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.2")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
             // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
         mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup "com.facebook.react"
            }
        }

        google()
        maven { url 'https://www.jitpack.io' }
        jcenter() {
            content {
                includeModule("com.yqritc", "android-scalablevideoview")
            }
        }
    }
}
</code>```

答:
You just need to add one line to the AndroidManifest.xml.

AndroidManifest.xml

```<code> <application
         ...
        android:usesCleartextTraffic="true"> <= you add here
</code>```

Body:
I am trying to build my RN app with eas:build. It is using gradle 7 and gradle 7 does not allow insecure protocol, I have already gone through this link. I understand that I need to add allowInsecureProtocol = true to the insecure maven repository. However, in my build gradle file I don't find any such maven repositories. So I don't know where to add this line to fix this issue. I investigated other packages gradle as well but so far I have not found any repo that has http.

This is my Gradle file,

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 30
        targetSdkVersion = 30
        ndkVersion = "21.4.7075529"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.2.2")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
             // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
         mavenCentral {
            // We don't want to fetch react-native from Maven Central as there are
            // older versions over there.
            content {
                excludeGroup "com.facebook.react"
            }
        }

        google()
        maven { url 'https://www.jitpack.io' }
        jcenter() {
            content {
                includeModule("com.yqritc", "android-scalablevideoview")
            }
        }
    }
}

Body:
You just need to add one line to the AndroidManifest.xml.

AndroidManifest.xml

 <application
         ...
        android:usesCleartextTraffic="true"> <= you add here


问:
How do I tell mock to call the original method under certain circumstances?
I have a class that would want to mock later in a test:

```<code>class Original {
  function calculate($a) { ... }
}
</code>```

in test:

```<code>$mock = $this->getMock('Original',['calculate']);
$mock->expcets($this->any())
     ->will($this->returnValueMap([
      [1,'ABC'],
      [2,'BCD']
      // somehow tell $mock to call the original calculate() here
);
</code>```

I want to tell $mock to fall back to the original calculate() under certain conditions, for example if arguments do not match any of provided checks. As I understand from reading PhpUnit code the invoker just returns null if no match is found :-?

答:
If the mocking system you use is PHP's Mockery, you could also make the Mock "partial".
When you do, all the methods that are not shouldReceive()d will call the original underlying method.

From the docs:

Partial doubles are useful when we want to stub out, set expectations for, or spy on some methods of a class, but run the actual code for other methods.

What we call a runtime partial, involves creating a test double and then telling it to make itself partial. Any method calls that the double hasn’t been told to allow or expect, will act as they would on a normal instance of the object.

```<code>class Foo {
    function foo() { return 123; }
}

$foo = mock(Foo::class)->makePartial();
$foo->foo(); // int(123);

$foo->shouldReceive('foo')->andReturn(456);
$foo->foo(); // int(456)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a class that would want to mock later in a test:

class Original {
  function calculate($a) { ... }
}

in test:

$mock = $this->getMock('Original',['calculate']);
$mock->expcets($this->any())
     ->will($this->returnValueMap([
      [1,'ABC'],
      [2,'BCD']
      // somehow tell $mock to call the original calculate() here
);

I want to tell $mock to fall back to the original calculate() under certain conditions, for example if arguments do not match any of provided checks. As I understand from reading PhpUnit code the invoker just returns null if no match is found :-?

Body:
If the mocking system you use is PHP's Mockery, you could also make the Mock "partial".
When you do, all the methods that are not shouldReceive()d will call the original underlying method.

From the docs:

Partial doubles are useful when we want to stub out, set expectations for, or spy on some methods of a class, but run the actual code for other methods.

What we call a runtime partial, involves creating a test double and then telling it to make itself partial. Any method calls that the double hasn’t been told to allow or expect, will act as they would on a normal instance of the object.

class Foo {
    function foo() { return 123; }
}

$foo = mock(Foo::class)->makePartial();
$foo->foo(); // int(123);

$foo->shouldReceive('foo')->andReturn(456);
$foo->foo(); // int(456)


问:
Getting "count: Parameter must be a NodeSet" trying to count nodes with a specific numeric value
I'm using Perl's XML::XPath package in a small script.  I'm pretty sure I have an xpath problem, not something specific to that package.

My test data is the following:

```<code><stuff>
 <things>
  <thing>
   <widgets>
    <widget>
     <junk>
      <value>0</value>
     </junk>
    </widget>
    <widget>
     <junk>
      <value>9.0</value>
     </junk>
    </widget>
   </widgets>
  </thing>
 </things>
</stuff>
</code>```

The expression I'm using is:

```<code>//thing[count(number(widgets/widget/junk/value/text())=0)=0]
</code>```

When I run this, it fails with "count: Parameter must be a NodeSet".

答:
the following code within the count() returns a boolean which is not a node:

```<code>number(widgets/widget/junk/value/text())=0
</code>```

This is not allowed in XPath 1.0

If you want to select <thing/> elements containing no <value/> element with value 0 you can use:

```<code>//thing[not(
    widgets/widget/junk/value[number(text())=0]
  )]
</code>```

Body:
I'm using Perl's XML::XPath package in a small script.  I'm pretty sure I have an xpath problem, not something specific to that package.

My test data is the following:

<stuff>
 <things>
  <thing>
   <widgets>
    <widget>
     <junk>
      <value>0</value>
     </junk>
    </widget>
    <widget>
     <junk>
      <value>9.0</value>
     </junk>
    </widget>
   </widgets>
  </thing>
 </things>
</stuff>

The expression I'm using is:

//thing[count(number(widgets/widget/junk/value/text())=0)=0]

When I run this, it fails with "count: Parameter must be a NodeSet".

Body:
the following code within the count() returns a boolean which is not a node:

number(widgets/widget/junk/value/text())=0

This is not allowed in XPath 1.0

If you want to select <thing/> elements containing no <value/> element with value 0 you can use:

//thing[not(
    widgets/widget/junk/value[number(text())=0]
  )]


问:
Handling consecutive DynamoDB calls in a node.js Lambda for AWS
My example is quite simple.  I am using AWS Lambda in proxy mode where the index.js looks like this.

```<code>const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
};

</code>```

I have a separate app.js file which has a POST endpoint.  Inside this endpoint I need to make two queries on a DynamoDB table.

I need to first query the table to determine if something exists.
My code looks like this.

```<code>// DynamoDB Document Client
const docClient = new AWS.DynamoDB.DocumentClient();
app.post('/profile/:userSub', (req, res) => {
  const userSub = req.params.userSub;
  const accountName = req.body.accountName;

  // First query
  const params = {
    TableName: profileTableName,
    IndexName: profileIndexAccountName,
    KeyConditionExpression: 'accountName = :accountName',
    ExpressionAttributeValues: {
      ':accountName' : accountName
    }
  };

  docClient.query(params, (err, data) => {
    // Process the results

  });
}
</code>```

The problem is that I want to do a follow up query docClient.put based on the results from the first query.

I don't understand how to chain the queries together so that the first one is completed before the second one is executed.

Can someone please point me to an example? Or alternatively, if there's a better using async/await then I'm happy to follow it.

答:
TL;DR prefer the SDK's async-await patterns.

Here is an example of consecutive async-await calls using the AWS SDK for JavaScript v3.*. Note the async keyword in the function signature and the await keyword before the promise-returning method calls. The docs have the complete client initialization code.

// myLambda.js
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';

// ... configure client

const ddbDocClient = DynamoDBDocument.from(client);

export async function handler(event) {
  // ... other stuff

  const getResult = await ddbDocClient.get({ TableName, Key });

  const putResult = await ddbDocClient.put({
    TableName,
    Item: { id: '2', content: getResult.Item.Name },
  });
}
```

* The @aws-sdk/lib-dynamodb library's DynamoDBDocument is the v3 equivalent of the v2 client in your code. It exposes convenience methods like .get and .put.  It also helps convert between native js types and DynamoDB attribute values.

Body:
My example is quite simple.  I am using AWS Lambda in proxy mode where the index.js looks like this.

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
};

I have a separate app.js file which has a POST endpoint.  Inside this endpoint I need to make two queries on a DynamoDB table.

I need to first query the table to determine if something exists.
My code looks like this.

// DynamoDB Document Client
const docClient = new AWS.DynamoDB.DocumentClient();
app.post('/profile/:userSub', (req, res) => {
  const userSub = req.params.userSub;
  const accountName = req.body.accountName;

  // First query
  const params = {
    TableName: profileTableName,
    IndexName: profileIndexAccountName,
    KeyConditionExpression: 'accountName = :accountName',
    ExpressionAttributeValues: {
      ':accountName' : accountName
    }
  };

  docClient.query(params, (err, data) => {
    // Process the results

  });
}

The problem is that I want to do a follow up query docClient.put based on the results from the first query.

I don't understand how to chain the queries together so that the first one is completed before the second one is executed.

Can someone please point me to an example? Or alternatively, if there's a better using async/await then I'm happy to follow it.

Body:
TL;DR prefer the SDK's async-await patterns.

Here is an example of consecutive async-await calls using the AWS SDK for JavaScript v3.*. Note the async keyword in the function signature and the await keyword before the promise-returning method calls. The docs have the complete client initialization code.

// myLambda.js
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';

// ... configure client

const ddbDocClient = DynamoDBDocument.from(client);

export async function handler(event) {
  // ... other stuff

  const getResult = await ddbDocClient.get({ TableName, Key });

  const putResult = await ddbDocClient.put({
    TableName,
    Item: { id: '2', content: getResult.Item.Name },
  });
}

* The @aws-sdk/lib-dynamodb library's DynamoDBDocument is the v3 equivalent of the v2 client in your code. It exposes convenience methods like .get and .put.  It also helps convert between native js types and DynamoDB attribute values.


问:
Print SQL Statement for Drupal 7 entities
How can i print the sql statement for</p>
```<code>   $entities = $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('type', "page")
    ->propertyCondition('uid', $user->uid)
    ->fieldCondition('field_item_r1', 'value', $title)
    ->addTag('debug')->execute();```

Please help me to print the sql statement
</code>```

答: You can use (string) $query (I prefer this method if possible) or add ->addTag('debug').

Body:
How can i print the sql statement for

   $entities = $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('type', "page")
    ->propertyCondition('uid', $user->uid)
    ->fieldCondition('field_item_r1', 'value', $title)
    ->addTag('debug')->execute();```

Please help me to print the sql statement


问:
Drag and drop feature of the custom tags in DocuSign to my web application using C#?
I am posting this question after searching a lot on stack over flow , but did not find any answer.

I want to drag and drop custom fields onto my PDF/Docx files, so that when I send this document to recipient, he/she sees pre populated information.

Why am I doing this?

because I don't want to use Embedded Sending feature via API, because it shows:

1.Standard Fields

2.Other Fields

3.It shows DocuSign look and feel as well

for better clarification , I am attaching the image as well

If you see above image, it has only draggable custom fields which are populated from DocuSign, but this whole user experience is inside a web application , not navigating to DocuSign console

Even if we have to DocuSign Embedded Sending, how can I show only :

1.My own created custom fields and SignHere tags

2.How can I hide other buttons from DocuSign like Save & Close, because if I do that, my changes will not be saved on templates

FYI, there are few applications already doing this.

答:
If I understand your question right, you want to create a drag and drop use experience for the sender and then send the signing request to one or more signers yes?

You don't want to use the DocuSign embedded sending UX.

Answer: no problem, just a small matter of programming!

What I'd do:

Create a graphical drag n drop app for tagging your docs with your data items

Your app's "toolbar" would also need the fields (tabs) that your use case needs for signing. Eg a sign here tab, and maybe other tabs such as date signed, initial here etc.

The output of your "tagger app" could be a PDF Form or HTML. In either case, you'll need to include the tags and their meta data in the output file.

Create a DocuSign API app that uses the DocuSign eSignature REST API to upload the output file and transform the tag data into DocuSign tags.

Send the envelope.

An easier solution

The above is certainly do-able but will be a lot of work.

An easier solution:

Use the DocuSign branding feature to update the Sending UX to better match your brand.

Use the DocuSign custom fields feature to add custom fields (draggable tab types) for each of your specific data types. Eg Agency Address, Agency ACN, etc. In each of those tab types, set the Data Label attribute. Later, your app will use the Data Label to locate the tabs.

The sender uses an embedded sender view to create the envelope

Before the envelope is actually sent, your app reads the draft envelope and lists the envelope's tabs. Then match the API's tabLabel attribute with the previously set Data Label attribute (they're the same thing). Set the tab values accordingly.

Then send the envelope.

Re changing the embedded signing controls

Yes, this is doable. See this blog post

If you want further customization of the embedded sending view make a suggestion via https://feedback.docusign.com and then follow up via your DocuSign account manager.

Added: examples of building a custom tagger?

I don't know of any open source document taggers. Building one is hard. DocuSign has many engineers dedicated to the DocuSign web app.

As the OP mentions in his comment, an alternative idea is to create a "tiny language" that document creators can then add to their documents. This can be done, but it is more difficult for document creators than a WYSIWYG drag and drop UX.

A more common business process flow is to carefully analyze the documents and then create standardized documents and document sets.

That way the sender does not need to use a tagger. Instead, they select from a list or fill in a form. The app then creates the document that is needed, complete with data fields pulled from other apps.

The DocuSign CLM product is designed for this type of use case.


问:
SQL giving me different results
If I run this two queries separately and combined the output in excel it gives me the correct results

```<code>select
    DISTINCT userid
  from
    table1
  where
    event like '%signup%'
    and date(root_tstamp) between '2022-02-01'
    and '2022-02-07'
    and userid is not null and userid <> ''),
</code>```

and

```<code>    select
        DISTINCT user_id,
        geo_country
      from
        table2
      where
        geo_country is not null
        and geo_country <> ''
        and user_id is not null
        and user_id <> ''
        and date(etl_tstsmp) between '2022-02-01'
        and '2022-02-07'
</code>```

But if I ran it on as a single query with CTE it gives me the wrong results as following query

```<code>with base1 as ( select
    DISTINCT userid
  from
    table1
  where
    event like '%signups%'
    and date(root_tstamp) between '2022-02-01'
    and '2022-02-07'
    and userid is not null and userid <> ''),
base2 as (
  select
    DISTINCT user_id,
    geo_country
  from
    table2
  where
    geo_country is not null
    and geo_country <> ''
    and user_id is not null
    and user_id <> ''
    and date(etl_tstamp) between '2022-02-01'
    and '2022-02-07'
)
select
base2.geo_country,
base1.userid
from base1
inner join base2 on base1.userid = base2.user_id
</code>```

any suggestion

答:
Based on your comments I suspect you need to change your base2 query to an aggregation, something like

```<code>select user_id, max(geo_country) geo_country
  from table2
  where
    geo_country is not null
    and geo_country <> ''
    and user_id is not null
    and user_id <> ''
    and date(etl_tstamp) between '2022-02-01' and '2022-02-07'
  group by user_id
</code>```

There is also no need for joining two separate CTEs, you can simply use the above query and implement an exists for your first query, correlating on user_id, ie,

```<code>select user_id, max(geo_country) geo_country
from table2 t2
where <criteria>
and exists (
  select * from table1 t1
  where t1.user_id=t2.user_id and <base1 criteria>
)
group by user_id
</code>```

Title: SQL giving me different results

Body:
If I run this two queries separately and combined the output in excel it gives me the correct results

select
    DISTINCT userid
  from
    table1
  where
    event like '%signup%'
    and date(root_tstamp) between '2022-02-01'
    and '2022-02-07'
    and userid is not null and userid <> ''),

and

    select
        DISTINCT user_id,
        geo_country
      from
        table2
      where
        geo_country is not null
        and geo_country <> ''
        and user_id is not null
        and user_id <> ''
        and date(etl_tstsmp) between '2022-02-01'
        and '2022-02-07'

But if I ran it on as a single query with CTE it gives me the wrong results as following query

with base1 as ( select
    DISTINCT userid
  from
    table1
  where
    event like '%signups%'
    and date(root_tstamp) between '2022-02-01'
    and '2022-02-07'
    and userid is not null and userid <> ''),
base2 as (
  select
    DISTINCT user_id,
    geo_country
  from
    table2
  where
    geo_country is not null
    and geo_country <> ''
    and user_id is not null
    and user_id <> ''
    and date(etl_tstamp) between '2022-02-01'
    and '2022-02-07'
)
select
base2.geo_country,
base1.userid
from base1
inner join base2 on base1.userid = base2.user_id

any suggestion

Body:
Based on your comments I suspect you need to change your base2 query to an aggregation, something like

select user_id, max(geo_country) geo_country
  from table2
  where
    geo_country is not null
    and geo_country <> ''
    and user_id is not null
    and user_id <> ''
    and date(etl_tstamp) between '2022-02-01' and '2022-02-07'
  group by user_id

There is also no need for joining two separate CTEs, you can simply use the above query and implement an exists for your first query, correlating on user_id, ie,

select user_id, max(geo_country) geo_country
from table2 t2
where <criteria>
and exists (
  select * from table1 t1
  where t1.user_id=t2.user_id and <base1 criteria>
)
group by user_id


问:
What is the difference between 'git pull' and 'git fetch'?
What are the differences between git pull and git fetch?

答:
git pull tries to automatically merge after fetching commits. It is context sensitive, so all pulled commits will be merged into your currently active branch.  git pull automatically merges the commits without letting you review them first. If you don’t carefully manage your branches, you may run into frequent conflicts.

git fetch gathers any commits from the target branch that do not exist in the current branch and stores them in your local repository. However, it does not merge them with your current branch. This is particularly useful if you need to keep your repository up to date, but are working on something that might break if you update your files. To integrate the commits into your current branch, you must use git merge afterwards.

OwnerDisplayName: J. Pablo Fernández


问:
How do I get the key from Map in a List and do a get rest request in Java
I want to do a get request and want to get all the jobs who have the "teacher" in it. In this case the map value 2 and 3.

How do I get there if I execute the code below then I only get the value from the Map 2. The best way is over a List? But how do I do it?

I have this method.

```<code>@GET
@Path("jobs")
public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
            System.out.println("I DID IT");
            System.out.println(entry.getKey());
            return berufe.get(entry.getKey());
        }

    }
    return berufe.get(id);
}
</code>```

and this Map:

```<code>jobs.put(1, new jobs(1, 1337, "student"));
jobs.put(2, new jobs(2, 420, "teacher"));
jobs.put(3, new jobs(3, 69, "schoolteacher"));
</code>```

---------------------------------EDIT----------------------------------

If I do this:

```<code>@GET
@Path("jobs")
public Collection<Job> getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    final Set<Beruf> result = new HashSet<>();

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()) == true) {

            result.add(jobs.get(entry.getKey()));
        } else {
          return jobs.values();
        }

    }
    return result;
}
</code>```

I get with a discription all Map values back and without I get an Error.

What do I do wrong here?

答:
A function can return only one element. If there more than one hit, you have to return an object that can take on multiple elements. As you already mentioned a list, as an representant of a collection, can do this job. For your use case is a map a better option:</p>
```<code>@GET
@Path("jobs")
 public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description)
 {
    //Declare an object that can take on multiple elements
    var Map<Job> jobList = new HashMap<>();
    for (final Map.Entry<Integer, Job> entry : jobs.entrySet())
    {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()))
        {
                System.out.println("I DID IT");
                System.out.println(entry.getKey());
                jobList.put(entry.getKey(), job.get(entry.getKey()));
        }

    }
    return jobList.get(id);
}
</code>```

Body:
I want to do a get request and want to get all the jobs who have the "teacher" in it. In this case the map value 2 and 3.

How do I get there if I execute the code below then I only get the value from the Map 2. The best way is over a List? But how do I do it?

I have this method.

@GET
@Path("jobs")
public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase())) {
            System.out.println("I DID IT");
            System.out.println(entry.getKey());
            return berufe.get(entry.getKey());
        }

    }
    return berufe.get(id);
}

and this Map:

jobs.put(1, new jobs(1, 1337, "student"));
jobs.put(2, new jobs(2, 420, "teacher"));
jobs.put(3, new jobs(3, 69, "schoolteacher"));

---------------------------------EDIT----------------------------------

If I do this:

@GET
@Path("jobs")
public Collection<Job> getJobsId(@QueryParam("id") int id, @QueryParam("description") String description) {

    final Set<Beruf> result = new HashSet<>();

    for (final Map.Entry<Integer, Job> entry : jobs.entrySet()) {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()) == true) {

            result.add(jobs.get(entry.getKey()));
        } else {
          return jobs.values();
        }

    }
    return result;
}

I get with a discription all Map values back and without I get an Error.

What do I do wrong here?

Body:
A function can return only one element. If there more than one hit, you have to return an object that can take on multiple elements. As you already mentioned a list, as an representant of a collection, can do this job. For your use case is a map a better option:

@GET
@Path("jobs")
 public Job getJobsId(@QueryParam("id") int id, @QueryParam("description") String description)
 {
    //Declare an object that can take on multiple elements
    var Map<Job> jobList = new HashMap<>();
    for (final Map.Entry<Integer, Job> entry : jobs.entrySet())
    {
        if (entry.getValue().getDescription().toLowerCase().contains(description.toLowerCase()))
        {
                System.out.println("I DID IT");
                System.out.println(entry.getKey());
                jobList.put(entry.getKey(), job.get(entry.getKey()));
        }

    }
    return jobList.get(id);
}


问:
Stop Button not working for flutter in Android studio
The stop button not working and run button is disabled

See the following picture:

I am using android studio on Macbook pro with M1 Chip.
I downloaded the M1 chip-optimized Android studio.
When I run the flutter project on the Android emulator with Android Studio,
It runs fine but after some time If I try to stop the app. It does not stop and if I try to reload it, the reload button becomes disabled.

If I use the IOS emulator, I do not get this issue.

It only happens when I run my flutter project on Android emulators or Real Android devices.

答:
Dart officially supports Apple Silicon, but the one which is bundled with Flutter SDK works with Intel.

I managed to replace it with the Apple Silicon compatible version using flutter_m1_patcher. There are more ways to replace it which you can find here:-
How to replace the bundled Dart SDK in Flutter to run natively on Apple Silicon (ARM64)?

After doing this, I have not faced this stop button issue from last three days. Will update here in case I face the problem again.

Update (15/02/2022)
Life is great after this. Resolves problem for me.

Update (25/05/2022)
Flutter 3 now have Apple M1 compatible Dart SDK bundled into it. Issue is resolved.


问:
ModuleNotFoundError: No module named 'flask_wtf' - pip install not solving
Trying to leverage flask_wtf, I've done all of the different suggested steps:

pip install flask_wtf

pip3 install flask_wtf

pip(3) install in each location to ensure that it wasn't due to that

C:\Users\Bob\flask_tutorial>python flask_blog.py -m flask run
Traceback (most recent call last):
File "C:\Users\Bob\flask_tutorial\flask_blog.py", line 3, in
from forms import RegistrationForm, LoginForm
File "C:\Users\Bob\flask_tutorial\forms.py", line 1, in
from flask_wtf import FlaskForm
ModuleNotFoundError: No module named 'flask_wtf'

答:
From the docs:</p>
```<code>pip install -U Flask-WTF
</code>```

Body:
From the docs:

pip install -U Flask-WTF


问:
How to gracefully shutdown spring-kafka consumer application
i have implemented spring-kafka consumer application.

i wants consumer application graceful shutdown.

the current consumer application is terminated with the Linux command kill -9 pid

i am using @KafkaListener annotation now.

if i quit the Spring boot app, i want to reliably close the consumer, what should i do ?

i've been using @Predestory to reliably exit the spring boot app, but i'm not quite sure if this has anything to do with it.

答:
Spring provides a sub-project Actuator, which allows you to receive information about the status of a component as well as control it.

In order to install it, simply add two dependencies to pom.xml

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</code>```

Also in the properties file you must assign the port number :

```<code>server.port= your free port like 8081
</code>```

Also, in order for the actuator to switch the component off correctly, another parameter must be set in the properties file :

```<code>server.shutdown=graceful
</code>```

To turn a component off using an actuator, use the command :

```<code>curl 'http://localhost:8080/actuator/shutdown' -i -X POST
</code>```

All Actuator's commands

Body:
Spring provides a sub-project Actuator, which allows you to receive information about the status of a component as well as control it.

In order to install it, simply add two dependencies to pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Also in the properties file you must assign the port number :

server.port= your free port like 8081

Also, in order for the actuator to switch the component off correctly, another parameter must be set in the properties file :

server.shutdown=graceful

To turn a component off using an actuator, use the command :

curl 'http://localhost:8080/actuator/shutdown' -i -X POST

All Actuator's commands


问:
Bundling typescript with RollUp - Couldn't process compiler options
I'm trying to bundle my typescript files RollUp (https://rollupjs.org/)

I used this configuration files:

rollup.config.js:

```<code>import alias from 'rollup-plugin-alias';
import resolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import angular from 'rollup-plugin-angular';

export default {
    entry: '../main.ts',
    format: 'iife',
    dest: 'dist/bundle.es2015.js',
    sourceMap: true,
    plugins: [
        angular(),
        typescript(),
        alias({ rxjs: __dirname + '/node_modules/rxjs-es' }),
        resolve({
            jsnext: true,
            main: true,
            browser: true
        })
    ],
    external: [
        '@angular/core',
        '@angular/common',
        '@angular/compiler',
        '@angular/core',
        '@angular/http',
        '@angular/platform-browser',
        '@angular/platform-browser-dynamic',
        '@angular/router',
        '@angular/router-deprecated'
    ],
    globals: {
        '@angular/common': 'vendor._angular_common',
        '@angular/compiler': 'vendor._angular_compiler',
        '@angular/core': 'vendor._angular_core',
        '@angular/http': 'vendor._angular_http',
        '@angular/platform-browser': 'vendor._angular_platformBrowser',
        '@angular/platform-browser-dynamic': 'vendor._angular_platformBrowserDynamic',
        '@angular/router': 'vendor._angular_router',
        '@angular/forms': 'vendor._angular_forms'
    }
}
</code>```

vendor.js:

```<code>import * as _angular_common from '@angular/common';
import * as _angular_compiler from '@angular/compiler';
import * as _angular_core from '@angular/core';
import * as _angular_http from '@angular/http';
import * as _angular_platformBrowser from '@angular/platform-browser';
import * as _angular_platformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as _angular_router from '@angular/router';
import * as _angular_forms from '@angular/forms';

export default {
    _angular_common,
    _angular_compiler,
    _angular_core,
    _angular_http,
    _angular_platformBrowser,
    _angular_platformBrowserDynamic,
    _angular_router,
    _angular_forms
};
</code>```

But I keep getting this error:

```<code>rollup-plugin-typescript: Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.
rollup-plugin-typescript: Unknown compiler option 'lib'.
rollup-plugin-typescript: Couldn't process compiler options
</code>```

What am I doing wrong? (I'm new at this so if I'm didn't write some needed information  - please tell me)

EDIT:

This is my tsconfig.json:

```<code>{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": ".\\Compiled-JS\\Apps\\Client",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
</code>```

答:
In my case, the rollup-plugin-typescript-2 runs into other errors, for which there is practically no documentation (at the time of writing this post).

So, without switching the rollup plugin, I got past this error by fixing the tsconfig.json compilerOptions. I had the include property in the wrong place. I finally understood that the error refers to an unsupported or incorrect property in the compilerOptions inside tsconfig.json. See the discussion here for examples of supported property values. For example, it also seems that module: commonjs isn't supported at the moment.

For instance, supported values for target and module

```<code>"target": "ES2015 (or greater)",
"module": "ES2015, ES2020, or ESNEXT"
</code>```

Body:
I'm trying to bundle my typescript files RollUp (https://rollupjs.org/)

I used this configuration files:

rollup.config.js:

import alias from 'rollup-plugin-alias';
import resolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import angular from 'rollup-plugin-angular';

export default {
    entry: '../main.ts',
    format: 'iife',
    dest: 'dist/bundle.es2015.js',
    sourceMap: true,
    plugins: [
        angular(),
        typescript(),
        alias({ rxjs: __dirname + '/node_modules/rxjs-es' }),
        resolve({
            jsnext: true,
            main: true,
            browser: true
        })
    ],
    external: [
        '@angular/core',
        '@angular/common',
        '@angular/compiler',
        '@angular/core',
        '@angular/http',
        '@angular/platform-browser',
        '@angular/platform-browser-dynamic',
        '@angular/router',
        '@angular/router-deprecated'
    ],
    globals: {
        '@angular/common': 'vendor._angular_common',
        '@angular/compiler': 'vendor._angular_compiler',
        '@angular/core': 'vendor._angular_core',
        '@angular/http': 'vendor._angular_http',
        '@angular/platform-browser': 'vendor._angular_platformBrowser',
        '@angular/platform-browser-dynamic': 'vendor._angular_platformBrowserDynamic',
        '@angular/router': 'vendor._angular_router',
        '@angular/forms': 'vendor._angular_forms'
    }
}

vendor.js:

import * as _angular_common from '@angular/common';
import * as _angular_compiler from '@angular/compiler';
import * as _angular_core from '@angular/core';
import * as _angular_http from '@angular/http';
import * as _angular_platformBrowser from '@angular/platform-browser';
import * as _angular_platformBrowserDynamic from '@angular/platform-browser-dynamic';
import * as _angular_router from '@angular/router';
import * as _angular_forms from '@angular/forms';

export default {
    _angular_common,
    _angular_compiler,
    _angular_core,
    _angular_http,
    _angular_platformBrowser,
    _angular_platformBrowserDynamic,
    _angular_router,
    _angular_forms
};

But I keep getting this error:

rollup-plugin-typescript: Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.
rollup-plugin-typescript: Unknown compiler option 'lib'.
rollup-plugin-typescript: Couldn't process compiler options

What am I doing wrong? (I'm new at this so if I'm didn't write some needed information  - please tell me)

EDIT:

This is my tsconfig.json:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": ".\\Compiled-JS\\Apps\\Client",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

Body:
In my case, the rollup-plugin-typescript-2 runs into other errors, for which there is practically no documentation (at the time of writing this post).

So, without switching the rollup plugin, I got past this error by fixing the tsconfig.json compilerOptions. I had the include property in the wrong place. I finally understood that the error refers to an unsupported or incorrect property in the compilerOptions inside tsconfig.json. See the discussion here for examples of supported property values. For example, it also seems that module: commonjs isn't supported at the moment.

For instance, supported values for target and module

"target": "ES2015 (or greater)",
"module": "ES2015, ES2020, or ESNEXT"


问:
Migrating :odd selector behaviour after jQuery Depreciation
I am having issues migrating the last bit of our code to exit depreciation.
We use jQuery 3.6, and since jQuery 3.4 the :odd selector is depreciated.

As of jQuery 3.4, the :odd pseudo-class is deprecated. Remove it from
your selectors and filter the results later using .odd() (available in
jQuery 3.5.0 or newer).

However, it appears to be very difficult to retain the background color for every 3rd row.

.divGrey {
  background-color: #c0c0c0;
}
```
<pre class="lang-js prettyprint-override"><code>$('.container').filter(function () {
  return $(this).children().length === 3;
}).filter(':odd').addClass('divGrey'); // :odd Depreciated
</code>```

I can do .odd().addClass('divGrey') but I lose the background I want to retain for every third child. How can I do this? Do I need to remove filter function?

Any help appreciated - thanks!

答:
To do what you require you can use the index argument provided to a function handler in filter() and return a boolean value to state if the element's index is even or odd, like this:

$('.container').filter(i => i % 2).addClass('divGrey');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.divGrey {
  background-color: #c0c0c0;
}</code>```

0

1

2

3

4

5
```

Note that I removed the first filter() call as it wasn't relevant to the question.

Body:
I am having issues migrating the last bit of our code to exit depreciation.
We use jQuery 3.6, and since jQuery 3.4 the :odd selector is depreciated.

As of jQuery 3.4, the :odd pseudo-class is deprecated. Remove it from
your selectors and filter the results later using .odd() (available in
jQuery 3.5.0 or newer).

However, it appears to be very difficult to retain the background color for every 3rd row.

.divGrey {
  background-color: #c0c0c0;
}

$('.container').filter(function () {
  return $(this).children().length === 3;
}).filter(':odd').addClass('divGrey'); // :odd Depreciated

I can do .odd().addClass('divGrey') but I lose the background I want to retain for every third child. How can I do this? Do I need to remove filter function?

Any help appreciated - thanks!

Body:
To do what you require you can use the index argument provided to a function handler in filter() and return a boolean value to state if the element's index is even or odd, like this:

$('.container').filter(i => i % 2).addClass('divGrey');

.divGrey {
  background-color: #c0c0c0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="container">0</div>
<div class="container">1</div>
<div class="container">2</div>
<div class="container">3</div>
<div class="container">4</div>
<div class="container">5</div>

Note that I removed the first filter() call as it wasn't relevant to the question.


问:
What are practical uses of applicative style?
I am a Scala programmer, learning Haskell now. It's easy to find practical use cases and real world examples for OO concepts, such as decorators, strategy pattern etc. Books and interwebs are filled with it.

I came to the realization that this somehow is not the case for functional concepts. Case in point: applicatives.

I am struggling to find practical use cases for applicatives. Almost all of the tutorials and books I have come across so far provide the examples of [] and Maybe. I expected applicatives to be more applicable than that, seeing all the attention they get in the FP community.

I think I understand the conceptual basis for applicatives (maybe I am wrong), and I have waited long for my moment of enlightenment. But it doesn't seem to be happening. Never while programming, have I had a moment when I would shout with a joy, "Eureka! I can use applicative here!" (except again, for [] and Maybe).

Can someone please guide me how applicatives can be used in a day-to-day programming? How do I start spotting the pattern? Thanks!

答:
Here is an example taken from the aeson package:

data Coord = Coord { x :: Double, y :: Double }

instance FromJSON Coord where
   parseJSON (Object v) =
      Coord <$>
        v .: "x" <*>
        v .: "y"
```


问:
fixed or sticky the header background image up to the specific section only
how could I fixed or sticky the header background image up to the first section only?
let's say this is the code:

```<code><header id="header-bg"> <!-- inside this id has a background cover img -->
     <!-- header content here -->
</header>

<section id="first-section">
     <!-- content here -->
</section>
</code>```

my goal is to stay/fixed or sticky the header background up to the first section when scrolling. once the first section is end, the header background is not fixed/sticky anymore.

答: i think using js to change position to fixed or sticky after your required amount of scrolling to change the position.</p>

Body:
how could I fixed or sticky the header background image up to the first section only?
let's say this is the code:

my goal is to stay/fixed or sticky the header background up to the first section when scrolling. once the first section is end, the header background is not fixed/sticky anymore.


问:
Import from a parent's parent package (Python)
The following is my folder structure:

```<code>/experiments
    /experiment_1
    /experiment_2
    /experiment_3
        /src
           /sample.py
helper.py
</code>```

All experiments share some code, which I have exported into helper.py. Now I'm trying to import a function from helper.py into sample.py:

```<code>from ...helper import my_function
</code>```

and I get the following error:

```<code>ImportError: attempted relative import with no known parent package
</code>```

Please note that I have tried many solutions offered here, but none worked.

答: create a __init__.py file in your parent folder.

Body:
The following is my folder structure:

/experiments
    /experiment_1
    /experiment_2
    /experiment_3
        /src
           /sample.py
helper.py

All experiments share some code, which I have exported into helper.py. Now I'm trying to import a function from helper.py into sample.py:

from ...helper import my_function

and I get the following error:

ImportError: attempted relative import with no known parent package

Please note that I have tried many solutions offered here, but none worked.


问:
How to use Ostrich
I have a task to collect and report some runtime statistics for my application. Ostrich looks quite friendly in both API and feature set. But I can't find any documentation about the most of declared features. Especially it is difficult to configure stats reporting through the web interface without any understanding of configuration principles.

So my main question: is there any documentation besides the README?

If no, could someone give an example of the following features (all of them are from the top of README):

load & reload per-environment configuration (there is example on SO already, but what if I want to use a classpath resource? how to define an environment? how to reload configuration?)

report statistics into log files

Or (perfectly) give a good architectural overview of configuration in Ostrich so I can find some way to do configuration by myself.

答:
Ostrich config files are just regular scala classes, so if you want to load a classpath resource, you probably should create the config instance in code instead.

Here is how I load default config if -f command-line arg is not specified:

```<code>val runtime = RuntimeEnvironment(this, args)
val server =
  if (runtime.configFile.exists) {
    runtime.loadRuntimeConfig[Server]()
  } else {
    (new RPCServerConfig)()(runtime)
  }
</code>```

Note that you have to
 - create config instance
 - then call it's apply() method
 - then apply(runtime) on the result

You can easily extend this to load different configs depending by e.g. lift's Props.mode

Title: How to use Ostrich

Body:
Ostrich config files are just regular scala classes, so if you want to load a classpath resource, you probably should create the config instance in code instead.

Here is how I load default config if -f command-line arg is not specified:

val runtime = RuntimeEnvironment(this, args)
val server =
  if (runtime.configFile.exists) {
    runtime.loadRuntimeConfig[Server]()
  } else {
    (new RPCServerConfig)()(runtime)
  }

Note that you have to
 - create config instance
 - then call it's apply() method
 - then apply(runtime) on the result

You can easily extend this to load different configs depending by e.g. lift's Props.mode


问:
How to use a reactive expression in updateSelectInput?
I know that reaction expressions must be used in reactive contexts and updateSelectInput is not a reactive context. I have used a reprex below but in my real application i get some data processed in a reactive() way. I want to use the first column of that data to be used in my select input and i cannot figure out how to do that:</p>
```<code>ui = fluidPage(
  selectInput("state", "Choose a state:",choices = NULL

  ),
  textOutput("result")
)

server <- function(input, output, session) {

    updateSelectInput(session, "state",
                      choices = hello())
    hello<-reactive({mtcars[1]})

}
</code>```

答:
Just wrap updateSelectInput in an observer:

```<code>library(shiny)

ui = fluidPage(
  selectInput("state", "Choose a state:", choices = NULL),
  textOutput("result")
)

server <- function(input, output, session) {
  hello <- reactive({mtcars[1]})
  observe({
    freezeReactiveValue(input, "state")
    updateSelectInput(session, "state", choices = hello())
    })
}

shinyApp(ui, server)
</code>```

Body:
I know that reaction expressions must be used in reactive contexts and updateSelectInput is not a reactive context. I have used a reprex below but in my real application i get some data processed in a reactive() way. I want to use the first column of that data to be used in my select input and i cannot figure out how to do that:

ui = fluidPage(
  selectInput("state", "Choose a state:",choices = NULL

  ),
  textOutput("result")
)

server <- function(input, output, session) {

    updateSelectInput(session, "state",
                      choices = hello())
    hello<-reactive({mtcars[1]})

}

Body:
Just wrap updateSelectInput in an observer:

library(shiny)

ui = fluidPage(
  selectInput("state", "Choose a state:", choices = NULL),
  textOutput("result")
)

server <- function(input, output, session) {
  hello <- reactive({mtcars[1]})
  observe({
    freezeReactiveValue(input, "state")
    updateSelectInput(session, "state", choices = hello())
    })
}

shinyApp(ui, server)


问:
Vue + chartjs : Nearest point on hover tooltip not working
I'm currently trying to get my tooltip's chart (vuejs + chartjs) running as following :

(Source with "mode: nearest, axis: xy" mode selected)

Here is my code for the component :

```<code>Vue.component('line-chart', {
  extends: VueChartJs.Line,
  mounted () {
    this.renderChart({
      labels: ['Dec 2017', 'Jan 2018', 'Feb 2018', 'Mar 2018', 'Apr 2018', 'May 2018', 'Jun 2018', 'Jul 2018', 'Aug 2018', 'Sep 2018', 'Oct 2018', 'Nov 2018'],
      datasets: [
        {
          label: '2018 pages read per month',
          backgroundColor: '#f87979',
          data: [1238, 1660, 1571, 976, 2344, 1227, 949, 1109, 900, 458, 240, 384]
        }
      ]
    }, {responsive: true, maintainAspectRatio: false,

        //Here is the part that doesn't seem to work
        interaction: {
         axis: 'xy',
         mode: 'nearest',
         intersect: false

        }
       })
  }
});

var vm = new Vue({
  el: '#app',
  data: { }
});
</code>```

You can find my codepen here

According to the documentation I can't figure out what i'm missing...

答:
After paraphrasing my question to the extreme, I just found a codepen whose code doesn't match the documentation BUT it answers my question perfectly.

So to get the result, you have to use options.tooltips.mode and not options.interaction.mode !

Then, you have to change :

```<code>    interaction: {
     axis: 'xy',
     mode: 'nearest',
     intersect: false

    }
</code>```

By :

```<code>tooltips: {
  mode: 'index',
  intersect: false,
},
</code>```

Here is the final code :

```<code>Vue.component('line-chart', {
      extends: VueChartJs.Line,
      mounted () {
        this.renderChart({
          labels: ['Dec 2017', 'Jan 2018', 'Feb 2018', 'Mar 2018', 'Apr 2018', 'May 2018', 'Jun 2018', 'Jul 2018', 'Aug 2018', 'Sep 2018', 'Oct 2018', 'Nov 2018'],
          datasets: [
            {
              label: '2018 pages read per month',
              backgroundColor: '#f87979',
              data: [1238, 1660, 1571, 976, 2344, 1227, 949, 1109, 900, 458, 240, 384]
            }
          ]
        }, {responsive: true, maintainAspectRatio: false,
              tooltips: {
             axis: 'xy',
             mode: 'nearest',
             intersect: false

            }
           })
      }
    });

    var vm = new Vue({
      el: '#app',
      data: { }
    });
</code>```

Here is the codepen working as excepted with tooltips in nearest mode on hovering the chart's line.

Final Result :

Body:
I'm currently trying to get my tooltip's chart (vuejs + chartjs) running as following :

(Source with "mode: nearest, axis: xy" mode selected)

Here is my code for the component :

Vue.component('line-chart', {
  extends: VueChartJs.Line,
  mounted () {
    this.renderChart({
      labels: ['Dec 2017', 'Jan 2018', 'Feb 2018', 'Mar 2018', 'Apr 2018', 'May 2018', 'Jun 2018', 'Jul 2018', 'Aug 2018', 'Sep 2018', 'Oct 2018', 'Nov 2018'],
      datasets: [
        {
          label: '2018 pages read per month',
          backgroundColor: '#f87979',
          data: [1238, 1660, 1571, 976, 2344, 1227, 949, 1109, 900, 458, 240, 384]
        }
      ]
    }, {responsive: true, maintainAspectRatio: false,

        //Here is the part that doesn't seem to work
        interaction: {
         axis: 'xy',
         mode: 'nearest',
         intersect: false

        }
       })
  }
});

var vm = new Vue({
  el: '#app',
  data: { }
});

You can find my codepen here

According to the documentation I can't figure out what i'm missing...

Body:
After paraphrasing my question to the extreme, I just found a codepen whose code doesn't match the documentation BUT it answers my question perfectly.

So to get the result, you have to use options.tooltips.mode and not options.interaction.mode !

Then, you have to change :

    interaction: {
     axis: 'xy',
     mode: 'nearest',
     intersect: false

    }

By :

tooltips: {
  mode: 'index',
  intersect: false,
},

Here is the final code :

Vue.component('line-chart', {
      extends: VueChartJs.Line,
      mounted () {
        this.renderChart({
          labels: ['Dec 2017', 'Jan 2018', 'Feb 2018', 'Mar 2018', 'Apr 2018', 'May 2018', 'Jun 2018', 'Jul 2018', 'Aug 2018', 'Sep 2018', 'Oct 2018', 'Nov 2018'],
          datasets: [
            {
              label: '2018 pages read per month',
              backgroundColor: '#f87979',
              data: [1238, 1660, 1571, 976, 2344, 1227, 949, 1109, 900, 458, 240, 384]
            }
          ]
        }, {responsive: true, maintainAspectRatio: false,
              tooltips: {
             axis: 'xy',
             mode: 'nearest',
             intersect: false

            }
           })
      }
    });

    var vm = new Vue({
      el: '#app',
      data: { }
    });

Here is the codepen working as excepted with tooltips in nearest mode on hovering the chart's line.

Final Result :


问:
In SwiftUI how to define a function pointer to the HStack or VStack constructor
I have this view and would like to simplify it:

```<code>struct SUIBorderedIconTextButton: View {

  struct IconInfo {
    enum Position {
      case left
      case right
      case top
      case bottom

      var isHorizontal: Bool {
        return self == .left || self == .right
      }

      var isBeforeText: Bool {
        return self == .left || self == .top
      }
    }

    let icon: Image
    let position: Position
  }

  let iconInfo: IconInfo?
  let title: String
  let fontSize: CGFloat
  let backgroundColor: Color
  let enabled: Bool
  let action: () -> Void

  @ViewBuilder
  private var content: some View {
    if let iconInfo = iconInfo {
      switch iconInfo.position {
      case .left:
        HStack {
          iconInfo.icon
          Text(title).fontSize(fontSize)
        }
      case .right:
        HStack {
          Text(title).fontSize(fontSize)
          iconInfo.icon
        }
      case .top:
        VStack {
          iconInfo.icon
          Text(title).fontSize(fontSize)
        }
      case .bottom:
        VStack {
          Text(title).fontSize(fontSize)
          iconInfo.icon
        }
      }
    } else {
      Text(title).fontSize(fontSize)
    }
  }

  var body: some View {
    Button(action: action) {
      content
        .padding()
        .foregroundColor(color_button_text)
        .background {
          RoundedRectangle(cornerRadius: text_button_border_radius)
            .foregroundColor(enabled ? backgroundColor : color_disabled_background)
        }
    }
    .disabled(!enabled)
  }
}
</code>```

This view simply displays a text button, with optional icon (either on left/right/top/bottom of the text)

if position is left or right, we want to use HStack. Otherwise, use VStack.

if position is top or left, we want to put icon before text. Otherwise, put icon after text.

Note that there are quite a lot of boilerplate in the content builder.

I created this helper function for the .top or .left cases:

```<code>
  @ViewBuilder
  private func group(iconInfo: IconInfo) -> some View {
    if iconInfo.position.isBeforeText {
      iconInfo.icon
      Text(title).fontSize(fontSize)
    } else {
      Text(title).fontSize(fontSize)
      iconInfo.icon
    }
  }

</code>```

But I am not sure how to handle choosing the constructor. I may need a pointer to the init function, but I have tried

```<code>let constructor = position.isHorizontal ? HStack.init : VStack.init
constructor {
  ...
}
</code>```

This obviously does not compile. I am not sure how to proceed. If you have other ideas to simplify this logic, feel free to try it out too.

答:
Ternary operator actually is not applicable to SwiftUI types as they all value-types with generics so result in constructed different type entities and cannot be assigned to one variable.

Instead possible approach for your case is something like

```<code>@ViewBuilder var content: some View {
    Text("Text")
    Image(systemName: "checkmark")
}

var body: some View {
    if isHorizontal {
        HStack{ content }
    } else {
        VStack{ content }
    }
}
</code>```

Body:
I have this view and would like to simplify it:

struct SUIBorderedIconTextButton: View {

  struct IconInfo {
    enum Position {
      case left
      case right
      case top
      case bottom

      var isHorizontal: Bool {
        return self == .left || self == .right
      }

      var isBeforeText: Bool {
        return self == .left || self == .top
      }
    }

    let icon: Image
    let position: Position
  }

  let iconInfo: IconInfo?
  let title: String
  let fontSize: CGFloat
  let backgroundColor: Color
  let enabled: Bool
  let action: () -> Void

  @ViewBuilder
  private var content: some View {
    if let iconInfo = iconInfo {
      switch iconInfo.position {
      case .left:
        HStack {
          iconInfo.icon
          Text(title).fontSize(fontSize)
        }
      case .right:
        HStack {
          Text(title).fontSize(fontSize)
          iconInfo.icon
        }
      case .top:
        VStack {
          iconInfo.icon
          Text(title).fontSize(fontSize)
        }
      case .bottom:
        VStack {
          Text(title).fontSize(fontSize)
          iconInfo.icon
        }
      }
    } else {
      Text(title).fontSize(fontSize)
    }
  }

  var body: some View {
    Button(action: action) {
      content
        .padding()
        .foregroundColor(color_button_text)
        .background {
          RoundedRectangle(cornerRadius: text_button_border_radius)
            .foregroundColor(enabled ? backgroundColor : color_disabled_background)
        }
    }
    .disabled(!enabled)
  }
}

This view simply displays a text button, with optional icon (either on left/right/top/bottom of the text)

if position is left or right, we want to use HStack. Otherwise, use VStack.

if position is top or left, we want to put icon before text. Otherwise, put icon after text.

Note that there are quite a lot of boilerplate in the content builder.

I created this helper function for the .top or .left cases:

  @ViewBuilder
  private func group(iconInfo: IconInfo) -> some View {
    if iconInfo.position.isBeforeText {
      iconInfo.icon
      Text(title).fontSize(fontSize)
    } else {
      Text(title).fontSize(fontSize)
      iconInfo.icon
    }
  }

But I am not sure how to handle choosing the constructor. I may need a pointer to the init function, but I have tried

let constructor = position.isHorizontal ? HStack.init : VStack.init
constructor {
  ...
}

This obviously does not compile. I am not sure how to proceed. If you have other ideas to simplify this logic, feel free to try it out too.

Body:
Ternary operator actually is not applicable to SwiftUI types as they all value-types with generics so result in constructed different type entities and cannot be assigned to one variable.

Instead possible approach for your case is something like

@ViewBuilder var content: some View {
    Text("Text")
    Image(systemName: "checkmark")
}

var body: some View {
    if isHorizontal {
        HStack{ content }
    } else {
        VStack{ content }
    }
}


问:
Why does this for loop in C program print Hi 11 times?
```<code>#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("Hi");
return 0;
}
</code>```

Why does the for loop print Hi 11 times? I don't understand.

答:
The expression i >>= 1 is equivalent to i = i / 2

So if initially i is equal to 1024 then the body of the loop will be executed for the values

```<code>1024 512 256 128 64 32 16 8 4 2 1
</code>```

that is 11 times. The value of the expression 1 / 2 is equal to 0 due to the integer arithmetic.

You could check that by changing the call of printf like

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

int main( void )
{
    int i = 1024;

    for (; i; i >>= 1) printf( "%d ", i );

    putchar( '\n' );
}
</code>```

Body:
#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("Hi");
return 0;
}

Why does the for loop print Hi 11 times? I don't understand.

Body:
The expression i >>= 1 is equivalent to i = i / 2

So if initially i is equal to 1024 then the body of the loop will be executed for the values

1024 512 256 128 64 32 16 8 4 2 1

that is 11 times. The value of the expression 1 / 2 is equal to 0 due to the integer arithmetic.

You could check that by changing the call of printf like

#include <stdio.h>

int main( void )
{
    int i = 1024;

    for (; i; i >>= 1) printf( "%d ", i );

    putchar( '\n' );
}


问:
Fetch data from three tables where a particular column from other two tables are null?
I have three tables: A, B and C.

Tables have the following columns:

```<code>A: id, name, shipdate
B: id, returndate
C: id, deliverydate
</code>```

I have fetched data of Tables A and B using INNER JOIN and the ID Column.

```<code>SELECT  A.name,
        A.shipdate,
        B.returndate
FROM A INNER JOIN B ON A.id = B.id
</code>```

Same I have fetched data  of Tables A nd C using INNER JOIN AND ID column.

But how to fetch data from Tables A, B and C where returndate is null and deliverydate is null?

Here's the query i tried:

```<code>SELECT   A.name,
         A.shipdate,
         B.returndate,
         C.deliverydate
FROM A
INNER JOIN B ON A.id = B.id
INNER JOIN C ON A.id = C.id
WHERE B.returndate = null
AND C.deliverydate = null
</code>```

答:
Just constrain your condition in WHERE:

```<code>SELECT A.*
FROM A
INNER JOIN B
  ON A.id = B.id
INNER JOIN C
  ON B.id = C.id
WHERE
  ISNULL(B.returndate) = 1 AND ISNULL(C.deliverydate) = 1
</code>```

Instead of ISNULL(B.returndate) = 1 you can use B.returndate is null, but a statement like B.returndate = null will always return false.

Body:
I have three tables: A, B and C.

Tables have the following columns:

A: id, name, shipdate
B: id, returndate
C: id, deliverydate

I have fetched data of Tables A and B using INNER JOIN and the ID Column.

SELECT  A.name,
        A.shipdate,
        B.returndate
FROM A INNER JOIN B ON A.id = B.id

Same I have fetched data  of Tables A nd C using INNER JOIN AND ID column.

But how to fetch data from Tables A, B and C where returndate is null and deliverydate is null?

Here's the query i tried:

SELECT   A.name,
         A.shipdate,
         B.returndate,
         C.deliverydate
FROM A
INNER JOIN B ON A.id = B.id
INNER JOIN C ON A.id = C.id
WHERE B.returndate = null
AND C.deliverydate = null

Body:
Just constrain your condition in WHERE:

SELECT A.*
FROM A
INNER JOIN B
  ON A.id = B.id
INNER JOIN C
  ON B.id = C.id
WHERE
  ISNULL(B.returndate) = 1 AND ISNULL(C.deliverydate) = 1

Instead of ISNULL(B.returndate) = 1 you can use B.returndate is null, but a statement like B.returndate = null will always return false.