问:
Moq.MockException: The following setups on mock were not matched
In below code i am using Moq to write a sample test. I have created a Mock Object and I am using SetupProperty to setup fake value to be returned for the property. But i get above error at line _sharedService.VerifyAll().

I know i am missing something trivial, but not exactly sure what. Could anyone please help?

```<code>[TestFixture]
public class ObjectFactoryTests : TestFixtureBase
{
    private Mock<ISharedService> _sharedService;

    [SetUp]
    public void SetUp()
    {
        _sharedService = new Mock<ISharedService>(MockBehavior.Strict);
    }

    protected override void VerifyAll()
    {
        _sharedService.VerifyAll();
    }

    private IObjectFactory GetObjectFactory()
    {
        return new ObjectFactory(sharedService.Object);
    }

    [Test]
    public void ObjectFactory_GenerateObject_Request_Success()
    {
        MyObject1 request = something;
        var requestData = new Dictionary<string, object>();
        requestData.TryAdd(Cache.Client, Constants.CLIENT);
        _sharedService.SetupProperty(m => m.RequestData, requestData);
        var factory = GetObjectFactory();
        var actual = factory.GenerateObject(request);
        Assert.That(actual.Client, Is.EqualTo(requestData[Cache.Client].ToString()), Constants.CLIENT);

        VerifyAll();
    }
}

public class ObjectFactory : IObjectFactory
{
    ISharedService SharedService = something;

    public MyObject GenerateObject(MyObject1 request)
    {
        MyObject obj = new MyObject(request);
        obj.Client = SharedService.RequestData[Cache.Client].ToString();
        return obj;
    }
}
</code>```

答:
If I understood correctly, you try to setup property expectations.

Try following instead of _sharedService.SetupProperty(m => m.RequestData, requestData);:

_sharedService.Setup(foo => foo.RequestData).Returns(requestData);
```

You can read more information in Moq documentation

Body:
In below code i am using Moq to write a sample test. I have created a Mock Object and I am using SetupProperty to setup fake value to be returned for the property. But i get above error at line _sharedService.VerifyAll().

I know i am missing something trivial, but not exactly sure what. Could anyone please help?

[TestFixture]
public class ObjectFactoryTests : TestFixtureBase
{
    private Mock<ISharedService> _sharedService;

    [SetUp]
    public void SetUp()
    {
        _sharedService = new Mock<ISharedService>(MockBehavior.Strict);
    }

    protected override void VerifyAll()
    {
        _sharedService.VerifyAll();
    }

    private IObjectFactory GetObjectFactory()
    {
        return new ObjectFactory(sharedService.Object);
    }

    [Test]
    public void ObjectFactory_GenerateObject_Request_Success()
    {
        MyObject1 request = something;
        var requestData = new Dictionary<string, object>();
        requestData.TryAdd(Cache.Client, Constants.CLIENT);
        _sharedService.SetupProperty(m => m.RequestData, requestData);
        var factory = GetObjectFactory();
        var actual = factory.GenerateObject(request);
        Assert.That(actual.Client, Is.EqualTo(requestData[Cache.Client].ToString()), Constants.CLIENT);

        VerifyAll();
    }
}

public class ObjectFactory : IObjectFactory
{
    ISharedService SharedService = something;

    public MyObject GenerateObject(MyObject1 request)
    {
        MyObject obj = new MyObject(request);
        obj.Client = SharedService.RequestData[Cache.Client].ToString();
        return obj;
    }
}

Body:
If I understood correctly, you try to setup property expectations.

Try following instead of _sharedService.SetupProperty(m => m.RequestData, requestData);:

_sharedService.Setup(foo => foo.RequestData).Returns(requestData);

You can read more information in Moq documentation


来源: stackexchange

问:
ClassCastException: Cannot be cast to com.sun.xml.internal.bind.v2.runtime.reflect.Accessor
I have a SOAP webservice that I am trying to call inside of an application. I am using the cxf-codegen-plugin (3.1.10) to generate sources from the WSDL.

Using the generated client, if I call the webservice within the application, it works great. However, I am also using another JAXB instance against the same package within the application which is causing an issue.

For example, the following works great:

```<code>OutboundServicePortType service = new OutboundService().getOutboundServicePort();
service.sendMessage(message);
</code>```

However, initializing a new JAXB instance right before causes the getOutboundServicePort() call to fail:

```<code>JAXBContext.newInstance(SendMessageRequest.class);

OutboundServicePortType service = new OutboundService().getOutboundServicePort();
service.sendMessage(message);
</code>```

With the following stacktrace:

```<code>Caused by: java.lang.ClassCastException: outbound.model.standard.StandardOutboundMessage$JaxbAccessorF_messageUUId cannot be cast to com.sun.xml.internal.bind.v2.runtime.reflect.Accessor
    at com.sun.xml.internal.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.instanciate(OptimizedAccessorFactory.java:190)
    at com.sun.xml.internal.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.get(OptimizedAccessorFactory.java:179)
    at com.sun.xml.internal.bind.v2.runtime.reflect.Accessor$FieldReflection.optimize(Accessor.java:271)
    at com.sun.xml.internal.bind.v2.runtime.property.SingleElementLeafProperty.<init>(SingleElementLeafProperty.java:77)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:113)
    at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:166)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:488)
    at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:153)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:488)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:305)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:124)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1123)
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
    at com.sun.xml.internal.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:152)
    at com.sun.xml.internal.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:96)
    at com.sun.xml.internal.ws.developer.JAXBContextFactory$1.createJAXBContext(JAXBContextFactory.java:98)
    at com.sun.xml.internal.ws.db.glassfish.JAXBRIContextFactory.newContext(JAXBRIContextFactory.java:79)
    ... 25 more
</code>```

Things I have tried so far:

JAXB classes from Webservice marshalling error

I have no endorsed jars in my JDK folder, so this answer does not apply

The jaxb-impl jar (2.2.11) is coming from camel-jaxb in my app so it seems very contained and not like this answer suggests.

This answer seems to describe the problem well, but the solution they took seems unclear to me.

Problems creating JAXBContext to marshal object as XML

This question seems to be identical to mine, but the solution they ended up going with can not work for my situation (see below)

Netbeans with JAXB Random ClassCastException ..cannot be cast to com.sun.xml.bind.v2.runtime.reflect.Accessor

I tried the accepted solution System.setProperty( "com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); which does work. However, setting this property is not an option for me unfortunately in my environment. Plus, it seems like it's a bit of a hack that does not address the real issue (unless I'm misunderstanding it).

I'm about to hang myself with the little rope I have left. What am I missing here?

答:
I ran into this error when trying to run my JUnit tests through Maven even though they passed locally in Eclipse. My solution was to in a @BeforeClass put:

```<code>System.setProperty("javax.xml.bind.JAXBContext", "com.sun.xml.internal.bind.v2.ContextFactory");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a SOAP webservice that I am trying to call inside of an application. I am using the cxf-codegen-plugin (3.1.10) to generate sources from the WSDL.

Using the generated client, if I call the webservice within the application, it works great. However, I am also using another JAXB instance against the same package within the application which is causing an issue.

For example, the following works great:

OutboundServicePortType service = new OutboundService().getOutboundServicePort();
service.sendMessage(message);

However, initializing a new JAXB instance right before causes the getOutboundServicePort() call to fail:

JAXBContext.newInstance(SendMessageRequest.class);

OutboundServicePortType service = new OutboundService().getOutboundServicePort();
service.sendMessage(message);

With the following stacktrace:

Caused by: java.lang.ClassCastException: outbound.model.standard.StandardOutboundMessage$JaxbAccessorF_messageUUId cannot be cast to com.sun.xml.internal.bind.v2.runtime.reflect.Accessor
    at com.sun.xml.internal.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.instanciate(OptimizedAccessorFactory.java:190)
    at com.sun.xml.internal.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.get(OptimizedAccessorFactory.java:179)
    at com.sun.xml.internal.bind.v2.runtime.reflect.Accessor$FieldReflection.optimize(Accessor.java:271)
    at com.sun.xml.internal.bind.v2.runtime.property.SingleElementLeafProperty.<init>(SingleElementLeafProperty.java:77)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:113)
    at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:166)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:488)
    at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:153)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:488)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:305)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:124)
    at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1123)
    at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
    at com.sun.xml.internal.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:152)
    at com.sun.xml.internal.bind.api.JAXBRIContext.newInstance(JAXBRIContext.java:96)
    at com.sun.xml.internal.ws.developer.JAXBContextFactory$1.createJAXBContext(JAXBContextFactory.java:98)
    at com.sun.xml.internal.ws.db.glassfish.JAXBRIContextFactory.newContext(JAXBRIContextFactory.java:79)
    ... 25 more

Things I have tried so far:

JAXB classes from Webservice marshalling error

I have no endorsed jars in my JDK folder, so this answer does not apply

The jaxb-impl jar (2.2.11) is coming from camel-jaxb in my app so it seems very contained and not like this answer suggests.

This answer seems to describe the problem well, but the solution they took seems unclear to me.

Problems creating JAXBContext to marshal object as XML

This question seems to be identical to mine, but the solution they ended up going with can not work for my situation (see below)

Netbeans with JAXB Random ClassCastException ..cannot be cast to com.sun.xml.bind.v2.runtime.reflect.Accessor

I tried the accepted solution System.setProperty( "com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); which does work. However, setting this property is not an option for me unfortunately in my environment. Plus, it seems like it's a bit of a hack that does not address the real issue (unless I'm misunderstanding it).

I'm about to hang myself with the little rope I have left. What am I missing here?

Body:
I ran into this error when trying to run my JUnit tests through Maven even though they passed locally in Eclipse. My solution was to in a @BeforeClass put:

System.setProperty("javax.xml.bind.JAXBContext", "com.sun.xml.internal.bind.v2.ContextFactory");

ContentLicense: CC BY-SA 4.0


问:
How to download files from server and rename it synchronously in Node.js?
I want to every client can download files from the server's folder, and I don't want that all those files be saved in the /download folder.

I thought first download the file and then rename it, but I need to run this code synchronously.

```<code>router.get('/', function(req, res){

        const file = `${__dirname}/upload-folder/apple.jpg`;
        const destination = `C:/Users/steve/Downloads/apple.jpg`;

        res.download(file);

         fs.renameSync(destination,"C:/Users/steve/Desktop/downloadedimg.jpg");
    }
);
</code>```

答:
It looks like you're conflating the client side vs. the server side.  The code you provided is for node.js on the server side.  You're not able to specify where on the client's computer a file is downloaded.  You can provide a different name for the file that's being downloaded:

```<code>res.download(`${__dirname}/upload-folder/apple.jpg`, 'orange.jpg');
</code>```

Reference: https://expressjs.com/en/api.html#res.download

Body:
I want to every client can download files from the server's folder, and I don't want that all those files be saved in the /download folder.

I thought first download the file and then rename it, but I need to run this code synchronously.

router.get('/', function(req, res){

        const file = `${__dirname}/upload-folder/apple.jpg`;
        const destination = `C:/Users/steve/Downloads/apple.jpg`;

        res.download(file);

         fs.renameSync(destination,"C:/Users/steve/Desktop/downloadedimg.jpg");
    }
);

Body:
It looks like you're conflating the client side vs. the server side.  The code you provided is for node.js on the server side.  You're not able to specify where on the client's computer a file is downloaded.  You can provide a different name for the file that's being downloaded:

res.download(`${__dirname}/upload-folder/apple.jpg`, 'orange.jpg');

Reference: https://expressjs.com/en/api.html#res.download


问:
Does variable declaration hoist to the top of if scope block?
When hoisting is occurring to the variable which declaring with keyword var inside an if block scope, does the ( var x;) hoisting to the top of current if block? or to the top of the global scope in this case?
Suppose we wrote the following piece of code directly in the global scope</p>

```<code>if (true) {
   some code;
   var x = 1;
}
</code>```

答:
The short answer is that yes, the declaration is hoisted but not to the top of the block. It is hoisted to the global level. But where it is assigned does not change.

This is tricky to test because an undeclared variable and a declared variable will both produce a typeof somevar of undefined.

var myVar;

console.log('typeof myVar');
console.log(typeof myVar);

console.log('typeof notDeclared');
console.log(typeof notDeclared);```
</div>
</div>
</p>

<p>However, if you try to use an defined variable it will throw an error, so we can use that to find out what has been declared and what has not.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myVar;

try {
  myVar;
  console.log('myVar was declared');
} catch(error) {
  console.log(error);
}

try {
  notDeclared;
  console.log('notDeclared was declared');
} catch(error) {
  // Error is unfortunately captured by the sandbox,
  // so we just get an empty object. :-(
  console.log(error);
}</code>```

Putting it all together, we can test your code to see what happens.

// Does myVar exist in global scope?
try {
  myVar;
  console.log('myVar exists in global scope.');
} catch (error) {
  console.log('myVar does NOT exist in global scope.');
}

if (true) {

  console.log('myVar value before assignment.', myVar);

  var myVar = 1;

  console.log('myVar value after assignment.', myVar);

}```

Body:
When hoisting is occurring to the variable which declaring with keyword var inside an if block scope, does the ( var x;) hoisting to the top of current if block? or to the top of the global scope in this case?
Suppose we wrote the following piece of code directly in the global scope

if (true) {
   some code;
   var x = 1;
}

Body:
The short answer is that yes, the declaration is hoisted but not to the top of the block. It is hoisted to the global level. But where it is assigned does not change.

This is tricky to test because an undeclared variable and a declared variable will both produce a typeof somevar of undefined.

var myVar;

console.log('typeof myVar');
console.log(typeof myVar);

console.log('typeof notDeclared');
console.log(typeof notDeclared);

However, if you try to use an defined variable it will throw an error, so we can use that to find out what has been declared and what has not.

var myVar;

try {
  myVar;
  console.log('myVar was declared');
} catch(error) {
  console.log(error);
}

try {
  notDeclared;
  console.log('notDeclared was declared');
} catch(error) {
  // Error is unfortunately captured by the sandbox,
  // so we just get an empty object. :-(
  console.log(error);
}

Putting it all together, we can test your code to see what happens.

// Does myVar exist in global scope?
try {
  myVar;
  console.log('myVar exists in global scope.');
} catch (error) {
  console.log('myVar does NOT exist in global scope.');
}

if (true) {

  console.log('myVar value before assignment.', myVar);

  var myVar = 1;

  console.log('myVar value after assignment.', myVar);

}


问:
Parse LiveQuery not receiving events AWS EB + Redis
I am trying to set up parse LiveQuery but am getting stuck. On the client I am able to open the connection, but the LiveQuery won't update the client when I make a change on the server. What am I doing wrong? Is there a better way to set up?

Here is what I have going on in the client:

```<code>Parse.liveQueryServerURL = 'ws://myawsEB-LiveQuery.com'

var Message = Parse.Object.extend('Room');
var query = new Parse.Query(Message);
    query.include("messages");

// Subscribes to incoming messages
query.subscribe().then(subscription =>{

    subscription.on('open', () => {
     console.log('subscription opened'); // THIS WORKS!
    });

    subscription.on('create', function (message) {
        console.log("create: ", message); //THIS DOES NOT WORK
    });

    subscription.on('update', function (message) {
        console.log("update: ", message); //THIS DOES NOT WORK
    });
})
.catch(error => {
    console.log(error)
});
</code>```

My AWS Setup:

```<code>AWS EB - Main App
AWS EB - Parse LiveQuery
AWS ElastiCache - Redis
</code>```

Here is my server config:

```<code>//Main APP
var api = new ParseServer({
  appName: "app-name",
  databaseURI: databaseUri,
  cloud: process.env.CLOUD_CODE_MAIN,
  appId: process.env.APP_ID,
  masterKey: process.env.MASTER_KEY
  fileKey: process.env.FILE_KEY,
  serverURL: process.env.SERVER_URL,
  publicServerURL: process.env.SERVER_URL,
  clientKey: process.env.CLIENT_KEY,
  javascriptKey: process.env.JAVASCRIPT_KEY,
  liveQuery: {
    classNames: ["Room", "Messages"], // List of classes to support for query subscriptions
    redisURL: process.env.redisURL
  },
  databaseOptions: { poolSize: 500 },
  maxUploadSize: "5mb",
  verbose: true
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('parse-server-example running on port ' + port + '.');
});
</code>```

Here is my LiveQuery Server Settings:

```<code>//Live Query Server

var express = require('express');
var cors = require('cors')
var ParseServer = require('parse-server').ParseServer;

var app = express();
app.use(cors());

// We include the lines below so that we can hit `/` and it passes the Elastic Beanstalk Health Check
app.get('/', function(req, res) {
  res.status(200).send('Make sure to star the parse-server repo on GitHub!');
});

var port = process.env.PORT || 1338;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('parse-server-example running on port ' + port + '.');
});

ParseServer.createLiveQueryServer(httpServer, {
  appId: process.env.APP_ID, // same as main-index.js file below
  masterKey: process.env.MASTER_KEY, // same as main-index.js
  serverURL: process.env.SERVER_URL, // socket.myApp.com
  javascriptKey: process.env.JAVASCRIPT_KEY,
  redisURL: process.env.redisURL,
  websocketTimeout: 10 * 1000,
  cacheTimeout: 60 * 600 * 1000,
  verbose: true
});
</code>```

答:
Check your Nginx Configuration.

Here is a great guide https://github.com/SoBump/ParseLiveQueryHelp/blob/master/guide.md
that was made specifically for AWS.

Hope this helps

Body:
I am trying to set up parse LiveQuery but am getting stuck. On the client I am able to open the connection, but the LiveQuery won't update the client when I make a change on the server. What am I doing wrong? Is there a better way to set up?

Here is what I have going on in the client:

Parse.liveQueryServerURL = 'ws://myawsEB-LiveQuery.com'

var Message = Parse.Object.extend('Room');
var query = new Parse.Query(Message);
    query.include("messages");

// Subscribes to incoming messages
query.subscribe().then(subscription =>{

    subscription.on('open', () => {
     console.log('subscription opened'); // THIS WORKS!
    });

    subscription.on('create', function (message) {
        console.log("create: ", message); //THIS DOES NOT WORK
    });

    subscription.on('update', function (message) {
        console.log("update: ", message); //THIS DOES NOT WORK
    });
})
.catch(error => {
    console.log(error)
});

My AWS Setup:

AWS EB - Main App
AWS EB - Parse LiveQuery
AWS ElastiCache - Redis

Here is my server config:

//Main APP
var api = new ParseServer({
  appName: "app-name",
  databaseURI: databaseUri,
  cloud: process.env.CLOUD_CODE_MAIN,
  appId: process.env.APP_ID,
  masterKey: process.env.MASTER_KEY
  fileKey: process.env.FILE_KEY,
  serverURL: process.env.SERVER_URL,
  publicServerURL: process.env.SERVER_URL,
  clientKey: process.env.CLIENT_KEY,
  javascriptKey: process.env.JAVASCRIPT_KEY,
  liveQuery: {
    classNames: ["Room", "Messages"], // List of classes to support for query subscriptions
    redisURL: process.env.redisURL
  },
  databaseOptions: { poolSize: 500 },
  maxUploadSize: "5mb",
  verbose: true
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('parse-server-example running on port ' + port + '.');
});

Here is my LiveQuery Server Settings:

//Live Query Server

var express = require('express');
var cors = require('cors')
var ParseServer = require('parse-server').ParseServer;

var app = express();
app.use(cors());

// We include the lines below so that we can hit `/` and it passes the Elastic Beanstalk Health Check
app.get('/', function(req, res) {
  res.status(200).send('Make sure to star the parse-server repo on GitHub!');
});

var port = process.env.PORT || 1338;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('parse-server-example running on port ' + port + '.');
});

ParseServer.createLiveQueryServer(httpServer, {
  appId: process.env.APP_ID, // same as main-index.js file below
  masterKey: process.env.MASTER_KEY, // same as main-index.js
  serverURL: process.env.SERVER_URL, // socket.myApp.com
  javascriptKey: process.env.JAVASCRIPT_KEY,
  redisURL: process.env.redisURL,
  websocketTimeout: 10 * 1000,
  cacheTimeout: 60 * 600 * 1000,
  verbose: true
});


答:
Absolutely.

// hoisted
if( true){
   x = 1;
   console.log( x, typeof x );
   var x;
}

// doesn't do what you thought it would, the assignment doesn't move, just the declaration.
if( true){
   console.log( y, typeof y );
   var y = 1;
}```

Title: Does variable declaration hoist to the top of if scope block?


问:
wrapAll() doesn't work for the first inserted data
I am trying to wrap
 and  together into a div. After inserting the first data, wrapAll() didn't work. But when I have entered second data, wrapAll() was worked for the first data not for the second data. I want to add wrap along with
 and  tag.

var messages = document.getElementById("messages");
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");

// with enter press button
textbox.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
       if(e.shiftKey) {
        }else {
            chatbox(e);
        }
    }
});

function chatbox(e) {
   var newMessage = document.createElement("p");
   newMessage.setAttribute('class', 'list');
   $( ".list, .c-hour" ).wrapAll( "

" );

   var hour = document.createElement("span");
   hour.setAttribute('class', 'c-hour');
   var d = new Date();
   var n = d.getHours();
   var m = d.getMinutes();
   hour.innerHTML = n + ":" + m;
   messages.appendChild(hour);

   newMessage.innerHTML = textbox.value;
   messages.appendChild(newMessage);
   textbox.value = "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
   <div class="chat-area">
      <ul id ="messages"></ul>
   </div>
   <textarea id="textbox" type="text" placeholder="shout"></textarea>
</div></code>```

答:
You have to call $( ".list, .c-hour" ).wrapAll( "

" ); after you add the created elements to the document.

So it should be put after messages.appendChild(newMessage); like

```<code>function chatbox(e) {
  var newMessage = document.createElement("p");
  newMessage.setAttribute('class', 'list');

  var hour = document.createElement("span");
  hour.setAttribute('class', 'c-hour');
  var d = new Date();
  var n = d.getHours();
  var m = d.getMinutes();
  hour.innerHTML = n + ":" + m;
  messages.appendChild(hour);

  newMessage.innerHTML = textbox.value;
  messages.appendChild(newMessage);

  $(newMessage).wrapAll( "<div class='new'></div>" );
  $(hour).wrapAll( "<div class='new'></div>" );
  textbox.value = "";
}
</code>```

Body:
I am trying to wrap
 and  together into a div. After inserting the first data, wrapAll() didn't work. But when I have entered second data, wrapAll() was worked for the first data not for the second data. I want to add wrap along with
 and  tag.

var messages = document.getElementById("messages");
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");

// with enter press button
textbox.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
       if(e.shiftKey) {
        }else {
            chatbox(e);
        }
    }
});

function chatbox(e) {
   var newMessage = document.createElement("p");
   newMessage.setAttribute('class', 'list');
   $( ".list, .c-hour" ).wrapAll( "

" );

   var hour = document.createElement("span");
   hour.setAttribute('class', 'c-hour');
   var d = new Date();
   var n = d.getHours();
   var m = d.getMinutes();
   hour.innerHTML = n + ":" + m;
   messages.appendChild(hour);

   newMessage.innerHTML = textbox.value;
   messages.appendChild(newMessage);
   textbox.value = "";
}

   <textarea id="textbox" type="text" placeholder="shout"></textarea>

Body:
You have to call $( ".list, .c-hour" ).wrapAll( "<div class='new'></div>" ); after you add the created elements to the document.

So it should be put after messages.appendChild(newMessage); like

function chatbox(e) {
  var newMessage = document.createElement("p");
  newMessage.setAttribute('class', 'list');

  var hour = document.createElement("span");
  hour.setAttribute('class', 'c-hour');
  var d = new Date();
  var n = d.getHours();
  var m = d.getMinutes();
  hour.innerHTML = n + ":" + m;
  messages.appendChild(hour);

  newMessage.innerHTML = textbox.value;
  messages.appendChild(newMessage);

  $(newMessage).wrapAll( "<div class='new'></div>" );
  $(hour).wrapAll( "<div class='new'></div>" );
  textbox.value = "";
}


问:
Multiple blinking cursors in the same Form
I have multiple blinking cursors in all TextFields, in the same Form. All of them are blinking, regardless the TextField in which I’m typing.

It happens in Simulator, Android, iOS and Javascript.

I’m not able to produce a test case: all my test cases are fine, this bugged behavior is only in my app, after changing the Form and the editable state.

Can you give me any hint to understand / investigate / solve this issue?

Thank you

答:
Updated answer

My old answer contained only a temporary workaround (field.setCursorBlinkTimeOff(1000 * 3600); for all TextFields) that has several issues that create a bad used experience.

Now I found a proper solution, that is simply to don't reuse the same TextFields (removing that from a "Container A" that has a Leader Component and putting them in another "Container B" that hasn't a Leader Component). This issue is related to the fact that the "Container A" has a Leader Component.

So, in this case, my solution is to remove the TextFields from "Container A" and add new TextFields to "Container" B using a method like:

```<code>private Component replaceWithNewTextField(Component cmp) {
        if (cmp instanceof TextField) {
            // it creates the new TextField
            TextField field = new TextField();
            field.setUIID(cmp.getUIID());
            field.setText(((TextField) cmp).getText());
            field.setName(((TextField) cmp).getName());
            field.setEditable(((TextField) cmp).isEditable());
            ((TextArea) field).setSingleLineTextArea(((TextArea) cmp).isSingleLineTextArea());
            ((TextArea) field).setRows(((TextArea) cmp).getRows());
            ((TextArea) field).setConstraint(((TextArea) cmp).getConstraint());

            etc.
</code>```

Body:
Updated answer

My old answer contained only a temporary workaround (field.setCursorBlinkTimeOff(1000 * 3600); for all TextFields) that has several issues that create a bad used experience.

Now I found a proper solution, that is simply to don't reuse the same TextFields (removing that from a "Container A" that has a Leader Component and putting them in another "Container B" that hasn't a Leader Component). This issue is related to the fact that the "Container A" has a Leader Component.

So, in this case, my solution is to remove the TextFields from "Container A" and add new TextFields to "Container" B using a method like:

private Component replaceWithNewTextField(Component cmp) {
        if (cmp instanceof TextField) {
            // it creates the new TextField
            TextField field = new TextField();
            field.setUIID(cmp.getUIID());
            field.setText(((TextField) cmp).getText());
            field.setName(((TextField) cmp).getName());
            field.setEditable(((TextField) cmp).isEditable());
            ((TextArea) field).setSingleLineTextArea(((TextArea) cmp).isSingleLineTextArea());
            ((TextArea) field).setRows(((TextArea) cmp).getRows());
            ((TextArea) field).setConstraint(((TextArea) cmp).getConstraint());

            etc.


问:
Getting the Listview default clicked color, depending on the Device
In my android application, I use a listview and some linear layout on wich the user can click.

Of course, I had to set the background of my LinearLayout to a xml file where the stated pressed, selected are defined:

```<code> myView.setBackgroundDrawable(
 getDrawable(android.R.drawable.list_selector_background));
</code>```

So no problem I set the drawable to transparent when normal use and orange when clicked.

My only problem is that on the galaxy S and some other customized phone (Sense UI) the color of the listview clicked is blue or green!

So I need to pick this color to set it to the background of my linearlayout.
I don't want to mix orange and blue, or orange and green for my user!

Where can I get this color???
That woule be really helpfull!

答:
Just found the answer:</p>

```<code>android:background="@android:drawable/list_selector_background"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In my android application, I use a listview and some linear layout on wich the user can click.

Of course, I had to set the background of my LinearLayout to a xml file where the stated pressed, selected are defined:

 myView.setBackgroundDrawable(
 getDrawable(android.R.drawable.list_selector_background));

So no problem I set the drawable to transparent when normal use and orange when clicked.

My only problem is that on the galaxy S and some other customized phone (Sense UI) the color of the listview clicked is blue or green!

So I need to pick this color to set it to the background of my linearlayout.
I don't want to mix orange and blue, or orange and green for my user!

Where can I get this color???
That woule be really helpfull!

Body:
Just found the answer:

android:background="@android:drawable/list_selector_background"


问:
Question about updating my angular project
I need to update my angular project but I'm having some issues.
It shows me the following  message:

```<code>Your global Angular CLI version (8.0.1) is greater than your local
version (1.7.4). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".

Error: Cannot update safely because packages have conflicting dependencies. Package @angular/core would need to match both versions "7.2.15" and "8.0.0, which are not compatible.
Cannot update safely because packages have conflicting dependencies. Package @angular/core would need to match both versions "7.2.15" and "8.0.0, which are not compatible.
</code>```

If anyone could help me ?

答:
When it comes to upgrading your Angular project in general, simply run this:

```<code>ng update
</code>```

Otherwise, if you want to perform an upgrade on just the CLI, you can the specific package as an option

```<code>ng update @angular/cli
</code>```

Or directly install via npm

```<code>npm install --save-dev @angular/cli
</code>```

If you need to do a hard reset, you can first install the CLI globally, followed by updating the one in your project itself.

```<code>npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest
</code>```

Then, you cd to our project directory,

```<code>rm -rf node_modules dist
npm install --save-dev @angular/cli@latest
npm i
ng update @angular/cli
ng update @angular/core
npm install --save-dev @angular-devkit/build-angular
</code>```

Body:
I need to update my angular project but I'm having some issues.
It shows me the following  message:

Your global Angular CLI version (8.0.1) is greater than your local
version (1.7.4). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".

Error: Cannot update safely because packages have conflicting dependencies. Package @angular/core would need to match both versions "7.2.15" and "8.0.0, which are not compatible.
Cannot update safely because packages have conflicting dependencies. Package @angular/core would need to match both versions "7.2.15" and "8.0.0, which are not compatible.

If anyone could help me ?

Body:
When it comes to upgrading your Angular project in general, simply run this:

ng update

Otherwise, if you want to perform an upgrade on just the CLI, you can the specific package as an option

ng update @angular/cli

Or directly install via npm

npm install --save-dev @angular/cli

If you need to do a hard reset, you can first install the CLI globally, followed by updating the one in your project itself.

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest

Then, you cd to our project directory,

rm -rf node_modules dist
npm install --save-dev @angular/cli@latest
npm i
ng update @angular/cli
ng update @angular/core
npm install --save-dev @angular-devkit/build-angular


问:
Is there anyway to remove the shadow, or force vuetify menu to fully align with the left side of the screen?
I am trying to use vuetify menu in a sidebar navigation. I would like for the menu to align perfectly to the left side of the screen. Instead what I am getting is the menu is insisting to be positioned 12px away from the edge of my screen and wrecking my alignment.

Is there a way to disable the shadow or to force the alignment? The left: 12px is specified directly on the element's style so CSS has no effect.

I have tried this but no luck:

```<code><v-menu offset-y nudge-left="-12" flat>
</code>```

https://codepen.io/RuttyJ/pen/BevNmy?editors=1010

Any ideas?

Update:
Made some progress:
https://codepen.io/anon/pen/WBLMob

This achieves the effect but requires the override of the menu nudge on a global level to 0px !important.

答:
To remove the shadow, you could simply override the styles for .v-menu__content. In some CSS:

```<code>.v-menu__content {
    box-shadow: none;
}
</code>```

Aligning to the left can be done setting the styles via javascript.

Having said that, I think it is easier to make a sidebar menu from scratch than trying to transform a component which is not meant to be a sidebar into one. Transitions will be off, and so much on.

Body:
I am trying to use vuetify menu in a sidebar navigation. I would like for the menu to align perfectly to the left side of the screen. Instead what I am getting is the menu is insisting to be positioned 12px away from the edge of my screen and wrecking my alignment.

Is there a way to disable the shadow or to force the alignment? The left: 12px is specified directly on the element's style so CSS has no effect.

I have tried this but no luck:

<v-menu offset-y nudge-left="-12" flat>

https://codepen.io/RuttyJ/pen/BevNmy?editors=1010

Any ideas?

Update:
Made some progress:
https://codepen.io/anon/pen/WBLMob

This achieves the effect but requires the override of the menu nudge on a global level to 0px !important.

Body:
To remove the shadow, you could simply override the styles for .v-menu__content. In some CSS:

.v-menu__content {
    box-shadow: none;
}

Aligning to the left can be done setting the styles via javascript.

Having said that, I think it is easier to make a sidebar menu from scratch than trying to transform a component which is not meant to be a sidebar into one. Transitions will be off, and so much on.


问:
How to fix this PHP error that prints the code instead of the result?
It should print the error message, but instead it prints:

"data['clan_id'] != 0){echo "You already have a clan.";} ?>"

here is an image of the error: https://i.imgur.com/BtV7i9s.png

my code:

```<code><html>
<style>
.createclanbutton {
background-color: green;
color: black;
padding: 3px;
border-radius: 9px;
}
</style>

<body>

<?php
if ($user->data['clan_id'] != 0)
{
echo "You already have a clan.";
}
?>
<br><br>
<form action="">

<h3>Create your own clan.<br><br>

Clan Name: <input type="text" name="ClanName" value="Clan Name"><br><br>

Description:<br> <textarea rows="6" cols="50">Brief description of your clan!
</textarea><br>
<button class="createclanbutton">Create your own clan!</button>
</form>

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

I am using phpbb and created a column called "clan_id" in my database which I set at "2" to try and echo the error message.

答: Looks like you have saved the file as .html or anything? :) You need to save this file as .php!</p>

Body:
It should print the error message, but instead it prints:

"data['clan_id'] != 0){echo "You already have a clan.";} ?>"

here is an image of the error: https://i.imgur.com/BtV7i9s.png

my code:

<?php
if ($user->data['clan_id'] != 0)
{
echo "You already have a clan.";
}
?>

<form action="">

Create your own clan.

Clan Name: <input type="text" name="ClanName" value="Clan Name">

Description:
 <textarea rows="6" cols="50">Brief description of your clan!
</textarea>

<button class="createclanbutton">Create your own clan!</button>
</form>

I am using phpbb and created a column called "clan_id" in my database which I set at "2" to try and echo the error message.


问:
Convert WordPress custom shortcodes to work in a different theme
I have exported pages from a WordPress website built with design themes template and imported them to a new one with a different theme (buddyboss).

The pages I have imported are not displaying as they have been built with custom shortcodes (design themes) not recognised by the new theme (buddyboss).

Is there a way to convert the shortcodes to work with the new (buddyboss) theme?

答: Search the old theme for calls to add_shortcode(link). The second parameter to add_shortcode should be a PHP function located somewhere in the theme. You will need to bring the function that is executed by the shortcode, along with any additional code that is relied on, into the new theme (ie: in functions.php in the theme).


问:
How can I achieve a dashed or dotted border in WPF?
I have a ListViewItem that I am applying a Style to and I would like to put a dotted grey line as the bottom Border.

How can I do this in WPF? I can only see solid color brushes.

答:
Xaml

<Grid>
<Grid.RowDefinitions><RowDefinition Height="auto"/></Grid.RowDefinitions>
<Grid.ColumnDefinitions><ColumnDefinition Width="auto"/></Grid.ColumnDefinitions>
<Rectangle RadiusX="9" RadiusY="9" Fill="White" Stroke="Black" StrokeDashArray="1,2"/>
<TextBlock Padding = "4,2" Text="Whatever"/>
</Grid>
```


问:
Anonymous function in dynamically generated list producing SyntaxError
I want to place an onclick event inside a dynamically generated list. I can't use it as it is, like updateRoomID(arg), because it would fire immediately. So I placed it inside an anonymous function, as advised by various sources online: function (){updateRoomID(arg)}. But this results in: "Uncaught SyntaxError: Unexpected token (". Developer tools says the problem is at function().

The section of code it's in:

```<code>socket.onmessage = function(event) {
    var msg = JSON.parse(event.data);
    for (let i = 0; i < msg.length; i++) {
        if (msg[i].beingserved == false) {
            listRooms.innerHTML += '<li id=' + msg[i].roomid +

                                   // Problem on following line.
                                   ' onclick=' + function () { updateRoomID(msg[i].roomid) } +
                                    '>' +
                                    '<a href="#">' +
                                    msg[i].roomid +
                                    '</a></li>';
        } else {
            document.getElementById(msg[i].roomid).remove();
        };
    };
};
</code>```

I've tried it with the function as a string inside quotations marks:
'. I've tried placing the onclick handler in href link instead, and also replaced it with addEventListener. But I got the same error with these attempts.

If I try function(){updateRoomID(arg)}() with the parentheses behind, it fires immediately as expected.

I've been looking through it all day and can't figure out where the syntax error is. I'm quite unfamiliar with JavaScript. What am I doing wrong?

答:
You can't put a function in the onclick attribute. It contains JavaScript source code that should be executed.

What you should do in this case is put the function call as a string, but substitute in the value of the argument.

Using a template literal makes this easier.

```<code>listRooms.innerHTML += `
    <li id="${msg[i].roomid}" onclick="updateRoomId(${msg[i].roomid})">
      <a href="#">${msg[i].roomid}</a>
    </li>`;
</code>```

Body:
I want to place an onclick event inside a dynamically generated list. I can't use it as it is, like updateRoomID(arg), because it would fire immediately. So I placed it inside an anonymous function, as advised by various sources online: function (){updateRoomID(arg)}. But this results in: "Uncaught SyntaxError: Unexpected token (". Developer tools says the problem is at function().

The section of code it's in:

socket.onmessage = function(event) {
    var msg = JSON.parse(event.data);
    for (let i = 0; i < msg.length; i++) {
        if (msg[i].beingserved == false) {
            listRooms.innerHTML += '
' +
                                    '' +
                                    msg[i].roomid +
                                    '
';
        } else {
            document.getElementById(msg[i].roomid).remove();
        };
    };
};

I've tried it with the function as a string inside quotations marks:
'. I've tried placing the onclick handler in href link instead, and also replaced it with addEventListener. But I got the same error with these attempts.

If I try function(){updateRoomID(arg)}() with the parentheses behind, it fires immediately as expected.

I've been looking through it all day and can't figure out where the syntax error is. I'm quite unfamiliar with JavaScript. What am I doing wrong?

Body:
You can't put a function in the onclick attribute. It contains JavaScript source code that should be executed.

What you should do in this case is put the function call as a string, but substitute in the value of the argument.

Using a template literal makes this easier.

listRooms.innerHTML += `
    <li id="${msg[i].roomid}" onclick="updateRoomId(${msg[i].roomid})">
      <a href="#">${msg[i].roomid}</a>
    </li>`;


问:
What's a good pattern to create DbContext when dynamic data determines connection string
I get a data set from another web api. It may contain multiple records from different clients. I have to transform these data and write them to the client's database. Each client has their own database. The schema of the client databases are exactly the same.

I created a DbContext factory that creates a new instance of DbContext based on the client the app is currently working on.

```<code>public ClientDbContext CreateClientDbContext(string clientNumber)
{
      var optionsBuilder = new DbContextOptionsBuilder<ClientDbContext>();
      var clientConnection = string.Format(_configuration.GetConnectionString("clientConnection"), clientNumber);
      optionsBuilder.UseSqlServer(clientConnection);

      clientDbContext clientDbContext = new ClientDbContext(optionsBuilder.Options);

      return clientDbContext;
}
</code>```

I use the factory this way:

```<code>foreach (var case in caseList)
{
    var clientDbContext = await _clientDbContextFactory.CreateClientDbContext(case.ClientNumber);
    _clientRepository = new ClientRepository(clientDbContext);
    var updatedCase = /// transform case here
    await _clientRepository.CreateCases(updatedCase);
}
</code>```

Is there an optimal why of doing this?
It's possible that several rows of data will have the same client, so I would like to reuse the same ClientDbContext.

答:
You can move your logic for creating ClientContext into another responsible class (according to SOLID principles), something like DbContextFactory and store there created DbContext's for each client. Like this:

```<code>public class DbContextFactory
{
    private readonly IConfiguration _configuration;
    private readonly Dictionary<string, ClientDbContext> _clientContexts = new Dictionary<string, ClientDbContext>();

    public DbContextFactory(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public ClientDbContext GetOrCreateClientContext(string clientNumber)
    {
        // if you have context already created - return it
        if (_clientContexts.ContainsKey(clientNumber))
            return _clientContexts[clientNumber];

        var optionsBuilder = new DbContextOptionsBuilder<ClientDbContext>();
        var clientConnection = string.Format(_configuration.GetConnectionString("clientConnection"), clientNumber);
        optionsBuilder.UseSqlServer(clientConnection);

        var clientDbContext = new ClientDbContext(optionsBuilder.Options);
        _clientContexts[clientNumber] = clientDbContext;

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

Then in your worker class you can group your data by ClientNumber, for each client create (or get already created) DbContext and repository, then do data update.

```<code>public class Worker
{
    private readonly DbContextFactory _factory;

    public Worker(DbContextFactory factory)
    {
        _factory = factory;
    }

    public async Task DoWorkAsync()
    {
        // group by ClientNumber
        var groupedCases = caseList.GroupBy(x => x.ClientNumber);

        foreach (var groupedCase in groupedCases)
        {
            // For each client create context and repository
            var clientContext = _factory.GetOrCreateClientContext(groupedCase.Key);
            var clientRepository = new ClientRepository(clientContext);

            foreach (var @case in groupedCases)
            {
                var updatedCase = // transform case here
                await clientRepository.CreateCases(updatedCase);
            }
        }
    }
}
</code>```

You can use dependency injection or just create these clases like that:

```<code>var factory = new DbContextFactory(yourConfiguration);
var worker = new Worker(factory);
await worker.DoWorkAsync();
</code>```

Body:
I get a data set from another web api. It may contain multiple records from different clients. I have to transform these data and write them to the client's database. Each client has their own database. The schema of the client databases are exactly the same.

I created a DbContext factory that creates a new instance of DbContext based on the client the app is currently working on.

public ClientDbContext CreateClientDbContext(string clientNumber)
{
      var optionsBuilder = new DbContextOptionsBuilder<ClientDbContext>();
      var clientConnection = string.Format(_configuration.GetConnectionString("clientConnection"), clientNumber);
      optionsBuilder.UseSqlServer(clientConnection);

      clientDbContext clientDbContext = new ClientDbContext(optionsBuilder.Options);

      return clientDbContext;
}

I use the factory this way:

foreach (var case in caseList)
{
    var clientDbContext = await _clientDbContextFactory.CreateClientDbContext(case.ClientNumber);
    _clientRepository = new ClientRepository(clientDbContext);
    var updatedCase = /// transform case here
    await _clientRepository.CreateCases(updatedCase);
}

Is there an optimal why of doing this?
It's possible that several rows of data will have the same client, so I would like to reuse the same ClientDbContext.

Body:
You can move your logic for creating ClientContext into another responsible class (according to SOLID principles), something like DbContextFactory and store there created DbContext's for each client. Like this:

public class DbContextFactory
{
    private readonly IConfiguration _configuration;
    private readonly Dictionary<string, ClientDbContext> _clientContexts = new Dictionary<string, ClientDbContext>();

    public DbContextFactory(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public ClientDbContext GetOrCreateClientContext(string clientNumber)
    {
        // if you have context already created - return it
        if (_clientContexts.ContainsKey(clientNumber))
            return _clientContexts[clientNumber];

        var optionsBuilder = new DbContextOptionsBuilder<ClientDbContext>();
        var clientConnection = string.Format(_configuration.GetConnectionString("clientConnection"), clientNumber);
        optionsBuilder.UseSqlServer(clientConnection);

        var clientDbContext = new ClientDbContext(optionsBuilder.Options);
        _clientContexts[clientNumber] = clientDbContext;

        return clientDbContext;
    }
}

Then in your worker class you can group your data by ClientNumber, for each client create (or get already created) DbContext and repository, then do data update.

public class Worker
{
    private readonly DbContextFactory _factory;

    public Worker(DbContextFactory factory)
    {
        _factory = factory;
    }

    public async Task DoWorkAsync()
    {
        // group by ClientNumber
        var groupedCases = caseList.GroupBy(x => x.ClientNumber);

        foreach (var groupedCase in groupedCases)
        {
            // For each client create context and repository
            var clientContext = _factory.GetOrCreateClientContext(groupedCase.Key);
            var clientRepository = new ClientRepository(clientContext);

            foreach (var @case in groupedCases)
            {
                var updatedCase = // transform case here
                await clientRepository.CreateCases(updatedCase);
            }
        }
    }
}

You can use dependency injection or just create these clases like that:

var factory = new DbContextFactory(yourConfiguration);
var worker = new Worker(factory);
await worker.DoWorkAsync();


问:
Error message 10054 when wescraping with requests module
New programmer here. Tried to webscrape pof site as I was learning python. Tried to webscrape using the requests and beautiful soup. Thanks in advance

Error seems to be from the line res=requests.get('https://www.pof.com/everyoneonline.aspx?page_id=%s' %pageId)

I tried to remove the pagination page and scrape only one page, but it didn't work
Also tried to use time.sleep 3 seconds between each request, but that didn't work either

```<code>#Username and password
username='MyUsername'
password='MyPassword'

#Login to pof site
from selenium import webdriver
import bs4,requests
browser = webdriver.Chrome(executable_path='/Users/Desktop/geckodriver-v0.24.0-win32/chromedriver.exe')
browser.get('https://www.pof.com')
linkElem= browser.find_element_by_link_text('Sign In')
linkElem.click()
usernameElem=browser.find_element_by_id('logincontrol_username')
usernameElem.send_keys(username)
passwordElem=browser.find_element_by_id('logincontrol_password')
passwordElem.send_keys(password)
passwordElem.submit()

#Webscraping online profile links from first 7 pagination pages
for pageId in range(7):
    res=requests.get('https://www.pof.com/everyoneonline.aspx?page_id=%s' %pageId)
    res.raise_for_status()
    soup= bs4.BeautifulSoup(res.text)
    profile = soup.findAll('div', attrs={'class' : 'rc'})
    for div in profile:
        print (div.findAll('a')['href'])
</code>```

Expected result:
Printing a list of all href links of profile, so I can later save them to a csv

Actual result:
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))enter code here

答:
I'm gonna give you some general info when scraping webpages:

First of all, don't use requests with selenium together! In my experience requests is the fastest and easiest solution 90% of the time.

Always try to provide headers to your request. Providing no headers causes the webpage to be suspicious and it might even block all your requests(the error you're getting could be because of this!)

For subsequent requests to the webpage, use a session!, this way your cookies get stored and you can actually access the logged in page for a long period of time.

This one is more objective, but i suggest using the re module if you already know regex. BeautifulSoup is great, but for general purpose uses, re is just easier in my experience.

So now to answer your question;  There are a lot of different webpages out there, but this is how i suggest scraping from all of them:

Extracting Data~

Header data

Open up your usual browser with inspect element support. Go to the webpage you're trying to scrape from and open the inspect element dock.

Go onto the Network section. Here you can see all the requests your browser is making, along with the headers and sources.

Make the request you want to emulate, keep a track of the network tab, go to the request that contains the desired GET or in your case POST method.

Copy the request headers for that particular request. You don't need all of them(for example the cookie parameter will be added by the session so it's not needed for this example; Also headers starting with : like :method: POST are not needed)

Put the copied headers from your browser to a python dict, here's an example from this very webpage:

headers = {
"accept": "application/json, text/javascript, */*; q=0.01",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9,fa-IR;q=0.8,fa;q=0.7,de;q=0.6",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"dnt": "1",
"origin": "https://stackoverflow.com",
"referer": "https://stackoverflow.com/questions/56399462/error-message-10054-when-wescraping-with-requests-module",
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36",
}
```

<h2>Post data</h2>

<ul>
<li>If you want to make a post request, there should be another section on the <code>Headers</code> section of the request, named something line "Payload" or "Form Data". Put it's contents in another python dict, and change it's contents as desired.</li>
</ul>

<h2>Using Data~</h2>

<hr>

<p>Now you're ready to put the extracted data to use with python requests, then using <code>re</code> or <code>BeautifulSoup</code> on the response contents to extract your desired data.<br>
In this example I'm logging in to https://aavtrain.com/index.asp<br>
Try to follow the steps I've written and make sense of what's happening here:   </p>

<pre class="lang-py prettyprint-override"><code>import requests
username = "something"
password = "somethingelse"
headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"accept-encoding": "gzip, deflate, br",
"cache-control": "max-age=0",
"content-type": "application/x-www-form-urlencoded",
"dnt": "1",
"origin": "https://aavtrain.com",
"referer": "https://aavtrain.com/index.asp",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36"
}
data = {
"user_name": username,
"password": password,
"Submit": "Submit",
"login": "true"
}
with requests.Session() as session:
    session.get("https://aavtrain.com/index.asp")
    loggedIn = session.post("https://aavtrain.com/index.asp", headers=headers, data=data)
    #... do stuff after logged in..
</code>```

I hope this helps, ask any lingering questions and i'll get back to you.

Body:
New programmer here. Tried to webscrape pof site as I was learning python. Tried to webscrape using the requests and beautiful soup. Thanks in advance

Error seems to be from the line res=requests.get('https://www.pof.com/everyoneonline.aspx?page_id=%s' %pageId)

I tried to remove the pagination page and scrape only one page, but it didn't work
Also tried to use time.sleep 3 seconds between each request, but that didn't work either

#Username and password
username='MyUsername'
password='MyPassword'

#Login to pof site
from selenium import webdriver
import bs4,requests
browser = webdriver.Chrome(executable_path='/Users/Desktop/geckodriver-v0.24.0-win32/chromedriver.exe')
browser.get('https://www.pof.com')
linkElem= browser.find_element_by_link_text('Sign In')
linkElem.click()
usernameElem=browser.find_element_by_id('logincontrol_username')
usernameElem.send_keys(username)
passwordElem=browser.find_element_by_id('logincontrol_password')
passwordElem.send_keys(password)
passwordElem.submit()

#Webscraping online profile links from first 7 pagination pages
for pageId in range(7):
    res=requests.get('https://www.pof.com/everyoneonline.aspx?page_id=%s' %pageId)
    res.raise_for_status()
    soup= bs4.BeautifulSoup(res.text)
    profile = soup.findAll('div', attrs={'class' : 'rc'})
    for div in profile:
        print (div.findAll('a')['href'])

Expected result:
Printing a list of all href links of profile, so I can later save them to a csv

Actual result:
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))enter code here

Body:
I'm gonna give you some general info when scraping webpages:

First of all, don't use requests with selenium together! In my experience requests is the fastest and easiest solution 90% of the time.

Always try to provide headers to your request. Providing no headers causes the webpage to be suspicious and it might even block all your requests(the error you're getting could be because of this!)

For subsequent requests to the webpage, use a session!, this way your cookies get stored and you can actually access the logged in page for a long period of time.

This one is more objective, but i suggest using the re module if you already know regex. BeautifulSoup is great, but for general purpose uses, re is just easier in my experience.

So now to answer your question;  There are a lot of different webpages out there, but this is how i suggest scraping from all of them:

Extracting Data~

Header data

Open up your usual browser with inspect element support. Go to the webpage you're trying to scrape from and open the inspect element dock.

Go onto the Network section. Here you can see all the requests your browser is making, along with the headers and sources.

Make the request you want to emulate, keep a track of the network tab, go to the request that contains the desired GET or in your case POST method.

Copy the request headers for that particular request. You don't need all of them(for example the cookie parameter will be added by the session so it's not needed for this example; Also headers starting with : like :method: POST are not needed)

Put the copied headers from your browser to a python dict, here's an example from this very webpage:

headers = {
"accept": "application/json, text/javascript, */*; q=0.01",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9,fa-IR;q=0.8,fa;q=0.7,de;q=0.6",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"dnt": "1",
"origin": "https://stackoverflow.com",
"referer": "https://stackoverflow.com/questions/56399462/error-message-10054-when-wescraping-with-requests-module",
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36",
}

Post data

If you want to make a post request, there should be another section on the Headers section of the request, named something line "Payload" or "Form Data". Put it's contents in another python dict, and change it's contents as desired.

Using Data~

Now you're ready to put the extracted data to use with python requests, then using re or BeautifulSoup on the response contents to extract your desired data.

In this example I'm logging in to https://aavtrain.com/index.asp

Try to follow the steps I've written and make sense of what's happening here:

import requests
username = "something"
password = "somethingelse"
headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"accept-encoding": "gzip, deflate, br",
"cache-control": "max-age=0",
"content-type": "application/x-www-form-urlencoded",
"dnt": "1",
"origin": "https://aavtrain.com",
"referer": "https://aavtrain.com/index.asp",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36"
}
data = {
"user_name": username,
"password": password,
"Submit": "Submit",
"login": "true"
}
with requests.Session() as session:
    session.get("https://aavtrain.com/index.asp")
    loggedIn = session.post("https://aavtrain.com/index.asp", headers=headers, data=data)
    #... do stuff after logged in..

I hope this helps, ask any lingering questions and i'll get back to you.


问:
Recognize small objects with OpenCV
I would like to be able to recognize the position (center) and the angle of some small components with openCV with C#. To achieve that, I am grabbing pictures from a webcam and try to process them with the Canny algorithm. Unfortunately, the results are not that good as expected. Sometimes it is ok sometimes it is not.

I have attached an example image from the cam and the corresponding output of OpenCV.

I hope that someone could give me hints or maybe some code snippets, how to achieve my desired results. Is this something that is usually done with AI?

Example images:

Input:

Output 1:

Output 2:

Expected:

Thanks.

Actual code:

```<code>        Mat src;
        src = BitmapConverter.ToMat(lastFrame);
        Mat dst = new Mat();
        Mat dst2 = new Mat();

        Cv2.Canny(src, dst, hScrollBar1.Value, hScrollBar2.Value);

        // Find contours
        OpenCvSharp.Point[][] contours; //vector<vector<Point>> contours;
        HierarchyIndex[] hierarchyIndexes; //vector<Vec4i> hierarchy;

        Cv2.FindContours(dst, out contours, out hierarchyIndexes, RetrievalModes.External, ContourApproximationModes.ApproxTC89L1);

        foreach (OpenCvSharp.Point[] element in contours)
        {
            var biggestContourRect = Cv2.BoundingRect(element);

            Cv2.Rectangle(dst,
                new OpenCvSharp.Point(biggestContourRect.X, biggestContourRect.Y),
                new OpenCvSharp.Point(biggestContourRect.X + biggestContourRect.Width, biggestContourRect.Y + biggestContourRect.Height),
                new Scalar(255, 0, 0), 3);
        }

        using (new Window("dst image", dst)) ;
        using (new Window("src image", src)) ;
</code>```

答:
If you already have a ROI (the box) and you just want to compute the actual orientation of it, you could use the contour inside the right box and compute its moments. A tutorial on how to do this is here (Sorry only C++).

Once you have the moments you can compute the orientation easily. To do this follow the solution here.

If you have trouble figuring out the right box itself, you are actually half way with canny boxes. You could then further try:

Equalize source image:

Posterize next (to 2 levels):

Threshold (255):

Then you can use all the canny boxes you found in the centre and use them as masks to get the right contour in the thresholded image. You can then find the biggest contour here and compute its orientation with image moments. Hope this helps!

Title: Recognize small objects with OpenCV

Body:
I would like to be able to recognize the position (center) and the angle of some small components with openCV with C#. To achieve that, I am grabbing pictures from a webcam and try to process them with the Canny algorithm. Unfortunately, the results are not that good as expected. Sometimes it is ok sometimes it is not.

I have attached an example image from the cam and the corresponding output of OpenCV.

I hope that someone could give me hints or maybe some code snippets, how to achieve my desired results. Is this something that is usually done with AI?

Example images:

Input:

Output 1:

Output 2:

Expected:

Thanks.

Actual code:

        Mat src;
        src = BitmapConverter.ToMat(lastFrame);
        Mat dst = new Mat();
        Mat dst2 = new Mat();

        Cv2.Canny(src, dst, hScrollBar1.Value, hScrollBar2.Value);

        // Find contours
        OpenCvSharp.Point[][] contours; //vector<vector<Point>> contours;
        HierarchyIndex[] hierarchyIndexes; //vector<Vec4i> hierarchy;

        Cv2.FindContours(dst, out contours, out hierarchyIndexes, RetrievalModes.External, ContourApproximationModes.ApproxTC89L1);

        foreach (OpenCvSharp.Point[] element in contours)
        {
            var biggestContourRect = Cv2.BoundingRect(element);

            Cv2.Rectangle(dst,
                new OpenCvSharp.Point(biggestContourRect.X, biggestContourRect.Y),
                new OpenCvSharp.Point(biggestContourRect.X + biggestContourRect.Width, biggestContourRect.Y + biggestContourRect.Height),
                new Scalar(255, 0, 0), 3);
        }

        using (new Window("dst image", dst)) ;
        using (new Window("src image", src)) ;


问:
JavaScript: Web Worker and Typed Arrays
I have a web worker (started with new Worker()) that does some processing and is supposed to return a Float32Array.

It seems however that after the worker postMessage()s the data, it goes through serialization and desirialization to JSON and what I end up with when receiving the message is a plain javascript Array (with all of the properties the original typed array had)

A trivial work around would be to just recreate the typed array from the javascript array but that's wasteful and takes up time and memory.

Is there a better way to do this? Some kind of way to tell the JSON deserialization to instantiate a Float32Array instead of a javascript array? or a way to otherwise transfer the binary data?

答:
update: this seems to be a Chrome bug at the moment:

http://code.google.com/p/chromium/issues/detail?id=73313

typed array are preserved in Firefox 4.

Title: JavaScript: Web Worker and Typed Arrays


问:
How to transfer the value from the filter to Power Query and insert it into the query?
I have a report that displays data for a certain period. There are two parameters in the report: the start date and the end date. Data is displayed for the specified period. I want to dynamically load data using a filter in the report, rather than changing the parameters of the query. How can this be implemented?</p>

答:
You can set up a Direct Query where it pulls in the data only when it needs it.

Note that you can have a composite model where some tables are Direct Query and others are Import.


问:
How do I pass a parameter to my url for a POST function that takes a string parameter?
I'm using ASP.NET Core for a Web API and created a POST function and don't know how to pass a string "name" in the URL such that the function can return the correct string.

The url should be :

https://localhost/44320/api/

```<code>//This is in my Controller class
[HttpPost("test/{name}")]
public string PostTest(string name)
{
    return "Name: " + name;
}
</code>```

The return value is self explanatory but I just get a 405 error for when I do
https://localhost:44320/api/test/bob/

答:
try like this:</p>

```<code>[HttpPost]
[Route("test/{name}")]
</code>```

Body:
I'm using ASP.NET Core for a Web API and created a POST function and don't know how to pass a string "name" in the URL such that the function can return the correct string.

The url should be :

https://localhost/44320/api/

//This is in my Controller class
[HttpPost("test/{name}")]
public string PostTest(string name)
{
    return "Name: " + name;
}

The return value is self explanatory but I just get a 405 error for when I do
https://localhost:44320/api/test/bob/

Body:
try like this:

[HttpPost]
[Route("test/{name}")]


问:
Keep all cells above given value in pandas DataFrame
I would like to discard all cells that contain a value below a given value. So not only the rows or only the columns that, but for for all cells.

Tried code below, where all values in each cell should be at least 3. Doesn't work.

```<code>df[(df >= 3).any(axis=1)]
</code>```

Example

```<code>import pandas as pd
my_dict = {'A':[1,5,6,2],'B':[9,9,1,2],'C':[1,1,3,5]}
df = pd.DataFrame(my_dict)
df
    A   B   C
0   1   9   1
1   5   9   1
2   6   1   3
3   2   2   5
</code>```

I want to keep only the cells that are at least 3.

答:
You can check if the value is >= 3 then drop all rows with NaN value.

```<code>df[df >= 3 ].dropna()
</code>```

DEMO:

```<code>import pandas as pd
my_dict = {'A':[1,5,6,3],'B':[9,9,1,3],'C':[1,1,3,5]}
df = pd.DataFrame(my_dict)
df

    A   B   C
0   1   9   1
1   5   9   1
2   6   1   3
3   3   3   5

df = df[df >= 3 ].dropna().reset_index(drop=True)
df

    A   B   C
0   3.0 3.0 5.0
</code>```

Body:
I would like to discard all cells that contain a value below a given value. So not only the rows or only the columns that, but for for all cells.

Tried code below, where all values in each cell should be at least 3. Doesn't work.

df[(df >= 3).any(axis=1)]

Example

import pandas as pd
my_dict = {'A':[1,5,6,2],'B':[9,9,1,2],'C':[1,1,3,5]}
df = pd.DataFrame(my_dict)
df
    A   B   C
0   1   9   1
1   5   9   1
2   6   1   3
3   2   2   5

I want to keep only the cells that are at least 3.

Body:
You can check if the value is >= 3 then drop all rows with NaN value.

df[df >= 3 ].dropna()

DEMO:

import pandas as pd
my_dict = {'A':[1,5,6,3],'B':[9,9,1,3],'C':[1,1,3,5]}
df = pd.DataFrame(my_dict)
df

    A   B   C
0   1   9   1
1   5   9   1
2   6   1   3
3   3   3   5

df = df[df >= 3 ].dropna().reset_index(drop=True)
df

    A   B   C
0   3.0 3.0 5.0


问:
Authorization header requires 'Credential' parameter
We are using Identity Server4 with .NET Core and deploy the application as AWS Serverless lambda function. When are calling the token endpoint to generated access token we got the following error message:

```<code>{
"message": "Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=Basic Y2xpZW50OnNlY3JldA=="
</code>```

}

Here is our ConfigurationServices method in Identity Server application:

```<code> public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(Configuration);

        //connection string
        string connectionString = Configuration.GetConnectionString("IdentityServer");

        var rsaProvider = new RSACryptoServiceProvider(2048);

        SecurityKey key = new RsaSecurityKey(rsaProvider);

        var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
              (key, SecurityAlgorithms.RsaSha256Signature);

        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddIdentityServer()
           .AddSigningCredential(credentials)
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                builder.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
            }) // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                builder.UseSqlServer(connectionString,
            sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                 options.EnableTokenCleanup = true;
                 options.TokenCleanupInterval = 30;
            });

        // Add S3 to the ASP.NET Core dependency injection framework.
        services.AddAWSService<Amazon.S3.IAmazonS3>();
    }
</code>```

Here is our client application that calling identity server's token endpoint to generate token:

```<code>[HttpGet]
    public async Task<IActionResult> Get(string client, string secret)
    {

        IActionResult result = null;

        //discover endpoints from metadata

        //var disco = await DiscoveryClient.GetAsync("http://localhost:3000/");

        var disco = await DiscoveryClient.GetAsync("hide for security reasons/");

        if (disco.IsError)
        {
            result = NotFound(disco.Error);

            return result;
        }
        //request token

        var tokenClient = new TokenClient(disco.TokenEndpoint, client, secret);

        var tokenResponse = await tokenClient.RequestClientCredentialsAsync(scope: "sup");

        if (tokenResponse.IsError)
        {
            result = NotFound(tokenResponse.Error);
        }

        result = Ok(tokenResponse.Json);

        return result;
    }
</code>```

答:
Just in case someone else makes their way here, this happened to me because I had a typo in the path of my URL.

When I corrected my typo, everything worked for me.

Mini context: I was confused because I was using a Lambda authorizer for my API Gateway resource, and I didn't even see anything hitting the Cloudwatch logs for that Lambda.

Body:
We are using Identity Server4 with .NET Core and deploy the application as AWS Serverless lambda function. When are calling the token endpoint to generated access token we got the following error message:

{
"message": "Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=Basic Y2xpZW50OnNlY3JldA=="

}

Here is our ConfigurationServices method in Identity Server application:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(Configuration);

        //connection string
        string connectionString = Configuration.GetConnectionString("IdentityServer");

        var rsaProvider = new RSACryptoServiceProvider(2048);

        SecurityKey key = new RsaSecurityKey(rsaProvider);

        var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
              (key, SecurityAlgorithms.RsaSha256Signature);

        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddIdentityServer()
           .AddSigningCredential(credentials)
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                builder.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
            }) // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                builder.UseSqlServer(connectionString,
            sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                 options.EnableTokenCleanup = true;
                 options.TokenCleanupInterval = 30;
            });

        // Add S3 to the ASP.NET Core dependency injection framework.
        services.AddAWSService<Amazon.S3.IAmazonS3>();
    }

Here is our client application that calling identity server's token endpoint to generate token:

[HttpGet]
    public async Task<IActionResult> Get(string client, string secret)
    {

        IActionResult result = null;

        //discover endpoints from metadata

        //var disco = await DiscoveryClient.GetAsync("http://localhost:3000/");

        var disco = await DiscoveryClient.GetAsync("hide for security reasons/");

        if (disco.IsError)
        {
            result = NotFound(disco.Error);

            return result;
        }
        //request token

        var tokenClient = new TokenClient(disco.TokenEndpoint, client, secret);

        var tokenResponse = await tokenClient.RequestClientCredentialsAsync(scope: "sup");

        if (tokenResponse.IsError)
        {
            result = NotFound(tokenResponse.Error);
        }

        result = Ok(tokenResponse.Json);

        return result;
    }


问:
Convert List of Lists to Dictionary with unique keys and all related values
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

```<code>data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)
</code>```

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

Body:
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

Body:
d=dict()
entries=[]
for i in range(0,13):
    entries=[]
    for j in data:
        if i in j:
            entries+=[num for num in j if num!=i]
    d[i]=entries

Output

{0: [1],
 1: [0, 2, 8],
 2: [1, 8, 4, 5],
 3: [4],
 4: [3, 2],
 5: [2, 6, 7],
 6: [5, 7],
 7: [5, 6],
 8: [1, 2, 9, 10, 11, 12],
 9: [8, 10, 11, 12],
 10: [8, 9, 11, 12],
 11: [8, 9, 10, 12],
 12: [8, 9, 10, 11]}


问:
not like does not apply to string extracted from dropdown menu
The following code should be able to return me some records that doesn't included the following:

```<code> RequestStatus <> 'Submission'
 OR RequestStatus <>'Pre-CRC submission'
 OR RequestStatus <>'CCT Review'
</code>```

Each of the items listed above are menu items coming from a drop down menu.Which should n't be listed in the final results. However, these items are listed in the results. Does anyone know what am I doing wrong here?

```<code>Select

    RequestStatus,
    IncidentID,
    max(LastModifiedDateTimeJ) as 'newfield',
    OwnedByTeamJ,
    DetailsJ,
    Status,
    OwnedByTeam
    from IncidentTicket
where
    CAST(CreatedDateTime as  DATE) >='05-01-2019'
    AND JournalTypeName like '%Journal - Note%'
    And OwnedByTeamJ like '%C - OS Review%'
    AND
       (
        RequestStatus <> 'Submission'
        OR RequestStatus <>'Pre-CRC submission'
        OR RequestStatus <>'CCT Review'
       )

group by  RequestStatus,IncidentID,OwnedByTeamJ
,DetailsJ,Status, OwnedByTeam
</code>```

Thanks,

答:
Use:

```<code>    where RequestStatus not in ('Submission','Pre-CRC submission','CCT Review')
</code>```

The ORs were messing you up

Body:
The following code should be able to return me some records that doesn't included the following:

 RequestStatus <> 'Submission'
 OR RequestStatus <>'Pre-CRC submission'
 OR RequestStatus <>'CCT Review'

Each of the items listed above are menu items coming from a drop down menu.Which should n't be listed in the final results. However, these items are listed in the results. Does anyone know what am I doing wrong here?

Select

    RequestStatus,
    IncidentID,
    max(LastModifiedDateTimeJ) as 'newfield',
    OwnedByTeamJ,
    DetailsJ,
    Status,
    OwnedByTeam
    from IncidentTicket
where
    CAST(CreatedDateTime as  DATE) >='05-01-2019'
    AND JournalTypeName like '%Journal - Note%'
    And OwnedByTeamJ like '%C - OS Review%'
    AND
       (
        RequestStatus <> 'Submission'
        OR RequestStatus <>'Pre-CRC submission'
        OR RequestStatus <>'CCT Review'
       )

group by  RequestStatus,IncidentID,OwnedByTeamJ
,DetailsJ,Status, OwnedByTeam

Thanks,

Body:
Use:

    where RequestStatus not in ('Submission','Pre-CRC submission','CCT Review')

The ORs were messing you up


问:
Join two Except Clauses into one result set
Is it possible to join two Except Clauses into a single result set ?

This does not work, but it is essentially what I would like to achieve

```<code>SELECT * FROM dbo.TemptblSHAREVendors EXCEPT SELECT * FROM dbo.tblSHAREVendors
UNION
SELECT * FROM dbo.tblSHAREVendors EXCEPT SELECT * FROM dbo.TemptblSHAREVendors
</code>```

答:
You can use parenthesis to force the precedence of operations.</p>

```<code>(SELECT *
        FROM dbo.TemptblSHAREVendors
 EXCEPT
 SELECT *
        FROM dbo.tblSHAREVendors)
UNION
(SELECT *
        FROM dbo.tblSHAREVendors
 EXCEPT
 SELECT *
        FROM dbo.TemptblSHAREVendors);
</code>```

Body:
Is it possible to join two Except Clauses into a single result set ?

This does not work, but it is essentially what I would like to achieve

SELECT * FROM dbo.TemptblSHAREVendors EXCEPT SELECT * FROM dbo.tblSHAREVendors
UNION
SELECT * FROM dbo.tblSHAREVendors EXCEPT SELECT * FROM dbo.TemptblSHAREVendors

Body:
You can use parenthesis to force the precedence of operations.

(SELECT *
        FROM dbo.TemptblSHAREVendors
 EXCEPT
 SELECT *
        FROM dbo.tblSHAREVendors)
UNION
(SELECT *
        FROM dbo.tblSHAREVendors
 EXCEPT
 SELECT *
        FROM dbo.TemptblSHAREVendors);


问:
How to return passed present items in an array of javascript?
I have a function and I want to return true if the passed item is present in all the arrays inside arrayOfArrays# check if it appears across all arrays.

```<code>function item(allArrays, item) {

}

Run against this code
  describe('item', () => {
    it('returns true if the passed value is present in all the arrays inside the passed array', () => {
      const allArrays= [
        [9, 2, 3],
        [4, 5, 9],
        [-2, 9, -1],
        [1, 2, 3, 4, 5, 9]
      ];
      expect(item(allArrays, 9)).to.be.true;
    });
it('returns false if the passed value is not present in at least one array inside the passed array', () => {
  let allArrays= [[9, 2, 3], [4, 5, 9], [-2, 1, -1]];
  expect(item(allArrays, 9)).to.be.false;
  allArrays= [[6, 2, 3], [4, 5, 8], [-2, 9, -1]];
  expect(item(allArrays, 9)).to.be.false;
  allArrays= [[4, 2, 3], [4, 5, 9], [-2, 9, -1]];
  expect(item(allArrays, 9)).to.be.false;
});
</code>```

});

答:
let isCommon = (arrays, v) =>
  arrays.every(a => a.includes(v));

const allArrays = [
  [9, 2, 3],
  [4, 5, 9],
  [-2, 9, -1],
  [1, 2, 3, 4, 5, 9]
];
console.log(isCommon(allArrays, 5)); // false
console.log(isCommon(allArrays, 9)); // true```

Body:
I have a function and I want to return true if the passed item is present in all the arrays inside arrayOfArrays# check if it appears across all arrays.

function item(allArrays, item) {

}

Run against this code
  describe('item', () => {
    it('returns true if the passed value is present in all the arrays inside the passed array', () => {
      const allArrays= [
        [9, 2, 3],
        [4, 5, 9],
        [-2, 9, -1],
        [1, 2, 3, 4, 5, 9]
      ];
      expect(item(allArrays, 9)).to.be.true;
    });
it('returns false if the passed value is not present in at least one array inside the passed array', () => {
  let allArrays= [[9, 2, 3], [4, 5, 9], [-2, 1, -1]];
  expect(item(allArrays, 9)).to.be.false;
  allArrays= [[6, 2, 3], [4, 5, 8], [-2, 9, -1]];
  expect(item(allArrays, 9)).to.be.false;
  allArrays= [[4, 2, 3], [4, 5, 9], [-2, 9, -1]];
  expect(item(allArrays, 9)).to.be.false;
});

});


答:
You could use a defaultdict here:

from collections import defaultdict

mylist = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

d = defaultdict(list) # a dictionary with all values defaulting to lists

for lst in mylist:
    for val in lst:
        # extend each list with new values provided they aren't
        # equal to the key in question
        d[val].extend([x for x in lst if x!=val])

d
# {0: [1], 1: [0, 2, 8], 2: [1, 8, 4, 5], 8: [1, 2, 9, 10, 11, 12], 3: [4], 4: [3, 2], 5: [2, 6, 7], 6: [5, 7], 7: [5, 6], 9: [8, 10, 11, 12], 10: [8, 9, 11, 12], 11: [8, 9, 10, 12], 12: [8, 9, 10, 11]}
```

<p>By using a defaultdict, you don't have to worry about assigning a list to the value by default, so you can just use the standard <code>list</code> attributes like <code>append</code> and <code>extend</code>. </p>

<p>There is a performance consideration, as you iterate over <code>lst</code> N+1 times, where N is the length of <code>lst</code>. <code>extend</code> is an O(N) operation, so building the list <em>and</em> extending the existing one isn't exactly performant. It also won't account for duplicate values (if that matters to you). However, it's a bit cleaner than trying to use a standard <code>dict</code>, which you could do:</p>

<pre class="lang-py prettyprint-override"><code>d = {}
for lst in mylist:
    for val in lst:
        if val not in d:
            d[val] = [x for x in lst if x!=val]
        else:
            d[val].extend([x for x in lst if x!=val])

d
# {0: [1], 1: [0, 2, 8], 2: [1, 8, 4, 5], 8: [1, 2, 9, 10, 11, 12], 3: [4], 4: [3, 2], 5: [2, 6, 7], 6: [5, 7], 7: [5, 6], 9: [8, 10, 11, 12], 10: [8, 9, 11, 12], 11: [8, 9, 10, 12], 12: [8, 9, 10, 11]}
</code>```

Where you have to check if val is in the dictionary to build the list, otherwise, you can modify the value in-place with extend

Title: Convert List of Lists to Dictionary with unique keys and all related values

Body:
You could use a defaultdict here:

from collections import defaultdict

mylist = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

d = defaultdict(list) # a dictionary with all values defaulting to lists

for lst in mylist:
    for val in lst:
        # extend each list with new values provided they aren't
        # equal to the key in question
        d[val].extend([x for x in lst if x!=val])

d
# {0: [1], 1: [0, 2, 8], 2: [1, 8, 4, 5], 8: [1, 2, 9, 10, 11, 12], 3: [4], 4: [3, 2], 5: [2, 6, 7], 6: [5, 7], 7: [5, 6], 9: [8, 10, 11, 12], 10: [8, 9, 11, 12], 11: [8, 9, 10, 12], 12: [8, 9, 10, 11]}

By using a defaultdict, you don't have to worry about assigning a list to the value by default, so you can just use the standard list attributes like append and extend.

There is a performance consideration, as you iterate over lst N+1 times, where N is the length of lst. extend is an O(N) operation, so building the list and extending the existing one isn't exactly performant. It also won't account for duplicate values (if that matters to you). However, it's a bit cleaner than trying to use a standard dict, which you could do:

d = {}
for lst in mylist:
    for val in lst:
        if val not in d:
            d[val] = [x for x in lst if x!=val]
        else:
            d[val].extend([x for x in lst if x!=val])

d
# {0: [1], 1: [0, 2, 8], 2: [1, 8, 4, 5], 8: [1, 2, 9, 10, 11, 12], 3: [4], 4: [3, 2], 5: [2, 6, 7], 6: [5, 7], 7: [5, 6], 9: [8, 10, 11, 12], 10: [8, 9, 11, 12], 11: [8, 9, 10, 12], 12: [8, 9, 10, 11]}

Where you have to check if val is in the dictionary to build the list, otherwise, you can modify the value in-place with extend


问:
Notice: Undefined offset: 2 in
I would like a help, I converted the input string from date to array and if I do not input for example 05/26/2019, all 3 fields did an explode to flip an array, then this error occurs. what can I do?

escola.php

```<code> <form method="POST" class="PesquisarData">
    <h5>Pesquisar Data:</h5>
    <input type="text" id="data" name="data" class="selectData">
    <input type="submit" value="Pesquisar" class="buttonData"><br/>
 </form>

if (!empty($_POST['data'])) {
        $_POST['disciplina'] = "";
        $_POST['professor'] = "";

        $data = explode('/', addslashes($_POST['data']));
        $data = $data[2].'-'.$data[1].'-'.$data[0];
        $sqlm = "SELECT * FROM {$pfx}Material WHERE Data LIKE CONCAT('%',?,'%') ORDER BY Data DESC";
        $qrym = $conn->prepare($sqlm);
        $qrym->bindParam(1, $data);
        $qrym->execute() or die('Ocorreu um erro em uma operação do banco de dados: VL0002.2');
}
</code>```

答:
Check that $data has 3 elements before trying to use it.

```<code>$data = explode('/', addslashes($_POST['data']));
if (count($data) != 3) {
    die('Invalid date ' . $_POST['data']);
}
$data = $data[2].'-'.$data[1].'-'.$data[0];
</code>```

Title: Notice: Undefined offset: 2 in

Body:
I would like a help, I converted the input string from date to array and if I do not input for example 05/26/2019, all 3 fields did an explode to flip an array, then this error occurs. what can I do?

escola.php

 <form method="POST" class="PesquisarData">

Pesquisar Data:

    <input type="text" id="data" name="data" class="selectData">
    <input type="submit" value="Pesquisar" class="buttonData">

 </form>

if (!empty($_POST['data'])) {
        $_POST['disciplina'] = "";
        $_POST['professor'] = "";

        $data = explode('/', addslashes($_POST['data']));
        $data = $data[2].'-'.$data[1].'-'.$data[0];
        $sqlm = "SELECT * FROM {$pfx}Material WHERE Data LIKE CONCAT('%',?,'%') ORDER BY Data DESC";
        $qrym = $conn->prepare($sqlm);
        $qrym->bindParam(1, $data);
        $qrym->execute() or die('Ocorreu um erro em uma operação do banco de dados: VL0002.2');
}

Body:
Check that $data has 3 elements before trying to use it.

$data = explode('/', addslashes($_POST['data']));
if (count($data) != 3) {
    die('Invalid date ' . $_POST['data']);
}
$data = $data[2].'-'.$data[1].'-'.$data[0];


问:
Extraction of Data using tbodyclass and Beautifulsoup
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

```<code>import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)
</code>```

Here is the Error

```<code>Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?
</code>```

答:
you can do this:</p>

```<code>required_data.find_all("tbody", class_="dataSmall")
</code>```

Body:
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)

Here is the Error

Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?

Body:
you can do this:

required_data.find_all("tbody", class_="dataSmall")