问:
XML C# Parse - Complex
I have been on google for a while but am just stumped.  I need to parse xml of this nature.  I can't seem to skip to elements in the middle, e.g. Folder.  I have limited the xml as there were many 'Folder' elements.  Any guidance would be appreciated.  I was after the FolderID element's attribute ID.</p>

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="14"
        MinorVersion="1"
        MajorBuildNumber="225"
        MinorBuildNumber="46"
        Version="Exchange2010_SP1"
        xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetFolderResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Folders>
            <t:Folder>
              <t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
              <t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
              <t:DisplayName>Top of Information Store</t:DisplayName>
              <t:TotalCount>0</t:TotalCount>
              <t:ChildFolderCount>15</t:ChildFolderCount>
              <t:EffectiveRights>
                <t:CreateAssociated>true</t:CreateAssociated>
                <t:CreateContents>true</t:CreateContents>
                <t:CreateHierarchy>true</t:CreateHierarchy>
                <t:Delete>true</t:Delete>
                <t:Modify>true</t:Modify>
                <t:Read>true</t:Read>
                <t:ViewPrivateItems>true</t:ViewPrivateItems>
              </t:EffectiveRights>
              <t:PermissionSet>
                <t:Permissions>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Default</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Anonymous</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                </t:Permissions>
              </t:PermissionSet>
              <t:UnreadCount>0</t:UnreadCount>
            </t:Folder>
          </m:Folders>
        </m:GetFolderResponseMessage>
      </m:ResponseMessages>
    </m:GetFolderResponse>
  </s:Body>
</s:Envelope>
</code>```

答:
You should learn about serlialization.  It's very easy to convert an XML to and from a object in C#.  https://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part

That said, this will get you the data you're after. It's not very reusable and won't help you with any xml files other than ones with one instance of that attribute, but it's what you're after so here you go.

```<code>string FolderId;
string ChangeKey;
using (StreamReader sr = new StreamReader("c:\\myfile.xml"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("<t:FolderId Id="))
        {
            try
            {
                var lineArray = line.Split('\"');
                FolderId = lineArray[1];
                ChangeKey = lineArray[3];
            }
            catch
            {
                // handle exception
            }
        }
    }
}
</code>```

Title: XML C# Parse - Complex

Body:
I have been on google for a while but am just stumped.  I need to parse xml of this nature.  I can't seem to skip to elements in the middle, e.g. Folder.  I have limited the xml as there were many 'Folder' elements.  Any guidance would be appreciated.  I was after the FolderID element's attribute ID.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="14"
        MinorVersion="1"
        MajorBuildNumber="225"
        MinorBuildNumber="46"
        Version="Exchange2010_SP1"
        xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetFolderResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Folders>
            <t:Folder>
              <t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
              <t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
              <t:DisplayName>Top of Information Store</t:DisplayName>
              <t:TotalCount>0</t:TotalCount>
              <t:ChildFolderCount>15</t:ChildFolderCount>
              <t:EffectiveRights>
                <t:CreateAssociated>true</t:CreateAssociated>
                <t:CreateContents>true</t:CreateContents>
                <t:CreateHierarchy>true</t:CreateHierarchy>
                <t:Delete>true</t:Delete>
                <t:Modify>true</t:Modify>
                <t:Read>true</t:Read>
                <t:ViewPrivateItems>true</t:ViewPrivateItems>
              </t:EffectiveRights>
              <t:PermissionSet>
                <t:Permissions>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Default</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Anonymous</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                </t:Permissions>
              </t:PermissionSet>
              <t:UnreadCount>0</t:UnreadCount>
            </t:Folder>
          </m:Folders>
        </m:GetFolderResponseMessage>
      </m:ResponseMessages>
    </m:GetFolderResponse>
  </s:Body>
</s:Envelope>

Body:
You should learn about serlialization.  It's very easy to convert an XML to and from a object in C#.  https://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part

That said, this will get you the data you're after. It's not very reusable and won't help you with any xml files other than ones with one instance of that attribute, but it's what you're after so here you go.

string FolderId;
string ChangeKey;
using (StreamReader sr = new StreamReader("c:\\myfile.xml"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.Contains("<t:FolderId Id="))
        {
            try
            {
                var lineArray = line.Split('\"');
                FolderId = lineArray[1];
                ChangeKey = lineArray[3];
            }
            catch
            {
                // handle exception
            }
        }
    }
}


来源: stackexchange

问:
Connecting to Oracle with .NET app error: System.BadImageFormatException: An attempt was made to load a program with an incorrect format
I am trying to Query a remote Oracle database from a Windows Server(production environment) through a .NET app.
I keep getting this exception. I have Oracle XE client installed on the system. I tried to install Oracle 64 bit connectors but the JVM won't allow me to do so.

Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

I'd appreciate any thoughts.

答: Compile your .NET application as x86, and then try again.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
&& is showing as unexpected token
I'm facing 'Unexpected token' error in if-else condition using &&. There's no any other error can be seen.

```<code>keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack
</code>```

I'm not able to understand that why it's showing Unexpected token here for using &&.

```<code>import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class Support extends AppCompatActivity {
    WebView webViewsupport;
    ProgressBar progressBar;

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

        webViewsupport = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar)findViewById(R.id.progressBar2);

        webViewsupport.setWebViewClient(new myWebClient());
        webViewsupport.getSettings().setJavaScriptEnabled(true);
        webViewsupport.loadUrl("https://example.com");

    }
    public class myWebClient extends WebViewClient{
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return super.shouldOverrideUrlLoading(view, url);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack(){
            webViewsupport.goBack();
        }
        return super.onKeyDown(keyCode, event);
    }
}
</code>```

This is screenshot

答:
There's a typo in your code (your ending parentheses is placed at the wrong spot):

```<code>if (keyCode == KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack(){
    webViewsupport.goBack();
}
</code>```

Should be:

```<code>if (keyCode == KeyEvent.KEYCODE_BACK && webViewsupport.canGoBack()) {
    webViewsupport.goBack();
}
</code>```

Voted to close for this reason.

Title: && is showing as unexpected token

Body:
I'm facing 'Unexpected token' error in if-else condition using &&. There's no any other error can be seen.

keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack

I'm not able to understand that why it's showing Unexpected token here for using &&.

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class Support extends AppCompatActivity {
    WebView webViewsupport;
    ProgressBar progressBar;

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

        webViewsupport = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar)findViewById(R.id.progressBar2);

        webViewsupport.setWebViewClient(new myWebClient());
        webViewsupport.getSettings().setJavaScriptEnabled(true);
        webViewsupport.loadUrl("https://example.com");

    }
    public class myWebClient extends WebViewClient{
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return super.shouldOverrideUrlLoading(view, url);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack(){
            webViewsupport.goBack();
        }
        return super.onKeyDown(keyCode, event);
    }
}

This is screenshot

Body:
There's a typo in your code (your ending parentheses is placed at the wrong spot):

if (keyCode == KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack(){
    webViewsupport.goBack();
}

Should be:

if (keyCode == KeyEvent.KEYCODE_BACK && webViewsupport.canGoBack()) {
    webViewsupport.goBack();
}

Voted to close for this reason.


问:
How to load new editorConfig for inline editor at run-time?
I have run the Toolbar Configurator to remove some unwanted items from the toolbar.  I can get the toolbar config, which consists of some javascript code which starts like this:

```<code>CKEDITOR.editorConfig = function( config ) {
    config.toolbarGroups = [
</code>```

However, it is unclear to me how to use this when instantiating a specific editor instead of using it globally.  I have tried pasting this in my code before I instantiate the editor in question, but it shows the full toolbar with the unwanted items.  I am also making some other CKEDITOR.config and CKEDITOR.on assignments at this time which do work.

I also tried modifying the configuration code within the function by changing the config to editor.config (where editor comes from the "editor" field of the event passed to the callback) and initializing it in the callback of CKEDITOR.on("instanceReady") but that also did not work.

Then I saw this question and tried using the replace function like so:

```<code>CKEDITOR.on("instanceReady", function(evt) {
    ...
    CKEDITOR.replace(evt.editor.name, {
        toolbarGroups: [
           ...
        ],

        removeButtons: "..."
    })
    ...
</code>```

This also doesn't work!

Then I tried pasting the raw config from the configurator into a new file "config2.js" in my ckeditor directory on the server as this page suggests should work, and changing the replace call to:

```<code>CKEDITOR.replace(evt.editor.name, {
    customConfig: "config2.js"
})
</code>```

This doesn't work, even if I replace the string with "../ckeditor/config2.js". Looking at the network requests I see it doesn't even try requesting "config2.js" from anywhere.

If it makes any difference, I am starting the editor using CKEDITOR.inline(div) so as far as I know I have to perform the configuration in an event callback.

I also tried calling the replace function from the "instanceCreated" callback - this resulted in an infinite loop / max recursion exceeded error.  I also tried it in the "instanceLoaded" event, also without effect.

Update:
I just noticed in the console that when it tries to call replace it throws this error:

```<code>Uncaught The editor instance "note1681" is already attached to the provided element.
</code>```

So it seems I am doing something incorrectly with replace.

答:
I believe it's impossible to hide buttons(change toolbar) after you initialized instance. However, you can recreate you ckeditor with new toolbar.
First, you need to destroy current instance, before creating new one.

 CKEDITOR.instances.note1681.destroy();
 CKEDITOR.replace('note1681');

For fast switching toolbar, i recommend use custom variable in configuration file.

Add in ckeditor/config.js your toolbar version

```<code>editor.my_toolbar  = [['Sourcedialog','Cut','Copy']];
</code>```

Init ckeditor with it

```<code>CKEDITOR.replace( 'note1681', { toolbar: my_toolbar })
</code>```

Body:
I have run the Toolbar Configurator to remove some unwanted items from the toolbar.  I can get the toolbar config, which consists of some javascript code which starts like this:

CKEDITOR.editorConfig = function( config ) {
    config.toolbarGroups = [

However, it is unclear to me how to use this when instantiating a specific editor instead of using it globally.  I have tried pasting this in my code before I instantiate the editor in question, but it shows the full toolbar with the unwanted items.  I am also making some other CKEDITOR.config and CKEDITOR.on assignments at this time which do work.

I also tried modifying the configuration code within the function by changing the config to editor.config (where editor comes from the "editor" field of the event passed to the callback) and initializing it in the callback of CKEDITOR.on("instanceReady") but that also did not work.

Then I saw this question and tried using the replace function like so:

CKEDITOR.on("instanceReady", function(evt) {
    ...
    CKEDITOR.replace(evt.editor.name, {
        toolbarGroups: [
           ...
        ],

        removeButtons: "..."
    })
    ...

This also doesn't work!

Then I tried pasting the raw config from the configurator into a new file "config2.js" in my ckeditor directory on the server as this page suggests should work, and changing the replace call to:

CKEDITOR.replace(evt.editor.name, {
    customConfig: "config2.js"
})

This doesn't work, even if I replace the string with "../ckeditor/config2.js". Looking at the network requests I see it doesn't even try requesting "config2.js" from anywhere.

If it makes any difference, I am starting the editor using CKEDITOR.inline(div) so as far as I know I have to perform the configuration in an event callback.

I also tried calling the replace function from the "instanceCreated" callback - this resulted in an infinite loop / max recursion exceeded error.  I also tried it in the "instanceLoaded" event, also without effect.

Update:
I just noticed in the console that when it tries to call replace it throws this error:

Uncaught The editor instance "note1681" is already attached to the provided element.

So it seems I am doing something incorrectly with replace.

Body:
I believe it's impossible to hide buttons(change toolbar) after you initialized instance. However, you can recreate you ckeditor with new toolbar.
First, you need to destroy current instance, before creating new one.

 CKEDITOR.instances.note1681.destroy();
 CKEDITOR.replace('note1681');

For fast switching toolbar, i recommend use custom variable in configuration file.

Add in ckeditor/config.js your toolbar version

editor.my_toolbar  = [['Sourcedialog','Cut','Copy']];

Init ckeditor with it

CKEDITOR.replace( 'note1681', { toolbar: my_toolbar })


问:
Angular 2 POST header error
I cannot get my header on POST request to work, I've tried pretty much every solution people posted on the internet.

here is the code:

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable } from "rxjs";
import { Headers } from '@angular/http';

@Injectable()
export class APIService {
    constructor(private http:HttpClient) { }

    function(url, var1, var2):Observable<any>{

        let data = {
            "status": var1,
            "duration": var2
      };

    let message = JSON.stringify(data );

    return this.http.post(url, message, <HELP>);
}
</code>```

here are the things I've tried:

```<code>const headerDict = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Access-Control-Allow-Headers': 'Content-Type',
};

const requestOptions = {
  headers: new Headers(headerDict),
};
return this.http.post(url, message, requestOptions );
</code>```

and

```<code>return this.http.post(url, message, {headers:{'Content-Type': 'application/json'}});
</code>```

and

```<code>//added above -> import { Headers, RequestOptions } from '@angular/http';

const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers: headers });
return this.http.post(url, message, options );
</code>```

and

```<code>var headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, message, options );
</code>```

and some others I don't remember. None of them worked. I've been stuck for hours. Most of the errors are:

"Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders; observe?: "body"; params?: HttpParams; (...) "

Types of property 'headers' are incompatible

Type 'Headers' is not assignable to type 'HttpHeaders'.

Property 'headers' is missing in type 'Headers'.

When I print "message" the output is what I want, but it won't get posted without the header (error 415 when I try posting on my API) and the only logical explanation is that the missing header is making it not work, but with a header it won't compile. Please help?

FYI: OS = Windows. I never had a problem before with my gets, only with this post attempt. I don't know if the OS may influence this so I thought it was better to let you know.

答:
Try this:</p>

```<code>return this.http.post(url, message, {
   headers: new HttpHeaders().set('Content-Type', 'application/json')
                             .set('Accept', 'application/json')
                             .set('Access-Control-Allow-Headers', 'Content-Type')
});
</code>```

Title: Angular 2 POST header error

Body:
I cannot get my header on POST request to work, I've tried pretty much every solution people posted on the internet.

here is the code:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable } from "rxjs";
import { Headers } from '@angular/http';

@Injectable()
export class APIService {
    constructor(private http:HttpClient) { }

    function(url, var1, var2):Observable<any>{

        let data = {
            "status": var1,
            "duration": var2
      };

    let message = JSON.stringify(data );

    return this.http.post(url, message, <HELP>);
}

here are the things I've tried:

const headerDict = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Access-Control-Allow-Headers': 'Content-Type',
};

const requestOptions = {
  headers: new Headers(headerDict),
};
return this.http.post(url, message, requestOptions );

and

return this.http.post(url, message, {headers:{'Content-Type': 'application/json'}});

and

//added above -> import { Headers, RequestOptions } from '@angular/http';

const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers: headers });
return this.http.post(url, message, options );

and

var headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, message, options );

and some others I don't remember. None of them worked. I've been stuck for hours. Most of the errors are:

"Argument of type 'RequestOptions' is not assignable to parameter of type '{ headers?: HttpHeaders; observe?: "body"; params?: HttpParams; (...) "

Types of property 'headers' are incompatible

Type 'Headers' is not assignable to type 'HttpHeaders'.

Property 'headers' is missing in type 'Headers'.

When I print "message" the output is what I want, but it won't get posted without the header (error 415 when I try posting on my API) and the only logical explanation is that the missing header is making it not work, but with a header it won't compile. Please help?

FYI: OS = Windows. I never had a problem before with my gets, only with this post attempt. I don't know if the OS may influence this so I thought it was better to let you know.

Body:
Try this:

return this.http.post(url, message, {
   headers: new HttpHeaders().set('Content-Type', 'application/json')
                             .set('Accept', 'application/json')
                             .set('Access-Control-Allow-Headers', 'Content-Type')
});


问:
How to compare two csv files?
I have a csv file1 which is like

FLAGSTAFF   AZ  50244.67    5.02    KA1_Podium_Garage_S
FLAGSTAFF   AZ  33752.13    3.38    KA1_Podium_Garage_S
FLAGSTAFF   AZ  11965.5      1.2    KA1_Podium_Garage_S
FLAGSTAFF   AZ  3966.48      0.4    KA1_Podium_Garage_S
SEATTLE     WA  12646.9      1.26   KA1_Podium_Garage_S
SEATTLE     WA  225053.92   22.51   KA1_Podium_Garage_S
SEATTLE     WA  23974.3      2.4    KA1_Podium_Garage_S
SEATTLE     WA  7036.4       0.7    KA1_Podium_Garage_S
SEATTLE     WA  3021.93      0.3    KA1_Podium_Garage_S
```

<p>I have a csv file 2 which is like ,</p>

<pre class="lang-none prettyprint-override"><code>Alabama     AL  1
Alaska      AK  2
Arizona     AZ  4
Arkansas    AR  5
California  CA  6
Colorado    CO  8
Connecticut CT  9
SEATTLE     WA  53
</code>```

Now i have to append the third column value  from csv file2 to csv file1,
by comparing second column

For example  it should look like,

AZ code is 4
WA code is 53
wherever AZ,WA is there in my csv file1 , the code should get appended into a column

My output should look like,

FLAGSTAFF   AZ  50244.67    5.02    KA1_Podium_Garage_S 4
FLAGSTAFF   AZ  33752.13    3.38    KA1_Podium_Garage_S 4
FLAGSTAFF   AZ  11965.5      1.2    KA1_Podium_Garage_S 4
FLAGSTAFF   AZ  3966.48      0.4    KA1_Podium_Garage_S 4
SEATTLE     WA  12646.9      1.26   KA1_Podium_Garage_S 53
SEATTLE     WA  225053.92   22.51   KA1_Podium_Garage_S 53
SEATTLE     WA  23974.3      2.4    KA1_Podium_Garage_S 53
SEATTLE     WA  7036.4       0.7    KA1_Podium_Garage_S 53
SEATTLE     WA  3021.93      0.3    KA1_Podium_Garage_S 53
```

<p>Here is the code which i tried,</p>

```with open("/home/sumit/Desktop/CSV_FILE1.csv", "r") as f:
    first = {rows[1]: rows[0:] for rows in list(csv.reader(f))}

# compare second csv and append Code
with open("CSVFILE2.csv", "r") as f1:
    for row in csv.reader(f1):
        if row[1] in first:
            first[row[1]].append(row[2])

# convert dict back to list
merged = [(k,) + tuple(v) for k, v in first.items()]

# write list to output csv
with open("output.csv", "w") as f1:
    csv.writer(f1).writerows(merged)
```

<p>Output am getting like,</p>

<pre class="lang-none prettyprint-override"><code>AZ  FLAGSTAFF   AZ  44230.4 4.42    KA1_Podium_Garage_S 4
WA  SEATTLE     WA  45329.3 4.53    KA1_Podium_Garage_S 53
</code>```

答:
This line is creating a dictionary, based on state abbreviation, from your first file.  This looks wrong, since a dictionary can only have each key once, and you have multiple rows with "AZ" for example.

```<code>first = { rows[1]: rows[0:] for rows in list(csv.reader(f)) }
</code>```

Instead, you should make your dictionary based on the second file:

```<code>with open("CSVFILE2.csv", "r") as f1:
    code = { row[1]: row[2] for row in csv.reader(f1) }
</code>```

Then, loop over your first file, and append the appropriate code to each row.

```<code>with open("/home/sumit/Desktop/CSV_FILE1.csv", "r") as f:
    merged = [ row + [code[row[1]]] for row in csv.reader(f) ]
</code>```

And write out the merged data to the new file.

Explanation of row + [code[row[1]]]:

If row is ["FLAGSTAFF", "AZ", 50244.67, 5.02, "KA1_Podium_Garage_S"], then

row[1] is "AZ",

code[row[1]] is code["AZ"] which is 4,

[code[row[1]]] is the list [4]

and row + [code[row[1]] is list concatenation, producing the desired new row value: ["FLAGSTAFF", "AZ", 50244.67, 5.02, "KA1_Podium_Garage_S", 4]

Title: How to compare two csv files?

Body:
I have a csv file1 which is like

FLAGSTAFF   AZ  50244.67    5.02    KA1_Podium_Garage_S
FLAGSTAFF   AZ  33752.13    3.38    KA1_Podium_Garage_S
FLAGSTAFF   AZ  11965.5      1.2    KA1_Podium_Garage_S
FLAGSTAFF   AZ  3966.48      0.4    KA1_Podium_Garage_S
SEATTLE     WA  12646.9      1.26   KA1_Podium_Garage_S
SEATTLE     WA  225053.92   22.51   KA1_Podium_Garage_S
SEATTLE     WA  23974.3      2.4    KA1_Podium_Garage_S
SEATTLE     WA  7036.4       0.7    KA1_Podium_Garage_S
SEATTLE     WA  3021.93      0.3    KA1_Podium_Garage_S

I have a csv file 2 which is like ,

Alabama     AL  1
Alaska      AK  2
Arizona     AZ  4
Arkansas    AR  5
California  CA  6
Colorado    CO  8
Connecticut CT  9
SEATTLE     WA  53

Now i have to append the third column value  from csv file2 to csv file1,
by comparing second column

For example  it should look like,

AZ code is 4
WA code is 53
wherever AZ,WA is there in my csv file1 , the code should get appended into a column

My output should look like,

FLAGSTAFF   AZ  50244.67    5.02    KA1_Podium_Garage_S 4
FLAGSTAFF   AZ  33752.13    3.38    KA1_Podium_Garage_S 4
FLAGSTAFF   AZ  11965.5      1.2    KA1_Podium_Garage_S 4
FLAGSTAFF   AZ  3966.48      0.4    KA1_Podium_Garage_S 4
SEATTLE     WA  12646.9      1.26   KA1_Podium_Garage_S 53
SEATTLE     WA  225053.92   22.51   KA1_Podium_Garage_S 53
SEATTLE     WA  23974.3      2.4    KA1_Podium_Garage_S 53
SEATTLE     WA  7036.4       0.7    KA1_Podium_Garage_S 53
SEATTLE     WA  3021.93      0.3    KA1_Podium_Garage_S 53

Here is the code which i tried,

with open("/home/sumit/Desktop/CSV_FILE1.csv", "r") as f:
    first = {rows[1]: rows[0:] for rows in list(csv.reader(f))}

# compare second csv and append Code
with open("CSVFILE2.csv", "r") as f1:
    for row in csv.reader(f1):
        if row[1] in first:
            first[row[1]].append(row[2])

# convert dict back to list
merged = [(k,) + tuple(v) for k, v in first.items()]

# write list to output csv
with open("output.csv", "w") as f1:
    csv.writer(f1).writerows(merged)

Output am getting like,

AZ  FLAGSTAFF   AZ  44230.4 4.42    KA1_Podium_Garage_S 4
WA  SEATTLE     WA  45329.3 4.53    KA1_Podium_Garage_S 53

Body:
This line is creating a dictionary, based on state abbreviation, from your first file.  This looks wrong, since a dictionary can only have each key once, and you have multiple rows with "AZ" for example.

first = { rows[1]: rows[0:] for rows in list(csv.reader(f)) }

Instead, you should make your dictionary based on the second file:

with open("CSVFILE2.csv", "r") as f1:
    code = { row[1]: row[2] for row in csv.reader(f1) }

Then, loop over your first file, and append the appropriate code to each row.

with open("/home/sumit/Desktop/CSV_FILE1.csv", "r") as f:
    merged = [ row + [code[row[1]]] for row in csv.reader(f) ]

And write out the merged data to the new file.

Explanation of row + [code[row[1]]]:

If row is ["FLAGSTAFF", "AZ", 50244.67, 5.02, "KA1_Podium_Garage_S"], then

row[1] is "AZ",

code[row[1]] is code["AZ"] which is 4,

[code[row[1]]] is the list [4]

and row + [code[row[1]] is list concatenation, producing the desired new row value: ["FLAGSTAFF", "AZ", 50244.67, 5.02, "KA1_Podium_Garage_S", 4]


问:
LXD/LXC gid mapping
I have a directory on disk that is owned by share with gid of 1001. I want to add that directory as a device on one of the lxc containers, and have that group to carry over.

I have tried using raw.idmap 'gid 1001 1001' but the lxc container won't start if a add this.

Thanks

答:
There are three parts needed to make the mapping work.

raw.idmap set (which you've already done)

the container has an existing gid to map to

the shadow file allows the id mapping

You're trying to map the host-gid 1001 (share) to a container-gid.  In this case you've chosen that the container-gid will be 1001 as well.

You've accomplished #1 above, you've setup the mapping.

Accomplishing #2 just requires you to create a group with gid 1001 inside the container.  In theory this could actually be any gid for the new group and you'd just have to modify the raw.idmap command to set the destination gid to match the one defined in the container.

For #3 above, you need to check /etc/subgid to make sure you're allowed to map host-gid 1001 to container-gid 1001.

When you look at /etc/subgid you should see some lines that looks something like the following, though the first number on each line may be different:

```<code>lxd:100000:65536
root:100000:65536
</code>```

This is the default configuration and says that lxd can use gids with a range starting at 100000, which produces containers that have a hidden offset relative to the host gids of 100000 (or whatever the first number in the line is).  If you create a file in a mounted directory from within the container, the gid visible from the host would be that offset + the container gid.

To allow lxd to use gid 1001, and therefore allow it to map host gid 1001 to container gid 1001 (or any container gid), you need to add the permissions to your /etc/subgid file.  You can do this by adding a line like this to the end of the file:

```<code>lxd:1001:1
root:1001:1
</code>```

If you have a number of different gids you want the host to allow lxd to map when you use the raw.idmap option, you can specify them as "

```<code>lxd:start-id-to-expose:count-of-ids-to-expose
root:start-id-to-expose:count-of-ids-to-expose
</code>```

with non-contiguous ranges being listed on additional lines in the file.

Make sure you always add both an lxd and root line whenever you need to add new lines since lxd documentation says they must be kept in sync for most uses.

Title: LXD/LXC gid mapping

Body:
There are three parts needed to make the mapping work.

raw.idmap set (which you've already done)

the container has an existing gid to map to

the shadow file allows the id mapping

You're trying to map the host-gid 1001 (share) to a container-gid.  In this case you've chosen that the container-gid will be 1001 as well.

You've accomplished #1 above, you've setup the mapping.

Accomplishing #2 just requires you to create a group with gid 1001 inside the container.  In theory this could actually be any gid for the new group and you'd just have to modify the raw.idmap command to set the destination gid to match the one defined in the container.

For #3 above, you need to check /etc/subgid to make sure you're allowed to map host-gid 1001 to container-gid 1001.

When you look at /etc/subgid you should see some lines that looks something like the following, though the first number on each line may be different:

lxd:100000:65536
root:100000:65536

This is the default configuration and says that lxd can use gids with a range starting at 100000, which produces containers that have a hidden offset relative to the host gids of 100000 (or whatever the first number in the line is).  If you create a file in a mounted directory from within the container, the gid visible from the host would be that offset + the container gid.

To allow lxd to use gid 1001, and therefore allow it to map host gid 1001 to container gid 1001 (or any container gid), you need to add the permissions to your /etc/subgid file.  You can do this by adding a line like this to the end of the file:

lxd:1001:1
root:1001:1

If you have a number of different gids you want the host to allow lxd to map when you use the raw.idmap option, you can specify them as "

lxd:start-id-to-expose:count-of-ids-to-expose
root:start-id-to-expose:count-of-ids-to-expose

with non-contiguous ranges being listed on additional lines in the file.

Make sure you always add both an lxd and root line whenever you need to add new lines since lxd documentation says they must be kept in sync for most uses.


问:
a simple regexp validator
How do a I create a validator, which has these simple rules. An expression is valid if

it must start with a letter

it must end with a letter

it can contain a dash (minus sign), but not at start or end of the expression

答:
```<code>^[A-Za-z].*[A-Za-z]$
</code>```

In other words: letter, anything, letter.

Might also want:

```<code>^[A-Za-z](.*[A-Za-z])?$
</code>```

so that a single letter is also matched.

OwnerDisplayName: new-to-rails

Title: a simple regexp validator

Body:
^[A-Za-z].*[A-Za-z]$

In other words: letter, anything, letter.

Might also want:

^[A-Za-z](.*[A-Za-z])?$

so that a single letter is also matched.

OwnerDisplayName: Douglas Leeder


问:
handle transaction in Linq to sql
I am implementing the asp.net MVC web application, where i am using the Linq to Sql to manipulate the data in database. but in my one of action, i want to insert multiple table entries which are depends upon each other by referring previous insertion Id's. So i just wnat to know how to handle the transaction, like begin transaction, commit,rollback and all like in ADO.net. how to manage this. what if one of insertion get crashed in the middle of manipulation?

Note:- I am not using the Stored procedures here. I am using Lambda expressions and methods. Also these are use in different manager classes.
Example:
For Create Subject - used method in SubjectManager class to insert subject infor, that returns subject Id. within this subjectid i am inserting the let say its chapters with another method in manager class  as ChapterManager. which again returns the ChapterId, on base of this chapeter Id , inserting the Topics of chapter. that again uses Topic manager same like above.in each manger class i am creating dataContext object for the same. and I am controlling all this within a single action in my controller. but worrying about the transaction management. how I can use here ?

答:
```<code>using(TransactionScope scope = new TransactionScope())
{
    using(DataContext ctx = new MyDataContext())
    {
        ctx.Subject.Add(subject);
        Chapter chapter = new Chapter();
        chapter.SubjectId = subject.Id;
        ctx.SubmitChanges();
        ctx.Chapter.Add(chapter);
        ctx.SubmitChanges();
        scope.Complete() // if it all worked out
    }
}
</code>```

From the System.Transactions namespace I believe.

Title: handle transaction in Linq to sql

Body:
using(TransactionScope scope = new TransactionScope())
{
    using(DataContext ctx = new MyDataContext())
    {
        ctx.Subject.Add(subject);
        Chapter chapter = new Chapter();
        chapter.SubjectId = subject.Id;
        ctx.SubmitChanges();
        ctx.Chapter.Add(chapter);
        ctx.SubmitChanges();
        scope.Complete() // if it all worked out
    }
}

From the System.Transactions namespace I believe.


答: You can use the XSD.exe to create a schema class. and then using XML deserializer, you can deserialize/parse xml to object</p>

Title: XML C# Parse - Complex


问:
Which css style has least effect on an element?
Today I was trying to create a dummy css rule for testing and investigation.

```<code>.dummy {
  some-style : somevalue;
}
</code>```

Ideally the class should have no visible effect.  I want to be able to apply the class to elements but cause the least visible effect possible on any elements it is applied to.  For example

 should look and behaves as much as possible like

I did not want the class to be empty.  Can anyone suggest a style that I could add to the class that would have the least visible impact when applied to a general html element?  I can't think of anything completely harmless.

UPDATE: I wanted to add the style to some existing html.  The reason was to use the style as a marker for diagnostic purposes.  It would help me see when and where styles and stylesheets were getting loaded/cached and where and why some styles were getting overridden, sometimes by the browser defaults which seemed odd.  At the time I didn't have exclusive use of the system I was working on so I wanted something that was going to be invisible to other users but I could see in Developer Tools.

UPDATE 2 : the html/css wasn't written by me and I didn't have my own environment in which to work. I was trying to investigate some problems in-situ in someone else's system.  I had tried using DevTools in the browser but wasn't getting anywhere with that.  I wanted to be able to make some small changes to their html/css to aid my diagnostics.  I didn't want them to have any obvious effect on the system for other people (except in DevTools, viewed by me).

It was a Wordpress site and they only had two environments, one for live and one for testing.  I was working with the test system.  There were other people testing at the time, though mainly checking content.

The real thorny problem was why was the font-size in the calendar widget much larger than everything else on the site?  Inspecting using DevTools I could see the font-size style was getting overridden by the browser default style when it seemed to me there were other css selectors that should have taken precedence.  It looked bizarre.  In the end it turned out to be a missing !DOCTYPE tag in the html.  So nothing to do with the css itself.

I didn't like this way of working, fiddling in someone's system, but there wasn't much else to do and it did help to resolve the problem for them.

Hopefully I don't have to do this again, but ever since I have been wondering what was the most harmless style that I could have used?

I thought I would ask here as there must be people who know CSS better than me.

答:
In principle, for any property you can have an arrangement like this:

```<code>div {
  some-style : a-valid-value-for-some-style;
}

.dummy {
  some-style : a-different-valid-value-for-some-style;
}
</code>```

And .dummy's style will have an effect, no matter what some-style is.

Your best bet is to make use of CSS variables. These are custom properties and start with a double hyphen. so

```<code>.dummy {
   --dummy-style: foo;
}
</code>```

will make --dummy-style a property with value "foo". So long as you don't employ the variable as the value in another property, it will have no visible effect.

Body:
Today I was trying to create a dummy css rule for testing and investigation.

.dummy {
  some-style : somevalue;
}

Ideally the class should have no visible effect.  I want to be able to apply the class to elements but cause the least visible effect possible on any elements it is applied to.  For example

 should look and behaves as much as possible like

I did not want the class to be empty.  Can anyone suggest a style that I could add to the class that would have the least visible impact when applied to a general html element?  I can't think of anything completely harmless.

UPDATE: I wanted to add the style to some existing html.  The reason was to use the style as a marker for diagnostic purposes.  It would help me see when and where styles and stylesheets were getting loaded/cached and where and why some styles were getting overridden, sometimes by the browser defaults which seemed odd.  At the time I didn't have exclusive use of the system I was working on so I wanted something that was going to be invisible to other users but I could see in Developer Tools.

UPDATE 2 : the html/css wasn't written by me and I didn't have my own environment in which to work. I was trying to investigate some problems in-situ in someone else's system.  I had tried using DevTools in the browser but wasn't getting anywhere with that.  I wanted to be able to make some small changes to their html/css to aid my diagnostics.  I didn't want them to have any obvious effect on the system for other people (except in DevTools, viewed by me).

It was a Wordpress site and they only had two environments, one for live and one for testing.  I was working with the test system.  There were other people testing at the time, though mainly checking content.

The real thorny problem was why was the font-size in the calendar widget much larger than everything else on the site?  Inspecting using DevTools I could see the font-size style was getting overridden by the browser default style when it seemed to me there were other css selectors that should have taken precedence.  It looked bizarre.  In the end it turned out to be a missing !DOCTYPE tag in the html.  So nothing to do with the css itself.

I didn't like this way of working, fiddling in someone's system, but there wasn't much else to do and it did help to resolve the problem for them.

Hopefully I don't have to do this again, but ever since I have been wondering what was the most harmless style that I could have used?

I thought I would ask here as there must be people who know CSS better than me.

Body:
In principle, for any property you can have an arrangement like this:

div {
  some-style : a-valid-value-for-some-style;
}

.dummy {
  some-style : a-different-valid-value-for-some-style;
}

And .dummy's style will have an effect, no matter what some-style is.

Your best bet is to make use of CSS variables. These are custom properties and start with a double hyphen. so

.dummy {
   --dummy-style: foo;
}

will make --dummy-style a property with value "foo". So long as you don't employ the variable as the value in another property, it will have no visible effect.


问:
Apartment gem Custom Tenants Rails 5
I am building a multitenant application using the Apartment gem. I have the core features that will be common across all tenants. But now I want to add a table the schema for TenantB that will not be in the schema for TenantA. If I do the following it adds the table to able tenants.

```<code>       class CreateStickies < ActiveRecord::Migration[5.0]

         def change
          if table_exists? :tenantb
           create_table :post do |t|
             t.text :body
             t.string :title

             t.timestamps
           end
          end
         end

       end
</code>```

How can I add this Posts table to my tenant(s) of choice?

答:
As I understand Apartement does not support what you are asking.

If you are developing a Rails application using apartment, you may have a work around.

Loading tenant specific configurations (Shamelessly copied from wiki)

```<code>#config/initializers/country_specific.rb
COUNTRY_CONFIGS = YAML.load_file(Rails.root.join('config', 'country_specific' , 'config.yml'))

#config/country_specific/config.yml
da:
site_name: Boligsurf.dk
se:
site_name: Bostadssurf.se

#app/controllers/application_controller
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_country_config
......
def set_country_config
    $COUNTRY_CONFIG = COUNTRY_CONFIGS['da'] #As default as some strange domains also refer this site, we'll just catch em as danish
    $COUNTRY_CONFIG = COUNTRY_CONFIGS['se'] if request.host.include? 'bostadssurf'
end

#Somewhere in your code
puts "Welcome to #{$COUNTRY_CONFIG['site_name']}"
</code>```

Probably you may explore the above feature to hide/expose the tenant specific areas of your applications based on the tenant.

Title: Apartment gem Custom Tenants Rails 5

Body:
I am building a multitenant application using the Apartment gem. I have the core features that will be common across all tenants. But now I want to add a table the schema for TenantB that will not be in the schema for TenantA. If I do the following it adds the table to able tenants.

       class CreateStickies < ActiveRecord::Migration[5.0]

         def change
          if table_exists? :tenantb
           create_table :post do |t|
             t.text :body
             t.string :title

             t.timestamps
           end
          end
         end

       end

How can I add this Posts table to my tenant(s) of choice?

Body:
As I understand Apartement does not support what you are asking.

If you are developing a Rails application using apartment, you may have a work around.

Loading tenant specific configurations (Shamelessly copied from wiki)

#config/initializers/country_specific.rb
COUNTRY_CONFIGS = YAML.load_file(Rails.root.join('config', 'country_specific' , 'config.yml'))

#config/country_specific/config.yml
da:
site_name: Boligsurf.dk
se:
site_name: Bostadssurf.se

#app/controllers/application_controller
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_country_config
......
def set_country_config
    $COUNTRY_CONFIG = COUNTRY_CONFIGS['da'] #As default as some strange domains also refer this site, we'll just catch em as danish
    $COUNTRY_CONFIG = COUNTRY_CONFIGS['se'] if request.host.include? 'bostadssurf'
end

#Somewhere in your code
puts "Welcome to #{$COUNTRY_CONFIG['site_name']}"

Probably you may explore the above feature to hide/expose the tenant specific areas of your applications based on the tenant.


问:
html aligning inputs under each other
I'm trying to get the following snippet to work so that the selects are aligned exactly underneath each other.

Type:
<select style="width: 200px"></select>Created at:

Encoding:
<select style="width: 200px"></select>Updated at:

Collation: <select style=" width: 200px"></select>

```

As you can see it doesn't look quite right and I'm not sure how, I've been experimenting with stuff like display and box-sizing as you can see but none of these seem to have any effect, I also tried to align the text to the right which makes it a little better but it's still not perfect.

Any ideas?

答:
Use CSS. It is much better than having to write it within your HTML.

Are you after something like this?

```<code><div class="container">

<div class="row">
 <label>Item 1</label>
 <select></select>
 <span class="updated">Updated:</span>
</div>

<div class="row">
 <label>Item 2</label>
 <select></select>
 <span class="updated">Updated:</span>
</div>

<div class="row">
  <label>Item 3</label>
  <select></select>
  <span class="updated">Updated:</span>
</div>

</div>
</code>```

Then in your CSS:

```<code>/* Add a row to fit each select item and its title, updated */
.container .row {
  margin-bottom: 10px;
}
.row:last-child {
  margin-bottom: 0
}
/* The text label for your form item */
label {
  padding-right: 5px
}
/* The select dropdown */
select {
  width: 65%;
  margin: auto;
}
</code>```

See this jsFiddle

Title: html aligning inputs under each other

Body:
I'm trying to get the following snippet to work so that the selects are aligned exactly underneath each other.

Type:
<select style="width: 200px"></select>Created at:

Encoding:
<select style="width: 200px"></select>Updated at:

Collation: <select style=" width: 200px"></select>

As you can see it doesn't look quite right and I'm not sure how, I've been experimenting with stuff like display and box-sizing as you can see but none of these seem to have any effect, I also tried to align the text to the right which makes it a little better but it's still not perfect.

Any ideas?

Body:
Use CSS. It is much better than having to write it within your HTML.

Are you after something like this?

<div class="container">

<div class="row">
 <label>Item 1</label>
 <select></select>
 <span class="updated">Updated:</span>
</div>

<div class="row">
 <label>Item 2</label>
 <select></select>
 <span class="updated">Updated:</span>
</div>

<div class="row">
  <label>Item 3</label>
  <select></select>
  <span class="updated">Updated:</span>
</div>

</div>

Then in your CSS:

/* Add a row to fit each select item and its title, updated */
.container .row {
  margin-bottom: 10px;
}
.row:last-child {
  margin-bottom: 0
}
/* The text label for your form item */
label {
  padding-right: 5px
}
/* The select dropdown */
select {
  width: 65%;
  margin: auto;
}

See this jsFiddle


问:
How to use absolute file path in liquibase change sets?
I have muli moduled maven based application. There are several change sets in each module. I want to write integration tests in one of them. I know it's bad idea but,  i have business log constraints.

In considered module i have code that uses repositories from 2 others modules. During tests i have to initialize tables from change sets in different modules. I don't know how to use absolute path to change sets or how to use liquibase config.

I tried use include or includeAll tags, but in classpath where tests run i can't call change sets out of module.

Hope for your ideas.

答:
you should be able to create liquibase instance in your junit by  passing absolute file paths. You can refer liquibase tests in github for more info

```<code>new Liquibase(changeLogFile, FileSystemResourceAccesor, database);
</code>```

https://github.com/liquibase/liquibase/blob/master/liquibase-integration-tests/src/test/java/liquibase/dbtest/AbstractIntegrationTest.java#L890

Body:
you should be able to create liquibase instance in your junit by  passing absolute file paths. You can refer liquibase tests in github for more info

new Liquibase(changeLogFile, FileSystemResourceAccesor, database);

https://github.com/liquibase/liquibase/blob/master/liquibase-integration-tests/src/test/java/liquibase/dbtest/AbstractIntegrationTest.java#L890


问:
Problem with Array Search in PHP
I am not finding what might be the problem in my program.

I am having an array like this

```<code>$arr = array("1", "urgent", "4", "low", "15", "avg");
</code>```

When i am searching this array using

```<code>$key = array_search("4", $arr);// Working
</code>```

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

```<code>$key = array_search("4", $arr); // Not working here - for searching "1"
</code>```

What might be the problem.

Thank You

答:
Remember that 0 is evaluated to FALSE in php.

so..

```<code>if($index = array_search("1",$arr)) {
    //will actually evaluate to false
}
</code>```

In case you are using it this way and think it's not working because the conditional isn't technically failing, the value is evaluated as FALSE.

Title: Problem with Array Search in PHP

Body:
I am not finding what might be the problem in my program.

I am having an array like this

$arr = array("1", "urgent", "4", "low", "15", "avg");

When i am searching this array using

$key = array_search("4", $arr);// Working

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

$key = array_search("4", $arr); // Not working here - for searching "1"

What might be the problem.

Thank You

Body:
Remember that 0 is evaluated to FALSE in php.

so..

if($index = array_search("1",$arr)) {
    //will actually evaluate to false
}

In case you are using it this way and think it's not working because the conditional isn't technically failing, the value is evaluated as FALSE.


问:
How to access entries of a list using a numpy array without using a for loop
Given a list L = [0,1,2,3,4,5,6,7,8,9]. What's the best way to access/extract elements where their indices are given by a numpy array? Let nArr=np.array([0,-1,2,6]).

The resulting output should be another list P = [0,9,2,6].

It is clear that when the elements are uniform in shape, we can simply cast it into another numpy array, but what if it isn't? For example, M = [np.random.rand(5,5), np.random.rand(1)].

答:
To summarize the comments: lists do not support indexing by an array, like L[nArr] where nArr is an array of indexes. One normally uses list comprehension, [L[i] for i in nArr]. But if you want to, you can cast the list to a NumPy array of objects, which can then be indexed and sliced as any other NumPy array:

```<code>np.array(L, dtype=object)[nArr]
</code>```

If you want a list returned, you can do:

```<code>np.array(L, dtype=object)[nArr].tolist()
</code>```

But that's not nearly as pythonic as list comprehension, requires more memory, and very likely doesn't improve the speed.

Body:
To summarize the comments: lists do not support indexing by an array, like L[nArr] where nArr is an array of indexes. One normally uses list comprehension, [L[i] for i in nArr]. But if you want to, you can cast the list to a NumPy array of objects, which can then be indexed and sliced as any other NumPy array:

np.array(L, dtype=object)[nArr]

If you want a list returned, you can do:

np.array(L, dtype=object)[nArr].tolist()

But that's not nearly as pythonic as list comprehension, requires more memory, and very likely doesn't improve the speed.


问:
Remove part of attributed string without removing attributes
I have some text in my attributed string that I am trying to remove. How can I do this without removing the attributes?

What I've tried:

I found this post on SO (Replace substring of NSAttributedString with another NSAttributedString) where OP is looking for the equivalent method to NSString's stringByReplacingOccurrencesOfString:withString: for NSAttributedString. I am new to Swift so I couldn't understand the accepted answer.

I moved on to the other answers and if they weren't written in objective c, they were methods that I could not get to compile.

This is as far as I have been able to get. I couldn't find any other posts on SO with a solution to my problem.

答:
To remove part of an attributed string you need to use the NSMutableAttributedString deleteCharacters(in:) method.

Here's some sample code:

```<code>// Create some attributes string
let attrs: [NSAttributedStringKey: Any] = [ .foregroundColor: UIColor.red, .font: UIFont.systemFont(ofSize: 24) ]
let attrStr = NSAttributedString(string: "Hello there", attributes: attrs)
print(attrStr)

// Create a mutable attributed string, find the range to remove and remove it
let mutStr = attrStr.mutableCopy() as! NSMutableAttributedString
let range = (mutStr.string as NSString).range(of: " there")
mutStr.deleteCharacters(in: range)
print(mutStr)
</code>```

Output:

```
Hello there{
    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";
}
Hello{
    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";
}
```

Body:
To remove part of an attributed string you need to use the NSMutableAttributedString deleteCharacters(in:) method.

Here's some sample code:

// Create some attributes string
let attrs: [NSAttributedStringKey: Any] = [ .foregroundColor: UIColor.red, .font: UIFont.systemFont(ofSize: 24) ]
let attrStr = NSAttributedString(string: "Hello there", attributes: attrs)
print(attrStr)

// Create a mutable attributed string, find the range to remove and remove it
let mutStr = attrStr.mutableCopy() as! NSMutableAttributedString
let range = (mutStr.string as NSString).range(of: " there")
mutStr.deleteCharacters(in: range)
print(mutStr)

Output:

Hello there{
    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";
}
Hello{
    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";
}


问:
How to find the values where the standardize factor is less than a certain value in r?
So in R I'm using principal component analysis for a csv file with variables each representing a year from 1 to 32.

Here is the code:

```<code>Xdata <- context2[2:ncol(context2)]
head(Xdata)
model5 <- prcomp(Xdata)
model5$rotation[,1]*100
screeplot(model5,type="lines")
factor <- model5$x[,1]
context2$factor <- factor
factor2 = matrix(c(factor), nrow=651, ncol=1)
factor <- factor2 %*% solve(sqrtm(crossprod(factor2))) * sqrt(nrow(factor2))
crossprod(factor)/nrow(factor)
</code>```

All of that code above works fine, but I need to find the year values where the standardized factor is less than -2.58. If I view the standardized factor in r I can get values less than -2.58 by just looking, but the numbers are outputs of the principal component 1 variable like this: https://imgur.com/a/OGNVq. How do I go about getting the years where the standardized factor is less than -2.58?

答:
It is not clear which is the that contains the standardized factor, nor which variable contains "years". I am guessing the variable is:

```<code>crossprod(factor)/nrow(factor)
</code>```

If the year variable and the variable I mentioned above are in the same order (that is, the year in the nth position corresponds to the factor in the same position), then you could use base R to get the year. For example:

```<code>factor_variable <- crossprod(factor)/nrow(factor)
year[which(factor_variable < -2.58)]
</code>```

Body:
So in R I'm using principal component analysis for a csv file with variables each representing a year from 1 to 32.

Here is the code:

Xdata <- context2[2:ncol(context2)]
head(Xdata)
model5 <- prcomp(Xdata)
model5$rotation[,1]*100
screeplot(model5,type="lines")
factor <- model5$x[,1]
context2$factor <- factor
factor2 = matrix(c(factor), nrow=651, ncol=1)
factor <- factor2 %*% solve(sqrtm(crossprod(factor2))) * sqrt(nrow(factor2))
crossprod(factor)/nrow(factor)

All of that code above works fine, but I need to find the year values where the standardized factor is less than -2.58. If I view the standardized factor in r I can get values less than -2.58 by just looking, but the numbers are outputs of the principal component 1 variable like this: https://imgur.com/a/OGNVq. How do I go about getting the years where the standardized factor is less than -2.58?

Body:
It is not clear which is the that contains the standardized factor, nor which variable contains "years". I am guessing the variable is:

crossprod(factor)/nrow(factor)

If the year variable and the variable I mentioned above are in the same order (that is, the year in the nth position corresponds to the factor in the same position), then you could use base R to get the year. For example:

factor_variable <- crossprod(factor)/nrow(factor)
year[which(factor_variable < -2.58)]


问:
Parsing #regions within Code Files
I'm trying to create a C# program that extracts the code contained within #region tags in *.cs files.  I more or less just want to be able to anotate the code I'm working on and have it be accessible to this other program as just text.

Is there something that already exists that accomplishes this?

Say I have code like this:

```<code>#region ClassName.Test()
public static void Test()
{
     //Some method that does stuff
}
#endregion
</code>```

I'd like to be able to extract

```<code>public static void Test()
{
     //Some method that does stuff
}
</code>```

from the *.cs as a string when I specify that I'm looking for Class.Test().

答:
If you are not worried about nested #regions. This code would do the trick.
Call GetCodeRegions() passing in your code string (you obtained by using File.ReadAlltext) to get a list of the code snippets within the regions you want.</p>

```<code>    static void Main(string[] args)
    {
        var code = @"#region ClassName.Test()    //Some method that does stuff
            //some stuff
            #endregion

            #region ClassCName.Random()
            public static void Test()
            {
                 //Some more stuff
            }
            #endregion";

        List<string> codeRegions = GetCodeRegions(code);
    }

    private static List<string> GetCodeRegions(string code)
    {
        List<string> codeRegions = new List<string>();

        //Split code into regions
        var matches = Regex.Matches(code, "#region.*?#endregion", RegexOptions.Singleline);

        foreach (var match in matches)
        {
            //split regions into lines
            string[] lines = match.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None);

            if (lines.Length > 2)
            {
                codeRegions.Add(string.Join("\r\n", lines, 1, lines.Length - 2));
            }

        }

        return codeRegions;
    }
</code>```

Title: Parsing #regions within Code Files

Body:
I'm trying to create a C# program that extracts the code contained within #region tags in *.cs files.  I more or less just want to be able to anotate the code I'm working on and have it be accessible to this other program as just text.

Is there something that already exists that accomplishes this?

Say I have code like this:

#region ClassName.Test()
public static void Test()
{
     //Some method that does stuff
}
#endregion

I'd like to be able to extract

public static void Test()
{
     //Some method that does stuff
}

from the *.cs as a string when I specify that I'm looking for Class.Test().

Body:
If you are not worried about nested #regions. This code would do the trick.
Call GetCodeRegions() passing in your code string (you obtained by using File.ReadAlltext) to get a list of the code snippets within the regions you want.

    static void Main(string[] args)
    {
        var code = @"#region ClassName.Test()    //Some method that does stuff
            //some stuff
            #endregion

            #region ClassCName.Random()
            public static void Test()
            {
                 //Some more stuff
            }
            #endregion";

        List<string> codeRegions = GetCodeRegions(code);
    }

    private static List<string> GetCodeRegions(string code)
    {
        List<string> codeRegions = new List<string>();

        //Split code into regions
        var matches = Regex.Matches(code, "#region.*?#endregion", RegexOptions.Singleline);

        foreach (var match in matches)
        {
            //split regions into lines
            string[] lines = match.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None);

            if (lines.Length > 2)
            {
                codeRegions.Add(string.Join("\r\n", lines, 1, lines.Length - 2));
            }

        }

        return codeRegions;
    }


问:
Azure functions post issue
Hi Iam new to Azure functions i am using VS 2017 15.4 and running helloworld function app on local. i was able to do get request on this function but when i perform post on same uri it gives.

mscorlib: Exception while executing function: HelloWorld. System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'application/octet-stream'.

can you tell me what i forgot bold line is giving problem in post request, i tried with contentType and without ContentType; with body and without body.

How can i parse Json object in request body in azure function. one way i could was to parse it in string then deserialized using jsonconvert. is their any better way of doing it like valueproviders modelbinders etc.

```<code>[FunctionName("HelloWorld")]
public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");

        // parse query parameter
        string name = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
            .Value;

        // Get request body
        *dynamic data = await req.Content.ReadAsAsync<object>();*

        // Set name to query string or body data
        name = name ?? data?.name;

        return name == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }.
</code>```

答:
This should work assuming the Content-Type header on your HTTP request is set to application/json.

Note that if the header's value is multipart/form-data, then this is a known bug documented here.

Title: Azure functions post issue

Body:
Hi Iam new to Azure functions i am using VS 2017 15.4 and running helloworld function app on local. i was able to do get request on this function but when i perform post on same uri it gives.

mscorlib: Exception while executing function: HelloWorld. System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'application/octet-stream'.

can you tell me what i forgot bold line is giving problem in post request, i tried with contentType and without ContentType; with body and without body.

How can i parse Json object in request body in azure function. one way i could was to parse it in string then deserialized using jsonconvert. is their any better way of doing it like valueproviders modelbinders etc.

[FunctionName("HelloWorld")]
public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");

        // parse query parameter
        string name = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
            .Value;

        // Get request body
        *dynamic data = await req.Content.ReadAsAsync<object>();*

        // Set name to query string or body data
        name = name ?? data?.name;

        return name == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }.


问:
CSS center with translate and prevent content overflow
I have this code for centering both horizontally and vertically. It works well except when there is more content than fits, the content gets cut off. Is there a way to restrict this with css so it doesn't go out of visible area? I dont want to involve javascript.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  <div class="b">dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus. </div>
</div></code>```

答:
Your div was going above the page height when you transformed the y by -50%.
Try this:

```<code>-webkit-transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0);
transform: translate(-50%, 0);
</code>```

Body:
I have this code for centering both horizontally and vertically. It works well except when there is more content than fits, the content gets cut off. Is there a way to restrict this with css so it doesn't go out of visible area? I dont want to involve javascript.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus.

Body:
Your div was going above the page height when you transformed the y by -50%.
Try this:

-webkit-transform: translate(-50%, 0);
-ms-transform: translate(-50%, 0);
transform: translate(-50%, 0);


问:
How to hook up NSWindowDelegate in macOS game template
This is a "how-to" for related question:
cocoa windowDidEnterFullScreen not being called

Using the Xcode (9.1) macOS "game" template -

I would like to create a simple NSWindowDelegate using the AppDelegate class. However I can't seem to connect the given NSWindow outlet to anything.

```<code>// AppDelegate.h
#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>

@property (assign) IBOutlet NSWindow *window; // won't connect

@end
</code>```

I assume I'm supposed to connect to a "Window" within the storyboard. This is what happens when I try to connect - the inspector does not show up.

What am I missing here?

Note: I'm just playing around so I don't care if AppDelegate is the right place or not, I just want something to work.

EDIT 1

Using suggestion from answer, I've tried connecting the 'TestFullscreen' window to the AppDelegate object, but it still won't connect, either from the AppDelegate inspector or the property declaration in the code.

答:
A workaround is to simply create non-Workspace project.

Editing the XIB allows you to connect the Window delegate outlet to the AppDelegate, after it has NSWindowDelegate protocol specified.

Body:
This is a "how-to" for related question:
cocoa windowDidEnterFullScreen not being called

Using the Xcode (9.1) macOS "game" template -

I would like to create a simple NSWindowDelegate using the AppDelegate class. However I can't seem to connect the given NSWindow outlet to anything.

// AppDelegate.h
#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>

@property (assign) IBOutlet NSWindow *window; // won't connect

@end

I assume I'm supposed to connect to a "Window" within the storyboard. This is what happens when I try to connect - the inspector does not show up.

What am I missing here?

Note: I'm just playing around so I don't care if AppDelegate is the right place or not, I just want something to work.

EDIT 1

Using suggestion from answer, I've tried connecting the 'TestFullscreen' window to the AppDelegate object, but it still won't connect, either from the AppDelegate inspector or the property declaration in the code.


问:
Using JSON result from Zippopotam.us for Google maps coordinate
The code that I made will ask the user to enter an input (any Malaysian Zip code), and the input will fetch a JSON result from Zippopotam.us. Below is my full codes :

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Assignment  Lab 3</title>
    <style>
input[type=text], select {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

button {
    width: 100%;
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

div #zipdiv, #citydiv, #statediv, #longitudediv, #latitudediv
{
    border-radius: 5px;
    background-color: #f2f2f2;
    padding: 20px;
}

</style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
$(function() {

  $(document).ready( function()
  {
    $("#citydiv").hide();
    $("#statediv").hide();
    $("#longitudediv").hide();
    $("#latitudediv").hide();
    $("#mapdiv").hide();

  });

  // OnKeyDown Function
  $("#zcode").keyup(function() {
    var zip_in = $(this);
    var zip_box = $('#zipdiv');

    if (zip_in.val().length<5)
    {
      zip_box.removeClass('error success');
    }
    else if ( zip_in.val().length>5)
    {
      zip_box.addClass('error').removeClass('success');
    }
    else if ((zip_in.val().length == 5) )
    {

      // Make HTTP Request
      $.ajax({
        url: "http://api.zippopotam.us/MY/" + zip_in.val(),
        cache: false,
        dataType: "json",
        type: "GET",
        success: function(result, success) {
          // Make the city and state boxes visible
          $('#citydiv').slideDown(200);
          $('#statediv').slideDown(200);
          $('#longitudediv').slideDown(200);
          $('#latitudediv').slideDown(200);

          // Zip Code Records Officially Map to only 1 Primary Location
          places = result['places'][0];
          $("#city").val(places['place name']);
          $("#state").val(places['state']);
          $("#long").val(places['longitude']);
          $("#lat").val(places['latitude']);
          zip_box.addClass('success').removeClass('error');
        },
        error: function(result, success) {
          zip_box.removeClass('success').addClass('error');
        }
      });
    }
});

});
function mapFunction() {

var mapOptions =
{
   // Set up the map options
  center: new google.maps.LatLng(),//coordinate should be from JSON results
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  zoom: 13,
};
var venueMap;                                      // Map() draws a map
venueMap = new google.maps.Map(document.getElementById('map'), mapOptions);
}

function loadScript()
{
var script = document.createElement('script');     // Create <script> element
script.src = 'http://maps.googleapis.com/maps/api/js?sensor=false&callback=mapFunction';
document.body.appendChild(script);                 // Add element to page
}

window.onload = loadScript;                          // on load call loadScript()

$(document).ready(function()
{
  $(".button").click(function()
  {
    $("#mapdiv").show(200);
  });
});

</script>

  </head>
  <body>
    <h3>Enter Malaysian Zip Code</h3>

<div>
  <form action="#" method="post" class="form fancy-form">
    <div id="zipdiv">
      <label for="zip">Zip Code</label>
      <input type="text" id="zcode" name="Zip code" placeholder="E.g : 48050">
    </div>

    <div id="citydiv">
      <label id="city_lbl" for="city">City</label>
      <input type="text" id="city" name="city">
  </div>

    <div id="statediv">
      <label id="state_lbl" for="state">State</label>
      <input type="text" id="state" name="state">
    </div>

    <div id="longitudediv">
      <label id="lgtd_lbl" for="longitude">Longitude</label>
      <input type="text" id="long" name="longitude">
    </div>

    <div id="latitudediv">
      <label id="lttd_lbl" for="latitude">Latitude</label>
      <input type="text" id="lat" name="latitude">
    </div>

    <button id="button" class="button" type="button" name="button">Submit</button>
    <div id="mapdiv">Map here: <div id="map" style="width:400px;height:400px;"></div></div>

</form>

</div>
  </body>
</html>
</code>```

Below is one of the many example of the JSON Result user can get from Zippopotam.us :

{"post code": "01000",
     "country": "Malaysia",
     "country abbreviation": "MY",
     "places": [{"place name": "Kangar", "longitude": "100.2056", "state": "Perlis",
    "state abbreviation": "PLS", "latitude": "6.4312"}]}

Another example :

{"post code": "48050", "country": "Malaysia", "country abbreviation": "MY", "places": [{"place name": "Rawang", "longitude": "101.5642", "state": "Selangor", "state abbreviation": "SGR", "latitude": "3.2559"}]}

My programme should take the value of latitude and longitude from these results to be inserted to

```<code>center: new google.maps.LatLng(latitude here, longitude here),
//coordinate should be from JSON results the user get
</code>```

The problem is, I've tried many ways, but it seems that I can't put the latitude and longitude from the JSON result to the above code (except from writing the numbers manually, but that's not how this programme supposed to work).

The programme should take the latitude and longitude value, and insert it automatically to the above code, so that when the user click the Submit button, a Google map is generated from that coordinates.

How do I solve this? Thank you in advance~

答:
Move the initialization of the map into the the .show complete function for the mapDiv, so it executes after the map has a size and the success function of the $.ajax call has run and populated the value of the places object:

```<code>$(document).ready(function()
{
  $(".button").click(function()
  {
    $("#mapdiv").show(200, function() {
      mapFunction();
    });
  });
});
</code>```

proof of concept fiddle

jQuery .show function documentation

.show( [duration ] [, complete ] )

  duration (default: 400)

  Type: Number or String

  A string or number determining how long the animation will run.

  complete

  Type: Function()

  A function to call once the animation is complete, called once per matched element.

Body:
The code that I made will ask the user to enter an input (any Malaysian Zip code), and the input will fetch a JSON result from Zippopotam.us. Below is my full codes :

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Assignment  Lab 3</title>

Enter Malaysian Zip Code

  <form action="#" method="post" class="form fancy-form">

      Zip Code
      <input type="text" id="zcode" name="Zip code" placeholder="E.g : 48050">

      City
      <input type="text" id="city" name="city">

      State
      <input type="text" id="state" name="state">

      Longitude
      <input type="text" id="long" name="longitude">

      Latitude
      <input type="text" id="lat" name="latitude">

    <button id="button" class="button" type="button" name="button">Submit</button>

Map here:

</form>

Below is one of the many example of the JSON Result user can get from Zippopotam.us :

{"post code": "01000",
     "country": "Malaysia",
     "country abbreviation": "MY",
     "places": [{"place name": "Kangar", "longitude": "100.2056", "state": "Perlis",
    "state abbreviation": "PLS", "latitude": "6.4312"}]}

Another example :

{"post code": "48050", "country": "Malaysia", "country abbreviation": "MY", "places": [{"place name": "Rawang", "longitude": "101.5642", "state": "Selangor", "state abbreviation": "SGR", "latitude": "3.2559"}]}

My programme should take the value of latitude and longitude from these results to be inserted to

center: new google.maps.LatLng(latitude here, longitude here),
//coordinate should be from JSON results the user get

The problem is, I've tried many ways, but it seems that I can't put the latitude and longitude from the JSON result to the above code (except from writing the numbers manually, but that's not how this programme supposed to work).

The programme should take the latitude and longitude value, and insert it automatically to the above code, so that when the user click the Submit button, a Google map is generated from that coordinates.

How do I solve this? Thank you in advance~

Body:
Move the initialization of the map into the the .show complete function for the mapDiv, so it executes after the map has a size and the success function of the $.ajax call has run and populated the value of the places object:

$(document).ready(function()
{
  $(".button").click(function()
  {
    $("#mapdiv").show(200, function() {
      mapFunction();
    });
  });
});

proof of concept fiddle

jQuery .show function documentation

.show( [duration ] [, complete ] )

  duration (default: 400)

  Type: Number or String

  A string or number determining how long the animation will run.

  complete

  Type: Function()

  A function to call once the animation is complete, called once per matched element.


问:
Install AWS Toolking For Visual Studio 2017 for MAC
Is there a way I can install AWS Toolkit For Visual Studio 17 on MAC?

I downloaded the toolkit from https://marketplace.visualstudio.com/items?itemName=AmazonWebServices.AWSToolkitforVisualStudio2017. If I open it with Visual Studio, it opens the file as a text editor.

I downloaded Visual Studio Community Edition from https://www.visualstudio.com/downloads/

答:
Currently the AWS Toolkit for Visual Studio does not support Visual Studio for Mac. See below:

https://aws.amazon.com/visualstudio/

It still does not on 21/03/2021.

ContentLicense: CC BY-SA 4.0


问:
how to append data after clear ckeditor
I need to append data after cleared in CKeditor but what happens is the all data cleared and no data appended

```<code>     $('.my_r_warning').on('click', function () {
                CKEDITOR.instances['js-ckeditor'].setData('');
            CKEDITOR.instances['js-ckeditor'].insertText('Reply :');
                $('html, body').animate({
                            scrollTop: $('#form').offset().top
                                    }, 2000)
          })
    </script>
</code>```

答:
If you need insert data to clear ckeditor, you can just do like this   </p>

```<code>   $('.my_r_warning').on('click', function () {
                CKEDITOR.instances['js-ckeditor'].setData('Reply :');
                $('html, body').animate({
                            scrollTop: $('#form').offset().top
                                    }, 2000)
          })
</code>```

Title: how to append data after clear ckeditor

Body:
I need to append data after cleared in CKeditor but what happens is the all data cleared and no data appended

     $('.my_r_warning').on('click', function () {
                CKEDITOR.instances['js-ckeditor'].setData('');
            CKEDITOR.instances['js-ckeditor'].insertText('Reply :');
                $('html, body').animate({
                            scrollTop: $('#form').offset().top
                                    }, 2000)
          })
    </script>

Body:
If you need insert data to clear ckeditor, you can just do like this

   $('.my_r_warning').on('click', function () {
                CKEDITOR.instances['js-ckeditor'].setData('Reply :');
                $('html, body').animate({
                            scrollTop: $('#form').offset().top
                                    }, 2000)
          })