问:
Vue: props doesn't get assigned automatically; when assigned manually - Avoid mutating a prop directly - error
I have two vue components: GetAnimal.vue and DisplayAnimal.vue. GetAnimal.vue send a JSON with animal data to DisplayAnimal.vue using router push. DisplayAnimal.vue displays that data. It works like this: I go to /getanimal, click a button that triggers the getAnimal() function which leads me to /viewanimal (via a router push):

GetAnimal.vue:

```<code><script>
    import axios from 'axios';

    export default {
        data: function () {
            return {
                name: 'defaultAnimal',
                defaultanimal: {
                    name: 'Cat',
                    furColor: 'red',
                    population: '10000',
                    isExtinct: false,
                    isDomesticated: true
                },
                animal: String
            }
        },
        methods: {
            getAnimal: function () {
                console.log("this.defaultanimal: " +
                    JSON.stringify(this.defaultanimal));

                this.$router.push({
                     name: "viewanimal",
                    params: {
                         animal: this.defaultanimal
                     }
                 });

            },
...
</code>```

DisplayAnimal.vue:

```<code><template>
    <div>
        <h1>Displaying animal:</h1>
        <p>Animal name: {{animal.name}}}</p>
        <p>Fur color: {{animal.furColor}}</p>
        <p>Population: {{animal.population}}</p>
        <p>Is extinct: {{animal.isExtinct}}</p>
        <p>Is domesticated: {{animal.isDomesticated}}</p>

    </div>
</template>

<script>
    import axios from "axios";

    export default {
        props:  {
            animal:  {
                name: {
                    type: String
                },
                furColor:  {
                    type: String
                },
                population: String,
                isExtinct: String,
                isDomesticated: String
            }
        },

        name: "DisplayAnimal",

        methods: {

        },
        created() {
            console.log("animal param: " +
                JSON.stringify(this.$route.params.animal));
            this.animal = this.$route.params.animal;
        }
    };
</script>
</code>```

The animal gets displayed just fine:

However I get the warning in console:

The this.animal = this.$route.params.animal; line that assigns the props explicitly is likely the cause of the warning.

However if I remove that line the animal doesn't get displayed at all:

I have this

router.js:

```<code>{
    path: "/viewanimal",
    name: "viewanimal",
    component: () => import('./views/DisplayAnimal.vue'),
    props: {animal: true}
},
{
    path: "/getanimal",
    name: "getanimal",
    component: () => import('./views/GetAnimal.vue')
}
</code>```

I thought setting props: {animal: true} would make sure it's autoassigned, but it doesn't seem to be the case. How should I fix it?

答:
Well updating prop directly is an antipattern

It also doesnt make sense to have animal prop in DisplayAnimal component when you know it is not part of parent component which passes data to it. animal should be inside data so you can update in created callback.

Example

data() {
  return {
    loading: true, // perhaps you'd like to show loader before data gets fetched
    animal: {
        id: -1,
        name: '',
        furColor: '',
        population: 0,
        isExtinct: false,
        isDomesticated: false
    }
  }
},
created() {
  this.animal = this.$route.params.animal;
  this.loading = false;
}
```

Body:
I have two vue components: GetAnimal.vue and DisplayAnimal.vue. GetAnimal.vue send a JSON with animal data to DisplayAnimal.vue using router push. DisplayAnimal.vue displays that data. It works like this: I go to /getanimal, click a button that triggers the getAnimal() function which leads me to /viewanimal (via a router push):

GetAnimal.vue:

The animal gets displayed just fine:

However I get the warning in console:

The this.animal = this.$route.params.animal; line that assigns the props explicitly is likely the cause of the warning.

However if I remove that line the animal doesn't get displayed at all:

I have this

router.js:

{
    path: "/viewanimal",
    name: "viewanimal",
    component: () => import('./views/DisplayAnimal.vue'),
    props: {animal: true}
},
{
    path: "/getanimal",
    name: "getanimal",
    component: () => import('./views/GetAnimal.vue')
}

I thought setting props: {animal: true} would make sure it's autoassigned, but it doesn't seem to be the case. How should I fix it?


来源: stackexchange

问:
Remove characters from url hash
Wanting to remove characters from a hash in a url

side bar create url with anchor

e.g

html/g_later_life_lett.html#3.-what-is-important?everything!

```<code>var test = window.location.hash;
$(test).replace('?', '')
</code>```

so when page loads it looks af any ? and ! in hash and removes them.

thanks for help

Updated: thanks add this works fine now

```<code>var currentHash = window.location.hash;
var cleanHash = currentHash.replace(/[?!]/g, "");
window.location.hash = cleanHash;
</code>```

答:
You don't need to use jQuery. you can do this with JavaScript string replace method.

var test = "html/g_later_life_lett.html#3.-what-is-important**?-everything!**";
test = test.replace(/[?!]/g, "")
console.log(test);```

The regular expression /[?!]/g selects all ? and ! from the input string.

g: stands for global. And then I am replacing all occurrences with empty string.

ContentLicense: CC BY-SA 4.0

Title: Remove characters from url hash

Body:
Wanting to remove characters from a hash in a url

side bar create url with anchor

e.g

html/g_later_life_lett.html#3.-what-is-important?everything!

var test = window.location.hash;
$(test).replace('?', '')

so when page loads it looks af any ? and ! in hash and removes them.

thanks for help

Updated: thanks add this works fine now

var currentHash = window.location.hash;
var cleanHash = currentHash.replace(/[?!]/g, "");
window.location.hash = cleanHash;

Body:
You don't need to use jQuery. you can do this with JavaScript string replace method.

var test = "html/g_later_life_lett.html#3.-what-is-important**?-everything!**";
test = test.replace(/[?!]/g, "")
console.log(test);

The regular expression /[?!]/g selects all ? and ! from the input string.

g: stands for global. And then I am replacing all occurrences with empty string.


问:
Add an image in a specific position in the document (.docx)?
I use Python-docx to generate Microsoft Word document.The user want that when he write for eg: "Good Morning every body,This is my %(profile_img)s do you like it?"
in a HTML field, i create a word document and i recuper the picture of the user from the database and i replace the key word %(profile_img)s by the picture of the user NOT at the END OF THE DOCUMENT. With Python-docx we use this instruction to add a picture:

```<code>document.add_picture('profile_img.png', width=Inches(1.25))
</code>```

The picture is added to the document but the problem that it is added at the end of the document.
Is it impossible to add a picture in a specific position in a microsoft word document with python? I've not found any answers to this in the net but have seen people asking the same elsewhere with no solution.

Thanks (note: I'm not a hugely experiance programmer and other than this awkward part the rest of my code will very basic)

答:
This is adopting the answer written by Robᵩ while considering more flexible input from user.
My assumption is that the HTML field mentioned by Kais Dkhili (orignal enquirer) is already loaded in docx.Document(). So...

Identify where is the related HTML text in the document.

```<code>import re
## regex module

img_tag = re.compile(r'%\(profile_img\)s') # declare pattern

for _p in enumerate(document.paragraphs):
    if bool(img_tag.match(_p.text)):

        img_paragraph = _p
        # if and only if; suggesting img_paragraph a list and
        # use append method instead for full document search

        break # lose the break if want full document search
</code>```

Replace desired image into placeholder identified as img_tag = '%(profile_img)s'

The following code is after considering the text contains only a single run
May be changed accordingly if condition otherwise

```<code>temp_text = img_tag.split(img_paragraph.text)

img_paragraph.runs[0].text = temp_text[0]

_r = img_paragraph.add_run()
_r.add_picture('profile_img.png', width = Inches(1.25))

img_paragraph.add_run(temp_text[1])
</code>```

and done. document.save() it if finalised.

In case you are wondering what to expect from the temp_text...

[In]

```<code>img_tag.split(img_paragraph.text)
</code>```

[Out]

```<code>['This is my ', ' do you like it?']
</code>```

Body:
I use Python-docx to generate Microsoft Word document.The user want that when he write for eg: "Good Morning every body,This is my %(profile_img)s do you like it?"
in a HTML field, i create a word document and i recuper the picture of the user from the database and i replace the key word %(profile_img)s by the picture of the user NOT at the END OF THE DOCUMENT. With Python-docx we use this instruction to add a picture:

document.add_picture('profile_img.png', width=Inches(1.25))

The picture is added to the document but the problem that it is added at the end of the document.
Is it impossible to add a picture in a specific position in a microsoft word document with python? I've not found any answers to this in the net but have seen people asking the same elsewhere with no solution.

Thanks (note: I'm not a hugely experiance programmer and other than this awkward part the rest of my code will very basic)

Body:
This is adopting the answer written by Robᵩ while considering more flexible input from user.
My assumption is that the HTML field mentioned by Kais Dkhili (orignal enquirer) is already loaded in docx.Document(). So...

Identify where is the related HTML text in the document.

import re
## regex module

img_tag = re.compile(r'%\(profile_img\)s') # declare pattern

for _p in enumerate(document.paragraphs):
    if bool(img_tag.match(_p.text)):

        img_paragraph = _p
        # if and only if; suggesting img_paragraph a list and
        # use append method instead for full document search

        break # lose the break if want full document search

Replace desired image into placeholder identified as img_tag = '%(profile_img)s'

The following code is after considering the text contains only a single run
May be changed accordingly if condition otherwise

temp_text = img_tag.split(img_paragraph.text)

img_paragraph.runs[0].text = temp_text[0]

_r = img_paragraph.add_run()
_r.add_picture('profile_img.png', width = Inches(1.25))

img_paragraph.add_run(temp_text[1])

and done. document.save() it if finalised.

In case you are wondering what to expect from the temp_text...

[In]

img_tag.split(img_paragraph.text)

[Out]

['This is my ', ' do you like it?']


问:
When does ElasticSearch performs a flush
What are the conditions that trigger a flush in ElasticSearch node/index/shard?

There are good explanations about the flow of ElasticSearch refreshing every second and flushing in a less frequent manner to avoid intensive CPU usage, but which component is responsible to perform the flush?

I tried to look over the source code but didn't manage to find the right place.

答:
There is no fixed interval, Elasticsearch uses some heuristic to determine when to call flush as mentioned in the official doc

Elasticsearch automatically triggers flushes as needed, using
  heuristics that trade off the size of the unflushed transaction log
  against the cost of performing each flush.

Also as explained in at the end of this SO answer from Elastic team member, this heuristic depends on

depending on how many operations get added to the transaction log, how
  big they are, and when the last flush happened.

Note: You can also tweak the setting of flush operation but not recommended.

Edit: https://github.com/elastic/elasticsearch/blob/master/server/src/main/java/org/elasticsearch/action/bulk/BulkProcessor.java#L48 is the source code which processes the flush operation.


问:
app works with yarn start but not in simulator
I am using yarn run ios to run a react native project in Xcode simulator. This was working perfectly till two weeks ago but it's not working right now. Now, I get errors like these:

```<code>error: /Users/app/ios/Pods/Target Support Files/Pods-Inst/Pods-Inst.debug.xcconfig: unable to open file (in target "Inst" in project "Inst") (in target 'Inst' from project 'Inst')

** BUILD FAILED **

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

I had already tried cleaning cache, removing node modules etc etc but nothing works.

error Command failed with exit code 1. when I try to run yarn

If I simply do yarn start, I think it builds successfully since I can see the flower and all on the terminal. However, when I try using the simulator, it doesn't work. How can I fix this?

答:
Go to /ios folder and the run the following command:

pod install && pod update
```</li>
<li><p>Then go back to the project folder and run the following command:</p>

<pre class="lang-none prettyprint-override"><code>rm -rf node_modules && npm install
</code>```

Next, clean the ios build folder:

rm -rf ios/build
```</li>
<li><p>After that, just run as usual:</p>

<pre class="lang-none prettyprint-override"><code>react-native run-ios
</code>```

Body:
I am using yarn run ios to run a react native project in Xcode simulator. This was working perfectly till two weeks ago but it's not working right now. Now, I get errors like these:

error: /Users/app/ios/Pods/Target Support Files/Pods-Inst/Pods-Inst.debug.xcconfig: unable to open file (in target "Inst" in project "Inst") (in target 'Inst' from project 'Inst')

** BUILD FAILED **

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I had already tried cleaning cache, removing node modules etc etc but nothing works.

error Command failed with exit code 1. when I try to run yarn

If I simply do yarn start, I think it builds successfully since I can see the flower and all on the terminal. However, when I try using the simulator, it doesn't work. How can I fix this?

Body:
Go to /ios folder and the run the following command:

pod install && pod update

Then go back to the project folder and run the following command:

rm -rf node_modules && npm install

Next, clean the ios build folder:

rm -rf ios/build

After that, just run as usual:

react-native run-ios


问:
Angular 8: ERROR in Can't resolve all parameters for TextAreaEditorComponent
We recently upgraded angular to 8.2.14 The below code was a class which i attempted to convert to a component. I get the following error

ERROR in Can't resolve all parameters for TextAreaEditorComponent

Basically the issue is the constructor  .

This was to extend a vendor app SpreadJS

```<code> import { Component, OnInit, ElementRef, ViewChild, Input, Optional } from '@angular/core';

@Component({
    styleUrls: ['./text-area-editor.component.scss'],
    templateUrl: './text-area-editor.component.html'
})
export class TextAreaEditorComponent implements OnInit {
   // @Input() options: any;
    options: any;
    textArea: any;
    containerKeyDownHandler: any;
    containerClickHandler: any;
    maxLength = 500;

    @ViewChild('container', { static: true }) input: ElementRef;

    constructor(
       options: any
    ) {
      this.options = options;
    }

    ngOnInit() {
    }

    init(): void {
        const options = this.options;
        const container = options.container;
        this.maxLength = this.options.col.editor.maxLength;

        this.textArea = container.children[0];

        this.textArea.value = options.value;
        this.textArea.focus();

        this.handleClick = this.handleClick.bind(this);
        this.handleKeyDown = this.handleKeyDown.bind(this);

        container.addEventListener('click', this.handleClick);
        container.addEventListener('keydown', this.handleKeyDown);
    }

    destroy() {
        const container = this.options.container;
        container.removeEventListener('click', this.handleClick);
        container.removeEventListener('keydown', this.handleKeyDown);
    }

    focus() {
        this.textArea.focus();
    }

    serialize() {
        return this.textArea.value;
    }

    handleClick(event) {
        event.stopPropagation();
        if (event.target && event.target.tagName.toLowerCase() === 'button') {
            if (event.target.className === 'save') {
                this.options.dataview.stopEditing();
            } else if (event.target.className === 'cancel') {
                this.options.dataview.cancelEditing();
            }
        }
    }

    handleKeyDown(event) {
        if (event.defaultPrevented || !document.activeElement) {
            return;
        }

        if (event.srcElement.value.length > this.maxLength) {
            event.srcElement.value = event.srcElement.value.substring(0, this.maxLength);

        }
        const key = event.key || event.keyCode;
        if (key === 'Enter' || key === 13) {
            if (document.activeElement.className === 'save') {
                event.stopPropagation();
                this.options.dataview.stopEditing();
            } else if (document.activeElement.className === 'cancel') {
                event.stopPropagation();
                this.options.dataview.cancelEditing();
            }
        }
    }
}
</code>```

答: In TextAreaComponent Decorator selector for this component is missing. There should be a selector for the component.</p>

Body:
We recently upgraded angular to 8.2.14 The below code was a class which i attempted to convert to a component. I get the following error

ERROR in Can't resolve all parameters for TextAreaEditorComponent

Basically the issue is the constructor  .

This was to extend a vendor app SpreadJS

 import { Component, OnInit, ElementRef, ViewChild, Input, Optional } from '@angular/core';

@Component({
    styleUrls: ['./text-area-editor.component.scss'],
    templateUrl: './text-area-editor.component.html'
})
export class TextAreaEditorComponent implements OnInit {
   // @Input() options: any;
    options: any;
    textArea: any;
    containerKeyDownHandler: any;
    containerClickHandler: any;
    maxLength = 500;

    @ViewChild('container', { static: true }) input: ElementRef;

    constructor(
       options: any
    ) {
      this.options = options;
    }

    ngOnInit() {
    }

    init(): void {
        const options = this.options;
        const container = options.container;
        this.maxLength = this.options.col.editor.maxLength;

        this.textArea = container.children[0];

        this.textArea.value = options.value;
        this.textArea.focus();

        this.handleClick = this.handleClick.bind(this);
        this.handleKeyDown = this.handleKeyDown.bind(this);

        container.addEventListener('click', this.handleClick);
        container.addEventListener('keydown', this.handleKeyDown);
    }

    destroy() {
        const container = this.options.container;
        container.removeEventListener('click', this.handleClick);
        container.removeEventListener('keydown', this.handleKeyDown);
    }

    focus() {
        this.textArea.focus();
    }

    serialize() {
        return this.textArea.value;
    }

    handleClick(event) {
        event.stopPropagation();
        if (event.target && event.target.tagName.toLowerCase() === 'button') {
            if (event.target.className === 'save') {
                this.options.dataview.stopEditing();
            } else if (event.target.className === 'cancel') {
                this.options.dataview.cancelEditing();
            }
        }
    }

    handleKeyDown(event) {
        if (event.defaultPrevented || !document.activeElement) {
            return;
        }

        if (event.srcElement.value.length > this.maxLength) {
            event.srcElement.value = event.srcElement.value.substring(0, this.maxLength);

        }
        const key = event.key || event.keyCode;
        if (key === 'Enter' || key === 13) {
            if (document.activeElement.className === 'save') {
                event.stopPropagation();
                this.options.dataview.stopEditing();
            } else if (document.activeElement.className === 'cancel') {
                event.stopPropagation();
                this.options.dataview.cancelEditing();
            }
        }
    }
}


问:
Print statement in cross-validation on custom estimator in Sklearn
I have build a custom estimator in sklearn, according to the documentation. Inside the fit method, I have a print statement, which I use for debugging. When I create an instance of this model and call the fit method, everything is working as expected. However, when calling cross_val_score, the statements are not printed anymore, although as far as I know, cross_val_score calls the fit method at each fold.
Is there any way to force the print statement inside cross-validation?

答:
Parallel processing in sklearn is handled by joblib.  When running cross_val_score with n_jobs != 1, evidently that doesn't play nicely with Jupyter output:

Printed output not displayed when using joblib in jupyter notebook


问:
jQuery Validation Plugin: Validating Checkboxes with Different Names
I have a set of 4 checkboxes, all with different names, and require that at least 1 is checked.

I have set the class on all of them to 'require-one'.

```<code><html>
<head>
<script src="scripts/lib/jquery.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.js" type="text/javascript"></script>

<script language="JavaScript" type="text/javascript">
 $(document).ready(function(){
    $("#itemForm").validate({

rules: {
    check1: {
        required : {
            depends: function(element) {
                $('.require-one:checked').size() == 0;
            }
        }
    }
}
    });
  });
</script>

</head>
<body>
<form name="itemForm" id="itemForm" method="post">
<input type="checkbox" name="check1" id="check1" class="require-one" value="1" />
<input type="checkbox" name="check2" id="check2" class="require-one" value="2" />
<input type="text" class="required" />
<input type="submit" />
</form>
</body>
</html>
</code>```

If you put in 'return' before the $('.require-one:checked').size() == 0; However, now my problem is the error message will only disappear if Checkbox #1 is selected.  If Checkbox #2 is selected it will not disappear, but will submit.  How do I remove the error if any of the checkboxes are checked?

```<code>rules: {
    'nameOfAnyCheckbox': {
        required : {
            depends: function(element) {
              return $('.require-one:checked').size() == 0;
            }
        }
    }
</code>```

答:
Justin has the correct answer.  Here is an extension that consolidates the error reporting for all the check boxes into a single message:

http://jsfiddle.net/twd8j0tu/

$.validator.addMethod('require-one', function (value) {
              return $('.require-one:checked').size() > 0; }, 'Please check at least one box.');

var checkboxes = $('.require-one');
var checkbox_names = $.map(checkboxes, function(e,i) { return $(e).attr("name")}).join(" ");

$("#itemForm").validate({
    groups: { checks: checkbox_names },
    errorPlacement: function(error, element) {
             if (element.attr("type") == "checkbox")
               error.insertAfter(checkboxes.last());
             else
               error.insertAfter(element);
    }
});
```

(Please note that this code doesn't seem to work after jquery.validate.js version 1.10.0.  You will have to modify it for later versions).

ContentLicense: CC BY-SA 2.5

Body:
I have a set of 4 checkboxes, all with different names, and require that at least 1 is checked.

I have set the class on all of them to 'require-one'.

<form name="itemForm" id="itemForm" method="post">
<input type="checkbox" name="check1" id="check1" class="require-one" value="1" />
<input type="checkbox" name="check2" id="check2" class="require-one" value="2" />
<input type="text" class="required" />
<input type="submit" />
</form>

If you put in 'return' before the $('.require-one:checked').size() == 0; However, now my problem is the error message will only disappear if Checkbox #1 is selected.  If Checkbox #2 is selected it will not disappear, but will submit.  How do I remove the error if any of the checkboxes are checked?

rules: {
    'nameOfAnyCheckbox': {
        required : {
            depends: function(element) {
              return $('.require-one:checked').size() == 0;
            }
        }
    }

Body:
Justin has the correct answer.  Here is an extension that consolidates the error reporting for all the check boxes into a single message:

http://jsfiddle.net/twd8j0tu/

$.validator.addMethod('require-one', function (value) {
              return $('.require-one:checked').size() > 0; }, 'Please check at least one box.');

var checkboxes = $('.require-one');
var checkbox_names = $.map(checkboxes, function(e,i) { return $(e).attr("name")}).join(" ");

$("#itemForm").validate({
    groups: { checks: checkbox_names },
    errorPlacement: function(error, element) {
             if (element.attr("type") == "checkbox")
               error.insertAfter(checkboxes.last());
             else
               error.insertAfter(element);
    }
});

(Please note that this code doesn't seem to work after jquery.validate.js version 1.10.0.  You will have to modify it for later versions).

ContentLicense: CC BY-SA 3.0


问:
how to access downloads folder in android?
I am new android, i'm making an app in which one can download files to downloads folder (using Download Manager). I can see pictures if i go to downloads folder in emulator. So if i want to show a slideshow of downloaded files how can i get the access to that folder? Secondly how to add progress bar to this code:--

```<code>import java.util.Arrays;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class Download_managerActivity extends Activity {
     private long quueue_for_url;

     private DownloadManager dm;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        long downloadId = intent.getLongExtra(
                                DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                        Query query = new Query();
                        query.setFilterById(quueue_for_url);
                        Cursor c = dm.query(query);
                        if (c.moveToFirst()) {
                            int columnIndex = c
                                    .getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == c
                                    .getInt(columnIndex)) {

                                ImageView view = (ImageView) findViewById(R.id.imageView1);
                                String uri_String_abcd = c
                                        .getString(c
                                                .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                                view.setImageURI(Uri.parse(uri_String_abcd));

                            }
                        }
                    }
                }
            };

            registerReceiver(receiver, new IntentFilter(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }

        public void onClick(View view) {
            dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

            Request request_for_url = new Request(
                    Uri.parse("http://fc03.deviantart.net/fs14/i/2007/086/9/1/Steve_Jobs_portrait_by_tumb.jpg"));

            Request request_for_url1 = new Request(
                    Uri.parse("http://2.bp.blogspot.com/_q7Rxg4wqDyc/S5ZRVLxVYuI/AAAAAAAAAvU/fQAUZ2XFcp8/s400/katrina-kaif.jpg"));
            Request request_for_url2 = new Request(
                    Uri.parse("http://www.buzzreactor.com/sites/default/files/Bill-Gates1.jpg"));

            quueue_for_url = dm.enqueue(request_for_url);
            quueue_for_url = dm.enqueue(request_for_url1);
            quueue_for_url = dm.enqueue(request_for_url2);

        }

        public void showDownload(View view) {
            Intent i = new Intent();
            //try more options to show downloading , retrieving and complete
            i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
            startActivity(i);
        }
    }
</code>```

I want to add a button which performs the function of taking the pictures from downloads folder and then display like a slideshow.

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="cmpe235.lab1"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Download_managerActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>
</code>```

main.xml:-

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button android:text="Start Download" android:id="@+id/button1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:layout_gravity="center_vertical|center_horizontal|center" android:textColor="#0000A0"
         android:typeface="serif" android:onClick="onClick"></Button>

    <Button android:text="View Downloads" android:id="@+id/button2"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:layout_gravity="center_vertical|center_horizontal|center" android:textColor="#0000A0"
         android:typeface="serif" android:onClick="showDownload"></Button>

    <ImageView android:layout_height="wrap_content" android:id="@+id/imageView1"
        android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>

</LinearLayout>
</code>```

答:
You should add next permission:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

And then here is usages in code:

```<code>val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)
</code>```

Body:
I am new android, i'm making an app in which one can download files to downloads folder (using Download Manager). I can see pictures if i go to downloads folder in emulator. So if i want to show a slideshow of downloaded files how can i get the access to that folder? Secondly how to add progress bar to this code:--

import java.util.Arrays;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class Download_managerActivity extends Activity {
     private long quueue_for_url;

     private DownloadManager dm;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        long downloadId = intent.getLongExtra(
                                DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                        Query query = new Query();
                        query.setFilterById(quueue_for_url);
                        Cursor c = dm.query(query);
                        if (c.moveToFirst()) {
                            int columnIndex = c
                                    .getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == c
                                    .getInt(columnIndex)) {

                                ImageView view = (ImageView) findViewById(R.id.imageView1);
                                String uri_String_abcd = c
                                        .getString(c
                                                .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                                view.setImageURI(Uri.parse(uri_String_abcd));

                            }
                        }
                    }
                }
            };

            registerReceiver(receiver, new IntentFilter(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }

        public void onClick(View view) {
            dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

            Request request_for_url = new Request(
                    Uri.parse("http://fc03.deviantart.net/fs14/i/2007/086/9/1/Steve_Jobs_portrait_by_tumb.jpg"));

            Request request_for_url1 = new Request(
                    Uri.parse("http://2.bp.blogspot.com/_q7Rxg4wqDyc/S5ZRVLxVYuI/AAAAAAAAAvU/fQAUZ2XFcp8/s400/katrina-kaif.jpg"));
            Request request_for_url2 = new Request(
                    Uri.parse("http://www.buzzreactor.com/sites/default/files/Bill-Gates1.jpg"));

            quueue_for_url = dm.enqueue(request_for_url);
            quueue_for_url = dm.enqueue(request_for_url1);
            quueue_for_url = dm.enqueue(request_for_url2);

        }

        public void showDownload(View view) {
            Intent i = new Intent();
            //try more options to show downloading , retrieving and complete
            i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
            startActivity(i);
        }
    }

I want to add a button which performs the function of taking the pictures from downloads folder and then display like a slideshow.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="cmpe235.lab1"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Download_managerActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

main.xml:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button android:text="Start Download" android:id="@+id/button1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:layout_gravity="center_vertical|center_horizontal|center" android:textColor="#0000A0"
         android:typeface="serif" android:onClick="onClick"></Button>

    <Button android:text="View Downloads" android:id="@+id/button2"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
         android:layout_gravity="center_vertical|center_horizontal|center" android:textColor="#0000A0"
         android:typeface="serif" android:onClick="showDownload"></Button>

    <ImageView android:layout_height="wrap_content" android:id="@+id/imageView1"
        android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>

</LinearLayout>

Body:
You should add next permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And then here is usages in code:

val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)


问:
How to plot average line for a month in a Python for loop?
I have code which looks something like this:

```<code>for _, d in Country_sim_count.set_index('Week').groupby('Home_Country'):
    fig, ax = plt.subplots()
    d['SIM_total'].plot()
    plt.axhline(y=d['SIM_total'].mean(), color='r', linestyle='--') #the line I would like to alter
    plt.xticks(rotation=90)
    plt.title(f"Weekly Sim Count for {d['Home_Country'].iat[0]}")
    plt.xlabel('Week')

    a = '2020-01-13' #Key dates area
    b = '2020-02-10'

    plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
    plt.legend()
    #plt.savefig(f"{d['Home_Country'].iat[0]}_plot.png")
    plt.show()
</code>```

The dataframe contains various months however on Line 4 I wanted to plot a red line which would show the average calculated for only February per country, instead of calculating the mean for all the months combined. The feb average will be different for each country in the loop.
Currently my plot looks like this:

The value for the red line is the average combined from Jan-May however I'm hoping to have the red line value show the average value for Feb throughout.

Is there a way I could do this?

答:
Maybe you could try including a condition inside the brackets?

```<code>plt.axhline(y=d[d['SIM_total'] == 'February'].mean(), color='r', linestyle='--')
</code>```

I hope it helps!

EDIT:

In that case I think it would be better not to set 'Week' as the index.

Thou it may not very pretty, you could use something like the code below.

```<code>feb_mean = d[d['Week'] == 'February']['SIM_total'].mean()

plt.axhline(y=feb_mean, color='r', linestyle='--')
</code>```

Let me know if this works for you!

Body:
I have code which looks something like this:

for _, d in Country_sim_count.set_index('Week').groupby('Home_Country'):
    fig, ax = plt.subplots()
    d['SIM_total'].plot()
    plt.axhline(y=d['SIM_total'].mean(), color='r', linestyle='--') #the line I would like to alter
    plt.xticks(rotation=90)
    plt.title(f"Weekly Sim Count for {d['Home_Country'].iat[0]}")
    plt.xlabel('Week')

    a = '2020-01-13' #Key dates area
    b = '2020-02-10'

    plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
    plt.legend()
    #plt.savefig(f"{d['Home_Country'].iat[0]}_plot.png")
    plt.show()

The dataframe contains various months however on Line 4 I wanted to plot a red line which would show the average calculated for only February per country, instead of calculating the mean for all the months combined. The feb average will be different for each country in the loop.
Currently my plot looks like this:

The value for the red line is the average combined from Jan-May however I'm hoping to have the red line value show the average value for Feb throughout.

Is there a way I could do this?

Body:
Maybe you could try including a condition inside the brackets?

plt.axhline(y=d[d['SIM_total'] == 'February'].mean(), color='r', linestyle='--')

I hope it helps!

EDIT:

In that case I think it would be better not to set 'Week' as the index.

Thou it may not very pretty, you could use something like the code below.

feb_mean = d[d['Week'] == 'February']['SIM_total'].mean()

plt.axhline(y=feb_mean, color='r', linestyle='--')

Let me know if this works for you!


问:
What is the alternative to deprecated poll() method in a Kafka Consumer in Scala?
I am trying to create a Scala consumer as below:

```<code>import java.util.Properties
import org.apache.kafka.clients.consumer.{ConsumerRecords, KafkaConsumer}
import org.apache.kafka.common.TopicPartition
import java.util.ArrayList
import scala.concurrent.duration._

object ScalaConsumer {

  def subscribePartitions() = {
    val props = new Properties()
    props.put("bootstrap.servers", "localhost:9092")
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringDeSerializer")
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringDeSerializer")

    val consumer = new KafkaConsumer[String, String](props)
    val partitionList:ArrayList[TopicPartition] = new ArrayList[TopicPartition]()
    val topicPartition1 = new TopicPartition("topicr1p3", 0)
    val topicPartition2 = new TopicPartition("othertopicr1p3", 2)
    partitionList.add(topicPartition1)
    partitionList.add(topicPartition2)
    consumer.assign(partitionList)
    try {
        val records:ConsumerRecords[String, String] = consumer.poll(10)
    } catch {
       case e:Exception => e.printStackTrace()
    }
  }

  def main(args: Array[String]): Unit = {

  }
}
</code>```

The above example is incomplete because the method poll() used in

```<code>    val records:ConsumerRecords[String, String] = consumer.poll(10)
</code>```

is deprecated in Scala.

It says the message: Symbol poll is deprecated.
So I use the alternate for poll which is marked in the image below:

in the code as:

```<code>val records:ConsumerRecords[String, String] = consumer.poll(Duration(1000, "millis"))
</code>```

But this time, the error message is: Cannot resolve overloaded method 'poll'

build.sbt contents:

```<code>name := "KafkaScalaImplementation"
version := "0.1"
scalaVersion := "2.12.10"
// https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients
libraryDependencies += "org.apache.kafka" % "kafka-clients" % "2.4.0"
</code>```

I am now confused a bit on what should I do here to use the poll(). Is there a new way of using poll method ?
Could anyone let me know how can I fix the error in a proper way ?

答:
The following worked for me:

import java.time.Duration
val records:ConsumerRecords[String, String] = consumer.poll(Duration.ofMillis(1000))
```
<p>According to the Java Docs of Duration class you have the following options:</p>
```static Duration     of(long amount, TemporalUnit unit)
// Obtains a Duration representing an amount in the specified unit.

static Duration     ofDays(long days)
// Obtains a Duration representing a number of standard 24 hour days.

static Duration     ofHours(long hours)
// Obtains a Duration representing a number of standard hours.

static Duration     ofMillis(long millis)
// Obtains a Duration representing a number of milliseconds.

static Duration     ofMinutes(long minutes)
// Obtains a Duration representing a number of standard minutes.

static Duration     ofNanos(long nanos)
// Obtains a Duration representing a number of nanoseconds.

static Duration     ofSeconds(long seconds)
```

Body:
I am trying to create a Scala consumer as below:

import java.util.Properties
import org.apache.kafka.clients.consumer.{ConsumerRecords, KafkaConsumer}
import org.apache.kafka.common.TopicPartition
import java.util.ArrayList
import scala.concurrent.duration._

object ScalaConsumer {

  def subscribePartitions() = {
    val props = new Properties()
    props.put("bootstrap.servers", "localhost:9092")
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringDeSerializer")
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringDeSerializer")

    val consumer = new KafkaConsumer[String, String](props)
    val partitionList:ArrayList[TopicPartition] = new ArrayList[TopicPartition]()
    val topicPartition1 = new TopicPartition("topicr1p3", 0)
    val topicPartition2 = new TopicPartition("othertopicr1p3", 2)
    partitionList.add(topicPartition1)
    partitionList.add(topicPartition2)
    consumer.assign(partitionList)
    try {
        val records:ConsumerRecords[String, String] = consumer.poll(10)
    } catch {
       case e:Exception => e.printStackTrace()
    }
  }

  def main(args: Array[String]): Unit = {

  }
}

The above example is incomplete because the method poll() used in

    val records:ConsumerRecords[String, String] = consumer.poll(10)

is deprecated in Scala.

It says the message: Symbol poll is deprecated.
So I use the alternate for poll which is marked in the image below:

in the code as:

val records:ConsumerRecords[String, String] = consumer.poll(Duration(1000, "millis"))

But this time, the error message is: Cannot resolve overloaded method 'poll'

build.sbt contents:

name := "KafkaScalaImplementation"
version := "0.1"
scalaVersion := "2.12.10"
// https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients
libraryDependencies += "org.apache.kafka" % "kafka-clients" % "2.4.0"

I am now confused a bit on what should I do here to use the poll(). Is there a new way of using poll method ?
Could anyone let me know how can I fix the error in a proper way ?

Body:
The following worked for me:

import java.time.Duration
val records:ConsumerRecords[String, String] = consumer.poll(Duration.ofMillis(1000))

According to the Java Docs of Duration class you have the following options:

static Duration     of(long amount, TemporalUnit unit)
// Obtains a Duration representing an amount in the specified unit.

static Duration     ofDays(long days)
// Obtains a Duration representing a number of standard 24 hour days.

static Duration     ofHours(long hours)
// Obtains a Duration representing a number of standard hours.

static Duration     ofMillis(long millis)
// Obtains a Duration representing a number of milliseconds.

static Duration     ofMinutes(long minutes)
// Obtains a Duration representing a number of standard minutes.

static Duration     ofNanos(long nanos)
// Obtains a Duration representing a number of nanoseconds.

static Duration     ofSeconds(long seconds)


问:
json array return as count in a key javascript
i have a json object that has json array inside

```<code>{
  "0": [
    {
      "accountId": "2020060",
      "status": "0"
    }
  ],
  "1": [
    {
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}
</code>```

how can i convert the json array into count so that the response would look like this?

```<code>{
   "0" : "1",
   "1" : "3"
}
</code>```

答:
If your intention is just to count the length of the array for each index, then here you go,

const obj = {
  "0": [{
    "accountId": "2020060",
    "status": "0"
  }],
  "1": [{
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

const result = {};

for (const [key, val] of Object.entries(obj)) {
  result[key] = val.length
}

console.log("result", result)```
</div>
</div>
</p>

<p>On the other hand, if you want to make the count based on the <code>status</code> field, then here you go,</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {
  "0": [{
    "accountId": "2020060",
    "status": "0"
  }],
  "1": [{
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

const result = {};

Object.entries(obj).forEach(([key, val]) => {
  let count = 0;
  val.forEach(({
    status
  }) => {
    if (key === status)
      count++;
  })
  result[key] = count
})

console.log("result", result)</code>```

Body:
i have a json object that has json array inside

{
  "0": [
    {
      "accountId": "2020060",
      "status": "0"
    }
  ],
  "1": [
    {
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

how can i convert the json array into count so that the response would look like this?

{
   "0" : "1",
   "1" : "3"
}

Body:
If your intention is just to count the length of the array for each index, then here you go,

const obj = {
  "0": [{
    "accountId": "2020060",
    "status": "0"
  }],
  "1": [{
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

const result = {};

for (const [key, val] of Object.entries(obj)) {
  result[key] = val.length
}

console.log("result", result)

On the other hand, if you want to make the count based on the status field, then here you go,

const obj = {
  "0": [{
    "accountId": "2020060",
    "status": "0"
  }],
  "1": [{
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
}

const result = {};

Object.entries(obj).forEach(([key, val]) => {
  let count = 0;
  val.forEach(({
    status
  }) => {
    if (key === status)
      count++;
  })
  result[key] = count
})

console.log("result", result)


问:
WordPress upload file
I would like to upload a file like as (.apk) but I can't. I receive this message.
Sorry, this file type is not allowed for security reasons.

I show solutions as to settings on multisite, but I don't have this choice on my version. In which way I could enable the settings of multisite?

Is there any way to upload files like apk,( may a plugin)?

Thank you in advance!

答:
Open your functions.php file and add the following code inside it.

```<code>add_filter('upload_mimes', 'allow_custom_mimes');

function allow_custom_mimes ( $existing_mimes = array() ) {
  // with mime type ‘application/vnd.android.package-archive
  $existing_mimes['apk'] = 'application/vnd.android.package-archive';
  return $existing_mimes;
}
</code>```

Restart your server after adding code and check.

Title: WordPress upload file

Body:
Open your functions.php file and add the following code inside it.

add_filter('upload_mimes', 'allow_custom_mimes');

function allow_custom_mimes ( $existing_mimes = array() ) {
  // with mime type ‘application/vnd.android.package-archive
  $existing_mimes['apk'] = 'application/vnd.android.package-archive';
  return $existing_mimes;
}

Restart your server after adding code and check.


问:
Google Cloud Build - build.yaml & app.yaml in a sub directory not building correct source
I'm having trouble setting up my yaml files for google app engine. The configuration works correctly when my app.yaml file is in the root of the project but if it is within a subdirectory it does not build the correct source. I suspect I need to set the dir: option in the build config, but I have tried multiple variations and I can't get it to work.

Working file structure, deployed app is ~3mb in size.

```<code>src
deployment
└── staging
    └── build.yaml
app.staging.yaml

# build.yaml
steps:
- name: node:12
  entrypoint: yarn
- name: node:12
  entrypoint: yarn
  args: ['build']
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy", "app.staging.yaml"]
timeout: "1800s"
</code>```

Not working file structure, deployed app is ~1kb in size.

```<code>src
deployment
└── staging
    └── build.yaml
    └── app.yaml

# build.yaml
steps:
- name: node:12
  entrypoint: yarn
- name: node:12
  entrypoint: yarn
  args: ['build']
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy", "deployment/staging/app.yaml"]
timeout: "1800s"
</code>```

In both scenarios I am kicking off the deployment with:
gcloud builds submit --config deployment/staging/build.yaml

What should my dir: be set to in the build.yaml steps so that the build step knows to build from root? Is there any way to debug this locally without having to upload the source every time?

Thanks!
A

答: you cannot have the app.yaml and the cloudbuild.yaml in the same directory if you are deploying in a non-custom runtime. Please see this comment</p>

Body:
I'm having trouble setting up my yaml files for google app engine. The configuration works correctly when my app.yaml file is in the root of the project but if it is within a subdirectory it does not build the correct source. I suspect I need to set the dir: option in the build config, but I have tried multiple variations and I can't get it to work.

Working file structure, deployed app is ~3mb in size.

src
deployment
└── staging
    └── build.yaml
app.staging.yaml

# build.yaml
steps:
- name: node:12
  entrypoint: yarn
- name: node:12
  entrypoint: yarn
  args: ['build']
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy", "app.staging.yaml"]
timeout: "1800s"

Not working file structure, deployed app is ~1kb in size.

src
deployment
└── staging
    └── build.yaml
    └── app.yaml

# build.yaml
steps:
- name: node:12
  entrypoint: yarn
- name: node:12
  entrypoint: yarn
  args: ['build']
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy", "deployment/staging/app.yaml"]
timeout: "1800s"

In both scenarios I am kicking off the deployment with:
gcloud builds submit --config deployment/staging/build.yaml

What should my dir: be set to in the build.yaml steps so that the build step knows to build from root? Is there any way to debug this locally without having to upload the source every time?

Thanks!
A


问:
why document.getElementsByName().length always return 0?
I'm new to JavaScript. In the following code getElementsByName("li").length always returns 0 although there are many
-tags in my HTML, why?

```<code>document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('li').length;
    alert(len);
})

art of my HTML:

<body>
    <ul>
        <li>aaaaaa</li>
        <li>bbbbbb</li>
        <li>cccccc</li>
    </ul>
</body>
</code>```

答:
Replace

document.getElementsByName('li')

with

document.getElementsByTagName('li')

This is happening cause you are selecting by tag name and not by name ! You are using wrong function!

Body:
I'm new to JavaScript. In the following code getElementsByName("li").length always returns 0 although there are many
-tags in my HTML, why?

document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('li').length;
    alert(len);
})

art of my HTML:

aaaaaa

bbbbbb

cccccc


问:
Permission review Google Play for access to background location
According to the Requesting access to background location, Google Play requires a strict(er) set of requirements to be able to use background permissions for apps installed via the Google Play store. It provides a set of guidelines which have to be fulfilled to allow an app to enter- or remain in the store with said permissions. According to the document, it states:

May: Developers can request feedback on their use case via the Play Console with an estimated reply time of two weeks.

Having adjusted the app we have in the store, we're ready for a review to see if everything is correctly implemented. The documentation states that feedback can be requested through the Play Console, but I don't see any such option. How do we go about request a reviewing so that we can keep background permissions for the continued operation of our app?

答:
I've just talked to the Play Console Support Team. This is not available yet. Google is still working on it and updates will be provided on the blog:

https://android-developers.googleblog.com/2020/02/safer-location-access.html

They're apologising for the delay ;)

June update from the blog:

In February, we announced developers will need to get approval to
access background location in their app to prevent misuse. We're
giving developers more time to make changes and won't be enforcing the
policy for existing apps until 2021.

https://android-developers.googleblog.com/2020/06/


答:
```<code>const jsonObj = {
  "0": [
    {
      "accountId": "2020060",
      "status": "0"
    }
  ],
  "1": [
    {
      "accountId": "2020025",
      "status": "1"
    },
    {
      "accountId": "2020027",
      "status": "1"
    },
    {
      "accountId": "2020057",
      "status": "1"
    }
  ],
};
const countObj = {};
for ( const key in jsonObj) {
  countObj[key] = jsonObj[key].length;
}
console.log(countObj);
</code>```

Title: json array return as count in a key javascript


问:
Add Request body Schema in loopback4
I'm new with loopback 4 and I really have difficulty with the documentation that is some time not up to date. I succeed to add an authentification system and a route to log in to the users. My problem is on the "/explorer" URL, I don't know how can I add example value on the request body schema of a custom route.

There is my route:

@post('/users/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string'
                }
              }
            }
          }
        }
      }
    }
  })
  async login(
    @requestBody() credentials: Credentials,
  ): Promise<{token: string}> {
    // make sure user exist,password should be valid
    const user = await this.userService.verifyCredentials(credentials);
    // console.log(user);
    const userProfile = await this.userService.convertToUserProfile(user);
    // console.log(userProfile);

    const token = await this.jwtService.generateToken(userProfile);
    return Promise.resolve({token: token})
  }
```

<p>And I wish to add:</p>

<pre class="lang-js prettyprint-override"><code>{
   "username": "string",
   "password": "string"
}
</code>```

Here:

I suppose that there is a simple way to do it but I really can't find anything about it.

答:
FYI: The loopback4 uses the route Decorator, which provides OpenAPI specification to describe the endpoint. There is en-detailed about OpenAPI decorator in loopbac4 here.

Now to solve the above issue. lets create:

Schema for User Login i.e {"username":string, "password":string}
in the schema definition you can also add the validation rules.

```<code>const  UserLoginSchema = {
type: 'object',
required: ['email', 'password'],
properties: {
  username: {
    type: 'string',
  },
  password: {
    type: 'string',
  },
},
}; ```
```</li>
<li><p>Now lets quickly create your RequestBody c'tor for login. Remember as per OpenApi Specification the request body would contain description, required and content. </p></li>
</ol>

``` export const UserLoginRequestBody = {
      description: 'Required input for login',
      required: true,
      content: {
        'application/json': {schema: UserLoginSchema},
      },
    };
```

<ol start="3">
<li>Now you are ready to use your request body. </li>
</ol>

```  async login(
    @requestBody(UserLoginRequestBody) credentials: Credentials,
  ): Promise<{token: string}> {
..restCode
```

Thats get you done.

Title: Add Request body Schema in loopback4

Body:
I'm new with loopback 4 and I really have difficulty with the documentation that is some time not up to date. I succeed to add an authentification system and a route to log in to the users. My problem is on the "/explorer" URL, I don't know how can I add example value on the request body schema of a custom route.

There is my route:

@post('/users/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string'
                }
              }
            }
          }
        }
      }
    }
  })
  async login(
    @requestBody() credentials: Credentials,
  ): Promise<{token: string}> {
    // make sure user exist,password should be valid
    const user = await this.userService.verifyCredentials(credentials);
    // console.log(user);
    const userProfile = await this.userService.convertToUserProfile(user);
    // console.log(userProfile);

    const token = await this.jwtService.generateToken(userProfile);
    return Promise.resolve({token: token})
  }

And I wish to add:

{
   "username": "string",
   "password": "string"
}

Here:

I suppose that there is a simple way to do it but I really can't find anything about it.

Body:
FYI: The loopback4 uses the route Decorator, which provides OpenAPI specification to describe the endpoint. There is en-detailed about OpenAPI decorator in loopbac4 here.

Now to solve the above issue. lets create:

Schema for User Login i.e {"username":string, "password":string}
in the schema definition you can also add the validation rules.

const  UserLoginSchema = {
type: 'object',
required: ['email', 'password'],
properties: {
  username: {
    type: 'string',
  },
  password: {
    type: 'string',
  },
},
}; ```

Now lets quickly create your RequestBody c'tor for login. Remember as per OpenApi Specification the request body would contain description, required and content.

 export const UserLoginRequestBody = {
      description: 'Required input for login',
      required: true,
      content: {
        'application/json': {schema: UserLoginSchema},
      },
    };

Now you are ready to use your request body.

  async login(
    @requestBody(UserLoginRequestBody) credentials: Credentials,
  ): Promise<{token: string}> {
..restCode

Thats get you done.


问:
aes-256-gcm encrypt with PHP, decrypt with javascript
I have some problems to decrypt my data in javascript side.
I successfully with aes-256-cbc but with aes-256-gcm, I have some trouble.

So I have an API in PHP and a front end in Reactjs.

See below the PHP side:

```<code>$algo = "aes-256-gcm";
$sKey = openssl_random_pseudo_bytes(16);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));

$sEncrypted = openssl_encrypt(
     json_encode($aData, true),
     $algo,
     $sKey,
     $options=0,
     $iv,
     $tag
);

$aEncrypt = [
    "ciphertext" => base64_encode($sEncrypted),
    "iv"         => base64_encode($iv),
    "tag"        => base64_encode($tag)
];

return $aEncrypt;
</code>```

on my javascript side:

```<code>import crypto from 'crypto';

// Retrieve json
let obj_json = JSON.parse(data);

// Define variable from API call
let algo = 'aes-256-gcm';
let key = "xx"; // Retrieved previously
let encrypted_data = obj_json.ciphertext; // Seems no need to decode b64 since update function will do it
let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode

// Let's decrypt
let decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(encrypted_data, 'base64','utf8');
decrypted += decipher.final('utf8');

</code>```

I get :

```<code>Error: Unsupported state or unable to authenticate data
</code>```

I tried different library (reactjs) but I get always this error.
Is there a problem with encoding iv or tag ?

Thank you :D

答:
I finally found the problem.

just replace

```<code>let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode
</code>```

by

```<code>let tag = Buffer.from(obj_json.tag, 'base64');
let iv = Buffer.from(obj_json.iv, 'base64');
</code>```

Body:
I have some problems to decrypt my data in javascript side.
I successfully with aes-256-cbc but with aes-256-gcm, I have some trouble.

So I have an API in PHP and a front end in Reactjs.

See below the PHP side:

$algo = "aes-256-gcm";
$sKey = openssl_random_pseudo_bytes(16);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));

$sEncrypted = openssl_encrypt(
     json_encode($aData, true),
     $algo,
     $sKey,
     $options=0,
     $iv,
     $tag
);

$aEncrypt = [
    "ciphertext" => base64_encode($sEncrypted),
    "iv"         => base64_encode($iv),
    "tag"        => base64_encode($tag)
];

return $aEncrypt;

on my javascript side:

import crypto from 'crypto';

// Retrieve json
let obj_json = JSON.parse(data);

// Define variable from API call
let algo = 'aes-256-gcm';
let key = "xx"; // Retrieved previously
let encrypted_data = obj_json.ciphertext; // Seems no need to decode b64 since update function will do it
let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode

// Let's decrypt
let decipher = crypto.createDecipheriv(algo, key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(encrypted_data, 'base64','utf8');
decrypted += decipher.final('utf8');

I get :

Error: Unsupported state or unable to authenticate data

I tried different library (reactjs) but I get always this error.
Is there a problem with encoding iv or tag ?

Thank you :D

Body:
I finally found the problem.

just replace

let tag = atob(obj_json.tag); // b64 decode
let iv = atob(obj_json.iv); // b64 decode

by

let tag = Buffer.from(obj_json.tag, 'base64');
let iv = Buffer.from(obj_json.iv, 'base64');


问:
Reshape pandas df of x,y,z in columns to x index, y header, and z values
I have a pandas df with x (latitudes), y (longitudes), and z (topography/elevation).

I want to plot a 3D surface plot but to do that I need a 2D z array whereas I have a 1D array (1 column).

Is there a way to pivot the dataframe so that the latitudes are the index, longitudes are the header and z are the values in the table?

I tried:

```<code>newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')
</code>```

but it gives me an index error:

```<code>Pt_Longitude  Pt_Latitude  topography    Coordinated_Universal_Time  S
0    272.799970   -45.261200     2670.92  2009-07-20T12:12:00.90412170  1
1    272.800520   -45.261986     2677.35  2009-07-20T12:12:00.90412170  2
2    272.798841   -45.261578     2670.04  2009-07-20T12:12:00.90412170  3
3    272.799396   -45.260423     2663.68  2009-07-20T12:12:00.90412170  4
4    272.801063   -45.260832     2671.67  2009-07-20T12:12:00.90412170  5
Traceback (most recent call last):
  File "catalan.py", line 28, in <module>
    newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\frame.py", line 5923, in pivot
    return pivot(self, index=index, columns=columns, values=values)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py", line 450, in pivot
    return indexed.unstack(columns)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\series.py", line 3550, in unstack
    return unstack(self, level, fill_value)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 419, in unstack
    constructor=obj._constructor_expanddim,
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 141, in __init__
    self._make_selectors()
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 176, in _make_selectors
    mask.put(selector, True)
IndexError: index 571859901 is out of bounds for axis 0 with size 571829246
</code>```

答:
I think that you are using the wrong tool here. The line works fine with a tiny dataframe like the one in the example, but produces a dataframe of size len(df)*len(df)! That means that you are likely to be bitten by a memory error.

Long story made short: I can see no way to pivot a large dataframe according to your requirement because it will exhaust the available memory.

Body:
I have a pandas df with x (latitudes), y (longitudes), and z (topography/elevation).

I want to plot a 3D surface plot but to do that I need a 2D z array whereas I have a 1D array (1 column).

Is there a way to pivot the dataframe so that the latitudes are the index, longitudes are the header and z are the values in the table?

I tried:

newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')

but it gives me an index error:

Pt_Longitude  Pt_Latitude  topography    Coordinated_Universal_Time  S
0    272.799970   -45.261200     2670.92  2009-07-20T12:12:00.90412170  1
1    272.800520   -45.261986     2677.35  2009-07-20T12:12:00.90412170  2
2    272.798841   -45.261578     2670.04  2009-07-20T12:12:00.90412170  3
3    272.799396   -45.260423     2663.68  2009-07-20T12:12:00.90412170  4
4    272.801063   -45.260832     2671.67  2009-07-20T12:12:00.90412170  5
Traceback (most recent call last):
  File "catalan.py", line 28, in <module>
    newdf = df.pivot(index='Pt_Latitude', columns='Pt_Longitude', values='topography')
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\frame.py", line 5923, in pivot
    return pivot(self, index=index, columns=columns, values=values)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\pivot.py", line 450, in pivot
    return indexed.unstack(columns)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\series.py", line 3550, in unstack
    return unstack(self, level, fill_value)
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 419, in unstack
    constructor=obj._constructor_expanddim,
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 141, in __init__
    self._make_selectors()
  File "C:\Users\polyq\Anaconda3\lib\site-packages\pandas\core\reshape\reshape.py", line 176, in _make_selectors
    mask.put(selector, True)
IndexError: index 571859901 is out of bounds for axis 0 with size 571829246


问:
SQL trying to use a column from a joined table in a subquery
Here is what I currently have which returns 3 columns for patient_id, group_concat_1, and group_concat_2:

```<code>SELECT patient_id,
(SELECT GROUP_CONCAT(column1) FROM
table1 where patient_id = patient.id
) group_concat_1,
(SELECT GROUP_CONCAT(column1) FROM
table2 where patient_id = patient.id
) group_concat_2
FROM patient
</code>```

However, I need to return a single column with group_concat_1 and group_concat_2 combined, so I tried this:

```<code>SELECT patient_id,
SELECT CONCAT(group_concat_1, group_concat_2) FROM (
    (SELECT GROUP_CONCAT(column1) FROM
    table1 where patient_id = patient.id
    ) group_concat_1,
    (SELECT GROUP_CONCAT(column1) FROM
    table2 where patient_id = patient.id
    ) group_concat_2
)
FROM patient
</code>```

But his clearly doesn't work since now it can't find patient.id in the inner subquery. Any advice? Thanks!

答:
I'm pretty sure you want concat_ws() for this purpose:

```<code>SELECT patient_id,
       CONCAT_WS(','
                 (SELECT GROUP_CONCAT(t1.column1) FROM table1 t1 where t1.patient_id = p.id
                 ),
                 (SELECT GROUP_CONCAT(t2.column1) FROM table2 t2 where t2.patient_id = p.id
                 )
                ) as combined
FROM patient p;
</code>```

There are two reasons:

You can distinguish between the last element from table1 and the first from `table2.

If one of the tables has no matching values, this returns the results from the other.

Also note that I added table aliases and qualified column names.  This is quite important when working with queries that have multiple table references -- it helps prevent some very hard to debug errors.

I should add that your original query would run in most databases.  MySQL and Oracle happen to be two that don't understand nested correlation clauses.

Body:
Here is what I currently have which returns 3 columns for patient_id, group_concat_1, and group_concat_2:

SELECT patient_id,
(SELECT GROUP_CONCAT(column1) FROM
table1 where patient_id = patient.id
) group_concat_1,
(SELECT GROUP_CONCAT(column1) FROM
table2 where patient_id = patient.id
) group_concat_2
FROM patient

However, I need to return a single column with group_concat_1 and group_concat_2 combined, so I tried this:

SELECT patient_id,
SELECT CONCAT(group_concat_1, group_concat_2) FROM (
    (SELECT GROUP_CONCAT(column1) FROM
    table1 where patient_id = patient.id
    ) group_concat_1,
    (SELECT GROUP_CONCAT(column1) FROM
    table2 where patient_id = patient.id
    ) group_concat_2
)
FROM patient

But his clearly doesn't work since now it can't find patient.id in the inner subquery. Any advice? Thanks!

Body:
I'm pretty sure you want concat_ws() for this purpose:

SELECT patient_id,
       CONCAT_WS(','
                 (SELECT GROUP_CONCAT(t1.column1) FROM table1 t1 where t1.patient_id = p.id
                 ),
                 (SELECT GROUP_CONCAT(t2.column1) FROM table2 t2 where t2.patient_id = p.id
                 )
                ) as combined
FROM patient p;

There are two reasons:

You can distinguish between the last element from table1 and the first from `table2.

If one of the tables has no matching values, this returns the results from the other.

Also note that I added table aliases and qualified column names.  This is quite important when working with queries that have multiple table references -- it helps prevent some very hard to debug errors.

I should add that your original query would run in most databases.  MySQL and Oracle happen to be two that don't understand nested correlation clauses.


问:
Webpack Unexpected Token / no loader for filetype
I have a plain JavaScript app that could not be build with WebPack. I removed everything until only those lines remain:

```<code>class MyClass {
    doStuff = (abc) => {

    }
}
</code>```

The error message I get is the following:

```<code>ERROR in ./src/js/mapdata.js 2:12
Module parse failed: Unexpected token (2:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class MyClass {
>     doStuff = (abc) => {
|
|     }
</code>```

My webpack.config looks like this:

```<code>const path = require('path');

module.exports = {
    entry: './src/js/mapdata.js',
    output: {
        filename: 'rwmaps.js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            { test: /\.json$/, use: 'json-loader' }
        ]
    }
};
</code>```

I have no clue what the problem is. The JS is working fine if I access it directly from a web page (with ). Any ideas?

答:
You might be missing the babel loader and class properties.
Try adding following dependencies in package.json

```<code>"@babel/core": "^7.10.1",    "@babel/plugin-proposal-class-properties": "^7.10.1",    "@babel/preset-env": "^7.10.1",    "babel-loader": "^8.1.0"
</code>```

Also, create .babelrc and add following code:

```<code>{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}
</code>```

Lastly, update webpack.config.js file with following rule:

```<code>    { test: /\.m?js$/,
      exclude: /(node_modules)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }
</code>```

I hope it helps!

Body:
I have a plain JavaScript app that could not be build with WebPack. I removed everything until only those lines remain:

class MyClass {
    doStuff = (abc) => {

    }
}

The error message I get is the following:

ERROR in ./src/js/mapdata.js 2:12
Module parse failed: Unexpected token (2:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class MyClass {
>     doStuff = (abc) => {
|
|     }

My webpack.config looks like this:

const path = require('path');

module.exports = {
    entry: './src/js/mapdata.js',
    output: {
        filename: 'rwmaps.js',
        path: path.resolve(__dirname, 'dist'),
    },
    module: {
        rules: [
            { test: /\.json$/, use: 'json-loader' }
        ]
    }
};

I have no clue what the problem is. The JS is working fine if I access it directly from a web page (with ). Any ideas?

Body:
You might be missing the babel loader and class properties.
Try adding following dependencies in package.json

"@babel/core": "^7.10.1",    "@babel/plugin-proposal-class-properties": "^7.10.1",    "@babel/preset-env": "^7.10.1",    "babel-loader": "^8.1.0"

Also, create .babelrc and add following code:

{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

Lastly, update webpack.config.js file with following rule:

    { test: /\.m?js$/,
      exclude: /(node_modules)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }

I hope it helps!


问:
Oracle AQ c# and dequeueing a message from oracle queue in c#
I am using Oracle 12.01, ODP.NET x64, version 4, and referencing Oracle.DataAccess.dll in .net framework 4.6.
Problem appears when I try to dequeue a message in visual studio. My user has granted dequeue right and the queue is part of client's another schema.
In c# code queue name is equals X_SHEMA.X.QUEUE_NAME.

sql script that executes successfuly in SQL Developer:

```<code>DECLARE
  queueopts dbms_aq.dequeue_options_t;
  msgprops  dbms_aq.message_properties_t;
  msg_id    RAW(16);
  message   sys.aq$_jms_text_message;
  msg_text  CLOB;
  msg_line  VARCHAR2(255);
  msg_count INTEGER;

  no_subscribers EXCEPTION;
  no_messages    EXCEPTION;
  PRAGMA EXCEPTION_INIT(no_subscribers, -24033);
  PRAGMA EXCEPTION_INIT(no_messages, -25228);
BEGIN
  queueopts.wait          := DBMS_AQ.NO_WAIT;
  queueopts.navigation    := DBMS_AQ.FIRST_MESSAGE;
  queueopts.dequeue_mode  := DBMS_AQ.LOCKED;
  queueopts.consumer_name := '&receiver';
  msg_count := 0;
  WHILE (queueopts.navigation = DBMS_AQ.FIRST_MESSAGE OR msg_id IS NOT NULL) LOOP
    BEGIN
      dbms_aq.dequeue(queue_name         => '&queue',
                      dequeue_options    => queueopts,
                      message_properties => msgprops,
                      payload            => message,
                      msgid              => msg_id);
      message.get_text(msg_text);
    EXCEPTION
      WHEN no_subscribers THEN
        -- Ignorieren.
        msg_text := NULL;
        msg_id := NULL;
      WHEN no_messages THEN
        -- Fertig.
        msg_text := NULL;
        msg_id := NULL;
    END;
    IF msg_id IS NULL THEN
      dbms_output.put_line('---------------==========##+##==========---------------');
      dbms_output.put_line(to_char(msg_count) || ' message(s) received');
    ELSE
      msg_count := msg_count + 1;
      dbms_output.put_line('---------------==========##+##==========---------------');
      dbms_output.put_line(':msg_nb     = ' || to_char(msg_count));
      dbms_output.put_line(':msg_id     = ' || RAWTOHEX(msg_id));
      dbms_output.put_line(':attempts   = ' || msgprops.attempts);
      dbms_output.put_line(':nl_msgtype = ' || message.get_string_property('NL_MSGTYPE'));
      dbms_output.put_line(':sender     = ' || message.get_string_property('SENDER'));
      dbms_output.put_line(':msg_text   = #' || length(msg_text));
      WHILE (length(msg_text) > 0) LOOP
        msg_line := substr(msg_text||chr(10),1,instr(msg_text||chr(10),chr(10)));
        msg_text := substr(msg_text,length(msg_line)+1);
        dbms_output.put_line(substr(msg_line,1,length(msg_line)-1));
      END LOOP;
    END IF;
    queueopts.navigation := DBMS_AQ.NEXT_MESSAGE;
  END LOOP;
  rollback;
END;
/
</code>```

c# code:

```<code>private Response ReceiveFromQueue()
        {
            #region data

            Response response = new Response ();

            OracleAQDequeueOptions options = new OracleAQDequeueOptions
            {
                DequeueMode = OracleAQDequeueMode.Locked,
                Wait = 0,
                NavigationMode = OracleAQNavigationMode.FirstMessage,
                ConsumerName = string.Empty,
                MessageId = new byte[16],
                ProviderSpecificType = true
            };

            string _connString = "data source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = X_IP_ADDRESS)(PORT = X_PORT)) (CONNECT_DATA = (ORACLE_SID = X_SID)));User Id=X_USER;Password=X_PASSWORD;";

            OracleAQQueue queue = new OracleAQQueue(queueName)
            {
                MessageType = OracleAQMessageType.Raw,
                DequeueOptions = new OracleAQDequeueOptions
                {
                    Visibility = OracleAQVisibilityMode.OnCommit,
                    DequeueMode = OracleAQDequeueMode.Locked,
                    NavigationMode = OracleAQNavigationMode.FirstMessage,
                    ConsumerName = string.Empty,
                    Wait = 0,
                    MessageId = new byte[16],
                    ProviderSpecificType = true,
                },
            };

            #endregion

            try
            {
                OracleConnection conn = new OracleConnection(_connString);
                conn.Open();

                queue.Connection = conn;

                OracleTransaction tnx = conn.BeginTransaction();

                OracleAQMessage deqMsg = queue.Dequeue(options);

                tnx.Commit();

                conn.Close();
                conn.Dispose();
                conn = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            return response;
        }
</code>```

Dequeue throws exception ORA-25215: user_data type and queue type do not match

When I change the options:

```<code>OracleAQQueue queue = new OracleAQQueue(queueName)
            {
                MessageType = OracleAQMessageType.Udt,
                DequeueOptions = new OracleAQDequeueOptions
                {
                    Visibility = OracleAQVisibilityMode.OnCommit,
                    DequeueMode = OracleAQDequeueMode.Locked,
                    NavigationMode = OracleAQNavigationMode.FirstMessage,
                    ConsumerName = string.Empty,
                    Wait = 0,
                    MessageId = new byte[16],
                    ProviderSpecificType = true,
                },
                UdtTypeName = "sys.aq$_jms_text_message"
            };
</code>```

I get the next exception OCI-22303: type "sys"."aq$_jms_text_message" not found

I am wondering whether you have an idea what might be an issue (c# code above, Dequeue method, queue etc.), how to solve it and dequeue a message, should I contact db admins, or you have any other suggestion?

Best regards

答:
I think you may need to create a C# class with the type SYS.AQ$_JMS_TEXT_MESSAGE specified.  You will need a Factory class:

```<code>[OracleCustomTypeMapping("SYS.AQ$_JMS_TEXT_MESSAGE")]
public class OraclePayloadFactory : IOracleCustomTypeFactory
{
    public IOracleCustomType CreateObject()
    {
        return new OraclePayload();
    }
}
</code>```

And then a Type as below:

```<code>public class OraclePayload : IOracleCustomType, INullable
{
    [OracleObjectMapping("FIELD")]
    public string Field{ get; set; }

    public void FromCustomObject(OracleConnection con, IntPtr pUdt)
    {
        OracleUdt.SetValue(con, pUdt, "FIELD", this.Field);
    }

    public void ToCustomObject(OracleConnection con, IntPtr pUdt)
    {
        if (OracleUdt.GetValue(con, pUdt, "FIELD") != null)
            Field = OracleUdt.GetValue(con, pUdt, "FIELD").ToString();
    }
}
</code>```

Obviously you will need to match the elements of the oracle type to a C# equivalent.

Body:
I am using Oracle 12.01, ODP.NET x64, version 4, and referencing Oracle.DataAccess.dll in .net framework 4.6.
Problem appears when I try to dequeue a message in visual studio. My user has granted dequeue right and the queue is part of client's another schema.
In c# code queue name is equals X_SHEMA.X.QUEUE_NAME.

sql script that executes successfuly in SQL Developer:

DECLARE
  queueopts dbms_aq.dequeue_options_t;
  msgprops  dbms_aq.message_properties_t;
  msg_id    RAW(16);
  message   sys.aq$_jms_text_message;
  msg_text  CLOB;
  msg_line  VARCHAR2(255);
  msg_count INTEGER;

  no_subscribers EXCEPTION;
  no_messages    EXCEPTION;
  PRAGMA EXCEPTION_INIT(no_subscribers, -24033);
  PRAGMA EXCEPTION_INIT(no_messages, -25228);
BEGIN
  queueopts.wait          := DBMS_AQ.NO_WAIT;
  queueopts.navigation    := DBMS_AQ.FIRST_MESSAGE;
  queueopts.dequeue_mode  := DBMS_AQ.LOCKED;
  queueopts.consumer_name := '&receiver';
  msg_count := 0;
  WHILE (queueopts.navigation = DBMS_AQ.FIRST_MESSAGE OR msg_id IS NOT NULL) LOOP
    BEGIN
      dbms_aq.dequeue(queue_name         => '&queue',
                      dequeue_options    => queueopts,
                      message_properties => msgprops,
                      payload            => message,
                      msgid              => msg_id);
      message.get_text(msg_text);
    EXCEPTION
      WHEN no_subscribers THEN
        -- Ignorieren.
        msg_text := NULL;
        msg_id := NULL;
      WHEN no_messages THEN
        -- Fertig.
        msg_text := NULL;
        msg_id := NULL;
    END;
    IF msg_id IS NULL THEN
      dbms_output.put_line('---------------==========##+##==========---------------');
      dbms_output.put_line(to_char(msg_count) || ' message(s) received');
    ELSE
      msg_count := msg_count + 1;
      dbms_output.put_line('---------------==========##+##==========---------------');
      dbms_output.put_line(':msg_nb     = ' || to_char(msg_count));
      dbms_output.put_line(':msg_id     = ' || RAWTOHEX(msg_id));
      dbms_output.put_line(':attempts   = ' || msgprops.attempts);
      dbms_output.put_line(':nl_msgtype = ' || message.get_string_property('NL_MSGTYPE'));
      dbms_output.put_line(':sender     = ' || message.get_string_property('SENDER'));
      dbms_output.put_line(':msg_text   = #' || length(msg_text));
      WHILE (length(msg_text) > 0) LOOP
        msg_line := substr(msg_text||chr(10),1,instr(msg_text||chr(10),chr(10)));
        msg_text := substr(msg_text,length(msg_line)+1);
        dbms_output.put_line(substr(msg_line,1,length(msg_line)-1));
      END LOOP;
    END IF;
    queueopts.navigation := DBMS_AQ.NEXT_MESSAGE;
  END LOOP;
  rollback;
END;
/

c# code:

private Response ReceiveFromQueue()
        {
            #region data

            Response response = new Response ();

            OracleAQDequeueOptions options = new OracleAQDequeueOptions
            {
                DequeueMode = OracleAQDequeueMode.Locked,
                Wait = 0,
                NavigationMode = OracleAQNavigationMode.FirstMessage,
                ConsumerName = string.Empty,
                MessageId = new byte[16],
                ProviderSpecificType = true
            };

            string _connString = "data source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = X_IP_ADDRESS)(PORT = X_PORT)) (CONNECT_DATA = (ORACLE_SID = X_SID)));User Id=X_USER;Password=X_PASSWORD;";

            OracleAQQueue queue = new OracleAQQueue(queueName)
            {
                MessageType = OracleAQMessageType.Raw,
                DequeueOptions = new OracleAQDequeueOptions
                {
                    Visibility = OracleAQVisibilityMode.OnCommit,
                    DequeueMode = OracleAQDequeueMode.Locked,
                    NavigationMode = OracleAQNavigationMode.FirstMessage,
                    ConsumerName = string.Empty,
                    Wait = 0,
                    MessageId = new byte[16],
                    ProviderSpecificType = true,
                },
            };

            #endregion

            try
            {
                OracleConnection conn = new OracleConnection(_connString);
                conn.Open();

                queue.Connection = conn;

                OracleTransaction tnx = conn.BeginTransaction();

                OracleAQMessage deqMsg = queue.Dequeue(options);

                tnx.Commit();

                conn.Close();
                conn.Dispose();
                conn = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            return response;
        }

Dequeue throws exception ORA-25215: user_data type and queue type do not match

When I change the options:

OracleAQQueue queue = new OracleAQQueue(queueName)
            {
                MessageType = OracleAQMessageType.Udt,
                DequeueOptions = new OracleAQDequeueOptions
                {
                    Visibility = OracleAQVisibilityMode.OnCommit,
                    DequeueMode = OracleAQDequeueMode.Locked,
                    NavigationMode = OracleAQNavigationMode.FirstMessage,
                    ConsumerName = string.Empty,
                    Wait = 0,
                    MessageId = new byte[16],
                    ProviderSpecificType = true,
                },
                UdtTypeName = "sys.aq$_jms_text_message"
            };

I get the next exception OCI-22303: type "sys"."aq$_jms_text_message" not found

I am wondering whether you have an idea what might be an issue (c# code above, Dequeue method, queue etc.), how to solve it and dequeue a message, should I contact db admins, or you have any other suggestion?

Best regards

Body:
I think you may need to create a C# class with the type SYS.AQ$_JMS_TEXT_MESSAGE specified.  You will need a Factory class:

[OracleCustomTypeMapping("SYS.AQ$_JMS_TEXT_MESSAGE")]
public class OraclePayloadFactory : IOracleCustomTypeFactory
{
    public IOracleCustomType CreateObject()
    {
        return new OraclePayload();
    }
}

And then a Type as below:

public class OraclePayload : IOracleCustomType, INullable
{
    [OracleObjectMapping("FIELD")]
    public string Field{ get; set; }

    public void FromCustomObject(OracleConnection con, IntPtr pUdt)
    {
        OracleUdt.SetValue(con, pUdt, "FIELD", this.Field);
    }

    public void ToCustomObject(OracleConnection con, IntPtr pUdt)
    {
        if (OracleUdt.GetValue(con, pUdt, "FIELD") != null)
            Field = OracleUdt.GetValue(con, pUdt, "FIELD").ToString();
    }
}

Obviously you will need to match the elements of the oracle type to a C# equivalent.


答:
The method you are attempting to use is trying to find a specific element by its name.

None of your list items have a name, to do this you should update your code so that your items have names.

```<code>document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('list_item_1').length;
    alert(len);
})

<li name="list_item1">aaaaaa</li>
</code>```

Title: why document.getElementsByName().length always return 0?

Body:
The method you are attempting to use is trying to find a specific element by its name.

None of your list items have a name, to do this you should update your code so that your items have names.

document.addEventListener('DOMContentLoaded', function() {
    var len = document.getElementsByName('list_item_1').length;
    alert(len);
})

<li name="list_item1">aaaaaa</li>


问:
How to add this if statement to a template with Django and improve the views.py
My knowledge of html and Django is very limited but I have this Django project with multiple (12) HTML pages that display information in a table similar to the code below. The table is conditionally displayed if there are any fixes left to make. If any of the data in the fixes was already tested it should be highlighted in red to avoid editing. I recently added the
 bit to do the highlighting but it felt really dumb to have to add it manually to all 12 pages. Is there a way that I can add it as part of an external template?

```<code>{% extends "admin/base_site.html" %}
{% load static %}

{% block content %}

<p><b>Description:</b> {{ docstring }}</p>
{% if count|length %}
    <p><b>Action:</b> Investigate why and fix.</p>
    <p style="color:red">If any table rows are highlighted red, indicating a tested profile, flag immediately to health report owner/Automation before editing.</p>
    <table>
      <tr bgcolor="#ccc">
        <th>Profile</th>
        <th>Name</th>
        <th>Type</th>
        <th>Tested</th>
        <th>e.g. Device</th>
      </tr>
    {% for p in count %}
      <tr {% if p.tested in green_tested %} bgcolor="red" {% endif %}>
        <td><a href={{ p.profile_url }}>{{ p.url }}</a></td>
        <td>{{ p.name }}</td>
        <td>{{ p.type }}</td>
        <td>{{ p.tested }}</td>
        <td><a href={{ p.device_url }}>{{ p.dev_id }}</a></td>
    {% endfor %}
      </tr>
    </table>
{% else %}
No fixes left to make!
{% endif %}

{% endblock %}
</code>```

My function in the views.py looks something like this:

```<code>def test_function(request):
    count = test_function_count()
    context = {'count': count,
                'green_tested': list(map(lambda x: x[0], models.GREEN_TESTED)),
                'docstring': test_function_count.__doc__}
    return render(request, 'health_report/test-function-page.html', context)
</code>```

It would also be nice to not have to add the 'green_tested' to all my functions in views.

答:
```<code>{% extends "admin/base_site.html" %}
{% load static %}

{% block content %}

<p><b>Description:</b> {{ docstring }}</p>
{% if count|length !=0 %}
    <p><b>Action:</b> Investigate why and fix.</p>
    <p style="color:red">If any table rows are highlighted red, indicating a tested profile, flag immediately to health report owner/Automation before editing.</p>
    <table>
      <tr bgcolor="#ccc">
        <th>Profile</th>
        <th>Name</th>
        <th>Type</th>
        <th>Tested</th>
        <th>e.g. Device</th>
      </tr>
    {% for p in count %}
      <tr {% if p.tested in green_tested %} bgcolor="red" {% endif %}>
        <td><a href="{{ p.profile_url }}">"{{ p.url }}"</a></td>
        <td>{{ p.name }}</td>
        <td>{{ p.type }}</td>
        <td>{{ p.tested }}</td>
        <td><a href={{ p.device_url }}>{{ p.dev_id }}</a></td>
    {% endfor %}
      </tr>
    </table>
{% else %}
No fixes left to make!
{% endif %}

{% endblock %}
</code>```

Body:
My knowledge of html and Django is very limited but I have this Django project with multiple (12) HTML pages that display information in a table similar to the code below. The table is conditionally displayed if there are any fixes left to make. If any of the data in the fixes was already tested it should be highlighted in red to avoid editing. I recently added the
 bit to do the highlighting but it felt really dumb to have to add it manually to all 12 pages. Is there a way that I can add it as part of an external template?

{% extends "admin/base_site.html" %}
{% load static %}

{% block content %}

Description: {{ docstring }}

{% if count|length %}

Action: Investigate why and fix.

If any table rows are highlighted red, indicating a tested profile, flag immediately to health report owner/Automation before editing.

        Profile
        Name
        Type
        Tested
        e.g. Device

    {% for p in count %}

        {{ p.url }}
        {{ p.name }}
        {{ p.type }}
        {{ p.tested }}
        {{ p.dev_id }}
    {% endfor %}

{% else %}
No fixes left to make!
{% endif %}

{% endblock %}

My function in the views.py looks something like this:

def test_function(request):
    count = test_function_count()
    context = {'count': count,
                'green_tested': list(map(lambda x: x[0], models.GREEN_TESTED)),
                'docstring': test_function_count.__doc__}
    return render(request, 'health_report/test-function-page.html', context)

It would also be nice to not have to add the 'green_tested' to all my functions in views.


问:
Using PIVOT to get SELECT into one column, not row
I am trying to make a select, which would show the result into ONE column, not row. I tried using PIVOT, but I am not successful at all.

Result of my select:

```<code>Customer_ID:   InsertionDate:  Name:   Birth:
  1234          2020-01-01     John  1993-01-01
</code>```

I want to have it like this:

```<code>                 MyColumn
 Customer_ID:    1234
 InsertionDate:  2020-01-01
 Name:           John
 Birth:          1993-01-01
</code>```

答:
You can use cross apply to obtain a single column:

```<code>declare @test table (Customer_ID int,  InsertionDate date,  Name varchar(50), Birth date)
insert into @test values (1234, '2020-01-01','John', '1993-01-01')

select  val as MyColumn
from @test
    CROSS APPLY
    (
    VALUES
        ('Customer_ID:'+   cast(Customer_ID as varchar)),
        ('InsertionDate:'+ cast(InsertionDate as varchar)),
        ('Name:'+ cast(Name as varchar)),
        ('Birth:'+ cast(Birth as varchar))
    )CS (val)
</code>```

results:

or, if you prefer having a separate column for descriptions:

```<code>select
    Col as ColumnName,
    val as MyColumn
from @test
    CROSS APPLY
    (
    VALUES
        ('Customer_ID:'  , cast(Customer_ID as varchar)),
        ('InsertionDate:', cast(InsertionDate as varchar)),
        ('Name:'         , cast(Name as varchar)),
        ('Birth:'        , cast(Birth as varchar))
    )CS (col, val)
</code>```

output:

Body:
I am trying to make a select, which would show the result into ONE column, not row. I tried using PIVOT, but I am not successful at all.

Result of my select:

Customer_ID:   InsertionDate:  Name:   Birth:
  1234          2020-01-01     John  1993-01-01

I want to have it like this:

                 MyColumn
 Customer_ID:    1234
 InsertionDate:  2020-01-01
 Name:           John
 Birth:          1993-01-01

Body:
You can use cross apply to obtain a single column:

declare @test table (Customer_ID int,  InsertionDate date,  Name varchar(50), Birth date)
insert into @test values (1234, '2020-01-01','John', '1993-01-01')

select  val as MyColumn
from @test
    CROSS APPLY
    (
    VALUES
        ('Customer_ID:'+   cast(Customer_ID as varchar)),
        ('InsertionDate:'+ cast(InsertionDate as varchar)),
        ('Name:'+ cast(Name as varchar)),
        ('Birth:'+ cast(Birth as varchar))
    )CS (val)

results:

or, if you prefer having a separate column for descriptions:

select
    Col as ColumnName,
    val as MyColumn
from @test
    CROSS APPLY
    (
    VALUES
        ('Customer_ID:'  , cast(Customer_ID as varchar)),
        ('InsertionDate:', cast(InsertionDate as varchar)),
        ('Name:'         , cast(Name as varchar)),
        ('Birth:'        , cast(Birth as varchar))
    )CS (col, val)

output: