问:
InvalidOperationException: Sequence contains no elements. In Asp.net Core MVC with Entity framework
I am getting this error one of my projects.

InvalidOperationException: Sequence contains no elements.

here is my code in this I am trying to create auto-generated Id with string format.

```<code> public async Task<IActionResult> Create()
    {
        int id = _db.Patient.Max(item => item.Id)+1;

        ViewBag.autoid = "BL0000"+id.ToString();
        return View();
    }
</code>```

答:
I resolved this issue </p>

```<code>public async Task<IActionResult> Create()
    {
        //x = _db.Patient.Max(item => item.Id);
        x=_db.Patient.DefaultIfEmpty().Max(item => item == null ? 1 : item.Id+1);

        ViewBag.autoid = "BL0000"+x.ToString();
        return View();
    }
</code>```

Body:
I am getting this error one of my projects.

InvalidOperationException: Sequence contains no elements.

here is my code in this I am trying to create auto-generated Id with string format.

 public async Task<IActionResult> Create()
    {
        int id = _db.Patient.Max(item => item.Id)+1;

        ViewBag.autoid = "BL0000"+id.ToString();
        return View();
    }

Body:
I resolved this issue

public async Task<IActionResult> Create()
    {
        //x = _db.Patient.Max(item => item.Id);
        x=_db.Patient.DefaultIfEmpty().Max(item => item == null ? 1 : item.Id+1);

        ViewBag.autoid = "BL0000"+x.ToString();
        return View();
    }


来源: stackexchange

问:
How to define a global variable in ASP.net web app
I have face a requirement,

I want client access a data center but without use database , so I want my web app can retain a global or Application session variable, that contains the data,  every client can access the same data... I am try to declare in golabl, but seem it only can store String but others ...

how to solve this problem ?

thanks.

答:
If you are using WebApplication or MVC just go to Global.asax (in WebSite project you need to add Global.asax from the add new item menu).

I will explain to deploy two global variables for your web application:

Open the Global.asax file, then define your variable in Application_Start function as following:

```<code>void Application_Start(object sender, EventArgs e)
{
   Application.Lock();
   Application["variable1"] = "Some Value for variable1";
   Application["variable2"] = "Some Value for variable2";
   Application.UnLock();
}
</code>```

If you want to use that those global variables in aspx pages just need to call them like this:

```<code><p>I want to call variable1 <%=Application["variable1"].ToString() %></p>
<p>I want to call variable1 <%=Application["variable2"].ToString() %></p>
</code>```

But if you want to use that those global variables in server-side  call'em like this:

```<code>protected void Page_Load(object sender, EventArgs e)
{
   string str1 = Application["variable1"].ToString();
   string str2 = Application["variable2"].ToString();
}
</code>```

Note: You must be aware that these global variables are public to all users and aren't suitable for authentication jobs.

ContentLicense: CC BY-SA 2.5

Body:
If you are using WebApplication or MVC just go to Global.asax (in WebSite project you need to add Global.asax from the add new item menu).

I will explain to deploy two global variables for your web application:

Open the Global.asax file, then define your variable in Application_Start function as following:

void Application_Start(object sender, EventArgs e)
{
   Application.Lock();
   Application["variable1"] = "Some Value for variable1";
   Application["variable2"] = "Some Value for variable2";
   Application.UnLock();
}

If you want to use that those global variables in aspx pages just need to call them like this:

<p>I want to call variable1 <%=Application["variable1"].ToString() %></p>
<p>I want to call variable1 <%=Application["variable2"].ToString() %></p>

But if you want to use that those global variables in server-side  call'em like this:

protected void Page_Load(object sender, EventArgs e)
{
   string str1 = Application["variable1"].ToString();
   string str2 = Application["variable2"].ToString();
}

Note: You must be aware that these global variables are public to all users and aren't suitable for authentication jobs.

ContentLicense: CC BY-SA 4.0


问:
Building the Pyspark sytax dynamically
We have a requirement where we need to save the ETL operations rules in mysql database and run the AWS glue job based on the rules coded in Pyspark.

we are going to save the actual Pysaprk syntax in the rules table as string like below.

s.no|rule|output

1|df1.join(df2, on=['age'], how='right_outer')|df3

2|df3.join(df4, on=['age'], how='right_outer')|df5

3|df5.join(df6, on=['age'], how='right_outer')|df7

we are going to pull this from DB and store it as DF.

For i in DF:

i.output = i.rule

#after substituting the value it look like (df3 = df1.join(df2, on=['age'], how='right_outer') )

But the join operation is not happening. Since the values are stored as string in the DB its just substituting the values.

Please help me here what needs to be changed for the join operations to be executed.do i need to change the data type?

Many thanks in advance.

答:
Can you try this :

```<code>df_all = df1.join(df2, on=['age'], how='right_outer')\
            .join(df3, on=['age'], how='right_outer')\
            .join(df4, on=['age'], how='right_outer')

df_all.show()
</code>```

Best,

Title: Building the Pyspark sytax dynamically

Body:
Can you try this :

df_all = df1.join(df2, on=['age'], how='right_outer')\
            .join(df3, on=['age'], how='right_outer')\
            .join(df4, on=['age'], how='right_outer')

df_all.show()

Best,


问:
Why array implements IList?
See the definition of System.Array class

```<code>public abstract class Array : IList, ...
</code>```

Theoretically, I should be able to write this bit and be happy

```<code>int[] list = new int[] {};
IList iList = (IList)list;
</code>```

I also should be able to call any method from the iList

```<code> ilist.Add(1); //exception here
</code>```

My question is not why I get an exception, but rather why Array implements IList?

答:
Having an array implement IList (and transitively, ICollection) simplified the Linq2Objects engine, since casting the IEnumerable to IList/ICollection would also work for arrays.

For example, a Count() ends up calling the Array.Length under-the-hood, since it's casted to ICollection and the array's implementation returns Length.

Without this, the Linq2Objects engine would not have special treatment for arrays and perform horribly, or they'd need to double the code adding special-case treatment for arrays (like they do for IList).  They must've opted to make array implement IList instead.

That's my take on "Why".

ContentLicense: CC BY-SA 3.0

Title: Why array implements IList?

Body:
See the definition of System.Array class

public abstract class Array : IList, ...

Theoretically, I should be able to write this bit and be happy

int[] list = new int[] {};
IList iList = (IList)list;

I also should be able to call any method from the iList

 ilist.Add(1); //exception here

My question is not why I get an exception, but rather why Array implements IList?


问:
Useful data structure for the following case
Which can be the beste data structures for the following case.

1.Should have operations like search, insert and delete. Mostly searching activities will be there.Around 90% of the operations will be search and rest are delete and insert.

2 Insertion,deletion and searching will  be based on the  key of the objects. Each key will point to a object. The keys will be sorted.

Any suggestion for optimal data structure will be highly appreciated.

答:
AVL tree, or at least BST.

If you want to acces often the same elements you might want to consider splay trees too.

(Should I explain why?)


问:
Place multiple SCN objects in touchesBegan method
My Swift code below uses func touchesBegan to place a SCN object in the ARKit view. The problem is – it's only placing the object one time. I would like to create the code in a way that users can select any area to place the SCN object and it can place it as many times as they want too.

Here's GitHub link.

```<code>class ViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet var sceneView: ARSCNView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        // Handle the shooting
        guard let frame = sceneView.session.currentFrame else { return }
        let camMatrix = SCNMatrix4(frame.camera.transform)

        let direction = SCNVector3Make(camMatrix.m31 * 5.0,
                                       camMatrix.m32 * 10.0,
                                       camMatrix.m33 * 5.0)

        let position = SCNVector3Make(camMatrix.m41, camMatrix.m42, camMatrix.m43)
        let scene = SCNScene(named: "art.scnassets/dontCare.scn")!
        sceneView.scene = scene
    }
}
</code>```

答:
Tip: If you use RealityKit, read this post.

Solution 1

Adding 3D models using touchesBegan(:with:)

Use the following code to get a desired effect (place as many objects into a scene as you want):

At first create an extension for your convenience:

```<code>import ARKit

extension SCNVector3 {

    static func + (lhs: SCNVector3, rhs: SCNVector3) -> SCNVector3 {
        return SCNVector3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
    }
}
</code>```

Then use it in your ViewController for adding a pointOfView.position to desiredVector:

```<code>class ViewController: UIViewController {

    @IBOutlet var sceneView: ARSCNView!

    override func touchesBegan(_ touches: Set<UITouch>,
                              with event: UIEvent?) {

        sceneView.isMultipleTouchEnabled = true

        guard let pointOfView = sceneView.pointOfView   // Camera of SCNScene
        else { return }

        let cameraMatrix = pointOfView.transform

        let desiredVector = SCNVector3(cameraMatrix.m31 * -0.5,
                                       cameraMatrix.m32 * -0.5,
                                       cameraMatrix.m33 * -0.5)

        // What the extension SCNVector3 is for //
        let position = pointOfView.position + desiredVector

        let sphereNode = SCNNode()
        sphereNode.geometry = SCNSphere(radius: 0.05)
        sphereNode.geometry?.firstMaterial?.diffuse.contents = UIColor.green
        sphereNode.position = position
        sceneView.scene.rootNode.addChildNode(sphereNode)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let scene = SCNScene(named: "art.scnassets/myScene.scn")!
        sceneView.scene = scene
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let config = ARWorldTrackingConfiguration()
        sceneView.session.run(config)
    }
}
</code>```

And if you want to retrieve a 3D model from .scn file use the following code:

(Instead of the sphereNode):

```<code>var model = SCNNode()
let myScene = SCNScene(named: "art.scnassets/ship.scn")

// Model's name in a Scene graph hierarchy.
// Pay particular attention – it's not a name of .scn file.
let nodeName = "ship"

model = (myScene?.rootNode.childNode(withName: nodeName, recursively: true))!
model.position = position
sceneView.scene.rootNode.addChildNode(model)
</code>```

Solution 2

Adding 3D models using Plane Detection + Hit-Testing

Use the following code if you want to add models using plane detection and Hit-testing :

At first create an extension for your convenience:

```<code>extension float4x4 {
    var simdThree: SIMD3<Float> {
        let translation = self.columns.3
        return SIMD3<Float>(translation.x, translation.y, translation.z)
    }
}
</code>```

Then use it in the ViewController:

```<code>class ViewController: UIViewController {

    @IBOutlet weak var sceneView: ARSCNView!

    override func viewDidLoad() {
        super.viewDidLoad()
        addGesture()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sceneView.delegate = self             // for ARSCNViewDelegate

        let config = ARWorldTrackingConfiguration()
        config.planeDetection = [.horizontal]
        sceneView.session.run(config)
    }

    func addGesture() {
        let tapGesture = UITapGestureRecognizer(target: self,
                                                action: #selector(addModel))
        sceneView.addGestureRecognizer(tapGesture)
    }

    // Don't forget to drag-and-drop TapGestureRecognizer object from library
    @objc func addModel(recognizer: UIGestureRecognizer) {

        let tap: CGPoint = recognizer.location(in: sceneView)

        let results: [ARHitTestResult] = sceneView.hitTest(tap,
                                           types: .existingPlaneUsingExtent)

        guard let hitTestResult = results.first
        else { return }

        let translation = hitTestResult.worldTransform.simdThree
        let x = translation.x
        let y = translation.y
        let z = translation.z

        guard let scene = SCNScene(named: "art.scnassets/myScene.scn"),
              let robotNode = scene.rootNode.childNode(withName: "robot",
                                                    recursively: true)
        else { return }

        robotNode.position = SCNVector3(x, y, z)
        robotNode.scale = SCNVector3(0.02, 0.02, 0.02)
        sceneView.scene.rootNode.addChildNode(robotNode)
    }
}
</code>```

And, you have to implement a logic inside two renderer() methods for ARPlaneAnchors:

```<code>extension ViewController: ARSCNViewDelegate {

    func renderer(_ renderer: SCNSceneRenderer,
                 didAdd node: SCNNode,
                  for anchor: ARAnchor) { // your logic here....  }

    func renderer(_ renderer: SCNSceneRenderer,
              didUpdate node: SCNNode,
                  for anchor: ARAnchor) { // your logic here....  }

}
</code>```

Body:
My Swift code below uses func touchesBegan to place a SCN object in the ARKit view. The problem is – it's only placing the object one time. I would like to create the code in a way that users can select any area to place the SCN object and it can place it as many times as they want too.

Here's GitHub link.

class ViewController: UIViewController, ARSCNViewDelegate {

    @IBOutlet var sceneView: ARSCNView!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        // Handle the shooting
        guard let frame = sceneView.session.currentFrame else { return }
        let camMatrix = SCNMatrix4(frame.camera.transform)

        let direction = SCNVector3Make(camMatrix.m31 * 5.0,
                                       camMatrix.m32 * 10.0,
                                       camMatrix.m33 * 5.0)

        let position = SCNVector3Make(camMatrix.m41, camMatrix.m42, camMatrix.m43)
        let scene = SCNScene(named: "art.scnassets/dontCare.scn")!
        sceneView.scene = scene
    }
}

Body:
Tip: If you use RealityKit, read this post.

Solution 1

Adding 3D models using touchesBegan(:with:)

Use the following code to get a desired effect (place as many objects into a scene as you want):

At first create an extension for your convenience:

import ARKit

extension SCNVector3 {

    static func + (lhs: SCNVector3, rhs: SCNVector3) -> SCNVector3 {
        return SCNVector3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
    }
}

Then use it in your ViewController for adding a pointOfView.position to desiredVector:

class ViewController: UIViewController {

    @IBOutlet var sceneView: ARSCNView!

    override func touchesBegan(_ touches: Set<UITouch>,
                              with event: UIEvent?) {

        sceneView.isMultipleTouchEnabled = true

        guard let pointOfView = sceneView.pointOfView   // Camera of SCNScene
        else { return }

        let cameraMatrix = pointOfView.transform

        let desiredVector = SCNVector3(cameraMatrix.m31 * -0.5,
                                       cameraMatrix.m32 * -0.5,
                                       cameraMatrix.m33 * -0.5)

        // What the extension SCNVector3 is for //
        let position = pointOfView.position + desiredVector

        let sphereNode = SCNNode()
        sphereNode.geometry = SCNSphere(radius: 0.05)
        sphereNode.geometry?.firstMaterial?.diffuse.contents = UIColor.green
        sphereNode.position = position
        sceneView.scene.rootNode.addChildNode(sphereNode)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let scene = SCNScene(named: "art.scnassets/myScene.scn")!
        sceneView.scene = scene
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let config = ARWorldTrackingConfiguration()
        sceneView.session.run(config)
    }
}

And if you want to retrieve a 3D model from .scn file use the following code:

(Instead of the sphereNode):

var model = SCNNode()
let myScene = SCNScene(named: "art.scnassets/ship.scn")

// Model's name in a Scene graph hierarchy.
// Pay particular attention – it's not a name of .scn file.
let nodeName = "ship"

model = (myScene?.rootNode.childNode(withName: nodeName, recursively: true))!
model.position = position
sceneView.scene.rootNode.addChildNode(model)

Solution 2

Adding 3D models using Plane Detection + Hit-Testing

Use the following code if you want to add models using plane detection and Hit-testing :

At first create an extension for your convenience:

extension float4x4 {
    var simdThree: SIMD3<Float> {
        let translation = self.columns.3
        return SIMD3<Float>(translation.x, translation.y, translation.z)
    }
}

Then use it in the ViewController:

class ViewController: UIViewController {

    @IBOutlet weak var sceneView: ARSCNView!

    override func viewDidLoad() {
        super.viewDidLoad()
        addGesture()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sceneView.delegate = self             // for ARSCNViewDelegate

        let config = ARWorldTrackingConfiguration()
        config.planeDetection = [.horizontal]
        sceneView.session.run(config)
    }

    func addGesture() {
        let tapGesture = UITapGestureRecognizer(target: self,
                                                action: #selector(addModel))
        sceneView.addGestureRecognizer(tapGesture)
    }

    // Don't forget to drag-and-drop TapGestureRecognizer object from library
    @objc func addModel(recognizer: UIGestureRecognizer) {

        let tap: CGPoint = recognizer.location(in: sceneView)

        let results: [ARHitTestResult] = sceneView.hitTest(tap,
                                           types: .existingPlaneUsingExtent)

        guard let hitTestResult = results.first
        else { return }

        let translation = hitTestResult.worldTransform.simdThree
        let x = translation.x
        let y = translation.y
        let z = translation.z

        guard let scene = SCNScene(named: "art.scnassets/myScene.scn"),
              let robotNode = scene.rootNode.childNode(withName: "robot",
                                                    recursively: true)
        else { return }

        robotNode.position = SCNVector3(x, y, z)
        robotNode.scale = SCNVector3(0.02, 0.02, 0.02)
        sceneView.scene.rootNode.addChildNode(robotNode)
    }
}

And, you have to implement a logic inside two renderer() methods for ARPlaneAnchors:

extension ViewController: ARSCNViewDelegate {

    func renderer(_ renderer: SCNSceneRenderer,
                 didAdd node: SCNNode,
                  for anchor: ARAnchor) { // your logic here....  }

    func renderer(_ renderer: SCNSceneRenderer,
              didUpdate node: SCNNode,
                  for anchor: ARAnchor) { // your logic here....  }

}


问:
ray.interstectObjects not intersecting correctly after geometry is dynamically modified
My ray.intersectObjects works really well with the objects in my scene until I dynamically modify the geometry of the object.  Although the renderer is showing the objects as being modified (vertices moved and faces changed), when an intersect is tried on the modified object, it produces strange results.  I need the intersect to work even on the modified geometry!

To help debug and track how the intersect is working in my scene, I've added a function: makeMiniSphere().  This makes a new sphere object in the scene at the point where the intersection occurs.  Using this, you can see that after the cube is modified, sometimes the intersect hits the cube and sometimes it goes right through (mostly the faces that have been modified).  It isn't a random problem, but the more you click around the modified cube, the more you can see a pattern develop.  It is almost as if the renderer for the visuals of the scene know which direction the cube was modified, but the ray.intersectObjects thinks that it has been modified in a different direction!

Here is a link to the test website: http://www.littledrop.net/html/cadiverse/HelloWorld.html

Directions to show problem:

Left click on cube to show intersect points.  Mini spheres will be created wherever Three.js sees an intersect.  The color of the selected object will change to yellow if not already selected.

Click on any face of the cube.  This will A. Turn it yellow if it isn't already yellow.  B. It will select the face of the cube, although the selected face won't look any different from the rest of the cube.

Press the "Right" arrow key to move the selected face to the right.  This will dynamically change the geometry of the cube.

Now try to click on the cube--especially in the area that it has been modified.  Again the Mini spheres will show where the software thinks the intersects are occurring.

Here is the intersect code:

```<code>function onDocumentMouseDown (event)
{
// the following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
//event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
document.getElementById('message1').innerHTML = window.innerHeight;
var isinworkingarea = window.innerHeight-menubarh;

if (event.clientY<=isinworkingarea)
{
    var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
    projector.unprojectVector( vector, camera );
    //var ray = new THREE.ReusableRay();
    var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
    // create an array containing all objects in the scene with which the ray intersects
    //  use this to select anything in the scene:
    var intersects = ray.intersectObjects( scene.children );
    if ( intersects.length > 0 )
    {
        if (cadjectNow)
            cadjects[cadjectNow].material.color.setHex(cadjects[cadjectNow].oldColor);
        if (intersects[0].object.cadNum)
            cadjectNow = intersects[0].object.cadNum;
        SELECTEDface=intersects[0].face;
        if (cadjectNow)
            cadjects[cadjectNow].material.color.setHex( selectColor );
        document.getElementById('message1').innerHTML = cadjects[cadjectNum].cadNum;

        ///// Information about selected /////
        var facestring = intersects[0].face.a  + " " + intersects[0].face.b + " " + intersects[0].face.c;
        if(intersects[0].face instanceof THREE.Face4)
        {
            facestring=facestring + " " + intersects[0].face.d;
        }

        copyGeometry=cadjects[cadjectNow].geometry;
        //makeCopy(copyGeometry,cadjects[cadjectNow].position.x,cadjects[cadjectNow].position.y,cadjects[cadjectNow].position.z);
        makeMiniSphere(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z);

        document.getElementById('message1').innerHTML = facestring;
        //document.getElementById('message2').innerHTML = cadjects[cadjectNow].geometry.vertices[SELECTEDface.a].x + " " + cadjects[cadjectNow].geometry.vertices[intersects[0].face.a].y + " " + cadjects[cadjectNow].geometry.vertices[intersects[0].face.a].z;
        document.getElementById('message2').innerHTML = intersects[0].point.x + " " + intersects[0].point.y + " " + intersects[0].point.z;

    }
}
}
</code>```

Here is the modify code:

```<code>if ( keyboard.pressed("right"))
{
    document.getElementById('message1').innerHTML = mouseMode;
    cadjects[cadjectNow].geometry.vertices[SELECTEDface.a].x+=10;
    cadjects[cadjectNow].geometry.vertices[SELECTEDface.b].x+=10;
    cadjects[cadjectNow].geometry.vertices[SELECTEDface.c].x+=10;
    if(SELECTEDface instanceof THREE.Face4)
    {
        cadjects[cadjectNow].geometry.vertices[SELECTEDface.d].x+=10;
    }
    cadjects[cadjectNow].geometry.verticesNeedUpdate = true;
    cadjects[cadjectNow].geometry.elementsNeedUpdate = true;
    cadjects[cadjectNow].geometry.normalsNeedUpdate = true;
}
</code>```

Thank you to everyone who has posted past questions and given the answers.  By perusing past questions, I've been able to get this far---so you guys have already been a great help.  Thanks in advance for help on this one.  (As this is my first question to post here, any suggestions on how to better present a question are also more than welcome.)

Update (3/21/13)--I've migrated to r57 as suggested and the updated code is shown above.  I've also debugged it so that it is working at least as well as it was before.  So now the geometry is still visually being changed dynamically, but the intersect is not detecting the change properly.  Thanks @WestLangley for the encouraging posts so far.

答:
I was having a similar issue with a modified BufferGeometry.

I got raycasting working by calling geometry.computeBoundingSphere() and geometry.computeBoundingBox() after modifying the array with vertex positions.

Setting verticesNeedUpdate was not needed.

Running r112.

Body:
My ray.intersectObjects works really well with the objects in my scene until I dynamically modify the geometry of the object.  Although the renderer is showing the objects as being modified (vertices moved and faces changed), when an intersect is tried on the modified object, it produces strange results.  I need the intersect to work even on the modified geometry!

To help debug and track how the intersect is working in my scene, I've added a function: makeMiniSphere().  This makes a new sphere object in the scene at the point where the intersection occurs.  Using this, you can see that after the cube is modified, sometimes the intersect hits the cube and sometimes it goes right through (mostly the faces that have been modified).  It isn't a random problem, but the more you click around the modified cube, the more you can see a pattern develop.  It is almost as if the renderer for the visuals of the scene know which direction the cube was modified, but the ray.intersectObjects thinks that it has been modified in a different direction!

Here is a link to the test website: http://www.littledrop.net/html/cadiverse/HelloWorld.html

Directions to show problem:

Left click on cube to show intersect points.  Mini spheres will be created wherever Three.js sees an intersect.  The color of the selected object will change to yellow if not already selected.

Click on any face of the cube.  This will A. Turn it yellow if it isn't already yellow.  B. It will select the face of the cube, although the selected face won't look any different from the rest of the cube.

Press the "Right" arrow key to move the selected face to the right.  This will dynamically change the geometry of the cube.

Now try to click on the cube--especially in the area that it has been modified.  Again the Mini spheres will show where the software thinks the intersects are occurring.

Here is the intersect code:

function onDocumentMouseDown (event)
{
// the following line would stop any other event handler from firing
// (such as the mouse's TrackballControls)
//event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
document.getElementById('message1').innerHTML = window.innerHeight;
var isinworkingarea = window.innerHeight-menubarh;

if (event.clientY<=isinworkingarea)
{
    var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
    projector.unprojectVector( vector, camera );
    //var ray = new THREE.ReusableRay();
    var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
    // create an array containing all objects in the scene with which the ray intersects
    //  use this to select anything in the scene:
    var intersects = ray.intersectObjects( scene.children );
    if ( intersects.length > 0 )
    {
        if (cadjectNow)
            cadjects[cadjectNow].material.color.setHex(cadjects[cadjectNow].oldColor);
        if (intersects[0].object.cadNum)
            cadjectNow = intersects[0].object.cadNum;
        SELECTEDface=intersects[0].face;
        if (cadjectNow)
            cadjects[cadjectNow].material.color.setHex( selectColor );
        document.getElementById('message1').innerHTML = cadjects[cadjectNum].cadNum;

        ///// Information about selected /////
        var facestring = intersects[0].face.a  + " " + intersects[0].face.b + " " + intersects[0].face.c;
        if(intersects[0].face instanceof THREE.Face4)
        {
            facestring=facestring + " " + intersects[0].face.d;
        }

        copyGeometry=cadjects[cadjectNow].geometry;
        //makeCopy(copyGeometry,cadjects[cadjectNow].position.x,cadjects[cadjectNow].position.y,cadjects[cadjectNow].position.z);
        makeMiniSphere(intersects[0].point.x, intersects[0].point.y, intersects[0].point.z);

        document.getElementById('message1').innerHTML = facestring;
        //document.getElementById('message2').innerHTML = cadjects[cadjectNow].geometry.vertices[SELECTEDface.a].x + " " + cadjects[cadjectNow].geometry.vertices[intersects[0].face.a].y + " " + cadjects[cadjectNow].geometry.vertices[intersects[0].face.a].z;
        document.getElementById('message2').innerHTML = intersects[0].point.x + " " + intersects[0].point.y + " " + intersects[0].point.z;

    }
}
}

Here is the modify code:

if ( keyboard.pressed("right"))
{
    document.getElementById('message1').innerHTML = mouseMode;
    cadjects[cadjectNow].geometry.vertices[SELECTEDface.a].x+=10;
    cadjects[cadjectNow].geometry.vertices[SELECTEDface.b].x+=10;
    cadjects[cadjectNow].geometry.vertices[SELECTEDface.c].x+=10;
    if(SELECTEDface instanceof THREE.Face4)
    {
        cadjects[cadjectNow].geometry.vertices[SELECTEDface.d].x+=10;
    }
    cadjects[cadjectNow].geometry.verticesNeedUpdate = true;
    cadjects[cadjectNow].geometry.elementsNeedUpdate = true;
    cadjects[cadjectNow].geometry.normalsNeedUpdate = true;
}

Thank you to everyone who has posted past questions and given the answers.  By perusing past questions, I've been able to get this far---so you guys have already been a great help.  Thanks in advance for help on this one.  (As this is my first question to post here, any suggestions on how to better present a question are also more than welcome.)

Update (3/21/13)--I've migrated to r57 as suggested and the updated code is shown above.  I've also debugged it so that it is working at least as well as it was before.  So now the geometry is still visually being changed dynamically, but the intersect is not detecting the change properly.  Thanks @WestLangley for the encouraging posts so far.


问:
@Pattern annotation for a method parameter
I am trying to validate a emailId which is part of a method parameter and a Query param for the rest endpoint. Using the @Pattern annotation in the method parameter is not working. Is there a better way to handle this scenario using annotation

```<code>public EmailResponse isEmailRegistered(HttpServletRequest request,
         @RequestParam("emailId") @Valid @Pattern(message = "Email is invalid", regexp = "^.+@.+\\..+$") final String emailId)
</code>```

I tried the above and it does not work. Because the email Id field is query parameter I cannot wrap it in a object and add validator on it.

I tried wrapping it in a wrapper object as below but to no luck

```<code>public EmailResponse isEmailRegistered(HttpServletRequest request,
         @RequestParam("emailId") @Valid final EmailIdWrapper emailId, final BindingResult bindingResult)
</code>```

EmailId Wrapper class

```<code>public class EmailIdWrapper implements Serializable{

@NotNull(message = "Email Id is required")
@Size(min = 5, max = 50, message = "Invalid length for email")
@Pattern(message = "Invalid email id", regexp = "^.+@.+\\..+$")
private String emailId;

public String getEmailId() {
    return emailId;
}

public void setEmailId(String emailId) {
    this.emailId = emailId;
}
</code>```

}

With this case I get a conversionnotsupported error which is quite obvious as the url parameter is a string and I am assigning to a object.

答:
I know it's a bit late, but
have you tried putting

@Validated

in the Controller class level?

Body:
I am trying to validate a emailId which is part of a method parameter and a Query param for the rest endpoint. Using the @Pattern annotation in the method parameter is not working. Is there a better way to handle this scenario using annotation

public EmailResponse isEmailRegistered(HttpServletRequest request,
         @RequestParam("emailId") @Valid @Pattern(message = "Email is invalid", regexp = "^.+@.+\\..+$") final String emailId)

I tried the above and it does not work. Because the email Id field is query parameter I cannot wrap it in a object and add validator on it.

I tried wrapping it in a wrapper object as below but to no luck

public EmailResponse isEmailRegistered(HttpServletRequest request,
         @RequestParam("emailId") @Valid final EmailIdWrapper emailId, final BindingResult bindingResult)

EmailId Wrapper class

public class EmailIdWrapper implements Serializable{

@NotNull(message = "Email Id is required")
@Size(min = 5, max = 50, message = "Invalid length for email")
@Pattern(message = "Invalid email id", regexp = "^.+@.+\\..+$")
private String emailId;

public String getEmailId() {
    return emailId;
}

public void setEmailId(String emailId) {
    this.emailId = emailId;
}

}

With this case I get a conversionnotsupported error which is quite obvious as the url parameter is a string and I am assigning to a object.


问:
My css code in Word Press is working for every other page in the website when i only want it to work for 1 page
I have currently made a code in CSS, which I wanted for a particular page but unfortunately, it is working for every other page as well and it makes the other pages look quite broken since the formatting of them goes very odd.

The solutions I have tried so far are:

Using the unique code of the page and making it something like this - * .post-id-17 .stop {code here}
But I got no results from using this solution.

Here is the HTML code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="seconds" placeholder="Seconds">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>

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

Here is the CSS code:

```<code>* .post-id-706 .stop {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}
</code>```

Here is the javascript code:

```<code>const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    if(stat.id == "start"){
        display("stop");
        remove("start");
        toCount = true;
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
        toCount = false
    }
    else{
        display("stop");
        remove("continue");
        toCount =true;
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);

    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}
</code>```

If you have any ideas in order to solve this issue please let me know.

答:
You can add a class to the page where you want to apply CSS, and change all CSS with reference to that class.
for example:

```<code><html class="some-class">
...<your code>
</html>
</code>```

CSS:

```<code>.some-class <your-selector>{
    <your css>
}
</code>```

Body:
I have currently made a code in CSS, which I wanted for a particular page but unfortunately, it is working for every other page as well and it makes the other pages look quite broken since the formatting of them goes very odd.

The solutions I have tried so far are:

Using the unique code of the page and making it something like this - * .post-id-17 .stop {code here}
But I got no results from using this solution.

Here is the HTML code:

<!DOCTYPE html>

    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">

CountDown

        <input type="number" id="seconds" placeholder="Seconds">

            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>

Here is the CSS code:

* .post-id-706 .stop {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}

Here is the javascript code:

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    if(stat.id == "start"){
        display("stop");
        remove("start");
        toCount = true;
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
        toCount = false
    }
    else{
        display("stop");
        remove("continue");
        toCount =true;
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);

    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}

If you have any ideas in order to solve this issue please let me know.

Body:
You can add a class to the page where you want to apply CSS, and change all CSS with reference to that class.
for example:

<html class="some-class">
...<your code>
</html>

CSS:

.some-class <your-selector>{
    <your css>
}


问:
gcc warning assignment makes pointer from integer without a cast
I am trying to make all possible combinations of alphabets using a number. Input NUM given by user.
The combinatitions are created by splitting input numbers upto two digits. Input Obtained as char*
I am Using C. I am getting output as Segmenation fault (core dumped), guessing because of the warning.

substr is my own function.
sample input and output

```<code>input: 11112
output:
AAAAB
AAAL
AAKB
AKAB
AKL
KAAB
KAL
KKB
</code>```

My CODE

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* substr(char* str,int l,int n)
{
    char* c;
    int len = n-l;
    while(l<n)
    {
        *c = *(str+l);
        l++;
        c++;
    }
    *c='\0';
    return c-len;
}

int printAlpha(char* str, char* word)
{
    char *sub;
    char* ch;
    int n = strlen(str);
    if(n == 0)
    {
        printf("%s",word);
    }
    else
    {

     sub = substr(str,0,1);
     int num = atoi(sub);
     str = substr(str,1,n);
     ch = 'A'+(num-1);
     printAlpha(str, strcat(word, ch));
     sub = substr(str,0,2);
     num = atoi(sub);
     if(strlen(str)>=2 && num <= 26)
     {
         str = substr(str,2,n);
         ch = 'A'+(num-1);
         printAlpha( str, strcat(word, ch) );
     }
    }
    return 0;
}

int main()
{
    char* str;
    char* word = '\0';
    scanf("%s",str);
    printAlpha(str,word);

    return 0;
}
</code>```

thanks in advance.

答:
As commenters have said you need to allocate memory in c dynamically.

In c if you need to store something like an array of characters you have 2 basic szenarios:

You know how many elements your array will contain before you compile then you can use

char word[numberOfLetters]

this will work as long as you dont need to store more letters, it becomes problematic in the other case

you dont know how big your array has to be before compiling

e.g when you are doing stuff with veriable lengths. imagine storing a user input into a char array. How should you make the array? if you make it 100 chars big and the user types 101 then you will get a segfault or loose everything he typed after the 100th char

you could also deal with this by making the array huge, but then with a short input youd be wasting a lot of memory and you still have the problem that if you need 1 char more than what you chose as size it wont work.

here is where you have to use dynamic memory allocation using functions like element_ptr* =malloc(numOfElements*sizeof(element)); to request memory during runtime.

what malloc does is it returns a pointer to the address, of the memory you requested

when you dont need the memory anymore you call free(element_ptr); this will free the memory again, otherwise it will stay blocked.

best you read up on malloc in the man pages

Body:
I am trying to make all possible combinations of alphabets using a number. Input NUM given by user.
The combinatitions are created by splitting input numbers upto two digits. Input Obtained as char*
I am Using C. I am getting output as Segmenation fault (core dumped), guessing because of the warning.

substr is my own function.
sample input and output

input: 11112
output:
AAAAB
AAAL
AAKB
AKAB
AKL
KAAB
KAL
KKB

My CODE

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* substr(char* str,int l,int n)
{
    char* c;
    int len = n-l;
    while(l<n)
    {
        *c = *(str+l);
        l++;
        c++;
    }
    *c='\0';
    return c-len;
}

int printAlpha(char* str, char* word)
{
    char *sub;
    char* ch;
    int n = strlen(str);
    if(n == 0)
    {
        printf("%s",word);
    }
    else
    {

     sub = substr(str,0,1);
     int num = atoi(sub);
     str = substr(str,1,n);
     ch = 'A'+(num-1);
     printAlpha(str, strcat(word, ch));
     sub = substr(str,0,2);
     num = atoi(sub);
     if(strlen(str)>=2 && num <= 26)
     {
         str = substr(str,2,n);
         ch = 'A'+(num-1);
         printAlpha( str, strcat(word, ch) );
     }
    }
    return 0;
}

int main()
{
    char* str;
    char* word = '\0';
    scanf("%s",str);
    printAlpha(str,word);

    return 0;
}

thanks in advance.


问:
First value of my PHP Array is returned as 'null' when it has a value
I'd really like some help with the following MySQL / PHP problem (maybe bug?)

I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.

So, even though the database has the following info:

```<code>"Example 1", "Example 2", "Example 3"...
</code>```

The php echos out:

```<code>"null", "Example 2, "Example 3"
</code>```

I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.

My PHP

```<code>/* If connection to database, run sql statement. */
if ($conn) {
    $fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");

    // declare empty array to fill later
    $result = array();

    // make sure the MySQL pointer is looking at the first row
    mysql_data_seek($fetch, 0);

    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {

        foreach ($row as $value) {

            $row_array = $value;

            // push info into new array with just the value
            array_push($result, $row_array);
        }
    }
}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);
</code>```

UPDATE

New code courtesy of Mark B:

```<code>if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());

$result = array();
while ($row = mysql_fetch_assoc($query)) {
    $result[] = $row['column_name'];

}

}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);
</code>```

NOTE:

The 'null' problem still occurs with or without the:

```<code> mysql_data_seek($fetch, 0);
</code>```

as that appears to do nothing.

Any help would be great!

SOLVED

Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.

答:
```<code>$sql = "SELECT column FROM table WHERE approved = '1'";
$result = mysql_query($sql) or die(mysql_error());

$data = array();
while($row = mysql_fetch_assoc($result)) {
    $data[] = $row['column'];
}

echo json_encode($data);
</code>```

You shouldn't have to do the seek, as you've not done anything with the result at the time. And since you're only fetching a single column from the database, there's no need for the inner foreach() loop either.

Body:
I'd really like some help with the following MySQL / PHP problem (maybe bug?)

I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.

So, even though the database has the following info:

"Example 1", "Example 2", "Example 3"...

The php echos out:

"null", "Example 2, "Example 3"

I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.

My PHP

/* If connection to database, run sql statement. */
if ($conn) {
    $fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");

    // declare empty array to fill later
    $result = array();

    // make sure the MySQL pointer is looking at the first row
    mysql_data_seek($fetch, 0);

    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {

        foreach ($row as $value) {

            $row_array = $value;

            // push info into new array with just the value
            array_push($result, $row_array);
        }
    }
}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);

UPDATE

New code courtesy of Mark B:

if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());

$result = array();
while ($row = mysql_fetch_assoc($query)) {
    $result[] = $row['column_name'];

}

}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);

NOTE:

The 'null' problem still occurs with or without the:

 mysql_data_seek($fetch, 0);

as that appears to do nothing.

Any help would be great!

SOLVED

Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.

Body:
$sql = "SELECT column FROM table WHERE approved = '1'";
$result = mysql_query($sql) or die(mysql_error());

$data = array();
while($row = mysql_fetch_assoc($result)) {
    $data[] = $row['column'];
}

echo json_encode($data);

You shouldn't have to do the seek, as you've not done anything with the result at the time. And since you're only fetching a single column from the database, there's no need for the inner foreach() loop either.


问:
Represent Mysql raw query with Typeorm QueryBuilder
I want to represent below mysql sql query with typeorm query builder:

SELECT
  new_rec.*
FROM (SELECT Replace(Replace(Replace(Json_extract(industries, '$[*].id'), '[', ''), ']', ''), ' ', '') AS ids,
  recruiter.*
FROM recruiter.recruiter) new_rec
WHERE Find_in_set('14', new_rec.ids) > 0 AND Find_in_set('16', new_rec.ids) > 0;
```

Could anyone expertise in typeorm help me?

答:
```<code>const subQuery = connection
            .createQueryBuilder()
            .select(`
                REPLACE(
                    REPLACE(
                        REPLACE(
                            JSON_EXTRACT(recruiter.industries, '$[*].id'),
                            '[',
                            ''
                        ),
                        ']',
                        ''
                    ),
                    ' ',
                    ''
                ) AS ids,
                recruiter.*
            `)
            .from('recruiter', 'recruiter');
        const selectQuery = this.connection
            .createQueryBuilder()
            .select('*')
            .from('(' + subQuery.getQuery() + ')', 'recruiter');
        selectQuery.getRawMany();
</code>```

With this query, you would get the same result as mysql query.

Body:
I want to represent below mysql sql query with typeorm query builder:

SELECT
  new_rec.*
FROM (SELECT Replace(Replace(Replace(Json_extract(industries, '$[*].id'), '[', ''), ']', ''), ' ', '') AS ids,
  recruiter.*
FROM recruiter.recruiter) new_rec
WHERE Find_in_set('14', new_rec.ids) > 0 AND Find_in_set('16', new_rec.ids) > 0;

Could anyone expertise in typeorm help me?

Body:
const subQuery = connection
            .createQueryBuilder()
            .select(`
                REPLACE(
                    REPLACE(
                        REPLACE(
                            JSON_EXTRACT(recruiter.industries, '$[*].id'),
                            '[',
                            ''
                        ),
                        ']',
                        ''
                    ),
                    ' ',
                    ''
                ) AS ids,
                recruiter.*
            `)
            .from('recruiter', 'recruiter');
        const selectQuery = this.connection
            .createQueryBuilder()
            .select('*')
            .from('(' + subQuery.getQuery() + ')', 'recruiter');
        selectQuery.getRawMany();

With this query, you would get the same result as mysql query.


问:
How to pass uncertain parameters to preparedQuery while using reactive-postgresql-client?
Anyone has idea how to pass uncertain parameters to client.preparedQuery? Pls look at the image below, appreciate any help!

```<code>@Override
public Future<List<User>> getByIds(List<String> ids) {
    Promise<List<User>> promise = Promise.promise();
    // How to pass the uncertain parameters to preparedQuery?
    pool.preparedQuery("SELECT * FROM users WHERE id IN ($1)", Tuple.wrap(ids.toArray()), ar -> {
        if (ar.succeeded()) {
            RowSet<Row> rows = ar.result();
            List<User> users = new ArrayList<>();
            for (Row row : rows) {
                User user = User.fromDatabaseRow(row);
                users.add(user);
            }
            promise.complete(users);
        } else {
            promise.fail(ar.cause());
        }
    });
    return promise.future();
}
</code>```

答:
To passe an array to PostgreSQL then you have to use = ANY(params) instead of IN(params)

```<code>SELECT * FROM users WHERE id = ANY($1)
</code>```

Also, you have to passe an array of String to ANY, your code should be :

```<code>pool.preparedQuery(
        "SELECT * FROM users WHERE id = ANY($1)",
        Tuple.of(ids.toArray(String[]::new)),
        ar -> {..}
)
</code>```

Body:
Anyone has idea how to pass uncertain parameters to client.preparedQuery? Pls look at the image below, appreciate any help!

@Override
public Future<List<User>> getByIds(List<String> ids) {
    Promise<List<User>> promise = Promise.promise();
    // How to pass the uncertain parameters to preparedQuery?
    pool.preparedQuery("SELECT * FROM users WHERE id IN ($1)", Tuple.wrap(ids.toArray()), ar -> {
        if (ar.succeeded()) {
            RowSet<Row> rows = ar.result();
            List<User> users = new ArrayList<>();
            for (Row row : rows) {
                User user = User.fromDatabaseRow(row);
                users.add(user);
            }
            promise.complete(users);
        } else {
            promise.fail(ar.cause());
        }
    });
    return promise.future();
}

Body:
To passe an array to PostgreSQL then you have to use = ANY(params) instead of IN(params)

SELECT * FROM users WHERE id = ANY($1)

Also, you have to passe an array of String to ANY, your code should be :

pool.preparedQuery(
        "SELECT * FROM users WHERE id = ANY($1)",
        Tuple.of(ids.toArray(String[]::new)),
        ar -> {..}
)


问:
How to prevent Maven from compiling classes in src/test/java, which are generated during the generate-sources phase?
In our jOOQ integration tests, we're using the jOOQ code generation plugin to generate classes into the src/test/java directory. We're doing that because:

We want to check in generated sources, so we can detect regressions in the code generator more easily

The generated classes are used by the tests

So, the (simplified) plugin configuration looks like this:

<plugin>
  <groupId>org.jooq</groupId>
  <artifactId>jooq-codegen-maven</artifactId>
  <executions>
    <execution>
      <id>some-id</id>
      <phase>generate-sources</phase>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <generator>
          <target>
            <directory>src/test/java</directory>
          </target>
        </generator>
      </configuration>
    </execution>
  </executions>
</plugin>
```

<p>Unfortunately, this seems to lead Maven to believe that the classes thus generated need to be compiled as well during the <code>compile</code> phase, as can be seen in the following log output:</p>

<pre class="lang-none prettyprint-override"><code>[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ ... ---
[INFO] Compiling 25 source files to C:\...\target\classes
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ ... ---
[INFO] Compiling 25 source files to C:\...\target\test-classes
</code>```

... which makes no sense at all. Debug output hints at both src/main/java and src/test/java being included as compileSourceRoots:

[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile' with basic configurator -->
[DEBUG]   (f) compileSourceRoots = [C:\...\src\main\java, C:\...\src\test\java]
```

<p>For the record, during the <code>testCompile</code> phase, as expected, only <code>src/test/java</code> is placed on the <code>compileSourceRoots</code> path:</p>

<pre class="lang-none prettyprint-override"><code>[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-compiler-plugin:3.8.1:testCompile' with basic configurator -->
[DEBUG]   (f) compileSourceRoots = [C:\...\src\test\java]
</code>```

For the record, we're using Maven 3.6.2

How can I prevent the src/test/java directory from being added to the compileSourceRoots variable?

答:
A workaround (not very pretty) is to exclude the test classes from the compiler plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <excludes>
            <exclude>com/example/test/**/*.java</exclude>
        </excludes>
    </configuration>
</plugin>
```

<p>Another is to use the <code>generate-test-sources</code> phase, which we avoided so far, because of some unrelated side effects that we wanted to test already before the <code>compile</code> phase:</p>

<pre class="lang-xml prettyprint-override"><code><phase>generate-test-sources</phase>
</code>```

I'm definitely hoping for a better solution!

Body:
In our jOOQ integration tests, we're using the jOOQ code generation plugin to generate classes into the src/test/java directory. We're doing that because:

We want to check in generated sources, so we can detect regressions in the code generator more easily

The generated classes are used by the tests

So, the (simplified) plugin configuration looks like this:

<plugin>
  <groupId>org.jooq</groupId>
  <artifactId>jooq-codegen-maven</artifactId>
  <executions>
    <execution>
      <id>some-id</id>
      <phase>generate-sources</phase>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <generator>
          <target>
            <directory>src/test/java</directory>
          </target>
        </generator>
      </configuration>
    </execution>
  </executions>
</plugin>

Unfortunately, this seems to lead Maven to believe that the classes thus generated need to be compiled as well during the compile phase, as can be seen in the following log output:

[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ ... ---
[INFO] Compiling 25 source files to C:\...\target\classes
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ ... ---
[INFO] Compiling 25 source files to C:\...\target\test-classes

... which makes no sense at all. Debug output hints at both src/main/java and src/test/java being included as compileSourceRoots:

[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile' with basic configurator -->
[DEBUG]   (f) compileSourceRoots = [C:\...\src\main\java, C:\...\src\test\java]

For the record, during the testCompile phase, as expected, only src/test/java is placed on the compileSourceRoots path:

[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-compiler-plugin:3.8.1:testCompile' with basic configurator -->
[DEBUG]   (f) compileSourceRoots = [C:\...\src\test\java]

For the record, we're using Maven 3.6.2

How can I prevent the src/test/java directory from being added to the compileSourceRoots variable?

Body:
A workaround (not very pretty) is to exclude the test classes from the compiler plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <excludes>
            <exclude>com/example/test/**/*.java</exclude>
        </excludes>
    </configuration>
</plugin>

Another is to use the generate-test-sources phase, which we avoided so far, because of some unrelated side effects that we wanted to test already before the compile phase:

<phase>generate-test-sources</phase>

I'm definitely hoping for a better solution!


问:
MongoDB: How to update field of array element depending on other field?
I am trying to update data in my MongoDB (4.2) by using update with a pipeline. The difficulty is that I want to add a field to an array element depending on another field. Also I want to do this for each element. I know I could do by Javascript for each but I was wondering if there is a better way. So this is what I want to do as an example

Before:

```<code>{
    "_id" : ObjectId("555555555"),
    "messages" : [
        {
            "author" : {
                "userId" : "12345",
                "name" : "John"
            },
            "text" : "Any text",
        },
        {
            "author" : {
                "userId" : "56789",
                "name" : "Jim"
            },
            "text" : "also text"
        }
    ]
}
</code>```

After

```<code>{
    "_id" : ObjectId("555555555"),
    "messages" : [
        {
            "author" : {
                "userId" : "12345",
                "name" : "John",
                "newId" : "00012345"
            },
            "text" : "Any text",
        },
        {
            "author" : {
                "userId" : "56789",
                "name" : "Jim",
                "newId" : "00056789"
            },
            "text" : "also text"
        }
    ]
}
</code>```

What I tried:

```<code>db.mail.update(
   {"_id" : ObjectId("555555555")},
  [{ $set: { "messages.$[].author.newId": { $concat: [ "000", "$messages.$[].author.userId"]}}}],
  { multi: true, writeConcern: {w: 0} }
)
</code>```

Does anybody know how to solve this?
Thank you

答:
This will do the required update.

```<code>db.test.update(
  { _id : ObjectId("555555555") },
  [
    {
      $set: {
          messages: {
              $map: {
                   input: "$messages",
                   in: {
                       $mergeObjects: [
                           "$$this",
                           { "author": {
                                  $mergeObjects: [
                                       "$$this.author",
                                       { newId: { $concat: [ "000", "$$this.author.userId"] } }
                                   ]
                           } }
                       ]
                   }
              }
          }
      }
    }
  ],
  { multi: true, writeConcern: {w: 0} }
)
</code>```

Note that the all positional operator $[] for array updates is to be used with update operations when not using the aggregation. You have to use aggregation to update when a field value depends upon another field in the document.

Body:
I am trying to update data in my MongoDB (4.2) by using update with a pipeline. The difficulty is that I want to add a field to an array element depending on another field. Also I want to do this for each element. I know I could do by Javascript for each but I was wondering if there is a better way. So this is what I want to do as an example

Before:

{
    "_id" : ObjectId("555555555"),
    "messages" : [
        {
            "author" : {
                "userId" : "12345",
                "name" : "John"
            },
            "text" : "Any text",
        },
        {
            "author" : {
                "userId" : "56789",
                "name" : "Jim"
            },
            "text" : "also text"
        }
    ]
}

After

{
    "_id" : ObjectId("555555555"),
    "messages" : [
        {
            "author" : {
                "userId" : "12345",
                "name" : "John",
                "newId" : "00012345"
            },
            "text" : "Any text",
        },
        {
            "author" : {
                "userId" : "56789",
                "name" : "Jim",
                "newId" : "00056789"
            },
            "text" : "also text"
        }
    ]
}

What I tried:

db.mail.update(
   {"_id" : ObjectId("555555555")},
  [{ $set: { "messages.$[].author.newId": { $concat: [ "000", "$messages.$[].author.userId"]}}}],
  { multi: true, writeConcern: {w: 0} }
)

Does anybody know how to solve this?
Thank you

Body:
This will do the required update.

db.test.update(
  { _id : ObjectId("555555555") },
  [
    {
      $set: {
          messages: {
              $map: {
                   input: "$messages",
                   in: {
                       $mergeObjects: [
                           "$$this",
                           { "author": {
                                  $mergeObjects: [
                                       "$$this.author",
                                       { newId: { $concat: [ "000", "$$this.author.userId"] } }
                                   ]
                           } }
                       ]
                   }
              }
          }
      }
    }
  ],
  { multi: true, writeConcern: {w: 0} }
)

Note that the all positional operator $[] for array updates is to be used with update operations when not using the aggregation. You have to use aggregation to update when a field value depends upon another field in the document.


问:
how to change net core router prefix
I have net core app which was deployed on linux,how can I change router api prefix by config.
it's like this https://localhost/api/index --> https://localhost/appName/api/index.
How can I add appname to router and don't change code.</p>

答: Inside your StartUp Configuration file change the routing to add your AppName. There are several ways to do it (depending on you'r app being an web API or MVC). You can find all of them here

Title: how to change net core router prefix


问:
Parsing specific region of a txt, comparing to list of strings, then generating new list composed of matches
I am trying to do the following:

Read through a specific portion of a text file (there is a known starting point and ending point)

While reading through these lines, check to see if a word matches a word that I have included in a list

If a match is detected, then add that specific word to a new list

I have been able to read through the text and grab other data from it that I need, but I've been unable to do the above mentioned thus far.

I have tried to implement the following example: Python - Search Text File For Any String In a List
But I have failed to make it read correctly.

I have also tried to adapt the following: https://www.geeksforgeeks.org/python-finding-strings-with-given-substring-in-list/
But I was equally unsuccessful.

Here is some of my code:

```<code>import re
from itertools import islice
import os

# list of all countries
oneCountries = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua & Deps, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina, Burma, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Central African Rep, Chad, Chile, China, Republic of China, Colombia, Comoros, Democratic Republic of the Congo, Republic of the Congo, Costa Rica,, Croatia, Cuba, Cyprus, Czech Republic, Danzig, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Fiji, Finland, France, Gabon, Gaza Strip, The Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Holy Roman Empire, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Republic of Ireland, Israel, Italy, Ivory Coast, Jamaica, Japan, Jonathanland, Jordan, Kazakhstan, Kenya, Kiribati, North Korea, South Korea, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mount Athos, Mozambique, Namibia, Nauru, Nepal, Newfoundland, Netherlands, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Ottoman Empire, Pakistan, Palau, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Prussia, Qatar, Romania, Rome, Russian Federation, Rwanda, St Kitts & Nevis, St Lucia, Saint Vincent & the Grenadines, Samoa, San Marino, Sao Tome & Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, Spain, Sri Lanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Tajikistan, Tanzania, Thailand, Togo, Tonga, Trinidad & Tobago, Tunisia, Turkey, Turkmenistan, Tuvalu, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe"
countries = oneCountries.split(",")

path = "C:/Users/me/Desktop/read.txt"
thefile = open(path, errors='ignore')

countryParsing = False
for line in thefile:
    line = line.strip()
#    if line.startswith("Submitting Author:"):
#    if re.match(r"Submitting Author:", line):
#        print("blahblah1")
#        countryParsing = True
#        if countryParsing == True:
#            print("blahblah2")
#
#            res = [x for x in line if re.search(countries, x)]
#            print("blah blah3: " + str(res))
#    elif re.match(r"Running Head:", line):
#        countryParsing = False
#    if countryParsing == True:
#        res = [x for x in line if re.search(countries, x)]
#        print("blah blah4: " + str(res))

#        for x in countries:
#            if x in thefile:
#                print("a country is: " + x)
#        if any(s in line for s in countries):
#            listOfAuthorCountries = listOfAuthorCountries + s + ", "
#    if re.match(f"Submitting Author:, line"):
</code>```

The #commented out lines are versions of the code that I've tried and failed to make work properly.

As requested, this is an example of the text file that I'm trying to grab the data from.  I've modified it to remove sensitive information, but in this particular case, the "new list" should be appended with a certain number of "France" entries:

```<code>    txt above....
Submitting Author:

    asdf, asdf  (proxy)
    France
    asdfasdf
    blah blah
    asdfasdf

    asdf, Provence-Alpes-Côte d'Azu 13354
    France

    blah blah
    France
    asdf
Running Head:
    ...more text below
</code>```

答:
Based on the three points you stated on what you want to accomplish and what I understand from your code (which may not be what you intended), I propose:

```<code># list of all countries
countries = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua & Deps, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina, Burma, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Central African Rep, Chad, Chile, China, Republic of China, Colombia, Comoros, Democratic Republic of the Congo, Republic of the Congo, Costa Rica, Croatia, Cuba, Cyprus, Czech Republic, Danzig, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Fiji, Finland, France, Gabon, Gaza Strip, The Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Holy Roman Empire, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Republic of Ireland, Israel, Italy, Ivory Coast, Jamaica, Japan, Jonathanland, Jordan, Kazakhstan, Kenya, Kiribati, North Korea, South Korea, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mount Athos, Mozambique, Namibia, Nauru, Nepal, Newfoundland, Netherlands, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Ottoman Empire, Pakistan, Palau, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Prussia, Qatar, Romania, Rome, Russian Federation, Rwanda, St Kitts & Nevis, St Lucia, Saint Vincent & the Grenadines, Samoa, San Marino, Sao Tome & Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, Spain, Sri Lanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Tajikistan, Tanzania, Thailand, Togo, Tonga, Trinidad & Tobago, Tunisia, Turkey, Turkmenistan, Tuvalu, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe"
countries = countries.split(",")
countries = [c.strip() for c in countries]

filename = "read.txt"
filehandle = open(filename, errors='ignore')
my_other_list = []
toParse = False
for line in filehandle:
    line = line.strip()
    if line.startswith("Submitting Author:"):
        toParse = True
        continue
    elif line.startswith("Running Head:"):
        toParse = False
        continue
    elif toParse:
        for c in countries:
            if c in line:
                my_other_list.append(c)
</code>```

EDIT SUMMARY

Adapted code to work on the text sample provided.

Fixed the list of countries (originally there were two commas after Costa Rica).

Body:
I am trying to do the following:

Read through a specific portion of a text file (there is a known starting point and ending point)

While reading through these lines, check to see if a word matches a word that I have included in a list

If a match is detected, then add that specific word to a new list

I have been able to read through the text and grab other data from it that I need, but I've been unable to do the above mentioned thus far.

I have tried to implement the following example: Python - Search Text File For Any String In a List
But I have failed to make it read correctly.

I have also tried to adapt the following: https://www.geeksforgeeks.org/python-finding-strings-with-given-substring-in-list/
But I was equally unsuccessful.

Here is some of my code:

import re
from itertools import islice
import os

# list of all countries
oneCountries = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua & Deps, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina, Burma, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Central African Rep, Chad, Chile, China, Republic of China, Colombia, Comoros, Democratic Republic of the Congo, Republic of the Congo, Costa Rica,, Croatia, Cuba, Cyprus, Czech Republic, Danzig, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Fiji, Finland, France, Gabon, Gaza Strip, The Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Holy Roman Empire, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Republic of Ireland, Israel, Italy, Ivory Coast, Jamaica, Japan, Jonathanland, Jordan, Kazakhstan, Kenya, Kiribati, North Korea, South Korea, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mount Athos, Mozambique, Namibia, Nauru, Nepal, Newfoundland, Netherlands, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Ottoman Empire, Pakistan, Palau, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Prussia, Qatar, Romania, Rome, Russian Federation, Rwanda, St Kitts & Nevis, St Lucia, Saint Vincent & the Grenadines, Samoa, San Marino, Sao Tome & Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, Spain, Sri Lanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Tajikistan, Tanzania, Thailand, Togo, Tonga, Trinidad & Tobago, Tunisia, Turkey, Turkmenistan, Tuvalu, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe"
countries = oneCountries.split(",")

path = "C:/Users/me/Desktop/read.txt"
thefile = open(path, errors='ignore')

countryParsing = False
for line in thefile:
    line = line.strip()
#    if line.startswith("Submitting Author:"):
#    if re.match(r"Submitting Author:", line):
#        print("blahblah1")
#        countryParsing = True
#        if countryParsing == True:
#            print("blahblah2")
#
#            res = [x for x in line if re.search(countries, x)]
#            print("blah blah3: " + str(res))
#    elif re.match(r"Running Head:", line):
#        countryParsing = False
#    if countryParsing == True:
#        res = [x for x in line if re.search(countries, x)]
#        print("blah blah4: " + str(res))

#        for x in countries:
#            if x in thefile:
#                print("a country is: " + x)
#        if any(s in line for s in countries):
#            listOfAuthorCountries = listOfAuthorCountries + s + ", "
#    if re.match(f"Submitting Author:, line"):

The #commented out lines are versions of the code that I've tried and failed to make work properly.

As requested, this is an example of the text file that I'm trying to grab the data from.  I've modified it to remove sensitive information, but in this particular case, the "new list" should be appended with a certain number of "France" entries:

    txt above....
Submitting Author:

    asdf, asdf  (proxy)
    France
    asdfasdf
    blah blah
    asdfasdf

    asdf, Provence-Alpes-Côte d'Azu 13354
    France

    blah blah
    France
    asdf
Running Head:
    ...more text below

Body:
Based on the three points you stated on what you want to accomplish and what I understand from your code (which may not be what you intended), I propose:

# list of all countries
countries = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua & Deps, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina, Burma, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Central African Rep, Chad, Chile, China, Republic of China, Colombia, Comoros, Democratic Republic of the Congo, Republic of the Congo, Costa Rica, Croatia, Cuba, Cyprus, Czech Republic, Danzig, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Fiji, Finland, France, Gabon, Gaza Strip, The Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Holy Roman Empire, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Republic of Ireland, Israel, Italy, Ivory Coast, Jamaica, Japan, Jonathanland, Jordan, Kazakhstan, Kenya, Kiribati, North Korea, South Korea, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mount Athos, Mozambique, Namibia, Nauru, Nepal, Newfoundland, Netherlands, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Ottoman Empire, Pakistan, Palau, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Prussia, Qatar, Romania, Rome, Russian Federation, Rwanda, St Kitts & Nevis, St Lucia, Saint Vincent & the Grenadines, Samoa, San Marino, Sao Tome & Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, Spain, Sri Lanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Tajikistan, Tanzania, Thailand, Togo, Tonga, Trinidad & Tobago, Tunisia, Turkey, Turkmenistan, Tuvalu, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe"
countries = countries.split(",")
countries = [c.strip() for c in countries]

filename = "read.txt"
filehandle = open(filename, errors='ignore')
my_other_list = []
toParse = False
for line in filehandle:
    line = line.strip()
    if line.startswith("Submitting Author:"):
        toParse = True
        continue
    elif line.startswith("Running Head:"):
        toParse = False
        continue
    elif toParse:
        for c in countries:
            if c in line:
                my_other_list.append(c)

EDIT SUMMARY

Adapted code to work on the text sample provided.

Fixed the list of countries (originally there were two commas after Costa Rica).


问:
Why can this constructor declared with two parameters be called with just one?
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

```<code>Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}
</code>```

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...

答:
When you do this:

```<code>Rational r(42);
</code>```

...the default value of 1 is supplied to the parameter bottom, because your constructor has default values for the bottom parameter.  (That's that the =1 is about)

If you were to change the declaration of th constructor to not include any defaults:

```<code>Rational(int top, int bottom)
</code>```

...then you would no longer be able to construct a Rational object without specifying both parameters explicitly.

Body:
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...

Body:
When you do this:

Rational r(42);

...the default value of 1 is supplied to the parameter bottom, because your constructor has default values for the bottom parameter.  (That's that the =1 is about)

If you were to change the declaration of th constructor to not include any defaults:

Rational(int top, int bottom)

...then you would no longer be able to construct a Rational object without specifying both parameters explicitly.


问:
How to remove duplicate values from a multi-dimensional array in PHP
How can I remove duplicate values from a multi-dimensional array in PHP?

Example array:

```<code>Array
(
    [0] => Array
    (
        [0] => abc
        [1] => def
    )

    [1] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [2] => Array
    (
        [0] => mno
        [1] => pql
    )

    [3] => Array
    (
        [0] => abc
        [1] => def
    )

    [4] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [5] => Array
    (
        [0] => mno
        [1] => pql
    )

)
</code>```

答:
Based on the Answer marked as correct, adding my answer. Small code added just to reset the indices-</p>

```<code>$input = array_values(array_map("unserialize", array_unique(array_map("serialize", $inputArray))));
</code>```

OwnerDisplayName: Ian Cook

Body:
How can I remove duplicate values from a multi-dimensional array in PHP?

Example array:

Array
(
    [0] => Array
    (
        [0] => abc
        [1] => def
    )

    [1] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [2] => Array
    (
        [0] => mno
        [1] => pql
    )

    [3] => Array
    (
        [0] => abc
        [1] => def
    )

    [4] => Array
    (
        [0] => ghi
        [1] => jkl
    )

    [5] => Array
    (
        [0] => mno
        [1] => pql
    )

)

Body:
Based on the Answer marked as correct, adding my answer. Small code added just to reset the indices-

$input = array_values(array_map("unserialize", array_unique(array_map("serialize", $inputArray))));


问:
Configure Istio Ingress Gateway to require header token using Authorization Policy
I configured Istio Ingress Gateway to accept my URLs (using https) like microservices.myexample.com, grafana.myexample.com and so on.

Everything is working but all the urls are public.

Beacause of that I was asked to configure ingress gateway to protect urls inside  microservices.myexample.com (Grafana has a login page). The idea is allow acess only if the request contains a token inside the header.

But when I applied this yml file all the URLs are blocked and they require the header including grafana.myexample.com:

```<code>apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
 name: ingress
 namespace: istio-system
spec:
 selector:
   matchLabels:
     app: istio-ingressgateway
 rules:
 - from: []
   to:
    - operation:
        #paths: ["/customers*"] # I also tried with paths. Every microservice has a path after microservices.myexample.com
        hosts: ["microservices.myexample.com"]
   when:
    - key: request.headers[token]
      values: ["test123"]

</code>```

答:
We did it.

Just in case if someone is stuck at the same problem. The following code will be applied to all services in mynamespace. All the urls will require the token except the ones ending with /actuator/health

```<code>apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: token-authorization
  namespace: mynamespace
spec:
  rules:
  - to:
    - operation:
        paths: ["*/actuator/health"]
  - to:
    - operation:
        paths: ["/*"]
    when:
    - key: request.headers[token]
      values: ["test123"]
</code>```

Body:
I configured Istio Ingress Gateway to accept my URLs (using https) like microservices.myexample.com, grafana.myexample.com and so on.

Everything is working but all the urls are public.

Beacause of that I was asked to configure ingress gateway to protect urls inside  microservices.myexample.com (Grafana has a login page). The idea is allow acess only if the request contains a token inside the header.

But when I applied this yml file all the URLs are blocked and they require the header including grafana.myexample.com:

apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
 name: ingress
 namespace: istio-system
spec:
 selector:
   matchLabels:
     app: istio-ingressgateway
 rules:
 - from: []
   to:
    - operation:
        #paths: ["/customers*"] # I also tried with paths. Every microservice has a path after microservices.myexample.com
        hosts: ["microservices.myexample.com"]
   when:
    - key: request.headers[token]
      values: ["test123"]

Body:
We did it.

Just in case if someone is stuck at the same problem. The following code will be applied to all services in mynamespace. All the urls will require the token except the ones ending with /actuator/health

apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: token-authorization
  namespace: mynamespace
spec:
  rules:
  - to:
    - operation:
        paths: ["*/actuator/health"]
  - to:
    - operation:
        paths: ["/*"]
    when:
    - key: request.headers[token]
      values: ["test123"]


问:
VSCode + WSL Remote + Git : Synchronizing changes take forever
I'm using VSCode remotly into my project folder located (symlink) into WSL 2 VM. I cloned my repo from Bitbucket using SSH and the terminal.

On the bottom left corner, it indicate WSL: Ubuntu, so I'm currently using it remotly. ALL GOOD

If I click the Git branch indicator, I can see local branchs and remote one. ALL GOOD

The problem is that when I click to synchronize everything after a local commit, it spins forever. Well, not really, I lose patience before forever happen... Currently about 30 minutes on the current test.

If I do git push into the terminal, everything goes as expected.

Any one got an idea on why it's doing this? How can I solve that problem?

My Git output into VSCode constantly return this git rev-parse --show-toplevel?

I did git config for both user.name and user.email

SSH key is set on Bitbucket. Windows and WSL 2 are using the same public/private key.

Thank you

答: Rather would just do push and pull from the command line than removing the passphrase!</p>


答:
Group using the dataframe's levels instead:</p>

```<code>df.groupby(level=[0,1,2]).amount.sum()

    date        id  type
2012-01-06  1   a        2
                b       12
2012-02-06  2   a        7
            3   b        3
2012-03-06  5   b        3
Name: amount, dtype: int64
</code>```

Title: How to turn a grouped df with hierarchical index back to a df with multi level index

Body:
My Dataframe:

df = pd.DataFrame([["2012-01-06",1,"a",2],["2012-01-06",1,"b",3],["2012-01-06",1,"b",4],["2012-01-06",1,"b",5],["2012-02-06",2,"a",3],["2012-02-06",2,"a",4],["2012-02-06",3,"b",3],["2012-03-06",5,"b",3]],columns=["date","id","type", "amount"])
df = df.set_index(["date","id","type"])
df

results in:

                    amount
date       id type
2012-01-06 1  a          2
              b          3
              b          4
              b          5
2012-02-06 2  a          3
              a          4
           3  b          3
2012-03-06 5  b          3

After I perform grouping

gr = df.groupby(df.index).agg({'amount':sum})
gr

I get:

                    amount
(2012-01-06, 1, a)       2
(2012-01-06, 1, b)      12
(2012-02-06, 2, a)       7
(2012-02-06, 3, b)       3
(2012-03-06, 5, b)       3

What do I need to turn gr into the same structure as my original df, i.e.

                    amount
date       id type
2012-01-06 1  a          2
              b         12
2012-02-06 2  a          7
           3  b          3
2012-03-06 5  b          3

Body:
Group using the dataframe's levels instead:

df.groupby(level=[0,1,2]).amount.sum()

    date        id  type
2012-01-06  1   a        2
                b       12
2012-02-06  2   a        7
            3   b        3
2012-03-06  5   b        3
Name: amount, dtype: int64


问:
Python-My string variable won't add up into one string
I seem to be having issues adding a String together.

I wrote a function which I keep calling up to decode or encode a string.

The issue is when I print the result it only works to print one char out, not the whole code.

Outside of the function this method work though by adding letter after letter.

Here I use numbers.

```<code>def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return
</code>```

For example if I put in: 01

I expect the result: 3

                     34

But it only prints: 3

                    4

So basically results after replaying deletes/overrides what was in the string before.

I want to print result in one string, not multiple line after line.

This is only part of my code cut short. Why won't result add up?

This is how I defined entered.

entered = input("Please type something.")

答:
Actually your code is right but only one problem that after passing the first nested if clause the code further goes to the next one, it goes into the nested else clause.

To stop this you have to return the program

You should make your code like this.

```<code>def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
      return
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
      return
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return
</code>```

Body:
I seem to be having issues adding a String together.

I wrote a function which I keep calling up to decode or encode a string.

The issue is when I print the result it only works to print one char out, not the whole code.

Outside of the function this method work though by adding letter after letter.

Here I use numbers.

def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return

For example if I put in: 01

I expect the result: 3

                     34

But it only prints: 3

                    4

So basically results after replaying deletes/overrides what was in the string before.

I want to print result in one string, not multiple line after line.

This is only part of my code cut short. Why won't result add up?

This is how I defined entered.

entered = input("Please type something.")

Body:
Actually your code is right but only one problem that after passing the first nested if clause the code further goes to the next one, it goes into the nested else clause.

To stop this you have to return the program

You should make your code like this.

def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
      return
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
      return
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return


问:
How to configure IPython to use gvim on Windows?
This really looks like something I should be able to find on Google, but for some reason I can't make heads or tails of it. There's the EDITOR environment variable, the ipy_user_conf.py file, the ipythonrc file, some weird thing about running gvim in server mode and a bunch of other stuff I can't wrap my head around (probably because of lack of sleep).

Is there a guide somewhere I can follow, or maybe someone can just outline the steps I need to take?

答:
edit file - C:\Users\[your username]\_ipython\ipythonrc.ini

replace line: editor 0 to editor gvim –f (or editor [whatever editor you_want to use and system recognize it])

save file

You may have problem that your Win doesn't recognize gvim as a command, you can fix it like this:

Control Panel -> System -> Advances system settings (System properties - Advanced tab) -> Enviroment Variables

In system variables edit Path and add this: ;C:\Program Files\Vim\vim73\ or path that leads to your gvim.exe

OwnerDisplayName: gooli