问:
How can I generate refresh token in asp.net?
I'm able to get access token from client side using google file picker. But the access token expires after 3600 seconds. I scratched my head to get the refresh token but unable to do it on C# ASP.NET. Can somebody help with the C# code to understand and retrieve the refresh token ? It will be very helpful. Thank You.

I tried using GoogleWebAuthorizationBroker.AuthorizeAsync, it works in my local machine but doesn't work on the production IIS server. I also tried GoogleAuthorizationCodeFlow but unable to go further in it and I don't know how to use it.

```<code>IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = System.Configuration.ConfigurationManager.AppSettings["GoogleDriveClientID"],
                        ClientSecret = System.Configuration.ConfigurationManager.AppSettings["GoogleDriveClientSecret"]
                    },
                    Scopes = Scopes,
                    DataStore = null
                });
</code>```

I tried this but I don't know how to move forward after this.

答:
It seems you are trying to generate refresh token from your C# code sample.

You could try following code snippet:

Refresh Token Example:

public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "yourClientId",
                        ClientSecret = "yourClientSecret"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });

        public override string GetUserId(Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();

        }

        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }
```

Note: If you have any more query on how you get ClientId, ClientSecret and Scope, please refer to this MVC Example.

Body:
I'm able to get access token from client side using google file picker. But the access token expires after 3600 seconds. I scratched my head to get the refresh token but unable to do it on C# ASP.NET. Can somebody help with the C# code to understand and retrieve the refresh token ? It will be very helpful. Thank You.

I tried using GoogleWebAuthorizationBroker.AuthorizeAsync, it works in my local machine but doesn't work on the production IIS server. I also tried GoogleAuthorizationCodeFlow but unable to go further in it and I don't know how to use it.

IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = System.Configuration.ConfigurationManager.AppSettings["GoogleDriveClientID"],
                        ClientSecret = System.Configuration.ConfigurationManager.AppSettings["GoogleDriveClientSecret"]
                    },
                    Scopes = Scopes,
                    DataStore = null
                });

I tried this but I don't know how to move forward after this.

Body:
It seems you are trying to generate refresh token from your C# code sample.

You could try following code snippet:

Refresh Token Example:

public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "yourClientId",
                        ClientSecret = "yourClientSecret"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });

        public override string GetUserId(Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();

        }

        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }

Note: If you have any more query on how you get ClientId, ClientSecret and Scope, please refer to this MVC Example.


来源: stackexchange

问:
Create JPEG thumb image with general fixed header
I want to create preview thumb for my photos like Facebook's preview photo. My plan:

Sender: generate a scaled thumb (with 30px max dimension) from original photo, strip out all fixed header to send.

Receiver: From the "minified" byte array, append with the fixed header (hardcode in the client code). Then convert it to Bitmap to display.

Finally I come up with the solution base on Q42.ImagePreview.

I split these parts as fixed header:

Start Of Image (0xFFD8)

App0 (start with 0xFFE0)

Define Quantization Table(s)

Define Huffman Table(s)

The dynamic parts are:

Start Of Frame (start with 0xFFC0): because it contains the width/height bytes.

Start Of Scan (start with 0xFFDA).

Compressed image data.

End Of Image (0xFFD9)

But it only works on 1 of my devices & not works on others.

So how to generate a fixed, general & standard JPEG header that can use on both Android & iOS devices?

Thank you.

More detail:

Generate minified data flow:

Create a scaled bitmap from original image (max dimension 30px, keep aspect ratio) using BitmapFactory & Matrix

Compress scaled bitmap with quality 64 using Bitmap#compress() and store in byte[] thumbData.

Sub-array the thumbData above from 0xFFDA to the end. (SOS, image data & EOI) and store in byte[] body.

Prepend with the 4 bytes that repsent width & height to body, convert to Base64 string & send.

In the device that working fine, the size of thumbData is longer than others devices that not work. And the different is in Huffman Table(s), SOS & image data parts, see this:
Diff check between 2 image photos

答:
I'm afraid you cannot do that using built-in method of each platform. The problem is in the compressing phase.

There are a number of variables in JPEG compression, including the type and breakdown of scans, samples, DHT selection, and DQT selection. If any of those are different in the encoder you use, you are going to get different output. It's the nature of the beast.

For example: The Define Huffman Table (DHT) define how the "image data" (after SoS segment) was compressed. And you use fixed Huffman tables only for decoding, that’s what caused the problem.

So you may have some options to choose:

Send the full quality image (without compressing) after scaled down to max dimension 30px as preview thumb photo.

Write your own compression algorithm or use a cross-platform library.

Upload entire original image to your server to process & send back the "minified data" to Android/iOS.

Telegram has preview photo too, and their approach is similar to you. But they transfer entire original image (in byte array) to server, create a thumb photo, strip out "fixed header" and send back to the receivers the "minified data".

When receive on mobile, they decode the "minified data" to bitmap, by appending it with "fixed header" (Bitmaps.java#L111) & update image size in SoF segment. See ImageLoader.java#L750.

ContentLicense: CC BY-SA 4.0


问:
Need to JSON stringify an object in ExtendScript
I am working on processing meta data information of my Indesign document links, using ExtentdScript.

I want to convert the object to string using JSON.stringify but when I use it, I am getting error saying:

can't execute script in target engine.

If I remove linkObjStr = JSON.stringify(linksInfObj);  from below code, then everything works fine.

What is the equivalent to JSON.stringify in ExtendScript, or is there any other possibilities to display linksInfObj with its proper contents instead [object object]?

```<code>for (var i = 0, len = doc.links.length; i < len; i++) {

    var linkFilepath = File(doc.links[i].filePath).fsName;
    var linkFileName = doc.links[i].name;

    var xmpFile = new XMPFile(linkFilepath, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_READ);
    var allXMP = xmpFile.getXMP();

    // Retrieve values from external links XMP.
    var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
    var instanceID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);
    linksInfObj[linkFileName] = {'docId': documentID, 'insId': instanceID};
    linkObjStr = JSON.stringify(linksInfObj);

    alert('Object' + linksInfObj, true); // I am getting [Object Object] here
    alert('String' + linkObjStr, true);

}
</code>```

答:
ExtendScript does not include a JSON object with the associated methods for parsing, namely JSON.parse() and JSON.stringify(). Nor does it provide any other builtin feature for parsing JSON.

Solution:

Consider utilizing a polyfill to provide JSON functionality such as JSON-js created by Douglas Crockford.

What you'll need to do:

Download the JavaScript file named json2.js from the Github repo and save it in the same location/folder as your .jsx file.

Note You can just copy and paste the raw version of json2.js from the same Github repo to create the json2.js file manually if you prefer.

Then at the top of your current .jsx file you'll need to #include the json2.js file by adding the following line of code:

 #include "json2.js";
```
<p>This is analogous to how you might utilize the <code>import</code> statement to include a module in modern day JavaScript (ES6).</p>
<p>A <em>pathname</em> to the location of the <code>json2.js</code> can be provided if you decide to save the file in a different location/folder than your <code>.jsx</code> file.</p>
</li>
<li><p>By including <code>json2.js</code> in your <code>.jsx</code> file you'll now have working JSON methods; <code>JSON.parse()</code> and <code>JSON.stringify()</code>.</p>
</li>
</ol>
<hr />
<h2>Example:</h2>
<p>The following ExtendScript (<code>.jsx</code>) is a working example that generates JSON to indicate all the links associated with the current InDesign document (<code>.indd</code>).</p>
<p><strong>example.jsx</strong></p>
```#include "json2.js";

$.level=0;

var doc = app.activeDocument;

/**
 * Loads the AdobeXMPScript library.
 * @returns {Boolean} True if the library loaded successfully, otherwise false.
 */
function loadXMPLibrary() {
  if (!ExternalObject.AdobeXMPScript) {
    try {
      ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
    } catch (e) {
      alert('Failed loading AdobeXMPScript library\n' + e.message, 'Error', true);
      return false;
    }
  }
  return true;
}

/**
 * Obtains the values f XMP properties for `DocumentID` and `instanceID` in
 * each linked file associated with an InDesign document (.indd). A returns the
 * information formatted as JSON,
 * @param {Object} doc - A reference to the .indd to check.
 * @returns {String} - The information formatted as JSON.
 */
function getLinksInfoAsJson(doc) {
  var linksInfObj = {};

  linksInfObj['indd-name'] = doc.name;
  linksInfObj.location = doc.filePath.fsName;
  linksInfObj.links = [];

  for (var i = 0, len = doc.links.length; i < len; i++) {
    var linkFilepath = File(doc.links[i].filePath).fsName;
    var linkFileName = doc.links[i].name;

    var xmpFile = new XMPFile(linkFilepath, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_READ);
    var allXMP = xmpFile.getXMP();

    // Retrieve values from external links XMP.
    var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
    var instanceID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);

    // Ensure we produce valid JSON...
    // - When `instanceID` or `documentID` values equal `undefined` change to `null`.
    // - When `instanceID` or `documentID` exist ensure it's a String.
    instanceID = instanceID ? String(instanceID) : null;
    documentID = documentID ? String(documentID) : null;

    linksInfObj.links.push({
      'name': linkFileName,
      'path': linkFilepath,
      'docId': documentID,
      'insId': instanceID
    });
  }

  return JSON.stringify(linksInfObj, null, 2);
}

if (loadXMPLibrary()) {
 var linksJson = getLinksInfoAsJson(doc);
 $.writeln(linksJson);
}
```
<p><strong>Output:</strong></p>
<p>Running the script above will log JSON formatted something like the following example to your console:</p>
<pre class="lang-json prettyprint-override"><code>{
  "indd-name": "foobar.indd",
  "location": "/path/to/the/document",
  "links":[
    {
      "name": "one.psd",
      "path": "/path/to/the/document/links/one.psd",
      "docId": "5E3AE91C0E2AD0A57A0318E078A125D6",
      "insId": "xmp.iid:0480117407206811AFFD9EEDCD311C32"
    },
    {
      "name": "two.jpg",
      "path": "/path/to/the/document/links/two.jpg",
      "docId": "EDC4CCF902ED087F654B6AB54C57A833",
      "insId": "xmp.iid:FE7F117407206811A61394AAF02B0DD6"
    },
    {
      "name": "three.png",
      "path": "/path/to/the/document/links/three.png",
      "docId": null,
      "insId": null
    }
  ]
}
</code>```

Sidenote: Modelling your JSON:

You'll have noticed that the JSON output (above) is structured differently to how you were attempting to structure it in your given example. The main difference is that you were using link filenames as property/key names, such as the following example:

Example of a problematic JSON structure

{
  "one.psd": {
    "docId": "5E3AE91C0E2AD0A57A0318E078A125D6",
    "insId": "xmp.iid:0480117407206811AFFD9EEDCD311C32"
  },
  "two.jpg": {
    "docId": "EDC4CCF902ED087F654B6AB54C57A833",
    "insId": "xmp.iid:FE7F117407206811A61394AAF02B0DD6"
  }
  ...
}
```
<p>Producing JSON like this example isn't ideal because if you were to have two links, both with the same name, you would only ever report one of them. You cannot have two properties/keys that have the same name within an Object.</p>
<hr />
<p><strong>Edit:</strong></p>
<p>As a response to the OP's comment:</p>
<blockquote>
<p><em>Hi RobC, other than using <code>#include 'json2.js'</code>, is there any other way to include external js file in the JSX file?</em></p>
</blockquote>
<p>There are a couple of alternative ways as follows:</p>
<ol>
<li><p>You could utilize <code>$.evalFile()</code>. For instance replace <code>#include "json2.js";</code> with the following two lines:</p>
 <pre class="lang-js prettyprint-override"><code> var json2 = File($.fileName).path + "/" + "json2.js";
 $.evalFile(json2);
</code>```

Note: This example assumes json2.js resides in the same folder as your .jsx

Alternatively, if you're wanting to avoid the existence of the additional json2.js file completely. You could add a IIFE (Immediately Invoked Function Expression) at the top of your .jsx file. Then copy and paste the content of the json2.js file into it. For instance:

 (function () {
     // <-- Paste the content of `json2.js` here.
 })();
```

Note: If code size is a concern then consider minifying the content of json2.js before pasting it into the IIFE.

Body:
I am working on processing meta data information of my Indesign document links, using ExtentdScript.

I want to convert the object to string using JSON.stringify but when I use it, I am getting error saying:

can't execute script in target engine.

If I remove linkObjStr = JSON.stringify(linksInfObj);  from below code, then everything works fine.

What is the equivalent to JSON.stringify in ExtendScript, or is there any other possibilities to display linksInfObj with its proper contents instead [object object]?

for (var i = 0, len = doc.links.length; i < len; i++) {

    var linkFilepath = File(doc.links[i].filePath).fsName;
    var linkFileName = doc.links[i].name;

    var xmpFile = new XMPFile(linkFilepath, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_READ);
    var allXMP = xmpFile.getXMP();

    // Retrieve values from external links XMP.
    var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
    var instanceID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);
    linksInfObj[linkFileName] = {'docId': documentID, 'insId': instanceID};
    linkObjStr = JSON.stringify(linksInfObj);

    alert('Object' + linksInfObj, true); // I am getting [Object Object] here
    alert('String' + linkObjStr, true);

}

Body:
ExtendScript does not include a JSON object with the associated methods for parsing, namely JSON.parse() and JSON.stringify(). Nor does it provide any other builtin feature for parsing JSON.

Solution:

Consider utilizing a polyfill to provide JSON functionality such as JSON-js created by Douglas Crockford.

What you'll need to do:

Download the JavaScript file named json2.js from the Github repo and save it in the same location/folder as your .jsx file.

Note You can just copy and paste the raw version of json2.js from the same Github repo to create the json2.js file manually if you prefer.

Then at the top of your current .jsx file you'll need to #include the json2.js file by adding the following line of code:

 #include "json2.js";

This is analogous to how you might utilize the import statement to include a module in modern day JavaScript (ES6).

A pathname to the location of the json2.js can be provided if you decide to save the file in a different location/folder than your .jsx file.

By including json2.js in your .jsx file you'll now have working JSON methods; JSON.parse() and JSON.stringify().

Example:

The following ExtendScript (.jsx) is a working example that generates JSON to indicate all the links associated with the current InDesign document (.indd).

example.jsx

#include "json2.js";

$.level=0;

var doc = app.activeDocument;

/**
 * Loads the AdobeXMPScript library.
 * @returns {Boolean} True if the library loaded successfully, otherwise false.
 */
function loadXMPLibrary() {
  if (!ExternalObject.AdobeXMPScript) {
    try {
      ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
    } catch (e) {
      alert('Failed loading AdobeXMPScript library\n' + e.message, 'Error', true);
      return false;
    }
  }
  return true;
}

/**
 * Obtains the values f XMP properties for `DocumentID` and `instanceID` in
 * each linked file associated with an InDesign document (.indd). A returns the
 * information formatted as JSON,
 * @param {Object} doc - A reference to the .indd to check.
 * @returns {String} - The information formatted as JSON.
 */
function getLinksInfoAsJson(doc) {
  var linksInfObj = {};

  linksInfObj['indd-name'] = doc.name;
  linksInfObj.location = doc.filePath.fsName;
  linksInfObj.links = [];

  for (var i = 0, len = doc.links.length; i < len; i++) {
    var linkFilepath = File(doc.links[i].filePath).fsName;
    var linkFileName = doc.links[i].name;

    var xmpFile = new XMPFile(linkFilepath, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_READ);
    var allXMP = xmpFile.getXMP();

    // Retrieve values from external links XMP.
    var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
    var instanceID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);

    // Ensure we produce valid JSON...
    // - When `instanceID` or `documentID` values equal `undefined` change to `null`.
    // - When `instanceID` or `documentID` exist ensure it's a String.
    instanceID = instanceID ? String(instanceID) : null;
    documentID = documentID ? String(documentID) : null;

    linksInfObj.links.push({
      'name': linkFileName,
      'path': linkFilepath,
      'docId': documentID,
      'insId': instanceID
    });
  }

  return JSON.stringify(linksInfObj, null, 2);
}

if (loadXMPLibrary()) {
 var linksJson = getLinksInfoAsJson(doc);
 $.writeln(linksJson);
}

Output:

Running the script above will log JSON formatted something like the following example to your console:

{
  "indd-name": "foobar.indd",
  "location": "/path/to/the/document",
  "links":[
    {
      "name": "one.psd",
      "path": "/path/to/the/document/links/one.psd",
      "docId": "5E3AE91C0E2AD0A57A0318E078A125D6",
      "insId": "xmp.iid:0480117407206811AFFD9EEDCD311C32"
    },
    {
      "name": "two.jpg",
      "path": "/path/to/the/document/links/two.jpg",
      "docId": "EDC4CCF902ED087F654B6AB54C57A833",
      "insId": "xmp.iid:FE7F117407206811A61394AAF02B0DD6"
    },
    {
      "name": "three.png",
      "path": "/path/to/the/document/links/three.png",
      "docId": null,
      "insId": null
    }
  ]
}

Sidenote: Modelling your JSON:

You'll have noticed that the JSON output (above) is structured differently to how you were attempting to structure it in your given example. The main difference is that you were using link filenames as property/key names, such as the following example:

Example of a problematic JSON structure

{
  "one.psd": {
    "docId": "5E3AE91C0E2AD0A57A0318E078A125D6",
    "insId": "xmp.iid:0480117407206811AFFD9EEDCD311C32"
  },
  "two.jpg": {
    "docId": "EDC4CCF902ED087F654B6AB54C57A833",
    "insId": "xmp.iid:FE7F117407206811A61394AAF02B0DD6"
  }
  ...
}

Producing JSON like this example isn't ideal because if you were to have two links, both with the same name, you would only ever report one of them. You cannot have two properties/keys that have the same name within an Object.

Edit:

As a response to the OP's comment:

Hi RobC, other than using #include 'json2.js', is there any other way to include external js file in the JSX file?

There are a couple of alternative ways as follows:

You could utilize $.evalFile(). For instance replace #include "json2.js"; with the following two lines:

 var json2 = File($.fileName).path + "/" + "json2.js";
 $.evalFile(json2);

Note: This example assumes json2.js resides in the same folder as your .jsx

Alternatively, if you're wanting to avoid the existence of the additional json2.js file completely. You could add a IIFE (Immediately Invoked Function Expression) at the top of your .jsx file. Then copy and paste the content of the json2.js file into it. For instance:

 (function () {
     // <-- Paste the content of `json2.js` here.
 })();

Note: If code size is a concern then consider minifying the content of json2.js before pasting it into the IIFE.


问:
docker container failed to start when mapping volume
When I run this command to run docker(Docker version 18.09.6, build 481bc77156):

```<code>sudo docker run -p 18084:8070 -v /opt/dabai/app/config-center/docker-apollo/apollo-portal/target/apollo-portal-1.4.0-github:/apollo-portal:rw apollo-portal
</code>```

The output is:

```<code>[daai@iZ3refzweg1d9dh94t9Z ~]$ sudo docker run -p 18084:8070 -v /opt/dabai/app/config-center/docker-apollo/apollo-portal/target/apollo-portal-1.4.0-github:/apollo-portal:rw apollo-portal
Fri May 31 07:59:06 UTC 2019 ==== Starting ====
Failed to start
Fri May 31 07:59:16 UTC 2019 Failed to start apollo-portal.jar, return code: 1
</code>```

I use this command to check the docker's log:

```<code>docker logs ce518631ced
</code>```

the output is the same.How do i detect where is the problem is? By the way, when I remove the volume mapping, the container starts up successfully.

答:
Copy container files to local machine to replace old mapping folder could solve this problem.

```<code>docker cp 12ba0764beff:/apollo-portal /opt/dabai/app/docker/apollo/apollo-portal
</code>```

12ba0764beff is the container id.start docker with mapping:

```<code>sudo docker run -p 18084:8070 -v /apollo-portal /opt/dabai/app/docker/apollo/apollo-portal:/apollo-portal:rw apollo-portal
</code>```

Body:
When I run this command to run docker(Docker version 18.09.6, build 481bc77156):

sudo docker run -p 18084:8070 -v /opt/dabai/app/config-center/docker-apollo/apollo-portal/target/apollo-portal-1.4.0-github:/apollo-portal:rw apollo-portal

The output is:

[daai@iZ3refzweg1d9dh94t9Z ~]$ sudo docker run -p 18084:8070 -v /opt/dabai/app/config-center/docker-apollo/apollo-portal/target/apollo-portal-1.4.0-github:/apollo-portal:rw apollo-portal
Fri May 31 07:59:06 UTC 2019 ==== Starting ====
Failed to start
Fri May 31 07:59:16 UTC 2019 Failed to start apollo-portal.jar, return code: 1

I use this command to check the docker's log:

docker logs ce518631ced

the output is the same.How do i detect where is the problem is? By the way, when I remove the volume mapping, the container starts up successfully.

Body:
Copy container files to local machine to replace old mapping folder could solve this problem.

docker cp 12ba0764beff:/apollo-portal /opt/dabai/app/docker/apollo/apollo-portal

12ba0764beff is the container id.start docker with mapping:

sudo docker run -p 18084:8070 -v /apollo-portal /opt/dabai/app/docker/apollo/apollo-portal:/apollo-portal:rw apollo-portal


问:
Calling an Oracle function in mule 4
How do I get the return value from an Oracle funtion with named parameters?

I am using

```<code><db:stored-procedure doc:name="Stored procedure" doc:id="607a27d0-0738-406b-900d-9490e3026c9a" config-ref="Database_Config">
        <db:sql >:result = call ib_gate.Listen_New(:i_Command,:i_Client_Id,:i_Params,:o_Err_Code,:o_Err_Msg)</db:sql>
        <db:input-parameters ><![CDATA[#[{'i_Command' : 'GET_DATA','i_Client_Id' : -1,'i_Params' : 'ID:386075'}]]]>
        </db:input-parameters>
        <db:output-parameters>
            <db:output-parameter key="result" type="VARCHAR"/>
            <db:output-parameter key="o_Err_Code" type="VARCHAR"/>
            <db:output-parameter key="o_Err_Msg" type="VARCHAR"/>
        </db:output-parameters>
</db:stored-procedure>
</code>```

but this return an error ORA-00900: invalid SQL statement

答:
It was necessary to use brackets ({}) here:</p>

```<code><db:sql>{:result = call ib_gate.Listen_New(:i_Command,:i_Client_Id,:i_Params,:o_Err_Code,:o_Err_Msg)}</db:sql>
</code>```

Title: Calling an Oracle function in mule 4

Body:
How do I get the return value from an Oracle funtion with named parameters?

I am using

<db:stored-procedure doc:name="Stored procedure" doc:id="607a27d0-0738-406b-900d-9490e3026c9a" config-ref="Database_Config">
        <db:sql >:result = call ib_gate.Listen_New(:i_Command,:i_Client_Id,:i_Params,:o_Err_Code,:o_Err_Msg)</db:sql>
        <db:input-parameters ><![CDATA[#[{'i_Command' : 'GET_DATA','i_Client_Id' : -1,'i_Params' : 'ID:386075'}]]]>
        </db:input-parameters>
        <db:output-parameters>
            <db:output-parameter key="result" type="VARCHAR"/>
            <db:output-parameter key="o_Err_Code" type="VARCHAR"/>
            <db:output-parameter key="o_Err_Msg" type="VARCHAR"/>
        </db:output-parameters>
</db:stored-procedure>

but this return an error ORA-00900: invalid SQL statement

Body:
It was necessary to use brackets ({}) here:

<db:sql>{:result = call ib_gate.Listen_New(:i_Command,:i_Client_Id,:i_Params,:o_Err_Code,:o_Err_Msg)}</db:sql>


问:
No xdebug in phpinfo()
I have added following lines into php.ini

```<code>[XDebug]
zend_extension = C:\PROGRA~1\PHP5\ext\php_xdebug-2.1.0-5.3-vc9.dll
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000
</code>```

Version of php_xdebug-2.1.0-5.3-vc9.dll is obtained via page http://www.xdebug.org/find-binary.php.

But there are no any mentions of 'xdebug' string in output of phpinfo().

What can be wrong?

(This is my second fight with php-xdebug to get working,  first time I gave up. If you have other suggestions concerning debugging please add them also, possibly as comments to the question. I would like to following scenario work under windows: "Set up break point, run my script, it stops on break point and I can see the value of some variable". Thanks)

UPDATE

Restart of Apache does not resolve the issue.
In log file the message appears:

Apache/2.2.14 (Win32) PHP/5.3.1 configured - resuming normal operations

答:
Just for the newbees:

If you want to check if the .dll, specified in the php.ini is loading properly:

Add php to the Windows Runtime Directory. For win10, refer to this post https://www.forevolve.com/en/articles/2016/10/27/how-to-add-your-php-runtime-directory-to-your-windows-10-path-environment-variable/

From the Windows command prompt, type php -m and check if any error is displayed.

ContentLicense: CC BY-SA 2.5

Title: No xdebug in phpinfo()

Body:
I have added following lines into php.ini

[XDebug]
zend_extension = C:\PROGRA~1\PHP5\ext\php_xdebug-2.1.0-5.3-vc9.dll
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000

Version of php_xdebug-2.1.0-5.3-vc9.dll is obtained via page http://www.xdebug.org/find-binary.php.

But there are no any mentions of 'xdebug' string in output of phpinfo().

What can be wrong?

(This is my second fight with php-xdebug to get working,  first time I gave up. If you have other suggestions concerning debugging please add them also, possibly as comments to the question. I would like to following scenario work under windows: "Set up break point, run my script, it stops on break point and I can see the value of some variable". Thanks)

UPDATE

Restart of Apache does not resolve the issue.
In log file the message appears:

Apache/2.2.14 (Win32) PHP/5.3.1 configured - resuming normal operations


问:
Using std::set's .begin() and .end() function produces unexpected results
I have the following simple program:

```<code>#include <iostream>
#include <set>
using namespace std;

int main()
{
    unsigned int qwer = 6132;
    unsigned int ty = 3512;
    unsigned int vv = 4331;
    unsigned int gg = 1337;
    set<unsigned int> asdf = {};
    asdf.insert(qwer);
    asdf.insert(ty);
    asdf.insert(vv);
    asdf.insert(gg);
    cout << "&asdf.begin() = " << &asdf.begin();
    unsigned int setint = *asdf.begin();
    cout << "\nsetint = " << setint;
    setint = *asdf.end();
    cout << "\nsetint = " << setint;
    cout << "\n&asdf.end() = " << &asdf.end();
    return 0;
}
</code>```

It produces this output:

&asdf.begin() = 0x22fe08
setint = 1337
setint = 4
&asdf.end() = 0x22fe08
```

Why does the address of asdf.begin() and asdf.end() match? I'd assume they'd have distinct addresses pointing to distinct values? And although their addresses do match, the values pointed to do not! Why is this?

EDIT: Also why does setint = asdf.end() appear to set setint's value to the amount of elements in the set rather than the last value in the set? (I'm assuming it should be 6132 right?)

答:
You have lots of undefined behaviour.

```<code>&asdf.begin()
&asdf.end()
</code>```

You are taking the address of prvalue. & can only be applied to lvalues and qualified-ids (things with names)

```<code>*asdf.end()
</code>```

The end iterator is not dereferencable. It points to the "one-past-the-end" position.

Body:
I have the following simple program:

#include <iostream>
#include <set>
using namespace std;

int main()
{
    unsigned int qwer = 6132;
    unsigned int ty = 3512;
    unsigned int vv = 4331;
    unsigned int gg = 1337;
    set<unsigned int> asdf = {};
    asdf.insert(qwer);
    asdf.insert(ty);
    asdf.insert(vv);
    asdf.insert(gg);
    cout << "&asdf.begin() = " << &asdf.begin();
    unsigned int setint = *asdf.begin();
    cout << "\nsetint = " << setint;
    setint = *asdf.end();
    cout << "\nsetint = " << setint;
    cout << "\n&asdf.end() = " << &asdf.end();
    return 0;
}

It produces this output:

&asdf.begin() = 0x22fe08
setint = 1337
setint = 4
&asdf.end() = 0x22fe08

Why does the address of asdf.begin() and asdf.end() match? I'd assume they'd have distinct addresses pointing to distinct values? And although their addresses do match, the values pointed to do not! Why is this?

EDIT: Also why does setint = asdf.end() appear to set setint's value to the amount of elements in the set rather than the last value in the set? (I'm assuming it should be 6132 right?)

Body:
You have lots of undefined behaviour.

&asdf.begin()
&asdf.end()

You are taking the address of prvalue. & can only be applied to lvalues and qualified-ids (things with names)

*asdf.end()

The end iterator is not dereferencable. It points to the "one-past-the-end" position.


问:
Big discrepancy between Analytics API/Query Explorer and Interface
I've been trying to use the Analytics API to get site search terms into a Google Ads script. I've used this basic setup before and it worked perfectly, but the data this time doesn't match what's in the interface by a long shot. I've also tried using the query explorer but that's also giving me very different numbers to what's in the interface (by almost a factor of 10).

I've checked and double checked that the metrics and dimensions I'm using are correct, but there really aren't that many options. Does anyone know what I'm doing wrong?

Here's the code I've been using:

```<code>  // Build the query for the Analytics API
  var query = {
    "optionalArgs": { "dimensions": "ga:searchKeyword", },
    "ids": "ga:" + analyticsView,
    "metrics": "ga:searchUniques",
    "start-date": startDate,
    "end-date": "yesterday" };
  var results = Analytics.Data.Ga.get(query.ids, query['start-date'], query['end-date'], query.metrics, query.optionalArgs);

  // Format the results for Javascript
  var formattedJson = JSON.stringify(results, null, 2);
  var jsonData = JSON.parse(formattedJson);

  // Iterate through the results
  for (var i = 0; i < jsonData.rows.length; i++) {
    var row = jsonData.rows[i];
    var searchTerm = row[0];
    var sessions = row[1];
</code>```

I've tried with ga:sessions instead of searchUniques and a few other combinations of metrics and dimensions but nothing works and based on the documentation the ones I have in the code really seem to me to be the right ones!

答: In case anyone else gets stuck here, my issue was simply that I was limited to a maximum of 10,000 entities returned, and since I wasn't sorting them I was getting 10,000 random ones back and not what I expected. As soon as I sorted them descending by what I needed I got exactly what I expected!</p>

Body:
I've been trying to use the Analytics API to get site search terms into a Google Ads script. I've used this basic setup before and it worked perfectly, but the data this time doesn't match what's in the interface by a long shot. I've also tried using the query explorer but that's also giving me very different numbers to what's in the interface (by almost a factor of 10).

I've checked and double checked that the metrics and dimensions I'm using are correct, but there really aren't that many options. Does anyone know what I'm doing wrong?

Here's the code I've been using:

  // Build the query for the Analytics API
  var query = {
    "optionalArgs": { "dimensions": "ga:searchKeyword", },
    "ids": "ga:" + analyticsView,
    "metrics": "ga:searchUniques",
    "start-date": startDate,
    "end-date": "yesterday" };
  var results = Analytics.Data.Ga.get(query.ids, query['start-date'], query['end-date'], query.metrics, query.optionalArgs);

  // Format the results for Javascript
  var formattedJson = JSON.stringify(results, null, 2);
  var jsonData = JSON.parse(formattedJson);

  // Iterate through the results
  for (var i = 0; i < jsonData.rows.length; i++) {
    var row = jsonData.rows[i];
    var searchTerm = row[0];
    var sessions = row[1];

I've tried with ga:sessions instead of searchUniques and a few other combinations of metrics and dimensions but nothing works and based on the documentation the ones I have in the code really seem to me to be the right ones!


问:
jQuerymobile button is only clickable/triggered once!
Hey!
I'm using jquerymobile Alpha 4.1 together with asp.net mvc3.

My situation:
I have two buttons in the footer with the url /booking/index/1 and /booking/index/-1.
They are used to step forward & backward (increasing / decreasing the date on serverside).

After clicking for example the next button, with url /booking/index/1, i step forward. Clicking it again does nothing, instead of stepping to the next date.

But now, if i click on the other button, with url /booking/index/-1, it steps back to the previouse day as expected. Although only once.

It loads the next day with "normal jqm ajax". I think it might be some history/"i am already on that page" problem?

Does anyone know how to solve this?

答:
Related:

AJAX Request Help for next/previous page

Multiple AJAX requests functions combined into one?

JQM (jQueryMobile) Dynamically added elements not displaying correctly and CSS is not applied

had the same issue

ContentLicense: CC BY-SA 3.0


问:
Spark find consecutive timeframes
I want to find continues timestamps in a really big dataset. This needs to be done in Spark using Java (code examples in Scala are also very welcome).

Each row looks like the following:

ID, startTime, endTime

For example the dataset:

[[1, 10, 15],[1, 15, 20], [2, 10, 13], [1, 22, 33], [2, 13, 16]]

The expected outcome are all continous time frames for the same id, with for each continous time frame only the start and ending time:

[[1, 10, 20],[1, 22, 33], [2, 10, 16]]

I already tried the following, but that doesn't work out because the order is not maintained. Thereby I would expect that there is a more efficient way to do this

```<code>textFile.mapToPair(x -> new Tuple2<>(x[0],new Tuple2<>(x[1], x[2])
    .mapValues(x -> new LinkedList<>(Arrays.asList(x)))
    .reduceByKey((x,y) -> {
         Tuple2<Long, Long> v1 = x.getLast();
         Tuple2<Long, Long> v2 = y.getFirst();
         Tuple2<Long, Long> v3 = v2;
         if(v2._1().equals(v1._2())) {
              v3 = new Tuple2<>(v1._1(), v2._2());
              x.removeLast();
         }
         x.addLast(v3);
         return x;
    })
    .flatMapValues(x -> x);
</code>```

答:
I think this is not a Spark problem, but the logical one.
You should consider the option of using several standalone functions:

to bind two intervals together (let's name it bindEntries())

to add new interval into the interval accumulator of intervals (let it be insertEntry())

Suggesting, we have mock data mockData:

```<code>+---+-----+---+
| id|start|end|
+---+-----+---+
|  1|   22| 33|
|  1|   15| 20|
|  1|   10| 15|
|  2|   13| 16|
|  2|   10| 13|
+---+-----+---+
</code>```

With the help of these functions, my solution to your problem will be like this:

val processed = mockData
      .groupByKey(_.id)
      .flatMapGroups { (id: Int, it: Iterator[Entry]) =>
        processEntries(it)
      }
```

<p>The only goal of <code>processEntries()</code> is to fold all the entries for each id into the collection of non-intersecting intervals.
Here is it's signature:</p>

<pre class="lang-scala prettyprint-override"><code>def processEntries(it: Iterator[Entry]): List[Entry] =
    it.foldLeft(Nil: List[Entry])(insertEntry)
</code>```

This function is used to get elements from your grouped entries one by one and push them into the accumulator, one by one as well.

Function insertEntry() handling this kind of insertion:

def insertEntry(acc: List[Entry], e: Entry): List[Entry] = acc match {
  case Nil => e :: Nil
  case a :: as =>
    val combined = bindEntries(a, e)
    combined match {
      case x :: y :: Nil => x :: insertEntry(as, y)
      case x :: Nil => insertEntry(as, x)
      case _ => a :: as
    }
}
```

<p>The <code>bindEntries()</code> function should handle the order of entries for you:</p>

<pre class="lang-scala prettyprint-override"><code>def bindEntries(x: Entry, y: Entry): List[Entry] =
  (x.start > y.end, x.end < y.start) match {
    case (true, _) => y :: x :: Nil
    case (_, true) => x :: y :: Nil
    case _ => x.copy(start = x.start min y.start, end = x.end max y.end) :: Nil
  }
</code>```

bindEntries() will return the list of one or two entries properly sorted.
This is the idea behind it:

insertEntry() will sort all the entries for you during insertion.

After all, the resulting dataset looks like this:

```<code>+---+-----+---+
| id|start|end|
+---+-----+---+
|  1|   10| 20|
|  1|   22| 33|
|  2|   10| 16|
+---+-----+---+
</code>```

Note: Function insertEntry() is not tail-recursive.
There is a good starting point for further optimisations.

And there is the complete solution:

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.{Dataset, Encoder, Encoders, SparkSession}

object AdHoc {

  Logger.getLogger("org").setLevel(Level.OFF)

  def main(args: Array[String]): Unit = {
    import spark.implicits._

    val processed = mockData
      .groupByKey(_.id)
      .flatMapGroups { (id, it) =>
        processEntries(it)
      }

    mockData.show()
    processed.show()
  }

  def processEntries(it: Iterator[Entry]): List[Entry] =
    it.foldLeft(Nil: List[Entry])(insertEntry)

  def insertEntry(acc: List[Entry], e: Entry): List[Entry] = acc match {
    case Nil => e :: Nil
    case a :: as =>
      val combined = bindEntries(a, e)
      combined match {
        case x :: y :: Nil => x :: insertEntry(as, y)
        case x :: Nil => insertEntry(as, x)
        case _ => a :: as
      }
  }

  def bindEntries(x: Entry, y: Entry): List[Entry] =
    (x.start > y.end, x.end < y.start) match {
      case (true, _) => y :: x :: Nil
      case (_, true) => x :: y :: Nil
      case _ => x.copy(start = x.start min y.start, end = x.end max y.end) :: Nil
    }

  lazy val mockData: Dataset[Entry] = spark.createDataset(Seq(
    Entry(1, 22, 33),
    Entry(1, 15, 20),
    Entry(1, 10, 15),
    Entry(2, 13, 16),
    Entry(2, 10, 13)
  ))

  case class Entry(id: Int, start: Int, end: Int)

  implicit lazy val entryEncoder: Encoder[Entry] = Encoders.product[Entry]

  lazy val spark: SparkSession = SparkSession.builder()
    .master("local")
    .getOrCreate()
}
```

Title: Spark find consecutive timeframes

Body:
I want to find continues timestamps in a really big dataset. This needs to be done in Spark using Java (code examples in Scala are also very welcome).

Each row looks like the following:

ID, startTime, endTime

For example the dataset:

[[1, 10, 15],[1, 15, 20], [2, 10, 13], [1, 22, 33], [2, 13, 16]]

The expected outcome are all continous time frames for the same id, with for each continous time frame only the start and ending time:

[[1, 10, 20],[1, 22, 33], [2, 10, 16]]

I already tried the following, but that doesn't work out because the order is not maintained. Thereby I would expect that there is a more efficient way to do this

textFile.mapToPair(x -> new Tuple2<>(x[0],new Tuple2<>(x[1], x[2])
    .mapValues(x -> new LinkedList<>(Arrays.asList(x)))
    .reduceByKey((x,y) -> {
         Tuple2<Long, Long> v1 = x.getLast();
         Tuple2<Long, Long> v2 = y.getFirst();
         Tuple2<Long, Long> v3 = v2;
         if(v2._1().equals(v1._2())) {
              v3 = new Tuple2<>(v1._1(), v2._2());
              x.removeLast();
         }
         x.addLast(v3);
         return x;
    })
    .flatMapValues(x -> x);

Body:
I think this is not a Spark problem, but the logical one.
You should consider the option of using several standalone functions:

to bind two intervals together (let's name it bindEntries())

to add new interval into the interval accumulator of intervals (let it be insertEntry())

Suggesting, we have mock data mockData:

+---+-----+---+
| id|start|end|
+---+-----+---+
|  1|   22| 33|
|  1|   15| 20|
|  1|   10| 15|
|  2|   13| 16|
|  2|   10| 13|
+---+-----+---+

With the help of these functions, my solution to your problem will be like this:

val processed = mockData
      .groupByKey(_.id)
      .flatMapGroups { (id: Int, it: Iterator[Entry]) =>
        processEntries(it)
      }

The only goal of processEntries() is to fold all the entries for each id into the collection of non-intersecting intervals.
Here is it's signature:

def processEntries(it: Iterator[Entry]): List[Entry] =
    it.foldLeft(Nil: List[Entry])(insertEntry)

This function is used to get elements from your grouped entries one by one and push them into the accumulator, one by one as well.

Function insertEntry() handling this kind of insertion:

def insertEntry(acc: List[Entry], e: Entry): List[Entry] = acc match {
  case Nil => e :: Nil
  case a :: as =>
    val combined = bindEntries(a, e)
    combined match {
      case x :: y :: Nil => x :: insertEntry(as, y)
      case x :: Nil => insertEntry(as, x)
      case _ => a :: as
    }
}

The bindEntries() function should handle the order of entries for you:

def bindEntries(x: Entry, y: Entry): List[Entry] =
  (x.start > y.end, x.end < y.start) match {
    case (true, _) => y :: x :: Nil
    case (_, true) => x :: y :: Nil
    case _ => x.copy(start = x.start min y.start, end = x.end max y.end) :: Nil
  }

bindEntries() will return the list of one or two entries properly sorted.
This is the idea behind it:

insertEntry() will sort all the entries for you during insertion.

After all, the resulting dataset looks like this:

+---+-----+---+
| id|start|end|
+---+-----+---+
|  1|   10| 20|
|  1|   22| 33|
|  2|   10| 16|
+---+-----+---+

Note: Function insertEntry() is not tail-recursive.
There is a good starting point for further optimisations.

And there is the complete solution:

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.{Dataset, Encoder, Encoders, SparkSession}

object AdHoc {

  Logger.getLogger("org").setLevel(Level.OFF)

  def main(args: Array[String]): Unit = {
    import spark.implicits._

    val processed = mockData
      .groupByKey(_.id)
      .flatMapGroups { (id, it) =>
        processEntries(it)
      }

    mockData.show()
    processed.show()
  }

  def processEntries(it: Iterator[Entry]): List[Entry] =
    it.foldLeft(Nil: List[Entry])(insertEntry)

  def insertEntry(acc: List[Entry], e: Entry): List[Entry] = acc match {
    case Nil => e :: Nil
    case a :: as =>
      val combined = bindEntries(a, e)
      combined match {
        case x :: y :: Nil => x :: insertEntry(as, y)
        case x :: Nil => insertEntry(as, x)
        case _ => a :: as
      }
  }

  def bindEntries(x: Entry, y: Entry): List[Entry] =
    (x.start > y.end, x.end < y.start) match {
      case (true, _) => y :: x :: Nil
      case (_, true) => x :: y :: Nil
      case _ => x.copy(start = x.start min y.start, end = x.end max y.end) :: Nil
    }

  lazy val mockData: Dataset[Entry] = spark.createDataset(Seq(
    Entry(1, 22, 33),
    Entry(1, 15, 20),
    Entry(1, 10, 15),
    Entry(2, 13, 16),
    Entry(2, 10, 13)
  ))

  case class Entry(id: Int, start: Int, end: Int)

  implicit lazy val entryEncoder: Encoder[Entry] = Encoders.product[Entry]

  lazy val spark: SparkSession = SparkSession.builder()
    .master("local")
    .getOrCreate()
}


问:
Some basic questions about Smart contracts
I had a few questions regarding Smart contract:

1) Are smart contracts legal like the traditional contract worldwide?

2) I read many pros and cons of smart contract where pros weigh higher, hence why aren't they been implemented fully?

I read a lot of links but I couldn't find the right answer to my questions.

Can someone please provide me answers to the above question with valid links to refer to?

答:
First and foremost, smart contracts are a technical construct that was conceived by Nick Szabo in 2001 and published in the FirstMonday journal. I recommend you read his paper to get a better idea.

Smart contracts have however only recently been implemented in distributed systems. The advent of blockchain offered a suitable framework that allowed for decentralized execution of virtualized program code. One of the first frameworks was the Ethereum blockchain framework, which executes Solidity smart contracts in the Ethereum Virtual Machine. By now, there are many other technical methods of executing smart contracts (examples: Hyperledger Fabric uses chaincode (language-agnostic), run in Docker containers; EOS uses Web Assembly). These smart contracts are used in many decentralized applications these days and are mostly used to run services in a decentralized fashion, without a trusted third party.

They are not equivalent to legal contracts so far in any country (as far as I know). There are efforts to make smart contracts legally binding in some US states. There are also several tech companies working on integrating technical smart contracts with legal contracts. See here for an article discussing the differences between real-world law and smart contracts and what it takes for the latter to impact the former.


问:
Get visible and not hidden items with jquery
I need a to take all li elements to array. And ul and li both should be not visibility: hidden and not display: none. This is my code.

```<code>var links = $("li").is(":visible").is(":hidden");
var currentLink = links.first();

alert(currentLink.text());
</code>```

This is my list

```<code><ul>
   <li style='display: none'>Coffee</li>
   <li style='visibility: hidden'>Tea</li>
   <li>Milk</li>
</ul>
</code>```

(I need to show tea in alert and not coffee)

but I'm getting this error,

TypeError: $(...).is(...).is is not a function

答:
You can use .css("visibility") != "hidden"

```<code>$(document).ready(function(){
    $('ul li').each(function(index, item){
        if($(item).css("visibility") != "hidden"){
          console.log($(item).text())
        }
    })
})
</code>```

$(document).ready(function(){
    $('ul li').each(function(index, item){
        if($(item).css("visibility") != "hidden"){
          console.log($(item).text())
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Test visible</li>
<li style="visibility: hidden">Hidden</li>
<li>Test visible2</li>
</ul></code>```

Body:
I need a to take all li elements to array. And ul and li both should be not visibility: hidden and not display: none. This is my code.

var links = $("li").is(":visible").is(":hidden");
var currentLink = links.first();

alert(currentLink.text());

This is my list

Coffee

Tea

Milk

(I need to show tea in alert and not coffee)

but I'm getting this error,

TypeError: $(...).is(...).is is not a function

Body:
You can use .css("visibility") != "hidden"

$(document).ready(function(){
    $('ul li').each(function(index, item){
        if($(item).css("visibility") != "hidden"){
          console.log($(item).text())
        }
    })
})

$(document).ready(function(){
    $('ul li').each(function(index, item){
        if($(item).css("visibility") != "hidden"){
          console.log($(item).text())
        }
    })
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Test visible</li>
<li style="visibility: hidden">Hidden</li>
<li>Test visible2</li>
</ul>


问:
Backend return html but frontend does not redirect
I hit an api endpoint and I checked the network call responses with an html response with status code of 302. However, I don't see the redirect happening on the UI. The redirect is to another application (a different url)

```<code>export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', headers: headers, body:
      JSON.stringify(payload) })
  .then((response) => response.json());
}
</code>```

Is there something I'm missing?

答:
You should use redirect: 'follow' in the request options.

```<code>export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', redirect: 'follow', headers: headers, body:
      JSON.stringify(payload) })
}
</code>```

If you want to know the redirect url and do manual operation, you have to use redirect: 'manual'.

```<code>export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', redirect: 'manual', headers: headers, body:
      JSON.stringify(payload) })
  .then((response) => {
     const redirectUrl = response.url // new redirect url
  })

}
</code>```

Hope this helps!

Body:
I hit an api endpoint and I checked the network call responses with an html response with status code of 302. However, I don't see the redirect happening on the UI. The redirect is to another application (a different url)

export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', headers: headers, body:
      JSON.stringify(payload) })
  .then((response) => response.json());
}

Is there something I'm missing?

Body:
You should use redirect: 'follow' in the request options.

export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', redirect: 'follow', headers: headers, body:
      JSON.stringify(payload) })
}

If you want to know the redirect url and do manual operation, you have to use redirect: 'manual'.

export function callThis(payload) {
  const url = "some-path";
  const headers = getHeaders();
  return fetch(url, { method: 'POST', redirect: 'manual', headers: headers, body:
      JSON.stringify(payload) })
  .then((response) => {
     const redirectUrl = response.url // new redirect url
  })

}

Hope this helps!


问:
C# if directive
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

```<code>void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif
</code>```

答: If your asking if you can conditional compile something based upon a condition in your code the answer is no.  The complier must know at compile time what to include in your assembly.  You can almost certainly achieve what you are attempting with out conditional compilation however what are you attempting to do?</p>

Title: C# if directive

Body:
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif


问:
DataGridView Showing Empty Rows when assigned to a List of Type containing internal properties
I experienced an issue which kind of opposed my basic C# concepts on Access Modifiers. So i build a Sample application reproducing Same Scenario.

There is a Parent Form with Click Button on the event of which a new Form spawns with a DataGridView. The Data Source is static string,string and the properties are internal as i am using everything in the same project.

To my surprise, there were 5 rows made since i had 5 data items bind to that grid but were just empty Rows. Then i made the properties as public and i was able to get them. All the Rows were populated with correct Data the second Time.

Parent Form

```<code>namespace SampleApp{
public partial class Form1 : Form
{
    List<ItemModel> modelList = new List<ItemModel>();

    public Form1()
    {
        InitializeComponent();
    }

    private void btnClick_Click(object sender, EventArgs e)
    {
        LoadData();
        using (SeperateWindow window = new SeperateWindow(modelList))
        {
            window.PopulateGrid();
            if(window.ShowDialog() == DialogResult.OK)
            {

            }
        }
    }

    public void LoadData()
    {
        for(int i= 0; i < 5; i++)
        {
            ItemModel item = new ItemModel($"Name { i}", i.ToString());
            modelList.Add(item);
        }
    }
}
</code>```

Model Class

```<code>namespace SampleApp.Model{
sealed class ItemModel
{
    internal string Textvalue { get; set; }
    internal string ID { get; set; }
    internal ItemModel(string text,string id)
    {
        Textvalue = text;
        ID = id;
    }
}
</code>```

Child Form Containing GridView

```<code>namespace SampleApp.Model{
public partial class SeperateWindow : Form
{
    List<ItemModel> _modelList = new List<ItemModel>();
    internal SeperateWindow(List<ItemModel> modelList)
    {
        _modelList = modelList;
        InitializeComponent();
    }

    public void PopulateGrid()
    {
        dataGridView1.DataSource = _modelList;
    }
}
</code>```

My issue is since everything is in the same project, and model class and child form are in the same Folder too, then also why am i getting Empty Rows? Given that it is working fine if i make them public.

答:
From MSDN

The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation.

Also please refer to this question, in which the difference between public and internal keywords in databinding has been discussed.

Body:
I experienced an issue which kind of opposed my basic C# concepts on Access Modifiers. So i build a Sample application reproducing Same Scenario.

There is a Parent Form with Click Button on the event of which a new Form spawns with a DataGridView. The Data Source is static string,string and the properties are internal as i am using everything in the same project.

To my surprise, there were 5 rows made since i had 5 data items bind to that grid but were just empty Rows. Then i made the properties as public and i was able to get them. All the Rows were populated with correct Data the second Time.

Parent Form

namespace SampleApp{
public partial class Form1 : Form
{
    List<ItemModel> modelList = new List<ItemModel>();

    public Form1()
    {
        InitializeComponent();
    }

    private void btnClick_Click(object sender, EventArgs e)
    {
        LoadData();
        using (SeperateWindow window = new SeperateWindow(modelList))
        {
            window.PopulateGrid();
            if(window.ShowDialog() == DialogResult.OK)
            {

            }
        }
    }

    public void LoadData()
    {
        for(int i= 0; i < 5; i++)
        {
            ItemModel item = new ItemModel($"Name { i}", i.ToString());
            modelList.Add(item);
        }
    }
}

Model Class

namespace SampleApp.Model{
sealed class ItemModel
{
    internal string Textvalue { get; set; }
    internal string ID { get; set; }
    internal ItemModel(string text,string id)
    {
        Textvalue = text;
        ID = id;
    }
}

Child Form Containing GridView

namespace SampleApp.Model{
public partial class SeperateWindow : Form
{
    List<ItemModel> _modelList = new List<ItemModel>();
    internal SeperateWindow(List<ItemModel> modelList)
    {
        _modelList = modelList;
        InitializeComponent();
    }

    public void PopulateGrid()
    {
        dataGridView1.DataSource = _modelList;
    }
}

My issue is since everything is in the same project, and model class and child form are in the same Folder too, then also why am i getting Empty Rows? Given that it is working fine if i make them public.


问:
VisualState storyboard not activating on path 'MouseOver' state
I'm trying to change the colour of a Path control on mouseover where the path data is always changing through a data binding.  It should change from yellow to red, but There is no colour change on the path as I move my mouse over it, it remains yellow.

my view:

MainWindow.xaml

```<code><reactiveui:ReactiveWindow
    x:Class="TestWpfAnim.MainWindow"
    x:TypeArguments="local:MainViewModel"

    xmlns:reactiveui="http://reactiveui.net"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestWpfAnim"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>

    <local:PointsToPathNormalConv x:Key="MyConv" />

</Window.Resources>
<Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualStateGroup.Transitions>
                    <!--Take one half second to transition to the MouseOver state.-->
                    <VisualTransition To="MouseOver" GeneratedDuration="0:0:0.5" />
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="MyAnimatedBrush" Storyboard.TargetProperty="Color" To="Red" Duration="0:0:0.5"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    <Path
        x:Name="MainPath" StrokeThickness="4"
        Data="{Binding Poly, Converter={StaticResource MyConv}}">
        <Path.Stroke>
            <SolidColorBrush Color="Yellow" x:Name="MyAnimatedBrush" />
        </Path.Stroke>
    </Path>
</Grid>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : ReactiveWindow<MainViewModel>
{
    public MainWindow()
    {
        InitializeComponent();
        ViewModel = new MainViewModel();
        DataContext = ViewModel;

        var timer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher.CurrentDispatcher)
        {
            Interval = TimeSpan.FromSeconds(2)
        };
        int x = 100;
        int y = 100;

        timer.Tick += (o, e) =>
        {
            ViewModel.Add(x++, y++ * 2);
        };

        timer.Start();

    }
}
</code>```

The converter

```<code>[ValueConversion(typeof(IEnumerable<System.Windows.Point>), typeof(Geometry))]
public class PointsToPathNormalConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is IEnumerable<System.Windows.Point> points && points.Any())
        {
            List<LineSegment> segments = new List<LineSegment>();

            foreach (var p in points)
            {
                segments.Add(new LineSegment(p, true));
            }

            PathFigure figure = new PathFigure(points.First(), segments, false); //true if closed
            PathGeometry geometry = new PathGeometry();
            geometry.Figures.Add(figure);

            return geometry;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

my viewmodel:
MainViewModel.cs

```<code>public class MainViewModel : AbstractNotifyPropertyChanged, IDisposable
{
    public MainViewModel()
    {
        Poly = new ObservableCollection<System.Windows.Point>();
    }

    public void Add(int x, int y)
    {
        var newlist = Poly.ToList();
        newlist.Add(new System.Windows.Point(x, y));
        Poly = new ObservableCollection<System.Windows.Point>(newlist);
    }

    public void Dispose()
    {
    }
    private ObservableCollection<System.Windows.Point> _poly;

    public ObservableCollection<System.Windows.Point> Poly
    {
        get => _poly;
        set => this.SetAndRaise(ref _poly, value);
    }
}
</code>```

答:
I see my mistake was making assumptions on pre-existing visual state names based on various sources from which I had first learned about using the VisualStateManager.

Adding the following code to my View functioned as expected:

MainWindow.xaml.cs

```<code>    public void Path_MouseEnter(object sender, MouseEventArgs e)
    {
        if (sender is FrameworkElement fe)
            VisualStateManager.GoToElementState(fe, "MouseEnter", true);
    }

    public void Path_MouseLeave(object sender, MouseEventArgs e)
    {
        if (sender is FrameworkElement fe)
            VisualStateManager.GoToElementState(fe, "MouseLeave", true);
    }
</code>```

MainWindow.xaml

Move state manager code into the Path element. Specify MouseEnter and MouseLeave actions on the path which will change the state.

```<code><Path
    x:Name="MainPath" StrokeThickness="4"
    Data="{Binding Poly, Converter={StaticResource MyConv}}"
    MouseEnter="Path_MouseEnter"
    MouseLeave="Path_MouseLeave">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="MouseLeave"/>
            <VisualState x:Name="MouseEnter">
                <Storyboard>
                    <ColorAnimation Storyboard.TargetName="MyAnimatedBrush" Storyboard.TargetProperty="Color" To="Red" Duration="0:0:0.5"/>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <Path.Stroke>
        <SolidColorBrush Color="Yellow" x:Name="MyAnimatedBrush" />
    </Path.Stroke>
</Path>
</code>```

Body:
I'm trying to change the colour of a Path control on mouseover where the path data is always changing through a data binding.  It should change from yellow to red, but There is no colour change on the path as I move my mouse over it, it remains yellow.

my view:

MainWindow.xaml

<reactiveui:ReactiveWindow
    x:Class="TestWpfAnim.MainWindow"
    x:TypeArguments="local:MainViewModel"

    xmlns:reactiveui="http://reactiveui.net"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestWpfAnim"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>

    <local:PointsToPathNormalConv x:Key="MyConv" />

</Window.Resources>
<Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualStateGroup.Transitions>

                    <VisualTransition To="MouseOver" GeneratedDuration="0:0:0.5" />
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="MyAnimatedBrush" Storyboard.TargetProperty="Color" To="Red" Duration="0:0:0.5"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    <Path
        x:Name="MainPath" StrokeThickness="4"
        Data="{Binding Poly, Converter={StaticResource MyConv}}">
        <Path.Stroke>
            <SolidColorBrush Color="Yellow" x:Name="MyAnimatedBrush" />
        </Path.Stroke>
    </Path>
</Grid>

MainWindow.xaml.cs

public partial class MainWindow : ReactiveWindow<MainViewModel>
{
    public MainWindow()
    {
        InitializeComponent();
        ViewModel = new MainViewModel();
        DataContext = ViewModel;

        var timer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher.CurrentDispatcher)
        {
            Interval = TimeSpan.FromSeconds(2)
        };
        int x = 100;
        int y = 100;

        timer.Tick += (o, e) =>
        {
            ViewModel.Add(x++, y++ * 2);
        };

        timer.Start();

    }
}

The converter

[ValueConversion(typeof(IEnumerable<System.Windows.Point>), typeof(Geometry))]
public class PointsToPathNormalConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is IEnumerable<System.Windows.Point> points && points.Any())
        {
            List<LineSegment> segments = new List<LineSegment>();

            foreach (var p in points)
            {
                segments.Add(new LineSegment(p, true));
            }

            PathFigure figure = new PathFigure(points.First(), segments, false); //true if closed
            PathGeometry geometry = new PathGeometry();
            geometry.Figures.Add(figure);

            return geometry;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

my viewmodel:
MainViewModel.cs

public class MainViewModel : AbstractNotifyPropertyChanged, IDisposable
{
    public MainViewModel()
    {
        Poly = new ObservableCollection<System.Windows.Point>();
    }

    public void Add(int x, int y)
    {
        var newlist = Poly.ToList();
        newlist.Add(new System.Windows.Point(x, y));
        Poly = new ObservableCollection<System.Windows.Point>(newlist);
    }

    public void Dispose()
    {
    }
    private ObservableCollection<System.Windows.Point> _poly;

    public ObservableCollection<System.Windows.Point> Poly
    {
        get => _poly;
        set => this.SetAndRaise(ref _poly, value);
    }
}

Body:
I see my mistake was making assumptions on pre-existing visual state names based on various sources from which I had first learned about using the VisualStateManager.

Adding the following code to my View functioned as expected:

MainWindow.xaml.cs

    public void Path_MouseEnter(object sender, MouseEventArgs e)
    {
        if (sender is FrameworkElement fe)
            VisualStateManager.GoToElementState(fe, "MouseEnter", true);
    }

    public void Path_MouseLeave(object sender, MouseEventArgs e)
    {
        if (sender is FrameworkElement fe)
            VisualStateManager.GoToElementState(fe, "MouseLeave", true);
    }

MainWindow.xaml

Move state manager code into the Path element. Specify MouseEnter and MouseLeave actions on the path which will change the state.

<Path
    x:Name="MainPath" StrokeThickness="4"
    Data="{Binding Poly, Converter={StaticResource MyConv}}"
    MouseEnter="Path_MouseEnter"
    MouseLeave="Path_MouseLeave">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="MouseLeave"/>
            <VisualState x:Name="MouseEnter">
                <Storyboard>
                    <ColorAnimation Storyboard.TargetName="MyAnimatedBrush" Storyboard.TargetProperty="Color" To="Red" Duration="0:0:0.5"/>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <Path.Stroke>
        <SolidColorBrush Color="Yellow" x:Name="MyAnimatedBrush" />
    </Path.Stroke>
</Path>


问:
how to store the primary key values to the foreign key at same time of save
I am new to the laravel and trying to store the primary key values of patientid to the foreign key of patient_id in address table

```<code>$patdet = $request->patdet;

foreach ($patdet as $patdets) {
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname = $patdets['mname'];
    $pdet->lname = $patdets['lname'];
    $pdet->age = $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender = $patdets['gender'];
    $ptid = $pdet->save();
}

$addr = $request->address[0];
$address = new Address;
$address->gps_lat = $addr['gps_lat'];
$address->gps_log = $addr['gps_long'];
$address->house_no = $addr['houseno'];
$address->zipcode = $addr['zip_code'];
$address->street = $addr['street'];
$address->chowk = $addr['chowk'];
$address->city = $addr['city'];
$address->patient_id = $patid->id;
$address->save();
</code>```

I know that $ptid is a local variable and cannot be used in address table,  so how can I store it in address table?

答:
Try the following</p>

```<code>    $patArray = $request->patdet;
    $addressArray = $request->address;
    $pId = array();
    foreach($patArray as $key => $patdets){
        $pdet = new Patient();
        $pdet->fname = $patdets['fname'];
        $pdet->mname =  $patdets['mname'];
        $pdet->lname =  $patdets['lname'];
        $pdet->age   =  $patdets['age'];
        $pdet->blood_group = $patdets['bloodgroup'];
        $pdet->gender  = $patdets['gender'];
        $pdet->save();
        $pId[$key] = ($pdet->id > 0) ? $pdet->id : 0;
    }
    foreach($addressArray as $key => $addr){
        $addrss = new Address;
        $addrss->gps_lat = $addr['gps_lat'];
        $addrss->gps_log = $addr['gps_long'];
        $addrss->house_no  = $addr['houseno'];
        $addrss->zipcode    =  $addr['zip_code'];
        $addrss->street    = $addr['street'];
        $addrss->chowk  = $addr['chowk'];
        $addrss->city   = $addr['city'];
        $addrss->patient_id = array_key_exists($key ,$pId) ? $pId[$key] : 0;
        $addrss->save();
        $i++;
    }
</code>```

Body:
I am new to the laravel and trying to store the primary key values of patientid to the foreign key of patient_id in address table

$patdet = $request->patdet;

foreach ($patdet as $patdets) {
    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname = $patdets['mname'];
    $pdet->lname = $patdets['lname'];
    $pdet->age = $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender = $patdets['gender'];
    $ptid = $pdet->save();
}

$addr = $request->address[0];
$address = new Address;
$address->gps_lat = $addr['gps_lat'];
$address->gps_log = $addr['gps_long'];
$address->house_no = $addr['houseno'];
$address->zipcode = $addr['zip_code'];
$address->street = $addr['street'];
$address->chowk = $addr['chowk'];
$address->city = $addr['city'];
$address->patient_id = $patid->id;
$address->save();

I know that $ptid is a local variable and cannot be used in address table,  so how can I store it in address table?

Body:
Try the following

    $patArray = $request->patdet;
    $addressArray = $request->address;
    $pId = array();
    foreach($patArray as $key => $patdets){
        $pdet = new Patient();
        $pdet->fname = $patdets['fname'];
        $pdet->mname =  $patdets['mname'];
        $pdet->lname =  $patdets['lname'];
        $pdet->age   =  $patdets['age'];
        $pdet->blood_group = $patdets['bloodgroup'];
        $pdet->gender  = $patdets['gender'];
        $pdet->save();
        $pId[$key] = ($pdet->id > 0) ? $pdet->id : 0;
    }
    foreach($addressArray as $key => $addr){
        $addrss = new Address;
        $addrss->gps_lat = $addr['gps_lat'];
        $addrss->gps_log = $addr['gps_long'];
        $addrss->house_no  = $addr['houseno'];
        $addrss->zipcode    =  $addr['zip_code'];
        $addrss->street    = $addr['street'];
        $addrss->chowk  = $addr['chowk'];
        $addrss->city   = $addr['city'];
        $addrss->patient_id = array_key_exists($key ,$pId) ? $pId[$key] : 0;
        $addrss->save();
        $i++;
    }


问:
How to call function from specific referenced DLL
I need to call a specific function from Castle.Core.dll but it seems as though AutoMapper and Moq have Castle.Core merged into their assemblies.

This is what I need to call

```<code>Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(System.Security.Permissions.UIPermissionAttribute));
</code>```

But I get an Ambiguous reference because Castle.Core is technically available in 3 locations (AutoMapper, Moq, and the standalone DLL)

I can't simply un-ref any of the dlls because they are all managed by NuGet and Castle.Core standalone is needed for NHib and the other dlls are what were pulled in by the AutoMapper and Moq nuget packages.

Any suggestions? other then not depending on NuGet for managing my library refs?

答:
You could try using extern aliases. You can find it as a property on your Assembly references.

Look at this question for detail:

What use is the Aliases property of assembly references in Visual Studio 8

Body:
I need to call a specific function from Castle.Core.dll but it seems as though AutoMapper and Moq have Castle.Core merged into their assemblies.

This is what I need to call

Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(System.Security.Permissions.UIPermissionAttribute));

But I get an Ambiguous reference because Castle.Core is technically available in 3 locations (AutoMapper, Moq, and the standalone DLL)

I can't simply un-ref any of the dlls because they are all managed by NuGet and Castle.Core standalone is needed for NHib and the other dlls are what were pulled in by the AutoMapper and Moq nuget packages.

Any suggestions? other then not depending on NuGet for managing my library refs?


问:
AWS S3 file (redirected from AWS Lambda Function) responds to CORS preflight OPTIONS request with a 403 error
I have an AWS S3 bucket configured as a static website with the following CORS configuration:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

I also have a Lambda function that redirects to a specific page on the aforementioned S3 bucket. Here is a gist of the code:

```<code>module.exports.endPoint = (event, context, callback) => {
  // Do some cool processing and on success:
  redirectToUrl(303, 's3-bucket.amazon.com/page.html', callback);
}

function redirectToUrl(statusCode, url, callback) {
    const response = {
        statusCode: statusCode,
        headers: {
            Location: url,
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json'
        },
        body: '',
    };

    console.log('Redirecting with status code ' + statusCode + ' to ' + url);

    callback(null, response);
}
</code>```

I'm able to access the S3 HTML page directly from the browser using the same URL in the code. Yes, the API domain is different from the S3 domain:

```<code>api.domain.com --> initiates the request (redirection)
sub.domain.com/page.html --> requested resource (redirection target)
</code>```

The server responds to the CORS preflight OPTIONS request with a 403 error, and the browser reports the following error message:

Access to XMLHttpRequest at 'S3 File' (redirected from 'API Endpoint')
  from origin 'null' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

I originally set up the site with Serverless Framework by adding the following lines to my serverless.yml:

```<code>SiteBucket:
      Type: AWS::S3::Bucket
      Properties:
        AccessControl: PublicRead
        BucketName: ${self:custom.siteName}
        WebsiteConfiguration:
          IndexDocument: index.html
          ErrorDocument: error.html
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
                - GET
                - HEAD
              AllowedOrigins:
                - "*"
              MaxAge: 3000
    SiteBucketPolicy:
      Type: "AWS::S3::BucketPolicy"
      DependsOn: "SiteBucket"
      Properties:
        Bucket: ${self:custom.siteName}
        PolicyDocument:
          Statement:
            - Effect: Allow
              Principal: "*"
              Action:
                - "s3:GetObject"
              Resource:
                - "arn:aws:s3:::${self:custom.siteName}/*"
</code>```

Once the bucket was created via Serverless Framework and seeing the CORS errors, I finagled the CORS policy on S3 manually without success.

It's also worth noting that the S3 site is set up with CloudFront Distribution but I'm not sure if that makes a difference.

This should be an easy fix, but it's proving to be quite tough. Please help.

答:
Isn't this supposed to include a proper URL:

```<code>redirectToUrl(303, 's3-bucket.amazon.com/page.html');
</code>```

I think changing it to the following might fix your issue:

```<code>redirectToUrl(303, 'https://s3-bucket.amazon.com/page.html');
</code>```

Body:
I have an AWS S3 bucket configured as a static website with the following CORS configuration:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

I also have a Lambda function that redirects to a specific page on the aforementioned S3 bucket. Here is a gist of the code:

module.exports.endPoint = (event, context, callback) => {
  // Do some cool processing and on success:
  redirectToUrl(303, 's3-bucket.amazon.com/page.html', callback);
}

function redirectToUrl(statusCode, url, callback) {
    const response = {
        statusCode: statusCode,
        headers: {
            Location: url,
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json'
        },
        body: '',
    };

    console.log('Redirecting with status code ' + statusCode + ' to ' + url);

    callback(null, response);
}

I'm able to access the S3 HTML page directly from the browser using the same URL in the code. Yes, the API domain is different from the S3 domain:

api.domain.com --> initiates the request (redirection)
sub.domain.com/page.html --> requested resource (redirection target)

The server responds to the CORS preflight OPTIONS request with a 403 error, and the browser reports the following error message:

Access to XMLHttpRequest at 'S3 File' (redirected from 'API Endpoint')
  from origin 'null' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

I originally set up the site with Serverless Framework by adding the following lines to my serverless.yml:

SiteBucket:
      Type: AWS::S3::Bucket
      Properties:
        AccessControl: PublicRead
        BucketName: ${self:custom.siteName}
        WebsiteConfiguration:
          IndexDocument: index.html
          ErrorDocument: error.html
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
                - GET
                - HEAD
              AllowedOrigins:
                - "*"
              MaxAge: 3000
    SiteBucketPolicy:
      Type: "AWS::S3::BucketPolicy"
      DependsOn: "SiteBucket"
      Properties:
        Bucket: ${self:custom.siteName}
        PolicyDocument:
          Statement:
            - Effect: Allow
              Principal: "*"
              Action:
                - "s3:GetObject"
              Resource:
                - "arn:aws:s3:::${self:custom.siteName}/*"

Once the bucket was created via Serverless Framework and seeing the CORS errors, I finagled the CORS policy on S3 manually without success.

It's also worth noting that the S3 site is set up with CloudFront Distribution but I'm not sure if that makes a difference.

This should be an easy fix, but it's proving to be quite tough. Please help.

Body:
Isn't this supposed to include a proper URL:

redirectToUrl(303, 's3-bucket.amazon.com/page.html');

I think changing it to the following might fix your issue:

redirectToUrl(303, 'https://s3-bucket.amazon.com/page.html');


问:
Which Cloudera version supports YARN node labels
I would like to know whether Cloudera supports YARN Node labels? if yes, then which version of Cloudera can be used? </p>

答:
Found the information in one of the cloudera documentation:

YARN Unsupported Features in Cloudera 6.2

Node labels are not supported.


问:
How to add a hashbang to an executable Javascript file without breaking browser support?
Is it possible to have code like this:

```<code>#! /usr/local/bin/node
console.log("Hello world")
</code>```

That I can also run in the browser?

I have a script that I run locally and want to run it in the browser but right now I need to "recompile" it for the browser target only to remove the hashbang line.

I can't think of a way around it. Any ideas?

Edit: my use is that I don't want to have 2 files, as I want to be able execute the current file while working on it, and also serve it via the web. I think the solution is going to have to be to either compile it for the browser to a second file or to use an alternative to #! that plays nice with javascript.

答:
If you only ever use bash, you can take advantage of one feature (?!) of bash: bash executes scripts without a shebang using bash. Other shells may leave it to the OS, which would usually use /bin/sh instead. For example:

```<code>bash-5.0$ echo 'echo $1 $BASH_VERSION' > foo.sh
bash-5.0$ for sh in sh bash dash ksh zsh; do $sh -c "./foo.sh $sh"; done
sh 3.2.57(1)-release
bash 5.0.7(1)-release
dash 3.2.57(1)-release
ksh
zsh 3.2.57(1)-release
</code>```

(/bin/sh being a link to an old version of bash here on macOS.)

So, you could have a file like this:

///usr/local/bin/node <(tail -n +1 "$0"); exit $?
console.log("Hello world")
```

<p>If you run this in a browser, or other means of running JavaScript, the first line should be ignored as a comment.</p>

<p>If you run this as a script in bash, the first line tells it to run <code>///usr/local/bin/node</code>, using process substitution with <code>tail</code> to feed the rest of the file to node, and then exits:</p>

```bash-5.0$ cat foo.js
///usr/local/bin/node <(tail -n +1 "$0"); exit $?
console.log("Hello world")
bash-5.0$ ./foo.js
Hello world
```

This trick might work with ksh as well. The /// at the beginning of the path shouldn't cause problems - three or more / at the start of a path are equivalent to a single /.

But I would strongly encourage you to use a wrapper script instead, as suggested by the comments.

Body:
Is it possible to have code like this:

#! /usr/local/bin/node
console.log("Hello world")

That I can also run in the browser?

I have a script that I run locally and want to run it in the browser but right now I need to "recompile" it for the browser target only to remove the hashbang line.

I can't think of a way around it. Any ideas?

Edit: my use is that I don't want to have 2 files, as I want to be able execute the current file while working on it, and also serve it via the web. I think the solution is going to have to be to either compile it for the browser to a second file or to use an alternative to #! that plays nice with javascript.

Body:
If you only ever use bash, you can take advantage of one feature (?!) of bash: bash executes scripts without a shebang using bash. Other shells may leave it to the OS, which would usually use /bin/sh instead. For example:

bash-5.0$ echo 'echo $1 $BASH_VERSION' > foo.sh
bash-5.0$ for sh in sh bash dash ksh zsh; do $sh -c "./foo.sh $sh"; done
sh 3.2.57(1)-release
bash 5.0.7(1)-release
dash 3.2.57(1)-release
ksh
zsh 3.2.57(1)-release

(/bin/sh being a link to an old version of bash here on macOS.)

So, you could have a file like this:

///usr/local/bin/node <(tail -n +1 "$0"); exit $?
console.log("Hello world")

If you run this in a browser, or other means of running JavaScript, the first line should be ignored as a comment.

If you run this as a script in bash, the first line tells it to run ///usr/local/bin/node, using process substitution with tail to feed the rest of the file to node, and then exits:

bash-5.0$ cat foo.js
///usr/local/bin/node <(tail -n +1 "$0"); exit $?
console.log("Hello world")
bash-5.0$ ./foo.js
Hello world

This trick might work with ksh as well. The /// at the beginning of the path shouldn't cause problems - three or more / at the start of a path are equivalent to a single /.

But I would strongly encourage you to use a wrapper script instead, as suggested by the comments.