问:
Unhandled Rejection (Error): Expected undefined to be a GraphQL schema
I'm trying to build the post pages imported from WordPress, I run "gatsby develop" and I head to the URL.
The front page flashes up and then I get this error:

```<code>Unhandled Rejection (Error): Expected undefined to be a GraphQL schema.
invariant
C:/Users/Phil/Repositories/Zym/node_modules/graphql/jsutils/invariant.mjs:12
assertSchema
C:/Users/Phil/Repositories/Zym/node_modules/graphql/type/schema.mjs:25
validateSchema
C:/Users/Phil/Repositories/Zym/node_modules/graphql/type/validate.mjs:31
graphqlImpl
C:/Users/Phil/Repositories/Zym/node_modules/graphql/graphql.mjs:44
(anonymous function)
C:/Users/Phil/Repositories/Zym/node_modules/graphql/graphql.mjs:20
graphql
C:/Users/Phil/Repositories/Zym/node_modules/graphql/graphql.mjs:18
</code>```

The query which is highlighted in my 'PostTemplate.js':

```<code>
export const query = graphql`
  query($id: String!) {
     wordpressPost(id: { eq: $id }) {
      date
      title
      slug
      content
      categories {
        name
      }
    }
  }
`;

</code>```

I run the same query through the GraphiQL interface and it sends me data?

Really unsure as to what I'm doing wrong here, see code bellow from gatsby-node.js

```<code>exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions

      return graphql(`
        {
          allWordpressPost {
            edges {
              node {
                id
                slug
                status
              }
            }
          }
        }
      `)
    .then(result => {
      if (result.errors) {
        result.errors.forEach(e => console.error(e.toString()))
        return Promise.reject(result.errors)
      }

      const postTemplate = path.resolve(`./src/templates/PostTemplate.js`)

      const posts = result.data.allWordpressPost.edges

      _.each(posts, ({ node: post }) => {
        createPage({
          path: `/${post.slug}/`,
          component: postTemplate,
          context: {
            id: post.id,
            slug: post.slug
          },
        })
      })
   })
})
</code>```

I've tried updating gatsby-cli -g, and uninstalled node_modules.

答:
I don't think your query is properly formatted in your gatsby-node.js file. It should be as follows:

return graphql(`
    query {
        allWordpressPost {
            edges {
                node {
                    id
                    slug
                    status
                }
            }
        }
    }
`);
```

Give that a try and let me know if that works for you.

Body:
I'm trying to build the post pages imported from WordPress, I run "gatsby develop" and I head to the URL.
The front page flashes up and then I get this error:

Unhandled Rejection (Error): Expected undefined to be a GraphQL schema.
invariant
C:/Users/Phil/Repositories/Zym/node_modules/graphql/jsutils/invariant.mjs:12
assertSchema
C:/Users/Phil/Repositories/Zym/node_modules/graphql/type/schema.mjs:25
validateSchema
C:/Users/Phil/Repositories/Zym/node_modules/graphql/type/validate.mjs:31
graphqlImpl
C:/Users/Phil/Repositories/Zym/node_modules/graphql/graphql.mjs:44
(anonymous function)
C:/Users/Phil/Repositories/Zym/node_modules/graphql/graphql.mjs:20
graphql
C:/Users/Phil/Repositories/Zym/node_modules/graphql/graphql.mjs:18

The query which is highlighted in my 'PostTemplate.js':

export const query = graphql`
  query($id: String!) {
     wordpressPost(id: { eq: $id }) {
      date
      title
      slug
      content
      categories {
        name
      }
    }
  }
`;

I run the same query through the GraphiQL interface and it sends me data?

Really unsure as to what I'm doing wrong here, see code bellow from gatsby-node.js

exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions

      return graphql(`
        {
          allWordpressPost {
            edges {
              node {
                id
                slug
                status
              }
            }
          }
        }
      `)
    .then(result => {
      if (result.errors) {
        result.errors.forEach(e => console.error(e.toString()))
        return Promise.reject(result.errors)
      }

      const postTemplate = path.resolve(`./src/templates/PostTemplate.js`)

      const posts = result.data.allWordpressPost.edges

      _.each(posts, ({ node: post }) => {
        createPage({
          path: `/${post.slug}/`,
          component: postTemplate,
          context: {
            id: post.id,
            slug: post.slug
          },
        })
      })
   })
})

I've tried updating gatsby-cli -g, and uninstalled node_modules.

Body:
I don't think your query is properly formatted in your gatsby-node.js file. It should be as follows:

return graphql(`
    query {
        allWordpressPost {
            edges {
                node {
                    id
                    slug
                    status
                }
            }
        }
    }
`);

Give that a try and let me know if that works for you.


来源: stackexchange

问:
Is there anyway to disable a bootstrap button permanently after one click on server side using PHP?
I'm trying to disable a bootstrap button permanently after one click. I know how to do this on client side using JavaScript but after refreshing page, it becomes enabled. So, I want to do it on the server side. But don't know how to do it. Can anyone help??</p>

答:
This solution worked for me to disable a bootstrap button:

```<code><?php
    $a=1;
    echo ($a==1) ? '<a href="update.php" class="btn btn-success btn-lg">Mark complete</a>' : '<a href="lect_pro_updater.php" class="btn btn-success btn-lg disabled">You completed this</a>';
?>
</code>```

It will keep button active if the condition is true else create a new disabled button.

If you don't want to use a ternary operator then use if and else statements like:

```<code>if($a==1){
'<a href="update.php" class="btn btn-success btn-lg">Mark complete</a>'
}

else{
'<a href="update.php" class="btn btn-success btn-lg disabled">Mark complete</a>'
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This solution worked for me to disable a bootstrap button:

<?php
    $a=1;
    echo ($a==1) ? '<a href="update.php" class="btn btn-success btn-lg">Mark complete</a>' : '<a href="lect_pro_updater.php" class="btn btn-success btn-lg disabled">You completed this</a>';
?>

It will keep button active if the condition is true else create a new disabled button.

If you don't want to use a ternary operator then use if and else statements like:

if($a==1){
'<a href="update.php" class="btn btn-success btn-lg">Mark complete</a>'
}

else{
'<a href="update.php" class="btn btn-success btn-lg disabled">Mark complete</a>'
}


问:
How to import something globally in React Native?
I'm developing an App using React Native and Firebase. So, I created a separate js file to store config of firebase database and then I imported that config file into my screen files when I need to connect with firebase database.

So, I have to import that config file into each and every screen file which I need connect with my firebase database.

I want to know that, is it possible to import that config file globally?

I mean, I create a separate config file, then import it only once into a particular js file (Just for an example, let's think, import it only once into the App.js file) and then, use it in my screen files whenever I need to connect with my firebase database. But in this case, is it possible to use that config file without importing it into each and every screen file?

Hope you will understand what I want to do.

答:
Yes, you just import the file in your main screen/ app entry point.

```<code>import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import 'firebase/storage';

const config = {
  apiKey: "API_KEY",
  authDomain: "DOMAIN",
  databaseURL: "DB_URL",
  projectId: "PROJECT_ID",
  storageBucket: "BUCKET",
  messagingSenderId: "MSG_ID",
  appId: "APP_ID"
};
app.initializeApp(config);

module.Store = {

  Firebase() {
    return app;
  },
}

if (global) {
  global.Store = module.Store;
}
</code>```

In your main screen

```<code>import './Global';
</code>```

all the functions in Global will be available to all screens.

Demo

Body:
Yes, you just import the file in your main screen/ app entry point.

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import 'firebase/storage';

const config = {
  apiKey: "API_KEY",
  authDomain: "DOMAIN",
  databaseURL: "DB_URL",
  projectId: "PROJECT_ID",
  storageBucket: "BUCKET",
  messagingSenderId: "MSG_ID",
  appId: "APP_ID"
};
app.initializeApp(config);

module.Store = {

  Firebase() {
    return app;
  },
}

if (global) {
  global.Store = module.Store;
}

In your main screen

import './Global';

all the functions in Global will be available to all screens.

Demo


问:
How to select drop-down value in Protractor using framework: 'jasmine',
I am trying to select drop down list using protractor. None of this code works.

```<code>it("Select Block from District", function() {

    const selectElement={}
    selectElement.selectElementDropdown =function(element,index,milliseconds){
     console.log("Selecting element by drop down","OK");

     element.all(by.tagName('option')).then(function(options){

         options[2].click();
    //here index 2 is hardcoded, which can be changed to options[index]
     });

     if(typeof milliseconds!=='undefined'){
         browser.sleep(milliseconds);
     }

    }

    module.exports =selectElement;

    const methodDropDown = {} //require('../Src/SelectElement.js');

    var DistrictDetails = function(){

    this.DistrictName = element.all(by.xpath("//label[text()='Select Block']")).get(7).element(by.xpath("//option[contains(text(),'Ambabhona')]"));
    //the selector is clicked to open the drop down
</code>```

I have already gone through pass the value using send keys to text box

```<code><div _ngcontent-c9="" class="col-sm-6">
    <label _ngcontent-c9="" class="col-md-5 control-label">District
        <span _ngcontent-c9="" class="err-msg">*</span>
    </label>
    <div _ngcontent-c9="" class="col-md-7">
        <p-dropdown _ngcontent-c9="" formcontrolname="districtId" placeholder="Select District"
            class="ng-tns-c6-189 ng-pristine ng-invalid ng-touched">
            <div class="ng-tns-c6-189 ui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix"
                style="width: 138px;">
                <!---->
                <div class="ui-helper-hidden-accessible ng-tns-c6-189 ng-star-inserted">
                    <select class="ng-tns-c6-189" aria-hidden="true" tabindex="-1" aria-label=" ">
                        <!---->
                        <option class="ng-tns-c6-189 ng-star-inserted">Select District</option>
                        <!---->
                        <!---->
                        <!---->
                        <!---->
                        <option class="ng-tns-c6-189 ng-star-inserted" value="390" style="">Bargarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="391" style="">Jharsuguda</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="392" style="">Sambalpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="393" style="">Deogarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="394" style="">Sundergarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="395" style="">Keonjhar</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="396" style="">Mayurbhanj</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="397" style="">Balasore</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="398" style="">Bhadrak</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="399" style="">Kendrapara</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="400" style="">Jagatsinghpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="401" style="">Cuttack</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="402" style="">Jajpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="403" style="">Dhenkanal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="404" style="">Angul</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="405" style="">Nayagarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="406" style="">Khordha</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="407" style="">Puri</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="408" style="">Ganjam</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="409" style="">Gajapati</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="410" style="">Kandhamal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="411" style="">Boudh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="412" style="">Sonepur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="413" style="">Bolangir</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="414" style="">Nuapada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="415" style="">Kalahandi</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="416" style="">Rayagada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="417" style="">Nabarangpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="418" style="">Koraput</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="419" style="">Malkangiri</option>
                        <!---->
                    </select>
                </div>
                <div class="ui-helper-hidden-accessible">
                    <input class="ng-tns-c6-189" readonly="" role="listbox" type="text" aria-label=" ">
                </div>
                <!---->
                <!----><label
                    class="ng-tns-c6-189 ui-dropdown-label ui-inputtext ui-corner-all ui-placeholder ng-star-inserted">
                    Select District
                </label>
                <!---->
                <!---->
                <div class="ui-dropdown-trigger ui-state-default ui-corner-right"><span
                        class="ui-dropdown-trigger-icon ui-clickable pi pi-caret-down"></span>
                </div>
                <div class="ng-tns-c6-189 ui-dropdown-panel ui-widget-content ui-corner-all ui-shadow ng-trigger ng-trigger-panelState"
                    style="display: none; z-index: 1181; top: 27px; left: 0px; opacity: 0;">
                    <!---->
                    <div class="ui-dropdown-items-wrapper" style="max-height: 200px;">
                        <!---->
                    </div>
                </div>
            </div>
        </p-dropdown>
        <!---->
    </div>
</div>
</code>```

Want to select value form drop-down list like  Deogarh

答:
Try the below option

```<code>const dropDown = element(by.css('div.ui-helper-hidden-accessible > select > option');

await dropDown.sendKeys('Deogarh');
</code>```

Hope it helps you

Body:
I am trying to select drop down list using protractor. None of this code works.

it("Select Block from District", function() {

    const selectElement={}
    selectElement.selectElementDropdown =function(element,index,milliseconds){
     console.log("Selecting element by drop down","OK");

     element.all(by.tagName('option')).then(function(options){

         options[2].click();
    //here index 2 is hardcoded, which can be changed to options[index]
     });

     if(typeof milliseconds!=='undefined'){
         browser.sleep(milliseconds);
     }

    }

    module.exports =selectElement;

    const methodDropDown = {} //require('../Src/SelectElement.js');

    var DistrictDetails = function(){

    this.DistrictName = element.all(by.xpath("//label[text()='Select Block']")).get(7).element(by.xpath("//option[contains(text(),'Ambabhona')]"));
    //the selector is clicked to open the drop down

I have already gone through pass the value using send keys to text box

    District
        *

                    <select class="ng-tns-c6-189" aria-hidden="true" tabindex="-1" aria-label=" ">

                        <option class="ng-tns-c6-189 ng-star-inserted">Select District</option>

                        <option class="ng-tns-c6-189 ng-star-inserted" value="390" style="">Bargarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="391" style="">Jharsuguda</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="392" style="">Sambalpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="393" style="">Deogarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="394" style="">Sundergarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="395" style="">Keonjhar</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="396" style="">Mayurbhanj</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="397" style="">Balasore</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="398" style="">Bhadrak</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="399" style="">Kendrapara</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="400" style="">Jagatsinghpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="401" style="">Cuttack</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="402" style="">Jajpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="403" style="">Dhenkanal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="404" style="">Angul</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="405" style="">Nayagarh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="406" style="">Khordha</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="407" style="">Puri</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="408" style="">Ganjam</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="409" style="">Gajapati</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="410" style="">Kandhamal</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="411" style="">Boudh</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="412" style="">Sonepur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="413" style="">Bolangir</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="414" style="">Nuapada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="415" style="">Kalahandi</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="416" style="">Rayagada</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="417" style="">Nabarangpur</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="418" style="">Koraput</option>
                        <option class="ng-tns-c6-189 ng-star-inserted" value="419" style="">Malkangiri</option>

                    </select>

                    <input class="ng-tns-c6-189" readonly="" role="listbox" type="text" aria-label=" ">

                    Select District

Want to select value form drop-down list like  Deogarh

Body:
Try the below option

const dropDown = element(by.css('div.ui-helper-hidden-accessible > select > option');

await dropDown.sendKeys('Deogarh');

Hope it helps you


问:
Could not find iPhone 6 simulator after upgrade to Xcode 10
I updated to Xcode 10 and since I did that, I can't run the simulator in terminal with the command react-native run-ios. I get this error:

Could not find iPhone 6 simulator

When I go to Xcode > Window > Devices and Simulator the simulator is there and when I do xcrun simctl list devices I also see the list of simulator.

I can run the app on my phone with react-native run-ios --device and from Xcode, and I tried with multiple apps so it's not the app.

When I go to Xcode > Preferences > Locations, Xcode 10.0 (10A255) is selected at Command Line Tools.

I tried restarting the computer, as well as deleting and re-installing Xcode.

Any ideas what it could be?

Here is my setup:

MacOs High Sierra 10.13.6

Xcode Version 10.0

react-native-cli: 2.0.1

react-native: 0.57.1

答:
it can be solved to fix the file below.

```<code>/node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js
</code>```

replace this line

```<code>if (!version.startsWith('iOS') && !version.startsWith('tvOS')) {
</code>```

with

```<code>if (!version.includes('iOS') && !version.includes('tvOS')) {
</code>```

Body:
it can be solved to fix the file below.

/node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js

replace this line

if (!version.startsWith('iOS') && !version.startsWith('tvOS')) {

with

if (!version.includes('iOS') && !version.includes('tvOS')) {


问:
how to Implement lit-element-bootstrap package in lit-lement
I would like to implement lit-element-bootstrap package in lit-element.

I am getting following error in console,
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec

```<code>//header.js
import { LitElement, html, css } from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';
import  'https://unpkg.com/lit-element-bootstrap@1.0.0-alpha.10/lit-element-bootstrap';

export class Header extends LitElement{
    constructor() {
        super();
    }
    render(){
        return html`
        <bs-alert primary>
         <div>A simple primary alert—check it out!</div>
        </bs-alert>
        `;
    }
}
customElements.define('header-element', Header);

//index.html

<!doctype html>
<html>
  <head>
  <script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js"></script>
  <script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-loader.js"></script>
     <script type = "module" src = "../components/header.js"></script>
  </head>
<body>
<header-element></header-element>
 </body>
</html>

</code>```

答:
The URL you are trying to import from is getting redirected (302).

Current URL: https://unpkg.com/@polymer/lit-element/lit-element.js?module

Try changing it to:
https://unpkg.com/@polymer/lit-element@0.7.1/lit-element.js?module

Not sure if you should be loading it from this URL always, you can download the file and import it from your directory, rather than downloading it from this new URL. As this new URL can also change in future.

Body:
I would like to implement lit-element-bootstrap package in lit-element.

I am getting following error in console,
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec

//header.js
import { LitElement, html, css } from 'https://unpkg.com/@polymer/lit-element/lit-element.js?module';
import  'https://unpkg.com/lit-element-bootstrap@1.0.0-alpha.10/lit-element-bootstrap';

export class Header extends LitElement{
    constructor() {
        super();
    }
    render(){
        return html`
        <bs-alert primary>

A simple primary alert—check it out!

        </bs-alert>
        `;
    }
}
customElements.define('header-element', Header);

//index.html

<!doctype html>


问:
Generate .txt files from pdf files keeping the name same as in pdf using python
I have a directory containing pdf files. I have written the code that performs OCR when you pass a filename to an object of the wand.image class. What I want to do presently is to loop over the directory of pdf files and generate a OCR'd txt file for each pdf and save it some directory. The code that I have written till now is as follows:

```<code>import io
from PIL import Image
import pytesseract
from wand.image import Image as wi

pdf = wi(filename = r"D:\files\aba7d525-04b8-4474-a40d-e94f9656ed42.pdf", resolution = 300)

pdfImg = pdf.convert('jpeg')

imgBlobs = []

for img in pdfImg.sequence:
    page = wi(image = img)
    imgBlobs.append(page.make_blob('jpeg'))

extracted_text = []

for imgBlob in imgBlobs:
    im = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(im, lang = 'eng')
    extracted_text.append(text)

print(extracted_text[0])
</code>```

The thing is if you see my code, ("pdf = .."), I have hardcoded a filename in my code but I need to pass a directory there so that all the files in that directory can be OCR'd and also I need to take as output all those files with their filenames with just .pdf being replaced by .txt. How can I do that

答:
You can use glob

Example:

```<code>import os
import glob
from wand.image import Image as wi

files = glob.glob("D:\files\*")

for file in files:
    pdf = wi(filename = file, resolution = 300)
    # write your code
    with open("D:\extracted_files\" + os.path.split(file)[-1].split(".")[0] + ".txt", 'w') as f:
        f.write(extracted_text)
</code>```

Body:
I have a directory containing pdf files. I have written the code that performs OCR when you pass a filename to an object of the wand.image class. What I want to do presently is to loop over the directory of pdf files and generate a OCR'd txt file for each pdf and save it some directory. The code that I have written till now is as follows:

import io
from PIL import Image
import pytesseract
from wand.image import Image as wi

pdf = wi(filename = r"D:\files\aba7d525-04b8-4474-a40d-e94f9656ed42.pdf", resolution = 300)

pdfImg = pdf.convert('jpeg')

imgBlobs = []

for img in pdfImg.sequence:
    page = wi(image = img)
    imgBlobs.append(page.make_blob('jpeg'))

extracted_text = []

for imgBlob in imgBlobs:
    im = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(im, lang = 'eng')
    extracted_text.append(text)

print(extracted_text[0])

The thing is if you see my code, ("pdf = .."), I have hardcoded a filename in my code but I need to pass a directory there so that all the files in that directory can be OCR'd and also I need to take as output all those files with their filenames with just .pdf being replaced by .txt. How can I do that

Body:
You can use glob

Example:

import os
import glob
from wand.image import Image as wi

files = glob.glob("D:\files\*")

for file in files:
    pdf = wi(filename = file, resolution = 300)
    # write your code
    with open("D:\extracted_files\" + os.path.split(file)[-1].split(".")[0] + ".txt", 'w') as f:
        f.write(extracted_text)


问:
using php-gzdeflate and pako-js
i am attempting to combine php-gzdeflate and pako.   to compress the string i am using:

```<code>const compressed = ' <?php echo base64_encode(gzdeflate('Compress me')); ?> ' ;
// compressed now contains: c87PLShKLS5WyE0FAA==
</code>```

but i cannot seem to read this string back using pako.  i have tried the following:

```<code>var enc = new TextEncoder("utf-8");
pako.ungzip(enc.encode(compressed) );
</code>```

i get this message back: uncaught incorrect header check

is there a simple way to compress using generic-php and inflate using pako?

so far i have tried adding various gzdeflate "levels" from one to nine, but none of them appear to make any difference.  and at this point, i am just guessing.

and we would rather not install any special extension to php if possible

thank you very much.

答:
Update to @edwardsmarkf's answer you can solve this without the atos function now. Most newer browsers have the TextDecoder api. You can use it like so:</p>

```<code>const decoder = new TextDecoder();
const result = decoder.decode(pako.ungzip(atob(compressedBase64Data)));
</code>```

ContentLicense: CC BY-SA 3.0

Title: using php-gzdeflate and pako-js

Body:
i am attempting to combine php-gzdeflate and pako.   to compress the string i am using:

const compressed = ' <?php echo base64_encode(gzdeflate('Compress me')); ?> ' ;
// compressed now contains: c87PLShKLS5WyE0FAA==

but i cannot seem to read this string back using pako.  i have tried the following:

var enc = new TextEncoder("utf-8");
pako.ungzip(enc.encode(compressed) );

i get this message back: uncaught incorrect header check

is there a simple way to compress using generic-php and inflate using pako?

so far i have tried adding various gzdeflate "levels" from one to nine, but none of them appear to make any difference.  and at this point, i am just guessing.

and we would rather not install any special extension to php if possible

thank you very much.

Body:
Update to @edwardsmarkf's answer you can solve this without the atos function now. Most newer browsers have the TextDecoder api. You can use it like so:

const decoder = new TextDecoder();
const result = decoder.decode(pako.ungzip(atob(compressedBase64Data)));


问:
Phantom
 within carousel
Having more trouble with this infographic. There seems to be a phantom
 appearing at the end of the carousel. Does anyone know how this has appeared?

http://weaver-wp.weavertest.com/radiation-infographic/

Cheers,
Dave

答:
It looks like the last
 contains the last 'slide' of your content. Is the 'navigating past the last slide' the behavior you're trying to suppress? If so, hide the 'right' navigation button when you're viewing the last slide and the 'left' navigation button when you're viewing the first slide, preventing the user from scrolling past the beginning or end of the carousel.

Title: Phantom <li> within carousel

Body: It looks like the last <li> contains the last 'slide' of your content. Is the 'navigating past the last slide' the behavior you're trying to suppress? If so, hide the 'right' navigation button when you're viewing the last slide and the 'left' navigation button when you're viewing the first slide, preventing the user from scrolling past the beginning or end of the carousel.


问:
Compare values from two queries and return matching values in Ruby
I need to get IDs of a model from two separate queries and check if the same IDs are present in both queries. If not then I must pass the string Not present wherever it is not or else I must pass the value.

```<code>class Purchase
    belongs_to :customer
    belongs_to :selected_items

class SelectedItem
    has_many :purchases
    has_many :sub_categories
    has_many :categories, through: :sub_categories

class SubCategory
    belongs_to :selected_item
    belongs_to :categories

class Category
    has_many :sub_categories
    has_many :selected_items, through: :sub_categories

class Customer
    has_many :purchases
</code>```

```<code>selected_items = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
    purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
    both_present = selected_items_ids & purchased_selected_items_ids
    # after this how can I send "Not purchased" string for whichever id is not present or send the send the purchased item name wherever ids present in both?
</code>```

In the get_values method I need to compare the ids of SelectedItem between purchases and selected_items. If the id of any item in selected_item is in any item in purchases then I should return purchased, if not then the purchase for that selected_item will not be in the database meaning it will return blank in the query. So then I must return Not purchased string. This is done for each customer. How can I do that? Here I am displaying the results in table in erb file. So the columns for each selected_item will be created. I should pass the values of whether each customer has purchased or not for each of the selected_item.

答:
You can do like,</p>

```<code>selected_items  = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    result = selected_items & purchases # will give common
    result.nil? ? "not_puchased" : "purchased"
end
</code>```

Body:
I need to get IDs of a model from two separate queries and check if the same IDs are present in both queries. If not then I must pass the string Not present wherever it is not or else I must pass the value.

class Purchase
    belongs_to :customer
    belongs_to :selected_items

class SelectedItem
    has_many :purchases
    has_many :sub_categories
    has_many :categories, through: :sub_categories

class SubCategory
    belongs_to :selected_item
    belongs_to :categories

class Category
    has_many :sub_categories
    has_many :selected_items, through: :sub_categories

class Customer
    has_many :purchases

selected_items = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
    purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
    both_present = selected_items_ids & purchased_selected_items_ids
    # after this how can I send "Not purchased" string for whichever id is not present or send the send the purchased item name wherever ids present in both?

In the get_values method I need to compare the ids of SelectedItem between purchases and selected_items. If the id of any item in selected_item is in any item in purchases then I should return purchased, if not then the purchase for that selected_item will not be in the database meaning it will return blank in the query. So then I must return Not purchased string. This is done for each customer. How can I do that? Here I am displaying the results in table in erb file. So the columns for each selected_item will be created. I should pass the values of whether each customer has purchased or not for each of the selected_item.

Body:
You can do like,

selected_items  = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    result = selected_items & purchases # will give common
    result.nil? ? "not_puchased" : "purchased"
end


问:
I need to add the items from list A to list B, only when the item already exists in list B
I need to add all the items in list A in to list B, if and only if the items already exist in list B, even if there are multiple items that are same in list A. How can I do this? Right now, it stops after the first of the same words. Say for example, List A is [the, a, sure, book, is, the, best], and list B is [the, rock], I need to add the two "the"s in list A to list B, to make a total of three "the"s in list B

It's for a beginner's class in python. I've tried different formats of the for loop, but it doesn't seem to work. There is a for loop before this, that creates the list B, I think it maybe because of the back to back for loops.

```<code>for word in list_a:
    if word[0].isupper() == True:
        list_b.append(word)

list_b = [word.lower() for word in list_b]

for word in list_a:
    if word in list_b:
        list_b.append(word)

list_b = [word.capitalize() for word in list_b]
</code>```

The second for loop is the one giving me trouble. I have pasted the larger code which I am trying to work with. So my main objective is to first separate the words that are capitalized in list A in to list B.

Then lowercase list B, so I can find the same words in list A that are not capitalized, and then add those to list B as well. Then capitalize all of list B again to print the count.

I know that there is an easier way to do this, where I can just make the original string lowercase and then work from there. However, in this case I need to keep track of the words that were originally capitalized, because when I print the words with their total counts, the words that were originally capitalized, need to print in their capitalized form rather than the lowercase form.

Therefore, the expected outcome I am looking for is list B as [the, rock, the, the].

答:
```<code>list_b = list_b + ([x for x in list_a if x in list_b])
</code>```

result:

```<code>['the', 'rock', 'the', 'the']
</code>```

Body:
I need to add all the items in list A in to list B, if and only if the items already exist in list B, even if there are multiple items that are same in list A. How can I do this? Right now, it stops after the first of the same words. Say for example, List A is [the, a, sure, book, is, the, best], and list B is [the, rock], I need to add the two "the"s in list A to list B, to make a total of three "the"s in list B

It's for a beginner's class in python. I've tried different formats of the for loop, but it doesn't seem to work. There is a for loop before this, that creates the list B, I think it maybe because of the back to back for loops.

for word in list_a:
    if word[0].isupper() == True:
        list_b.append(word)

list_b = [word.lower() for word in list_b]

for word in list_a:
    if word in list_b:
        list_b.append(word)

list_b = [word.capitalize() for word in list_b]

The second for loop is the one giving me trouble. I have pasted the larger code which I am trying to work with. So my main objective is to first separate the words that are capitalized in list A in to list B.

Then lowercase list B, so I can find the same words in list A that are not capitalized, and then add those to list B as well. Then capitalize all of list B again to print the count.

I know that there is an easier way to do this, where I can just make the original string lowercase and then work from there. However, in this case I need to keep track of the words that were originally capitalized, because when I print the words with their total counts, the words that were originally capitalized, need to print in their capitalized form rather than the lowercase form.

Therefore, the expected outcome I am looking for is list B as [the, rock, the, the].

Body:
list_b = list_b + ([x for x in list_a if x in list_b])

result:

['the', 'rock', 'the', 'the']


问:
Data has been deleted from database but table row not removed and total record not reduced in php using ajax
Data is Deleted database but table row not removed and total not reduced php ajax
I am creating an e-commerce site for my final year project. I am running into the problem with delete the product. if I delete product has been deleted from database success. but final total didn’t reduce and table row not removed what I tried so far I attached below along with screenshot image below.

Table

```<code><div class="container">
                <table class="table table-striped" id="mytable">
                    <thead>
                    <tr>
                        <th>ProductID</th>
                        <th>Productname</th>
                        <th>Price</th>
                        <th>Qty</th>
                        <th>Amount</th>
                        <th>Delete</th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>

        </div>

        <div style='text-align: right; margin:10px'>
            <label><h3>Total amount: </h3></label>
            <span style="font-size: 40px; color: #ff0911" id='total-amount'></span>
        </div>
</code>```

Display the Products

```<code><script>
getProducts();
function getProducts() {
    $.ajax({
        type: 'GET',
        url: 'all_cart.php',
        dataType: 'JSON',
        success: function(data) {
            data.forEach(function(element) {
                var id = element.id;
                var product_name = element.product_name;
                var price = element.price;
                $('#mytable tbody').after
                (
                    '<tr> ' +
                    '<td>' + id + '</td>' +
                    '<td>' + product_name + '</td>' +
                    '<td>' + price + '</td>' +
                    "<input type='hidden' class='price' name='price' value='" + price + "'>" +
                    '<td>' + "<input type = 'text' class='qty' name='qty' value='1'/>" + '</td>' +
                    '<td>' + "<input type = 'text' class='amount' id='amount' disabled/>" + '</td>' +

                    '<td>' +  " <Button type='button' class='btn btn-primary' onclick='deleteProduct(this," + id + ")' >Delete</Button> " + '</td>' +
                    '</tr>');
            });
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}
</code>```

Calculating the Total

```<code>$(function() {
    $(".price, .qty").on("keydown keyup click", function () {
        var price = $(this).parents('tr').find('.price');
        var qty= $(this).parents('tr').find('.qty');
        var sum = (
        Number($(price).val()) * Number($(qty).val())
        );
        $(this).parents('tr').find('.amount').val(sum);
        calculateAmount();
    });
});

function calculateAmount() {
    var total = 0;
    $('.amount').each(function(e){
        total += Number($(this).val());
    });
    $('#total-amount').text(total);
}
</code>```

delete product function

```<code>function deleteProduct(event, id) {
                $.ajax({
                    type: 'POST',
                    url: 'remove.php',
                    dataType: 'JSON',
                    data: {id: id},
                    success: function (data) {
                        $(event).parent('tr').remove();
                        calculateAmount();
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);

                    }
                });
}
</code>```

remove.php

```<code><?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include "db.php";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $stmt = $conn->prepare("delete from cart where id=?");
    $stmt->bind_param("s", $id);
    $id = $_POST["id"];
    if ($stmt->execute())
        {
            echo 1;
        }
    else
        {
                echo 0;
        }
        $stmt->close();
        }
?>
</code>```

答:
if your removing data from table after delete try to use this code

1.after success return delete function run again getProducts() function data again fetch and reset in table

2.delete functionality return all data in success function using php go to remove.php and select all data query and return all data

```<code>function deleteProduct(event, id) {
            $.ajax({
                type: 'POST',
                url: 'remove.php',
                dataType: 'JSON',
                data: {id: id},
                success: function (data) {
                     getProducts();
                    $(event).parent('tr').remove();
                    calculateAmount();
                },
                error: function (xhr, status, error) {
                    alert(xhr.responseText);

                }
            });
</code>```

Body:
Data is Deleted database but table row not removed and total not reduced php ajax
I am creating an e-commerce site for my final year project. I am running into the problem with delete the product. if I delete product has been deleted from database success. but final total didn’t reduce and table row not removed what I tried so far I attached below along with screenshot image below.

Table

                        ProductID
                        Productname
                        Price
                        Qty
                        Amount
                        Delete

Total amount:

Display the Products

Body:
if your removing data from table after delete try to use this code

1.after success return delete function run again getProducts() function data again fetch and reset in table

2.delete functionality return all data in success function using php go to remove.php and select all data query and return all data

function deleteProduct(event, id) {
            $.ajax({
                type: 'POST',
                url: 'remove.php',
                dataType: 'JSON',
                data: {id: id},
                success: function (data) {
                     getProducts();
                    $(event).parent('tr').remove();
                    calculateAmount();
                },
                error: function (xhr, status, error) {
                    alert(xhr.responseText);

                }
            });


问:
applying concat function on one column values to get data from another table
table :

```<code>value
- v1
- v2
</code>```

Now , I need to apply concat function on value col

concat(v1 , ' ' , v2)
```

like this.

I have used concat() on two or more col values but not on rows of one column.

How should I do it?

答:
You may use STUFF for your solution.

```<code> select stuff( (select ',' + column from table for xml path('')), 1,1,'')
</code>```

Body:
table :

value
- v1
- v2

Now , I need to apply concat function on value col

concat(v1 , ' ' , v2)

like this.

I have used concat() on two or more col values but not on rows of one column.

How should I do it?

Body:
You may use STUFF for your solution.

 select stuff( (select ',' + column from table for xml path('')), 1,1,'')


问:
How to hide Router navbar from privacy policy component
Once the app launches privacy policy component will arrive. in this component, want to hide the routers navbar using React.

```<code><li>
<NavLink to="/profile" ><i className="fas fa-epi-profile"></i></NavLink>
</li>
<li>
<NavLink to="/Home"><i className="fas fa-epi-good_picker"></i></NavLink>
</li>
<li>
<NavLink to="/TaskListTabs"><i className="fas fa-epi-task"></i></NavLink> </li>
<li>
<NavLink to="/Notification"><i className="fas fa-epi-notification"></i></NavLink>
</li>
</code>```

( this is App.js file)

```<code>class App extends Component { render() { return ( <RoutersNav /> ); } }
</code>```

but in privacy, component am using the navigation to another component which is code

```<code><NavLink to="/login" className="float-right">
<input type="submit" className="btn" onClick={this.routeChange} name="accept" value="Accept" />
</NavLink>
</code>```

once click on button giving error as "Uncaught Error: Invariant failed: You should not use <Route> outside a <Router>

答:
you can try conditional rendering,
try to wrap your code inside <BrowserRouter>

```<code>class App extends Component {

this.state={header:{ visible:false }};

render() {

    return (
    if(this.state.header.visible) ?
    <RoutersNav />
    <ToastBody className="provacy-policy-content">
    <h4>Sample text</h4> Privacy Content
    <input type="submit" className="btn float-left" name="accept" value="Accept" /> );
 :

    <ToastBody className="provacy-policy-content">
    <h4>Sample text</h4> Privacy Content
    <input type="submit" className="btn float-left" name="accept" value="Accept" /> );

); } }
</code>```

a good idea is ,

```<code><BrowserRouter>
<NavLink to="/">/home</NavLink>
<Route path="/" component={Home} />
</BrowserRouter>
</code>```

Body:
Once the app launches privacy policy component will arrive. in this component, want to hide the routers navbar using React.

<NavLink to="/profile" ></NavLink>

<NavLink to="/Home"></NavLink>

<NavLink to="/TaskListTabs"></NavLink>

<NavLink to="/Notification"></NavLink>

( this is App.js file)

class App extends Component { render() { return ( <RoutersNav /> ); } }

but in privacy, component am using the navigation to another component which is code

<NavLink to="/login" className="float-right">
<input type="submit" className="btn" onClick={this.routeChange} name="accept" value="Accept" />
</NavLink>

once click on button giving error as "Uncaught Error: Invariant failed: You should not use <Route> outside a <Router>

Body:
you can try conditional rendering,
try to wrap your code inside <BrowserRouter>

class App extends Component {

this.state={header:{ visible:false }};

render() {

    return (
    if(this.state.header.visible) ?
    <RoutersNav />
    <ToastBody className="provacy-policy-content">
    <h4>Sample text</h4> Privacy Content
    <input type="submit" className="btn float-left" name="accept" value="Accept" /> );
 :

    <ToastBody className="provacy-policy-content">
    <h4>Sample text</h4> Privacy Content
    <input type="submit" className="btn float-left" name="accept" value="Accept" /> );

); } }

a good idea is ,

<BrowserRouter>
<NavLink to="/">/home</NavLink>
<Route path="/" component={Home} />
</BrowserRouter>


问:
How can I unit test my log messages using testng
We use testng as out testing framework.  We also use Lombok @Log4j2 to instantiate our log objects. I need to test some code that it logs certain messages under certain conditions.

I have seen examples using junit and Mockito. But I cannot find how to do it in testng.  Switching to junit is not an option.

Edit

I have implemented a class (CaptureLogger) which extends AbstractLogger

```<code>import org.apache.logging.log4j.spi.AbstractLogger;

public class CaptureLogger extends AbstractLogger {
    ...
}
</code>```

I am unable to to hook it up to the logger for the class under test.

```<code>CaptureLogger customLogger = (CaptureLogger) LogManager.getLogger(MyClassUnderTest.class);
</code>```

generates an error message:

```<code>java.lang.ClassCastException: org.apache.logging.log4j.core.Logger cannot be cast to CaptureLogger
</code>```

I have found out that LogManager.getLogger returns the Logger interface, not the Logger object (which implements the Logger interface).

How can I create an instance of my CaptureLogger?

答:
As Long as you're using Lombok for logger generation you can't do much at the level of the source code itself with the given tools. For example, if you place @Log4j2 annotation, it generates:

```<code>private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
</code>```

The compiled code already comes with this line.

You can try to mock LogManager.getLogger method with PowerMockito but I don't really like this kind of tools. Stating this though since it can be a viable direction.

There are couple of ways to work with the framework itself.

One way (and I'm not familiar with Log4j2 specifically but it should offer this capability - I did something similar with Log4j 1.x many years ago) is to provide your own implementation of logger and associate it with the logger factory at the level of Log4j2 configurations.
Now if you do this, then the code generated by lombok will return your instance of logger that can memorize the messages that were logged at different levels (it's the custom logic you'll have to implement at the level of Logger).

Then the logger will have a method public List<String> getResults() and you'll call the following code during the verification phase:

```<code>   public void test() {
     UnderTest objectUnderTest = ...
     //test test test

     // verification
     MyCustomLogger logger = (MyCutomLogger)LogManager.getLogger(UnderTest.class);

     List<String> results =  logger.getResults();
     assertThat(results, contains("My Log Message with Params I expect or whatever");

   }
</code>```

Another somewhat similar way  I can think of is to create a custom appender that will memorize all the messages that were sent during the test. Then you could (declaratively or programmatically bind that appender to the Logger obtained by the LogFactory.getLogger  for the class under test (or also for other classes depending on your actual needs).

Then let the test work and when it comes to verification - get the reference to the appender from the log4j2 system and ask for results with some public List<String> getResults() method what must exist on the appender in addition to the methods that it must implement in order to obey the Appender contract.

So the test could look something like this:

```<code>public void test () {
     MyTestAppender app = createMemorizingAppender();
     associateAppenderWithLoggerUnderTest(app, UnderTest.class);
     UnderTest underTest = ...

     // do your tests that involve logging operations

     // now the verification phase:

     List<String> results =  app.getResults();
     assertThat(results, contains("My Log Message with Params I expect or whatever");

}
</code>```

Body:
We use testng as out testing framework.  We also use Lombok @Log4j2 to instantiate our log objects. I need to test some code that it logs certain messages under certain conditions.

I have seen examples using junit and Mockito. But I cannot find how to do it in testng.  Switching to junit is not an option.

Edit

I have implemented a class (CaptureLogger) which extends AbstractLogger

import org.apache.logging.log4j.spi.AbstractLogger;

public class CaptureLogger extends AbstractLogger {
    ...
}

I am unable to to hook it up to the logger for the class under test.

CaptureLogger customLogger = (CaptureLogger) LogManager.getLogger(MyClassUnderTest.class);

generates an error message:

java.lang.ClassCastException: org.apache.logging.log4j.core.Logger cannot be cast to CaptureLogger

I have found out that LogManager.getLogger returns the Logger interface, not the Logger object (which implements the Logger interface).

How can I create an instance of my CaptureLogger?

Body:
As Long as you're using Lombok for logger generation you can't do much at the level of the source code itself with the given tools. For example, if you place @Log4j2 annotation, it generates:

private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);

The compiled code already comes with this line.

You can try to mock LogManager.getLogger method with PowerMockito but I don't really like this kind of tools. Stating this though since it can be a viable direction.

There are couple of ways to work with the framework itself.

One way (and I'm not familiar with Log4j2 specifically but it should offer this capability - I did something similar with Log4j 1.x many years ago) is to provide your own implementation of logger and associate it with the logger factory at the level of Log4j2 configurations.
Now if you do this, then the code generated by lombok will return your instance of logger that can memorize the messages that were logged at different levels (it's the custom logic you'll have to implement at the level of Logger).

Then the logger will have a method public List<String> getResults() and you'll call the following code during the verification phase:

   public void test() {
     UnderTest objectUnderTest = ...
     //test test test

     // verification
     MyCustomLogger logger = (MyCutomLogger)LogManager.getLogger(UnderTest.class);

     List<String> results =  logger.getResults();
     assertThat(results, contains("My Log Message with Params I expect or whatever");

   }

Another somewhat similar way  I can think of is to create a custom appender that will memorize all the messages that were sent during the test. Then you could (declaratively or programmatically bind that appender to the Logger obtained by the LogFactory.getLogger  for the class under test (or also for other classes depending on your actual needs).

Then let the test work and when it comes to verification - get the reference to the appender from the log4j2 system and ask for results with some public List<String> getResults() method what must exist on the appender in addition to the methods that it must implement in order to obey the Appender contract.

So the test could look something like this:

public void test () {
     MyTestAppender app = createMemorizingAppender();
     associateAppenderWithLoggerUnderTest(app, UnderTest.class);
     UnderTest underTest = ...

     // do your tests that involve logging operations

     // now the verification phase:

     List<String> results =  app.getResults();
     assertThat(results, contains("My Log Message with Params I expect or whatever");

}


问:
ASP.NET MVC slow image loading through MVC framework?
On some photobook page i want to show appr 20 thumbnails. These thumbnails are programatically loaded from a database. those thumbnails are already resized. When i show them the images load kinda slow. some take 0.5 seconds to load some wait for 2 secons. The database doesn't matter because when i remove the database layer, the performance issue still exists.When i load the same images directly with html the problem the images do load immediately.

Is loading images/files through the mvc framework slow or am i missing something?

This goes too slow

```<code>//in html
<img src='/File/Image.jpg' border='0'>

//in controller
public FileResult File(string ID)
{
    //database connection removed, just show a pic
    byte[] imageFile = System.IO.File.ReadAllBytes(ID);
    return new FileContentResult(imageFile,"image/pjpeg");
}
</code>```

This goes immediately

```<code><img src='/Content/Images/Image.jpg' border='0'>
</code>```

答:
I had the same issue.  I'm using MVC 3.  After pulling my hair out, what I discovered is that once you use Session State in your web app, dynamic image loading seems to get clogged, due to the pounding session requests.  To fix this, I decorated my controller with:

[SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]

This disabled the session state for my Photos controller, and the speed returned.  If you are using an earlier version of MVC, you'll need to jump through some hoops and create a Controller/Controller factory to do this.  See How can I disable session state in ASP.NET MVC?

Hope this helps!

ContentLicense: CC BY-SA 2.5

Body:
On some photobook page i want to show appr 20 thumbnails. These thumbnails are programatically loaded from a database. those thumbnails are already resized. When i show them the images load kinda slow. some take 0.5 seconds to load some wait for 2 secons. The database doesn't matter because when i remove the database layer, the performance issue still exists.When i load the same images directly with html the problem the images do load immediately.

Is loading images/files through the mvc framework slow or am i missing something?

This goes too slow

//in html

//in controller
public FileResult File(string ID)
{
    //database connection removed, just show a pic
    byte[] imageFile = System.IO.File.ReadAllBytes(ID);
    return new FileContentResult(imageFile,"image/pjpeg");
}

This goes immediately


问:
For keywords(strings) in one column and values(floats) in another, I want to count the number ok keywords that fall per unit range of the value
I have a dataframe:

```<code>            keyword     val
    0   nt              0.93
    1   atm             0.94
    2   bank            1.00
    3   long            1.02
    4   number          1.11
    5   get             2.20
    6   money           3.50
    7   account         3.80
    8   deposit         3.90
    9   card            5.00
    10  credit          0.8
    11  debit           1.23
</code>```

I want to find out the number of keywords per unit range of value
ie from 0.9-1 => [nt,atm]=>2
   from 1-1.1 => [bank,long,number] =>3 and so on

答:
Try using groupby with some column value modifications, then use count on 'keyword' column:

```<code>>>> df.groupby(df['val'].astype(int))['keyword'].count()
val
0    3
1    4
2    1
3    3
4    1
Name: keyword, dtype: int64
</code>```

Edit:

```<code>>>> df.groupby(df['val'].apply("{:.1f}".format))['keyword'].count()
val
0.8    1
0.9    2
1.0    2
1.1    1
1.2    1
2.2    1
3.5    1
3.8    1
3.9    1
5.0    1
Name: keyword, dtype: int64
</code>```

If mind rounding (1.9 won't be in the same group as 1.1 though):

```<code>>>> df.groupby(df['val'].round(1))['keyword'].count()
val
0.8    1
0.9    2
1.0    2
1.1    1
1.2    1
2.2    1
3.5    1
3.8    1
3.9    1
5.0    1
Name: keyword, dtype: int64
</code>```

Body:
I have a dataframe:

            keyword     val
    0   nt              0.93
    1   atm             0.94
    2   bank            1.00
    3   long            1.02
    4   number          1.11
    5   get             2.20
    6   money           3.50
    7   account         3.80
    8   deposit         3.90
    9   card            5.00
    10  credit          0.8
    11  debit           1.23

I want to find out the number of keywords per unit range of value
ie from 0.9-1 => [nt,atm]=>2
   from 1-1.1 => [bank,long,number] =>3 and so on

Body:
Try using groupby with some column value modifications, then use count on 'keyword' column:

>>> df.groupby(df['val'].astype(int))['keyword'].count()
val
0    3
1    4
2    1
3    3
4    1
Name: keyword, dtype: int64

Edit:

>>> df.groupby(df['val'].apply("{:.1f}".format))['keyword'].count()
val
0.8    1
0.9    2
1.0    2
1.1    1
1.2    1
2.2    1
3.5    1
3.8    1
3.9    1
5.0    1
Name: keyword, dtype: int64

If mind rounding (1.9 won't be in the same group as 1.1 though):

>>> df.groupby(df['val'].round(1))['keyword'].count()
val
0.8    1
0.9    2
1.0    2
1.1    1
1.2    1
2.2    1
3.5    1
3.8    1
3.9    1
5.0    1
Name: keyword, dtype: int64


问:
After upgrading my project to Angular 8 from Angular 7.2, compile time increased 3 times. How can I fix it
I upgraded my project to Angular 8 version. While upgrading process, I haven't  met any error. But the compile time increased 3 time without any error. At least, How can I get the old compile time?

** P.S.: There is a bug cause to this problem. The issue related to this bug** https://github.com/angular/angular-cli/issues/13734

```<code>Last Compile Before Angular 8  (with Angular 7.2)
Time: 1382.536ms -> main.cf29a89468d732f3f363.js (main) 12.4 MB

First Compile After Upgrading to Angular 8
Time: 6379.317ms -> main.da4147c72278bc767ee4.js (main) 12.3 MB

Second Compile After Upgrading to Angular 8 and After restart PC
Time: 3147.254ms -> main.da4147c72278bc767ee4.js (main) 12.3 MB
</code>```

tsconfig.json

```<code>    {
     "compileOnSave": false,
     "compilerOptions": {
        "baseUrl": "",
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "mapRoot": "./",
        "moduleResolution": "node",
        "outDir": "../__dist_cli",
        "sourceMap": true,
        "target": "es5 ",
        "module": "es2015",
        "lib": [
            "es2016",
            "dom"
        ],
        "typeRoots": [
            "node_modules/@types",
            "typings/custom"
        ]
    }
</code>```

```<code>Angular CLI: 8.0.0
Node: 12.3.1
OS: win32 x64
Angular: 8.0.0
</code>```

答:
Try building package with command

```<code>ng build --es5BrowserSupport=false
</code>```

This will produce package for only modern browsers.
This will help you to figure out whether the differential loading packaging building took additional time.

Body:
I upgraded my project to Angular 8 version. While upgrading process, I haven't  met any error. But the compile time increased 3 time without any error. At least, How can I get the old compile time?

** P.S.: There is a bug cause to this problem. The issue related to this bug** https://github.com/angular/angular-cli/issues/13734

Last Compile Before Angular 8  (with Angular 7.2)
Time: 1382.536ms -> main.cf29a89468d732f3f363.js (main) 12.4 MB

First Compile After Upgrading to Angular 8
Time: 6379.317ms -> main.da4147c72278bc767ee4.js (main) 12.3 MB

Second Compile After Upgrading to Angular 8 and After restart PC
Time: 3147.254ms -> main.da4147c72278bc767ee4.js (main) 12.3 MB

tsconfig.json

    {
     "compileOnSave": false,
     "compilerOptions": {
        "baseUrl": "",
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "mapRoot": "./",
        "moduleResolution": "node",
        "outDir": "../__dist_cli",
        "sourceMap": true,
        "target": "es5 ",
        "module": "es2015",
        "lib": [
            "es2016",
            "dom"
        ],
        "typeRoots": [
            "node_modules/@types",
            "typings/custom"
        ]
    }

Angular CLI: 8.0.0
Node: 12.3.1
OS: win32 x64
Angular: 8.0.0

Body:
Try building package with command

ng build --es5BrowserSupport=false

This will produce package for only modern browsers.
This will help you to figure out whether the differential loading packaging building took additional time.


问:
Hide all rows in a DataGridView using VB
I am trying to filter data in a DataGridView and I need to hide all rows and columns. I try to do this using looping list LINQ & lambda expressions because if I use a foreach it is slow when I try to filter 3000 rows.

The following code executes without errors and works perfectly in c# but doesn't hide the rows in vb:

c# works perfectly

```<code>dataGridView1.Columns.OfType<DataGridViewColumn>().ToList().ForEach(col => col.Visible = false);
</code>```

vb doesnt works

```<code>datagrid.Rows.OfType(Of DataGridViewRow)().ToList().ForEach(Function(obj) obj.Visible = False)
</code>```

I'm looking for the equivalent code in vb.

答:
this will do exactly what you want</p>

```<code>Dim dv As DataView
dv = New DataView(ds.Tables(0), "name = 'Devcon' ", "type Desc", DataViewRowState.CurrentRows)
DataGridView1.DataSource = dv
</code>```

Body:
I am trying to filter data in a DataGridView and I need to hide all rows and columns. I try to do this using looping list LINQ & lambda expressions because if I use a foreach it is slow when I try to filter 3000 rows.

The following code executes without errors and works perfectly in c# but doesn't hide the rows in vb:

c# works perfectly

dataGridView1.Columns.OfType<DataGridViewColumn>().ToList().ForEach(col => col.Visible = false);

vb doesnt works

datagrid.Rows.OfType(Of DataGridViewRow)().ToList().ForEach(Function(obj) obj.Visible = False)

I'm looking for the equivalent code in vb.

Body:
this will do exactly what you want

Dim dv As DataView
dv = New DataView(ds.Tables(0), "name = 'Devcon' ", "type Desc", DataViewRowState.CurrentRows)
DataGridView1.DataSource = dv


问:
I want to compare 2 hash sets and take out the differences
I have 2 hash sets like this.

```<code>Hash_1 = {1, 2, 3, 4, 5}
Hash_2 = {4, 5, 6, 7, 8}
</code>```

I am using C#

I want to compare those two sets and want to get the output like

```<code>Hash_3 = {1, 2, 3, 6, 7, 8}
</code>```

答:
What you want is: Hash_1 without Hash_2, and Hash_2 without Hash_1, then combined into one set.

So let's start with Hash_1 without Hash_2:

```<code>var modified1 = Hash_1.Except(Hash_2);
</code>```

and then Hash_2 without Hash_1:

```<code>var modified2 = Hash_2.Except(Hash_1);
</code>```

And now let's combine them:

```<code>var result = modified1.Concat(modified2);
</code>```

Or in short:

```<code>var result = Hash_1.Except(Hash_2).Concat(Hash_2.Except(Hash_1));
</code>```

Try it online

Body:
I have 2 hash sets like this.

Hash_1 = {1, 2, 3, 4, 5}
Hash_2 = {4, 5, 6, 7, 8}

I am using C#

I want to compare those two sets and want to get the output like

Hash_3 = {1, 2, 3, 6, 7, 8}

Body:
What you want is: Hash_1 without Hash_2, and Hash_2 without Hash_1, then combined into one set.

So let's start with Hash_1 without Hash_2:

var modified1 = Hash_1.Except(Hash_2);

and then Hash_2 without Hash_1:

var modified2 = Hash_2.Except(Hash_1);

And now let's combine them:

var result = modified1.Concat(modified2);

Or in short:

var result = Hash_1.Except(Hash_2).Concat(Hash_2.Except(Hash_1));

Try it online


问:
Submit button in a hyperlink
I would have never thought that it was valid markup to put a <input type="submit" /> in an anchor  like so:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Submit input in a hyperlink</title>
</head>
<body>
    <form action="/form-submission" method="get">
        <a href="/hyperlink-click"><input type="submit" /></a>
    </form>
</body>
</html>
</code>```

Oddly enough though, if you feed this into the w3c validator, it validates.

What is supposed to happen when a user clicks on the submit button? Would this kind of setup just be unpredictable with different browsers doing whatever they please, or are there explicit rules dictating expected behavior? Would doing something like this ever come in handy?

答:
In short, it isn't valid HTML.  It probably shouldn't be valid and, as Richard points out, it's interesting it's been addressed in HTML5

Try running the same code as HTML5. The HTML5 definition has corrected this by giving the error: ```The element input must not appear as a descendant of the a element.```

This is because you are displaying two buttons on the same place, so which button action should take preference? Essentially you're hiding one button action from the user, which is as good as having no second button at all.

There's more information on this in HTML: The Markup Language Reference

Title: Submit button in a hyperlink

Body:
I would have never thought that it was valid markup to put a <input type="submit" /> in an anchor  like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Submit input in a hyperlink</title>

    <form action="/form-submission" method="get">
        <input type="submit" />
    </form>

Oddly enough though, if you feed this into the w3c validator, it validates.

What is supposed to happen when a user clicks on the submit button? Would this kind of setup just be unpredictable with different browsers doing whatever they please, or are there explicit rules dictating expected behavior? Would doing something like this ever come in handy?

Body:
In short, it isn't valid HTML.  It probably shouldn't be valid and, as Richard points out, it's interesting it's been addressed in HTML5

Try running the same code as HTML5. The HTML5 definition has corrected this by giving the error:
The element input must not appear as a descendant of the a element.

This is because you are displaying two buttons on the same place, so which button action should take preference? Essentially you're hiding one button action from the user, which is as good as having no second button at all.

There's more information on this in HTML: The Markup Language Reference


问:
Why some method doesn't work after embedding custom manifest file?
I try to embed custom manifest file to vb.net source code in order to get Administrator level.

But Console.WriteLine method does not work after embedding the manifest file.

Target source file and manifest file is as below.

' test.vb
Module Test
  Sub Main
    Console.WriteLine("Hello")
  End Sub
End Module
```

<pre class="lang-xml prettyprint-override"><code><!--manifest.xml-->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>
</code>```

I compile this files using Mono compiler on Windows 10.

```<code>vbc /win32manifest:manifest.xml test.vb
</code>```

How can I solve this problem?

Thanks!

答:
I don't think this will work with Mono compiler.

The manifest file is the only option that will set permission to the administrator for your .exe.

This can be done using .Net framework with Visual Studio.

Body:
I try to embed custom manifest file to vb.net source code in order to get Administrator level.

But Console.WriteLine method does not work after embedding the manifest file.

Target source file and manifest file is as below.

' test.vb
Module Test
  Sub Main
    Console.WriteLine("Hello")
  End Sub
End Module

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

I compile this files using Mono compiler on Windows 10.

vbc /win32manifest:manifest.xml test.vb

How can I solve this problem?

Thanks!


问:
Time Complexity Of Merge Sort In Special Condition
What would be the time complexity If I will apply merge sort on an already sorted array?</p>

答:
Usual merge sort still uses O(nlogn) for sorted data.

But there is natural merge sort variant that provides linear complexity for sorted arrays.

Note that natural merge sort also gives O(nlogn) for arbitrary data, compared with isertion sort, that behaves well for sorted data but becomes quadratic in the worst case


问:
Gnuplot: Plotting from *txt files from different directories by reading column header
My folder structure looks kind of like this

```<code>$ tree
.
├── Original_folder
│   └── cat.txt
├── folder1
│   └── cat.txt
├── folder2
│   └── cat.txt
├── folder3
│
└── cat.txt
</code>```

Each cat.txt file has 5 line before starting the column header.
Sample cat.txt file is like this

```<code>Version LRv1.10.0
Build date 2017-12-06
MOL-calc
PRESSURE
!
      Time[s]     InletT[K]   InletP[Pa]   O2_GasOut     C_GasOut
       100         0.000885   1000000       0.0007       0.2111
and so on....
</code>```

I want to plot first column along with the column which have column header with a keyword "_GasOut". (There are unknown number of header with this keywords, For each column I would like to have a separate graph). Additionally, the graphical results of Original_folder should be plotted in the same graph for all the plots from folder1, folder2, folder3...... and so on.

Corresponding graph should be saved in the corresponding folders.

N.B: folder numbers are not fixed.
I added one of the cat.txt file for reference. https://1drv.ms/t/s!Aoomvi55MLAQh1wMmpnPGnliFmgg

答:
This example shows how to plot all columns whose header contains the substring "_GasOut".   The strategy is to test each column header for the substring; if it matches then the column values are plotted, if there is no match then all values are treated as NaN.  set datafile missing NaN then causes the entire plot to be skipped.

I do not repeat here the iteration over subdirectories as shown in previous examples.

```<code>set rmargin at screen 0.85
set key reverse Left top left at screen 0.85, 0.9
set log y

data = 'cat.txt'
set datafile missing NaN

plot for [i=1:99] data skip 5 using 1:(strstrt(columnhead(i),"_GasOut") ? column(i) : NaN) title columnhead(i) noenhanced lw 2
</code>```

Body:
My folder structure looks kind of like this

$ tree
.
├── Original_folder
│   └── cat.txt
├── folder1
│   └── cat.txt
├── folder2
│   └── cat.txt
├── folder3
│
└── cat.txt

Each cat.txt file has 5 line before starting the column header.
Sample cat.txt file is like this

Version LRv1.10.0
Build date 2017-12-06
MOL-calc
PRESSURE
!
      Time[s]     InletT[K]   InletP[Pa]   O2_GasOut     C_GasOut
       100         0.000885   1000000       0.0007       0.2111
and so on....

I want to plot first column along with the column which have column header with a keyword "_GasOut". (There are unknown number of header with this keywords, For each column I would like to have a separate graph). Additionally, the graphical results of Original_folder should be plotted in the same graph for all the plots from folder1, folder2, folder3...... and so on.

Corresponding graph should be saved in the corresponding folders.

N.B: folder numbers are not fixed.
I added one of the cat.txt file for reference. https://1drv.ms/t/s!Aoomvi55MLAQh1wMmpnPGnliFmgg

Body:
This example shows how to plot all columns whose header contains the substring "_GasOut".   The strategy is to test each column header for the substring; if it matches then the column values are plotted, if there is no match then all values are treated as NaN.  set datafile missing NaN then causes the entire plot to be skipped.

I do not repeat here the iteration over subdirectories as shown in previous examples.

set rmargin at screen 0.85
set key reverse Left top left at screen 0.85, 0.9
set log y

data = 'cat.txt'
set datafile missing NaN

plot for [i=1:99] data skip 5 using 1:(strstrt(columnhead(i),"_GasOut") ? column(i) : NaN) title columnhead(i) noenhanced lw 2


问:
Silverlight 3 class library
I'm currently working on a UI development project and it was decided to implement it in Silvelight. I understand that Microsoft developers try to minimize size of the distribution and that's why some (lots) of the classes in regular .NET Framework are not included. Is it expected to see more classes included in Silverlight 3 library?</p>

答:
The .NET framework contains heaps of stuff that is of little or no use in a sandboxed environment like Silverlight.

I would not expect to see much more of the standard .NET framework included in the Core CLR, however there'll be a bunch of stuff coming into Silverlight3 from WPF.

OwnerDisplayName: buckethead

Title: Silverlight 3 class library

LastEditorDisplayName: buckethead

OwnerDisplayName: geofftnz


问:
Scheduled batch file not running
I have a .bat file. If I run it manually (double click), it works. If I schedule it, it doesn't.

I tried solutions from similar questions on StackOverflow but none of them is working. Like:

Batch not scheduled

WIN 10 task scheduler

I changed general options.

Run no matter user connection

I changed the user starting the scheduled task.

Mine, BTW, has maximum permissions and when double clicked, it works.

I allowed maximum permissions.

Modified "Add argument" and "Start in"

I set no conditions in the "conditions" tab

I'm new to scripting, so it is possible I set something wrong.

That's my code:

```<code>@echo off

"C:\Program Files (x86)\WinSCP\winscp.com" /log=winscp.log /ini=nul /command ^
"open sftp://user:password@mySite.com -hostkey=""ssh-rsa 4096 xxxxxxxxx/yyyyw=""" ^
"option batch" ^
"option transfer binary" ^
"synchronize remote -filemask=""*.png>=2016-01-01<4M;*.jpg>=2016-01-01<4M "" \\FromFolder /destination/ -nopreservetime"

"exit"
</code>```

If I put md C:\Temp & echo %TIME%>C:\Temp\Test.txt as 2° row, it writes the Test.txt file. If i put it in the end of the file it doesn't. No problems if i run it by double click.

I need the task to run the .bat file just as if I am double clicking it. I don't know if is it possible to open the shell or run it in background, as both of them are good for me. Let me know.

Thanks for suggestions.

Edit_1)

I removed the echo %TIME% >> C:\Temp\Test.txt  and kept the "exit" >> C:\Temp\Test.txt .

If I double click my bat file, this is the log:

```<code>Host Search ...
Host connection ...
Authentication ...
Use username "xxxx".
Authentication with preset password
Authenticated.
Starting session ...
Session started.
Active session: [1] xxx@site.com
batch abort
transfer binary
Comparison...
Local 'file\MyFolder1' => remote '/ images'
Nothing to synchronize
Comparison...
Local 'H:\MyPath\MyFolder2' => remote '/ images'
Synchronization...
Local 'H:\MyPath\MyFolder2' => remote '/ images'
H:\MyPath\MyFolder2 image.JPG | 617 KB | 50.4 KB / s | binary | 100%
</code>```

And it works perfectly.

If i run it from schedule (using my same user)
this is the log.

```<code>Host Search ...
Host connection ...
Authentication ...
Use username "xxxx".
Authentication with preset password
Authenticated.
Starting session ...
Session started.
Active session: [1] xxx@site.com
batch abort
transfer binary
Comparison...
Local 'file\MyFolder1' => remote '/ images'
Nothing to synchronize
Comparison...
Local 'H:\MyPath\MyFolder2' => remote '/ images'
Folder List Error Request 'H:\MyPath\MyFolder2\*.*'.
Error retrieving file list for "H:\MyPath\MyFolder2\*.*'.

System error. Code: 3.

The specified path could not be found
(I) nterrupt, (R) etry, (S) top: Stop
Folder List Error Request 'H:\MyPath\MyFolder2\*.*'
Error retrieving file list for "H:\MyPath\MyFolder2\*.*'

System error. Code: 3.

The specified path could not be found
</code>```

I schedule the bat file using my user and max privileges so it should find the folder in the H:\ disk.

答:
WinSCP most probably fails. I would guess that because the batch file working directory is not hat you think and winscp.log cannot be created there. Try using a path like for your debug test: C:\Temp\winscp.log.

The reason why the md C:\Temp & echo %TIME%>C:\Temp\Test.txt does not work at the end of your batch file is the exit command. You probably believe it's interpreted as WinSCP command. But it's not. You are missing ^ after the synchronize command. And additionally, you have a blank space after it. As a consequence, the exit is not part of WinSCP command-line, but it exits the batch file instead. Also the lines have to be indented (though I assume that it's rather due to your post formatting).

Try something like this:

```<code>@echo off

md C:\Temp
echo %TIME% > C:\Temp\Test.txt

"C:\Program Files (x86)\WinSCP\winscp.com" /log=C:\temp\winscp.log /ini=nul /command ^
    "open sftp://user:password@mySite.com -hostkey=""ssh-rsa 4096 xxxxxxxxx/yyyyw=""" ^
    "option batch" ^
    "option transfer binary" ^
    "synchronize remote -filemask=""*.png>=2016-01-01<4M;*.jpg>=2016-01-01<4M "" \\FromFolder /destination/ -nopreservetime" ^
    "exit" >> C:\Temp\Test.txt

echo %TIME% >> C:\Temp\Test.txt
</code>```

See also WinSCP FAQ Why are some WinSCP scripting commands specified in a batch file not executed/failing?

Title: Scheduled batch file not running

Body:
I have a .bat file. If I run it manually (double click), it works. If I schedule it, it doesn't.

I tried solutions from similar questions on StackOverflow but none of them is working. Like:

Batch not scheduled

WIN 10 task scheduler

I changed general options.

Run no matter user connection

I changed the user starting the scheduled task.

Mine, BTW, has maximum permissions and when double clicked, it works.

I allowed maximum permissions.

Modified "Add argument" and "Start in"

I set no conditions in the "conditions" tab

I'm new to scripting, so it is possible I set something wrong.

That's my code:

@echo off

"C:\Program Files (x86)\WinSCP\winscp.com" /log=winscp.log /ini=nul /command ^
"open sftp://user:password@mySite.com -hostkey=""ssh-rsa 4096 xxxxxxxxx/yyyyw=""" ^
"option batch" ^
"option transfer binary" ^
"synchronize remote -filemask=""*.png>=2016-01-01<4M;*.jpg>=2016-01-01<4M "" \\FromFolder /destination/ -nopreservetime"

"exit"

If I put md C:\Temp & echo %TIME%>C:\Temp\Test.txt as 2° row, it writes the Test.txt file. If i put it in the end of the file it doesn't. No problems if i run it by double click.

I need the task to run the .bat file just as if I am double clicking it. I don't know if is it possible to open the shell or run it in background, as both of them are good for me. Let me know.

Thanks for suggestions.

Edit_1)

I removed the echo %TIME% >> C:\Temp\Test.txt  and kept the "exit" >> C:\Temp\Test.txt .

If I double click my bat file, this is the log:

Host Search ...
Host connection ...
Authentication ...
Use username "xxxx".
Authentication with preset password
Authenticated.
Starting session ...
Session started.
Active session: [1] xxx@site.com
batch abort
transfer binary
Comparison...
Local 'file\MyFolder1' => remote '/ images'
Nothing to synchronize
Comparison...
Local 'H:\MyPath\MyFolder2' => remote '/ images'
Synchronization...
Local 'H:\MyPath\MyFolder2' => remote '/ images'
H:\MyPath\MyFolder2 image.JPG | 617 KB | 50.4 KB / s | binary | 100%

And it works perfectly.

If i run it from schedule (using my same user)
this is the log.

Host Search ...
Host connection ...
Authentication ...
Use username "xxxx".
Authentication with preset password
Authenticated.
Starting session ...
Session started.
Active session: [1] xxx@site.com
batch abort
transfer binary
Comparison...
Local 'file\MyFolder1' => remote '/ images'
Nothing to synchronize
Comparison...
Local 'H:\MyPath\MyFolder2' => remote '/ images'
Folder List Error Request 'H:\MyPath\MyFolder2\*.*'.
Error retrieving file list for "H:\MyPath\MyFolder2\*.*'.

System error. Code: 3.

The specified path could not be found
(I) nterrupt, (R) etry, (S) top: Stop
Folder List Error Request 'H:\MyPath\MyFolder2\*.*'
Error retrieving file list for "H:\MyPath\MyFolder2\*.*'

System error. Code: 3.

The specified path could not be found

I schedule the bat file using my user and max privileges so it should find the folder in the H:\ disk.

Body:
WinSCP most probably fails. I would guess that because the batch file working directory is not hat you think and winscp.log cannot be created there. Try using a path like for your debug test: C:\Temp\winscp.log.

The reason why the md C:\Temp & echo %TIME%>C:\Temp\Test.txt does not work at the end of your batch file is the exit command. You probably believe it's interpreted as WinSCP command. But it's not. You are missing ^ after the synchronize command. And additionally, you have a blank space after it. As a consequence, the exit is not part of WinSCP command-line, but it exits the batch file instead. Also the lines have to be indented (though I assume that it's rather due to your post formatting).

Try something like this:

@echo off

md C:\Temp
echo %TIME% > C:\Temp\Test.txt

"C:\Program Files (x86)\WinSCP\winscp.com" /log=C:\temp\winscp.log /ini=nul /command ^
    "open sftp://user:password@mySite.com -hostkey=""ssh-rsa 4096 xxxxxxxxx/yyyyw=""" ^
    "option batch" ^
    "option transfer binary" ^
    "synchronize remote -filemask=""*.png>=2016-01-01<4M;*.jpg>=2016-01-01<4M "" \\FromFolder /destination/ -nopreservetime" ^
    "exit" >> C:\Temp\Test.txt

echo %TIME% >> C:\Temp\Test.txt

See also WinSCP FAQ Why are some WinSCP scripting commands specified in a batch file not executed/failing?


问:
How to Pass an Array from a JSR223 Sampler to Another JSR223 Sampler?
I just want to know how to pass an array from a JSR223 sampler to another JSR223 sampler. Note that the two JSR223 are just in the same thread. I had been searching and I cannot find the exact solution. I'm just a newbie in Jmeter, just searching for java codes etc. So here is the code:

```<code>import groovy.json.JsonSlurper;

String response = prev.getResponseDataAsString();

def jsonSlurper = new JsonSlurper();
def json = jsonSlurper.parseText(response);

int size = json.records.size;
vars.put("intDashboardMeetingsCount", size);

def strMeetingsArray = new String[size];

if (size > 0) {
    for (int i=0;i<size;i++) {
        strMeetingsArray[i] = json.records.get(i).id;
    }
}
</code>```

I already got the number of records in intDashboardMeetingsCount, and I just need to know how will I able to get the data of strMeetingsArray[]

Thanks in advance!

答:
you can use variables (vars) for a single thread. When you do a multi-thread test, you can use the properties (props).

Sample Variable Used Javascript  Code:

```<code>vars.put("myString","mysamplestring");
var getString= vars.get("myString");

var array = ['bilal','demir'];
vars.putObject("myArray",array);
var getArray = vars.getObject("myArray");

log.info( "*getString : {} *getArray :{} *firstItem: {} *length : {}" , getString, getArray, getArray.length, getArray[0]);
//output: *getString : mysamplestring *getArray :{0=bilal, 1=demir} *firstItem: bilal *length : 2
</code>```

Sample Properties Used Javascript  Code:

```<code>var array = ['bilal','demir'];
props.put("myArray",array);
var getArray = props.get("myArray");

log.info( "getArray :{}  length : {}" , getArray, getArray.length);
//output: getArray :{0=bilal, 1=demir}  length : 2
</code>```

For groovy change define variable code var to def

Body:
I just want to know how to pass an array from a JSR223 sampler to another JSR223 sampler. Note that the two JSR223 are just in the same thread. I had been searching and I cannot find the exact solution. I'm just a newbie in Jmeter, just searching for java codes etc. So here is the code:

import groovy.json.JsonSlurper;

String response = prev.getResponseDataAsString();

def jsonSlurper = new JsonSlurper();
def json = jsonSlurper.parseText(response);

int size = json.records.size;
vars.put("intDashboardMeetingsCount", size);

def strMeetingsArray = new String[size];

if (size > 0) {
    for (int i=0;i<size;i++) {
        strMeetingsArray[i] = json.records.get(i).id;
    }
}

I already got the number of records in intDashboardMeetingsCount, and I just need to know how will I able to get the data of strMeetingsArray[]

Thanks in advance!

Body:
you can use variables (vars) for a single thread. When you do a multi-thread test, you can use the properties (props).

Sample Variable Used Javascript  Code:

vars.put("myString","mysamplestring");
var getString= vars.get("myString");

var array = ['bilal','demir'];
vars.putObject("myArray",array);
var getArray = vars.getObject("myArray");

log.info( "*getString : {} *getArray :{} *firstItem: {} *length : {}" , getString, getArray, getArray.length, getArray[0]);
//output: *getString : mysamplestring *getArray :{0=bilal, 1=demir} *firstItem: bilal *length : 2

Sample Properties Used Javascript  Code:

var array = ['bilal','demir'];
props.put("myArray",array);
var getArray = props.get("myArray");

log.info( "getArray :{}  length : {}" , getArray, getArray.length);
//output: getArray :{0=bilal, 1=demir}  length : 2

For groovy change define variable code var to def


问:
How to count records of particular id in spring boot and hibernate
I am working on a project using Spring boot and hibernate. I want to count records against an id in table. I can count all records of the table but unable to count records against a foreign key.

Here is my controller code

```<code>@RequestMapping("/rating/{id}")
@ResponseBody
 public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

long postobj = myDao.count();
return postobj;
}
</code>```

Here i am passing an id in url but there is no method of count to pass this id to find records.

And here is my Dao Interface

```<code>@Transactional
public interface MyDaoInterface extends CrudRepository<Rating, Long>{
}
</code>```

答:
```<code>@RequestMapping("/rating/{id}")
@ResponseBody
public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

 List<Rating> ratings = myDao.findByPostId(id);
 long postobj = ratings.size() //use this code where you effectively need the # of entires.

 return ratings;
}
</code>```

Body:
I am working on a project using Spring boot and hibernate. I want to count records against an id in table. I can count all records of the table but unable to count records against a foreign key.

Here is my controller code

@RequestMapping("/rating/{id}")
@ResponseBody
 public long getRatingInfo(@PathVariable("id") long id, HttpServletRequest req, HttpServletResponse res) throws Exception {

long postobj = myDao.count();
return postobj;
}

Here i am passing an id in url but there is no method of count to pass this id to find records.

And here is my Dao Interface

@Transactional
public interface MyDaoInterface extends CrudRepository<Rating, Long>{
}


问:
Functional programming functions using 2 lists in D
If I have 2 lists:

```<code>list1 = [1, 2, 3, 4];
list2 = [10, 25, 35, 58];
</code>```

and I want to get a list which has products of corresponding elements of 2 lists;

In Python one can do:

```<code>outlist = list(map(lambda a,b: a*b, list1, list2))
</code>```

However, in D, I know of following method:

```<code>import std.stdio;
void main(){
    auto list1 = [1, 2, 3, 4];
    auto list2 = [10, 25, 35, 58];
    int[] outlist;
    foreach(i, item; list1){
        outlist ~= item*list2[i];
    }
    writeln(outlist);
}
</code>```

My questions are:

Q1: Can one keep both lists as argument of foreach?

Q2: How to multiply corresponding elements of 2 lists using map function?

Thanks for your insight.

答:
The key is to use zip to combine the elements of the two lists (or dynamic arrays as they are known in D) to a single array of tuples before applying map or foreach. The tuple elements can be accessed with a zero based index (i.e. a[0] and a[1] in this example).

```<code>import std.algorithm.iteration : map;
import std.range : zip;
import std.stdio : writeln;

void main() {
  auto list1 = [1, 2, 3, 4];
  auto list2 = [10, 25, 35, 58];

  // Question #2
  auto list3 = zip(list1, list2).map!(a => a[0] * a[1]);

  writeln(list3);

  // Question #1
  typeof(list1) list4;
  foreach(a; zip(list1, list2)) {
    list4 ~= a[0] * a[1];
  }

  writeln(list4);
}
</code>```

The code above prints twice:

```<code>[10, 50, 105, 232]
</code>```

as expected.

Body:
If I have 2 lists:

list1 = [1, 2, 3, 4];
list2 = [10, 25, 35, 58];

and I want to get a list which has products of corresponding elements of 2 lists;

In Python one can do:

outlist = list(map(lambda a,b: a*b, list1, list2))

However, in D, I know of following method:

import std.stdio;
void main(){
    auto list1 = [1, 2, 3, 4];
    auto list2 = [10, 25, 35, 58];
    int[] outlist;
    foreach(i, item; list1){
        outlist ~= item*list2[i];
    }
    writeln(outlist);
}

My questions are:

Q1: Can one keep both lists as argument of foreach?

Q2: How to multiply corresponding elements of 2 lists using map function?

Thanks for your insight.

Body:
The key is to use zip to combine the elements of the two lists (or dynamic arrays as they are known in D) to a single array of tuples before applying map or foreach. The tuple elements can be accessed with a zero based index (i.e. a[0] and a[1] in this example).

import std.algorithm.iteration : map;
import std.range : zip;
import std.stdio : writeln;

void main() {
  auto list1 = [1, 2, 3, 4];
  auto list2 = [10, 25, 35, 58];

  // Question #2
  auto list3 = zip(list1, list2).map!(a => a[0] * a[1]);

  writeln(list3);

  // Question #1
  typeof(list1) list4;
  foreach(a; zip(list1, list2)) {
    list4 ~= a[0] * a[1];
  }

  writeln(list4);
}

The code above prints twice:

[10, 50, 105, 232]

as expected.


问:
I found one link but i don't know what is that
In my website I check security scan and I found one link but I don't know where is that link

I search my whole website pages but don't find anything

```<code>/index.php
/                          <-- this link
/artists.php
/byartwork.php
/bytattoo.php
/byartist.php
/contactus.php
/appointment.php
/cdn-cgi/l/email-protection
</code>```

I want to remove this link. Please tell me where I can find this and what it is.

答: The / means that is the website's root directory. It basically means that is the home page of your website. For example, the moment you go to https://www.google.com you will be greeted by the home page.</p>

Body:
In my website I check security scan and I found one link but I don't know where is that link

I search my whole website pages but don't find anything

/index.php
/                          <-- this link
/artists.php
/byartwork.php
/bytattoo.php
/byartist.php
/contactus.php
/appointment.php
/cdn-cgi/l/email-protection

I want to remove this link. Please tell me where I can find this and what it is.


问:
C++ char* array
When I create something like

```<code>char* t = new char[44];
t = strcpy(s,t);
</code>```

then strlen(t); return some wrong results. how I can change this?

答:
Both strcpy and strlen expect to find the special character NUL or '\0' in the array. An uninitialized array, as the one you've created, may contain anything at all, which means the behavior of your program is undefined when it is passed to strcpy as the source argument.

Assuming the goal was to copy s into t, to make the program behave as expected, try this:

```<code>#include <iostream>
#include <cstring>
int main()
{
    const char* s = "test string";
    char* t = new char[44];
//  std::strcpy(t, s); // t is the destination, s is the source!
    std::strncpy(t, s, 44); // you know the size of the target, use it
    std::cout << "length of the C-string in t is " << std::strlen(t) << '\n';
    delete[] t;
}
</code>```

But keep in mind that in C++, strings are handled as objects of type std::string.

```<code>#include <iostream>
#include <string>
int main()
{
    const std::string s = "test string";
    std::string t = s;
    std::cout << "length of the string in t is " << t.size() << '\n';
}
</code>```

OwnerDisplayName: Александр Брус

Title: C++ char* array

Body:
When I create something like

char* t = new char[44];
t = strcpy(s,t);

then strlen(t); return some wrong results. how I can change this?

Body:
Both strcpy and strlen expect to find the special character NUL or '\0' in the array. An uninitialized array, as the one you've created, may contain anything at all, which means the behavior of your program is undefined when it is passed to strcpy as the source argument.

Assuming the goal was to copy s into t, to make the program behave as expected, try this:

#include <iostream>
#include <cstring>
int main()
{
    const char* s = "test string";
    char* t = new char[44];
//  std::strcpy(t, s); // t is the destination, s is the source!
    std::strncpy(t, s, 44); // you know the size of the target, use it
    std::cout << "length of the C-string in t is " << std::strlen(t) << '\n';
    delete[] t;
}

But keep in mind that in C++, strings are handled as objects of type std::string.

#include <iostream>
#include <string>
int main()
{
    const std::string s = "test string";
    std::string t = s;
    std::cout << "length of the string in t is " << t.size() << '\n';
}