text:
Q: Where and Group By Using Moongose API MongoDB I have written an aggregation function which will count the Message. Based on Message Status.
exports.countRecords = function(req, res) {
Message.aggregate([{
    $group: {
        _id: "$message_status",
        count: {
            $sum: 1
        }
    }
}, {
    $sort: {
        _id: 1
    }
}], function(err, result) {
    if (err) {
        console.log(err);
        return;
    }
    console.log(result);
    res.jsonp(result);
});
};

Now i need to add a condition to count only when the channel_message_ID and channel_thread_Id are equal so i have modified the logic like below:
Message.aggregate([{
   $match: {
        channel_message_ID: { $eq: ["$channel_message_ID", "$channel_thread_Id"]}
    }},
    {$group: {
        _id: "$message_status",
        count: {
            $sum: 1
        }
    },

}, {
    $sort: {
        _id: 1
    }
}], function(err, result) {
    if (err) {
        console.log(err);
        return;
    }
    console.log(result);
    res.jsonp(result);
});

};
It is not at all working. Thanks in Advance.

A: try below solution:
$project:
Message.aggregate([{
{"$project": {
      "channel_message_ID":1,
      "channel_thread_Id":1,
      "message_status": 1,
      "cond": {"$eq":["$channel_message_ID","$channel_thread_Id"]}
    }
  },
  {"$match":{"cond": true}},
    {$group: {
        _id: "$message_status",
        count: {
            $sum: 1
        }
    },

}, {
    $sort: {
        _id: 1
    }
}], function(err, result) {
    if (err) {
        console.log(err);
        return;
    }
    console.log(result);
    res.jsonp(result);
});

A: You'll need to add a new field to the document at the first stage of the aggregation pipeline, this can be done by using the [$addFields]
(https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/) stage
{ "$addFields" : { "idMatch" : { "$eq" : [ "$channel_message_ID" , "$channel_thread_Id" ] } } }

This will create us a new field on the documents flowing through the pipeline telling us if there is a match on the 2 fields. We can then push this in to a $match stage
{ $match: { "idMatch" : true } }

Then you can run the rest of the $group:
{ "$group" : { "_id" : "$message_status", "count" : { "$sum" : 1 } } }

then sort stage:
{ "$sort" : { "_id" : 1 } }

So for example if we add the following documents to a mongodb collection:
db.test.insertMany([{
    message_status: "In Progress",
    channel_thread_Id: "A",
    channel_message_ID: "A"
},
{
    message_status: "Completed",
    channel_thread_Id: "A",
    channel_message_ID: "A"
},
{
    message_status: "In Progress",
    channel_thread_Id: "A",
    channel_message_ID: "B"
},
{
    message_status: "Completed",
    channel_thread_Id: "A",
    channel_message_ID: "B"
}]);

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("599abef4f0cd60f52d67215a"),
                ObjectId("599abef4f0cd60f52d67215b"),
                ObjectId("599abef4f0cd60f52d67215c"),
                ObjectId("599abef4f0cd60f52d67215d")
        ]
}

We can then run the following aggregation query:
db.test.aggregate([
   { "$addFields" : { "idMatch" : { "$eq" : [ "$channel_message_ID" , "$channel_thread_Id" ] } } },
   { $match: { "idMatch" : true } },
   { "$group" : { "_id" : "$message_status", "count" : { "$sum" : 1 } } },
   { "$sort" : { "_id" : 1 } }
]);

Which will return the expected results of
{ "_id" : "Completed", "count" : 1 }
{ "_id" : "In Progress", "count" : 1 }


text:
Q: AppleScript issues with Terminal commands I want to run this command in Terminal via AppleScript but Script Editor doesn't like the dollar sign. It says: Syntax Error: Expected end of line but found unknown token. How can I enter this command into Terminal without Script Editor complaining? I'm totally new to this and this command is not mine, I don't really want to change it.
tell application "Terminal"
do script "exec ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)""
end tell

A: You are having problems with the quoting of commands in a command.
An easy way out is to put the command ina shellscript e.g. name the script ~/bin/install_homebrew and after creating it make it executable
Script is
#!/bin/bash
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)

the call the script from the terminal or from Applescript
tell application "Terminal"
    do script exec "~/bin/install_homebrew "
end tell

A: Try escaping the inner double quotes (") with a backslash (), like so
do script "exec ruby -e \"$(curl -fsSL https://raw.githubuser......install)\""

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do I need a private docker registry? I've recently discovered docker.  It looks very useful for us.
But what I don't understand is the role of the registry beyond getting initial docker images.  We'll likely be starting with some images based on those from docker.io, but will be customizing those and adding some private closed source software.
What concerns me is if the images were large enough then could I run out of space on my / drive.
Can /var/lib/docker just be a mount to a shared file system like cephfs or nfs?
I'm also interested in using CoreOS in a PXE or iPXE configuration.  It appears that in that scenario / is mounted as tmpfs up to 50% RAM which is needlessly wasteful for pulling images that could be available on a shared file system.  However I've read comments that for some reason /var/lib/docker needs to be on btrfs.  Is this true? why?

Ok I've found an answer to my last question.  CoreOS requires /var/lib/docker to be mounted on btrfs because it uses the btrfs backend.  This backend uses btrfs snapshots to implement the layers docker uses to represent it's image.
Which helps with my second question.  Can /var/lib/docker just be a mount to a shared file system.  By the looks of it, no. Not unless the super slow vfs backend is used.

A: It's easy and cheap to store your registry in S3.
I would recommend against mounting /var/lib/docker on nfs.  If someone hammers the nfs, all your services will essentially stop working, since the file systems of the containers live there.


text:
Q: how to override the position of an onItemClick in Android So I have a button, and this button switches the cell of a listview with the cell above, and vise versa for ANOTHER button which is for down (this one is for up... It doesn't matter which, I just decided to talk about this one). The whole button and list view thing is working, but my problem is when I press the up button, and then decide to press it again, it just acts as a down button. The reason for this is because it's still stuck on the same item/position of the list view, and I need to figure out a way to Override the position of the onItemClick in the code??
```
upButton.setOnClickListener(new View.OnClickListener() {
                            @Override

                            public void onClick(View v) {

                                //upButton onClick

                                Integer myTeam = position; //7 -159

                                Integer otherTeam = position - 1; //6 - 1678

                                Map<Integer, String> onClickMap = sortByValue(Constants.picklistMap);

                                String extraValue;

                                Log.e("myposition", myTeam.toString());

                                Log.e("otherposition", otherTeam.toString());

                                extraValue = onClickMap.get(myTeam); //159

                                String team = onClickMap.get(otherTeam);

                                Constants.picklistMap.put(myTeam, onClickMap.get(otherTeam));

                                Constants.picklistMap.put(otherTeam, extraValue); //6

                                Log.e("Position: ",Constants.picklistMap.get(position));

                                Log.e("Position - 1: ",Constants.picklistMap.get(position - 1));

                                if(myTeam != 0) {

                                    dref.child("picklist").child(myTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(myTeam)));
                                    dref.child("picklist").child(otherTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(otherTeam)));

                                } else {

                                    Toast.makeText(getActivity(), "Nice try.
    If you try it again, the app is going to crash as punishment ... (:",
                                            Toast.LENGTH_LONG).show();

                                }

                            }

                        });

```
By overriding the position, I just mean how
position =+ 1
would make position = position + 1 in python, and I want to do the same thing in Java. The problem is I know that can't be done using the snippet of code I just used to increment the value of position!
Please help!
The reason I can't use position = position + 1 is because on the onItemClick, int position is defined, and then the onClick is created for the buttons, so I need position to be final for me to use it in the onClick, and if I got rid of final, i wouldn't be able to use it in the onClick as it can't be accessed from within an inner class when it's not final

A: Define which position you want to change, and use this method to update position. You can use this method in onClickListener. This should work.
    private int position = 0;

    private void up(ArrayList<Integer> arr){
            if (position < 1 || position >= arr.size()) return;
            int temp = arr.get(position - 1);
            arr.set(position - 1, arr.get(position));
            arr.set(position, temp);
            position --;
        }


text:
Q: What does :className() mean in a constructor for className? I see some code in a codebase I'm working on that looks like:
 ZfooName::ZfooName(int magoo)
    : ZfooName()
 {
    fGoo = magoo;
 }

I'm assuming this is a C++11 feature, since it breaks in VS2012, but what does it mean?

A: This is a new feature in C++11. It's called a delegating constructor.
The constructor calls the default constructor first (the constructor that is being delegated to). After the default constructor returns, the body of the delegating constructor is executed.
See http://www.stroustrup.com/C++11FAQ.html#delegating-ctor and https://en.cppreference.com/w/cpp/language/initializer_list#Delegating_constructor for additional information.


text:
Q: Python: shared variable across three Processes I need to have a shared value between 3 different processes. The code looks like this:
import multiprocessing
from multiprocessing import Queue, Process

def Process_B(q4: multiprocessing.Queue):
    while True:
        if q4.qsize() > 0:
            var1, var2 = q4.get()
            print(var1, var2)

def Process_A2_3_4(q123: multiprocessing.Queue, q4: multiprocessing.Queue, name):
    supProcesses = SubProcesses123(q4, name)
    while True:
        if q123.qsize() > 0:
            var1, var2, var3 = q123.get()
            supProcesses.doSomething(var1, var2, var3)

class SubProcesses123:
    def __init__(self, q4: multiprocessing.Queue, name):
        self.name = name
        self.q4 = q4
        self.sharedlist = []#this list needs to be shared between the three processes.

    def doSomething(self, var1, var2, var3):
        print('doing something')
        self.q4.put(var1,var2)

class Process_A:
    def __init__(self):
        self.a2 = Queue()
        self.a3 = Queue()
        self.a4 = Queue()
        self.b1 = Queue()
        self.startProcess234()
        self.doSomething()

    def startProcess234(self):
        a2 = Process(target=Process_A2_3_4, args=(self.a2, self.b1, "a2"))
        a3 = Process(target=Process_A2_3_4, args=(self.a3, self.b1, "a3"))
        a4 = Process(target=Process_A2_3_4, args=(self.a4, self.b1, "a4"))
        b1 = Process(target=Process_B, args=(self.b1,))
        a2.start()
        a3.start()
        a4.start()
        b1.start()

    def doSomething(self):
        print('doing something')
        #self.a2.pu(var1, var2, var3)
        #self.a3.pu(var1, var2, var3)
        #self.a4.pu(var1, var2, var3)

if __name__ == '__main__':
    retrieve = Process(target=Process_A)
    retrieve.start()

I tried to condense the code a bit without leaving out anything important. Every way i can think of leads to the problem that the three processes are completely seperate. Mind, they do need to be seperate, i just need to find a way to be able to have 1 shared list. It is unfortunately not an option to use the Queue from Process_B to handle the task, it really needs to be some form of shared list between the three processes (Process_A2_3_4). Im also unable to just make a Queue for the three processes because as far to my knowledge you can use the queue from 1 process to another but not from one process to multiple.
Im scratching the back of my head. If anyone has a solution or an idea, it would be very much appreciated if you could share it. Thank you for your time.


text:
Q: image not getting displayed on html page using sails js I am using sails Js and Mongo DB in my application. I upload an image and content for a blog post. I save it in images folder.I save the file destination and content to my mongodb. using the file destination, I want to display the content and image in my HTML page. Content is being displayed but image is not getting displayed.
controller:
savepost:function(req,res){
        var uploadFile=req.file("image")
        uploadFile.upload({maxBytes:1000000,dirname:'../../assets/images'}, function onUploadComplete(err, files) {
            // Files will be uploaded to ./assets/images
            // Access it via localhost:1337/images/file-name
            if (err) return res.serverError(err);
            // IF ERROR Return and send 500 error
            filename=files[0].fd;
        var content=req.body.content;
        var title=req.body.title;
       Cyberblog.create({title:title,content:content,date:date,filename:filename,}).exec(function(err){
            if(err){
              console.log(err);
              message="content not saved";
                console.log(message)
              res.redirect('/newpost');
            }
            else{
     var start=filename.lastIndexOf('\\');
     fd="images/"+filename.substring(start+1)
      post={
          title:title,
          content:content,
          fd:fd,
      }
      res.view('pages/blog/blog',{post:post})
    console.log("succesfully saved")}
    }); }); },

Html file:

          <a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.fd %>);">

<%= post.title %>

I am unable to figure out if this is correct or not <%= post.fd %>. Please help me.

A: The /assets/images directory is moved to the .tmp/public/images when you run sails lift if you are using tasks with Grunt.
Then, you need to check the uploadedFile.fd value to verify the right directory where your file is stored because your public directory is .tmp/public, then to get images as localhost:1337/images/my-image.png it should be in the local directory as .tmp/public/images/my-image.png.
When that is resolved, you could use the relative path to access the file via URL or something like that in the controller:
const url = require('url')
post.imageUrl = url.resolve(sails.config.custom.baseUrl, post.fd)

And then, in the view, use this value to show the image:
<a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.imageUrl %>);">


text:
Q: Bulk delete ec2 snapshots from Jenkins Use case:
Export list of snapshots in txt file (old_snapshots.txt) to S3 bucket. From Jenkins, use aws cp command copy file to Jenkins /tmp/directory
--dry-run did not show any error

However, when passed the following bash line with aws delete command in Jenkins it shows SUCCESS, at the same says error has occurred and the snapshots are not deleted.
## actual deletion
        file="/tmp/old_snapshots.txt"
         while read delete_data
         do
        aws ec2 --region eu-west-1 delete-snapshot --snapshot-id $file
        echo "Deleting snapshot $delete_data"
        done <"$file"

Output
An error occurred (InvalidParameterValue) when calling the DeleteSnapshot operation: Value (/tmp/old_snapshots.txt) for parameter snapshotId is invalid. Expected: 'snap-...'.
Deleting snapshot snap-xxxx81xxxxxx7fxxx

An error occurred (InvalidParameterValue) when calling the DeleteSnapshot operation: Value (/tmp/old_snapshots.txt) for parameter snapshotId is invalid. Expected: 'snap-...'.
Deleting snapshot snap-xxxacc49xxxxxxc26

An error occurred (InvalidParameterValue) when calling the DeleteSnapshot operation: Value (/tmp/old_snapshots.txt) for parameter snapshotId is invalid. Expected: 'snap-...'.
Deleting snapshot snap-04xxxxxxxx3fa3cxxxxxxf4

[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Request: This error An error occurred (InvalidParameterValue) when calling the DeleteSnapshot operationseems too generic? Have anyone experienced seem issue? Also, I did a manual test of deleting just a single snapshot with aws cli by manually adding the snapshot id in Jenkins and that works fine. Any suggestion would be greatly appreciated.
Including aws command
aws ec2 --region eu-west-1 delete-snapshot --snapshot-id snap-01x1618xxxxxxa51x
Found snapshotid: snap-01x1618xxxxxxa51x in the uploaded file: /tmp/old_snapshots.txt
Now deleting snapshot id snap-01x1618xxxxxxa51x

A: You need to change your script a bit.
$ sh abc.sh

What is in delete_data snap-xxxx81xxxxxx7fxxx
What is in file /tmp/old_snapshots.txt
Deleting snapshot snap-xxxx81xxxxxx7fxxx
What is in delete_data snap-xxxacc49xxxxxxc26
What is in file /tmp/old_snapshots.txt
Deleting snapshot snap-xxxacc49xxxxxxc26
What is in delete_data snap-04xxxxxxxx3fa3cxxxxxxf4
What is in file /tmp/old_snapshots.txt
Deleting snapshot snap-04xxxxxxxx3fa3cxxxxxxf4

$ cat abc.sh
## actual deletion

    file="/tmp/old_snapshots.txt"
    while read delete_data
    do
    #aws ec2 --region eu-west-1 delete-snapshot --snapshot-id $file
    echo "What is in delete_data $delete_data"
    echo "What is in file $file"
    echo "Deleting snapshot $delete_data"
    done < $file

Your script is calling file variable is constant but you need to pass content of file line by line.
So, replace below
aws ec2 --region eu-west-1 delete-snapshot --snapshot-id $file

With
aws ec2 --region eu-west-1 delete-snapshot --snapshot-id $delete_data

A: For the benefit of other community users, I used the --debug flag to discover that additional character '\r' were being added to the snap-#
Debug output
2020-01-28 18:09:02,295 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.ec2.delete-snapshot.snapshot-id: calling handler <awscli.paramfile.URIArgumentHandler object at >
2020-01-28 18:09:02,296 - MainThread - botocore.hooks - DEBUG - Event process-cli-arg.ec2.delete-snapshot: calling handler <awscli.argprocess.ParamShorthandParser object at >
2020-01-28 18:09:02,296 - MainThread - awscli.arguments - DEBUG - Unpacked value of u'snap-0xxxxxxxxxxxxxxxx\r' for parameter "snapshot_id": u'snap-0xxxxxxxxxxxxxxxx\r'

To solve the issue: I passed tr -d '\r' to variable holding the value, to make the conversation.
Example:
tr -d '\r' < input > output

Updated script
file="/tmp/old_snapshots.txt"
cat $file | tr -d '\r' | while read -r line;
do
aws ec2 --region eu-west-1 delete-snapshot --snapshot-id $line
done


text:
Q: How to find out the different data types for sparse matrices in R When using the fac2sparse command in r I can decide in the to option whether the entries should be of type c("d", "i", "l", "n", "z") . The help only says that the standard option is d which stands for double. I can guess that the next two are integer and logic, I read somewhere that n stands for pattern and I have no idea what z stands for.
This shouldn't require guessing, so where in the help files can find this information? I looked around in the related help pages and the general matrix documentation but I didn't find it.

A: You can see it in the source code,
if (to != "n")
    df$x <- rep.int(switch(to, d = 1, i = 1L, l = TRUE, z = 1 +
        (0+0i)), nrow(df))

so like you said, d is double, i is integer, l is logical, z is complex number with 1 on the real with 0 on the imaginary part. I am not sure how you transform something from factor to complex number though.
And as @dww correctly pointed out, "n" creates a nsparsematrix, where only the positional information is stored:
fac2sparse(factor(c(1:3,1:2)),to="l")@x
[1] TRUE TRUE TRUE TRUE TRUE

fac2sparse(factor(c(1:3,1:2)),to="d")@x
[1] 1 1 1 1 1

fac2sparse(factor(c(1:3,1:2)),to="n")@x
Error: no slot of name "x" for this object of class "ngCMatrix"


text:
Q: Regex allow digits and a single dot What would be the regex to allow digits and a dot? Regarding this \D only allows digits, but it doesn't allow a dot, I need it to allow digits and one dot this is refer as a float value I need to be valid when doing a keyup function in jQuery, but all I need is the regex that only allows what I need it to allow.
This will be in the native of JavaScript replace function to remove non-digits and other symbols (except a dot).
Cheers.

A: Try this
boxValue = boxValue.replace(/[^0-9\.]/g,"");

This Regular Expression will allow only digits and dots in the value of text box.

A: If you want to allow 1 and 1.2:
(?<=^| )\d+(\.\d+)?(?=$| )

If you want to allow 1, 1.2 and .1:
(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )

If you want to only allow 1.2 (only floats):
(?<=^| )\d+\.\d+(?=$| )

\d allows digits (while \D allows anything but digits).
(?<=^| ) checks that the number is preceded by either a space or the beginning of the string. (?=$| ) makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.
Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.

A: My try is combined solution.
string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;

First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.
Second line cleans numbers after dot.

A: \d*\.\d*

Explanation:
\d* - any number of digits
\. - a dot
\d* - more digits.
This will match 123.456, .123, 123., but not 123
If you want the dot to be optional, in most languages (don't know about jquery) you can use
\d*\.?\d*

A: Try the following expression
/^\d{0,2}(\.\d{1,2})?$/.test()


text:
Q: Most efficient way to create fill rectangles in NumPy Given a list of coordinates that represent a rectangle in a grid (e.g. the upper-left and lower-right coordinate), which would be the most efficient way to fill a binary NumPy array with ones in the place of that rectangles?
The simple way would be to do a for loop such as
arr = np.zeros((w, h))
for x1, y1, x2, y2 in coordinates:
    arr[x1:x2, y1:y2] = True

where coordinates is something like [(x_11, y_11, x_22, y_22), ..., (x_n1, y_n1, x_n2, y_n2)]
However, I want to try to avoid it, as it is one of the advantages of using vectorial inner NumPy operations. I have tried the logical_and but it seems that it works for a single rectangle or condition. How could I do it in a more "numpy" way?
The resulting image would be something like this for 2 rectangles:

A: Let say (1,1) are the upper-left coordinates of the rectangle,
and (5,4) the lower-right.
Then
arr = np.zeros((10, 10))
arr[1:5, 1:4] = 1

returns
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])


text:
Q: Checkbox and hexadecimal equivalent I have four check boxes, check box 1 through checkbox4. Consider those four check boxes as binary 0000. If check box 1 is selected, the binary should change to 1000. The same way for the other check boxes, the corresponding bit should be set. Finally the output that I want is the hexa decimal equivalent of the four bits. That is 0 throgh F.0 should be returned if no checkboxes are selected. F, when all checkboxes are selected.

A: There's loads of ways.  For example, if it is just 4 bits, add them up individually:
    Dim intValue As Integer = 0
    If CheckBox0.Checked Then intValue += 1
    If CheckBox1.Checked Then intValue += 2
    If CheckBox2.Checked Then intValue += 4
    If CheckBox3.Checked Then intValue += 8
    Dim strHex As String = intValue.ToString("x")

If there could be more than 4, it would be better to replace the middle bit with a loop.
The .ToString("x") on the last line gives the number in hex representation.  I think that's all you needed?


text:
Q: Getting all var from a javastring function by Regular Expression Hi I am new for Regex and trying to get below,
there is a string below in javascript,
"function(){var a; var a,b,c;}"

and I am trying to find [a,b,c] from it.
Please suggest me to get all variable declared in string, what will be regex.

A: A very very manipulative solution, but will serve your purpose
function uniq(value,index,self){
    return self.indexOf(value) === index;
}

var str = "function(){var a; var a,b,c;}";
var ptrn = /var [^;]+/g;
var match;
var matches = []
while ( ( match = ptrn.exec(str) ) != null )
{
    matches.push(match.join().split(" ")[1]);
}
console.log(matches.join(",").split(",").filter(uniq));

but if you understand this code you wont have to ever search for:

*

*how to get unique values from js array

*how matching a pattern with exec only returns the first match and we have to loop to get the rest of the values

*finally adding a filter with a function.


text:
Q: Visual studio asp.net sql Server insert form I have to do this thing for work that's really just a formality. Normally I'm a linux/UNIX guy but they're making me do this. I need to have an asp webpage that displays data from two different database servers. This is easy -- just a drag and drop in visual studio. The problem is I also need a way to insert a new row into a table on the SQL Server 2008 database. Right now I have:

...
<asp...
stuff to display data
...>
...
<form>
Name: <input type="text" name="name" id="name" />

Quantity: <input type="text" name="quantity" id="quantity" />

<input type="submit" />
</form>

I know html quite well and I've also done quite a bit of web programming in python that uses MySQL in the backend but I can't stand programming with a GUI. I know how to do the connection string I just don't know how to make asp.net see the data in the fields.
Oh and the table is a simple two column table: one varchar for a product's name and an int for its quantity. All this has to be done in visual studio.

A: In Visual Studio for an ASP.NET page you can use the DetailsView control to perform an insert. Follow these simple steps:

*

*Create a new Web Form in Visual Studio

*Make sure you're in Design View (and not Source View)

*Drag and drop a SqlDataSource onto the form (in the toolbox's Data category)

*Click on the little |> arrow next to the SqlDataSource's gray blob and run the Configure Data Source wizard

*Select the database and table and fields that you want

*On the last page of the wizard you can test the query to make sure it works

*Drag and drop a DetailsView onto the form (also in the toolbox's Data category)

*Click on the little |> arrow next to it and in the list of data sources choose the SqlDataSource that you just created

Now you're done!
Regarding your sample about raw HTML - that's generally not the recommended approach when using ASP.NET Web Forms. With Web Forms there are rich "server controls" that worry about most of the HTML rendering for you. They also have logic in them to help make a site more secure such as HTML encoding values.

A: OP here. (created an account so I hvae a diff. name.)
Your answer wasn't quite what I was looking for but it taught m3 how to use Visual Studio enough to get it done. (I didn't know there was a toolbox) Thanks again for the help:)
Also, I couldn't figure out how to reply again so this is an "answer."


text:
Q: Using ADF REST connector to read and transform FHIR data I am trying to use Azure Data Factory to read data from a FHIR server and transform the results into newline delimited JSON (ndjson) files in Azure Blob storage. Specifically, if you query a FHIR server, you might get something like:
{
    "resourceType": "Bundle",
    "id": "som-id",
    "type": "searchset",
    "link": [
        {
            "relation": "next",
            "url": "https://fhirserver/?ct=token"
        },
        {
            "relation": "self",
            "url": "https://fhirserver/"
        }
    ],
    "entry": [
        {
            "fullUrl": "https://fhirserver/Organization/1234",
            "resource": {
                "resourceType": "Organization",
                "id": "1234",
                // More fields
        },
        {
            "fullUrl": "https://fhirserver/Organization/456",
            "resource": {
                "resourceType": "Organization",
                "id": "456",
                // More fields
        },

        // More resources
    ]
}

Basically a bundle of resources. I would like to transform that into a newline delimited (aka ndjson) file where each line is just the json for a resource:
{"resourceType": "Organization", "id": "1234", // More fields }
{"resourceType": "Organization", "id": "456", // More fields }
// More lines with resources

I am able to get the REST connector set up and it can query the FHIR server (including pagination), but no matter what I try I cannot seem to generate the ouput I want. I set up an Azure Blob storage dataset:
{
    "name": "AzureBlob1",
    "properties": {
        "linkedServiceName": {
            "referenceName": "AzureBlobStorage1",
            "type": "LinkedServiceReference"
        },
        "type": "AzureBlob",
        "typeProperties": {
            "format": {
                "type": "JsonFormat",
                "filePattern": "setOfObjects"
            },
            "fileName": "myout.json",
            "folderPath": "outfhirfromadf"
        }
    },
    "type": "Microsoft.DataFactory/factories/datasets"
}

And configure a copy activity:
{
    "name": "pipeline1",
    "properties": {
        "activities": [
            {
                "name": "Copy Data1",
                "type": "Copy",
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "typeProperties": {
                    "source": {
                        "type": "RestSource",
                        "httpRequestTimeout": "00:01:40",
                        "requestInterval": "00.00:00:00.010"
                    },
                    "sink": {
                        "type": "BlobSink"
                    },
                    "enableStaging": false,
                    "translator": {
                        "type": "TabularTranslator",
                        "schemaMapping": {
                            "resource": "resource"
                        },
                        "collectionReference": "$.entry"
                    }
                },
                "inputs": [
                    {
                        "referenceName": "FHIRSource",
                        "type": "DatasetReference"
                    }
                ],
                "outputs": [
                    {
                        "referenceName": "AzureBlob1",
                        "type": "DatasetReference"
                    }
                ]
            }
        ]
    },
    "type": "Microsoft.DataFactory/factories/pipelines"
}

But at the end (in spite of configuring the schema mapping), it the end result in the blob is always just the original bundle returned from the server. If I configure the output blob as being a comma delimited text, I can extract fields and create a flattened tabular view, but that is not really what I want.
Any suggestions would be much appreciated.

A: So I sort of found a solution. If I do the original step of converting where the bundles are simply dumped in the JSON file and then do a nother conversion from the JSON file to what I pretend to be a text file into another blob, I can get the njson file created.
Basically, define another blob dataset:
{
    "name": "AzureBlob2",
    "properties": {
        "linkedServiceName": {
            "referenceName": "AzureBlobStorage1",
            "type": "LinkedServiceReference"
        },
        "type": "AzureBlob",
        "structure": [
            {
                "name": "Prop_0",
                "type": "String"
            }
        ],
        "typeProperties": {
            "format": {
                "type": "TextFormat",
                "columnDelimiter": ",",
                "rowDelimiter": "",
                "quoteChar": "",
                "nullValue": "\\N",
                "encodingName": null,
                "treatEmptyAsNull": true,
                "skipLineCount": 0,
                "firstRowAsHeader": false
            },
            "fileName": "myout.json",
            "folderPath": "adfjsonout2"
        }
    },
    "type": "Microsoft.DataFactory/factories/datasets"
}

Note that this one TextFormat and also note that the quoteChar is blank. If I then add another Copy Activity:
{
    "name": "pipeline1",
    "properties": {
        "activities": [
            {
                "name": "Copy Data1",
                "type": "Copy",
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "typeProperties": {
                    "source": {
                        "type": "RestSource",
                        "httpRequestTimeout": "00:01:40",
                        "requestInterval": "00.00:00:00.010"
                    },
                    "sink": {
                        "type": "BlobSink"
                    },
                    "enableStaging": false,
                    "translator": {
                        "type": "TabularTranslator",
                        "schemaMapping": {
                            "['resource']": "resource"
                        },
                        "collectionReference": "$.entry"
                    }
                },
                "inputs": [
                    {
                        "referenceName": "FHIRSource",
                        "type": "DatasetReference"
                    }
                ],
                "outputs": [
                    {
                        "referenceName": "AzureBlob1",
                        "type": "DatasetReference"
                    }
                ]
            },
            {
                "name": "Copy Data2",
                "type": "Copy",
                "dependsOn": [
                    {
                        "activity": "Copy Data1",
                        "dependencyConditions": [
                            "Succeeded"
                        ]
                    }
                ],
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "typeProperties": {
                    "source": {
                        "type": "BlobSource",
                        "recursive": true
                    },
                    "sink": {
                        "type": "BlobSink"
                    },
                    "enableStaging": false,
                    "translator": {
                        "type": "TabularTranslator",
                        "columnMappings": {
                            "resource": "Prop_0"
                        }
                    }
                },
                "inputs": [
                    {
                        "referenceName": "AzureBlob1",
                        "type": "DatasetReference"
                    }
                ],
                "outputs": [
                    {
                        "referenceName": "AzureBlob2",
                        "type": "DatasetReference"
                    }
                ]
            }
        ]
    },
    "type": "Microsoft.DataFactory/factories/pipelines"
}

Then it all works out. It is not ideal in that I now have two copies of the data in blobs, but one can easily be deleted, I suppose.
I would still love to hear about it if somebody has a one-step solution.

A: As briefly discussed in the comment, the Copy Activity does not provide much functionality aside from mapping data. As stated in the documentation, the Copy activity does the following operations:

*

*Reads data from a source data store.

*Performs serialization/deserialization, compression/decompression, column mapping, etc. It does these operations based on the
  configurations of the input dataset, output dataset, and Copy
  Activity.

*Writes data to the sink/destination data store.

It does not look like that the Copy Activity does anything else aside from efficiently copying stuff around.
What I found out to be working was to use Databrick.
Here are the steps:

*

*Add a Databricks account to your subscription;

*Go to the Databricks page by clicking the authoring button;

*Create a notebook;

*Write the script (Scala, Python or .Net was recently announced).

The script would the following:

*

*Read the data from the Blob storage;

*Filter out & transform the data as needed;

*Write the data back to a Blob storage;

You can test your script from there and, once ready, you can go back to your pipeline and create a Notebook activity that will point to your notebook containing the script.
I struggled coding in Scala but it was worth it :)

A: For anyone finding this post in the future you can just can use the $export api call to accomplish this. Note that you have to have a storage account linked to your Fhir server.
https://build.fhir.org/ig/HL7/bulk-data/export.html#endpoint---system-level-export


text:
Q: List local running services on Windows 10 using Python? All I need to do is create a program that lists all running services on my Windows machine. I have tried a number of methods including psutil to no avail. I have since tried to simplify it by just trying to execute the "net stat" command. It works, but the output is garbled. Is there anyway to save this to a text file nice and neat? Also, I'd like to append the word 'Running' next to each line. When I try to add that I get the following error:
File "./Python37/test3.py", line 3, in
    print(str(result.stdout + 'running'))
TypeError: can't concat str to bytes
Here is my code so far:
import subprocess
result = subprocess.run(['net', 'start'], stdout=subprocess.PIPE)
print(str(result.stdout + 'running'))

A: Use EnumServicesStatus API like this :
import win32con
import win32service

def ListServices():
    resume = 0
    accessSCM = win32con.GENERIC_READ
    accessSrv = win32service.SC_MANAGER_ALL_ACCESS

    #Open Service Control Manager
    hscm = win32service.OpenSCManager(None, None, accessSCM)

    #Enumerate Service Control Manager DB
    typeFilter = win32service.SERVICE_WIN32
    stateFilter = win32service.SERVICE_STATE_ALL

    statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)

    for (short_name, desc, status) in statuses:
        print(short_name, desc, status)

ListServices();

*

*win32service and win32con is part of pywin32 opensource project which you can download the lastest version here
.

A: From psutil 4.2.0 onwards you can list and query the windows services using following APIs.

*

*psutil.win_service_iter()
Usage:
>>> import psutil
>>>
>>> list(psutil.win_service_iter())
[<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>,
 <WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>,
 <WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>,
 <WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>,
 ...]

*

*psutil.win_service_get(name) - To get a windows service by name

Usage:
>>> import psutil
>>> s = psutil.win_service_get('alg')
>>> s.as_dict()
{'binpath': 'C:\\Windows\\System32\\alg.exe',
 'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
 'display_name': 'Application Layer Gateway Service',
 'name': 'alg',
 'pid': None,
 'start_type': 'manual',
 'status': 'stopped',
 'username': 'NT AUTHORITY\\LocalService'}


text:
Q: What is the right syntax for updating table on Redshift? (code example) I want to create a scheduled query to update an existing table on Redshift daily.
The idea is that I want to add daily new rows with events that happen with unique key1 and key2. Also, I want to update rows in the last week that had updates in value1, value2 or value3, but I want to insert these values only if in the original prod table they were null (and so I cannot delete rows and insert them again for that key1 and key2). And I want to leave rows that happened more than a week ago untouched.
I'm missing the right syntax probably because the code below doesn't work. Query for temp table works fine. Could you please advise on what I'm missing here?
Redshift documentation with example is here: https://docs.amazonaws.cn/en_us/redshift/latest/dg/merge-specify-a-column-list.html
create temp table [temp_table_name] as

[SELECT * FROM temp_table_name];

begin transaction;

update [prod_table_name]
set value1 = NVL(value1, temp_table_name.value1),
value2 = NVL(value2, temp_table_name.value1),
value3 = NVL(value3, temp_table_name.value1)
from [temp_table_name]
where key1 = temp_table_name.key1
and key2 = temp_table_name.key2
and key3 = temp_table_name.key3
and key4 = temp_table_name.key4;

insert into [prod_table_name]
select *
from [temp_table_name]
where value1 <> temp_table_name.value1
and value2 <> temp_table_name.value2;

end transaction;

I run into all different kinds of errors and cannot find out where the problem is.

A: I suspect that the issue is the ambiguity of "key1" and "value1".  I think you need to specify the target table by name in the WHERE clauses.  Like this:
where prod_table_name.key1 = temp_table_name.key1

and:
where prod_table_name.value1 <> temp_table_name.value1


text:
Q: Apply an if/then condition over all elements of a Pandas dataframe I need to apply a very simple if/then function to every element in a Pandas Dataframe.
If the value of any element is over 0.5, I need to return a 1. Otherwise, I need to return a 0.
This seemed really simple with a lambda function, but every time I try I get an error: 'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()'
So far I have:
df_new = df.apply(lambda x: 1 if x > 0.5 else 1)

I'd be grateful for any help.

A: You should use applymap instead because you want the operation to be performed on each element in your dataframe, not each column, which is what apply does.
df = pd.DataFrame({"A": [0.1, 0.2, 0.5, 0.6, 0.7],
                  "B": [0.75, 0.85, 0.2, 0.9, 0.0],
                  "C": [0.2, 0.51, 0.49, 0.3, 0.1]})

print(df)

      A        B       C
0   0.1     0.75    0.20
1   0.2     0.85    0.51
2   0.5     0.20    0.49
3   0.6     0.90    0.30
4   0.7     0.00    0.10

df_new = df.applymap(lambda x: 1 if x > 0.5 else 0)

print(df_new)

    A   B   C
0   0   1   0
1   0   1   1
2   0   0   0
3   1   1   0
4   1   0   0

A: If it is something binary, you could use the following:
df = (df > 0.5).astype(int)

The code in the parentheses would generate a dataframe of bools, which would then be converted to the ints 1 and 0 (1 for True, 0 for False)


text:
Q: submit form with out spring form tags I am developing a simple app in spring mvc without using spring form tags, currently my work is done by using below code but for understanding purpose I am asking this question.
I have two backing beans classes which I have bound to one html <form> tag which is not possible in spring form tags.
bean 1
   public class Interim {
    private int interimId;
    private BigDecimal amount;
    private int interimCategory;
    // setter n getter
    }

bean 2
    public class Bcr {
    private int bcrId;
    private BigDecimal cashAmount;
    private int interimCategory;
    }

html form
<form action="/interim" method="get">
<input type="text" name="amount" />
<input type="text" name="cashAmount" />
<input type="text" name="interimCategory" />
<button type="submit" name="Month" > month </button>
</from>

spring controller
@Controller
public TestController {

   @RequestMapping(value = "/interim", method = RequestMethod.GET)
    public String interimInit(ModelMap map) {
        map.addAttribute("interim",new Interim());
        map.addAttribute("bcr",new Bcr());
        return "interim";
    }

/// on form submit
@RequestMapping(value = "/interim", method = RequestMethod.GET, params = "Month")
    public String getMonthlyInterim(@ModelAttribute("bcr") Bcr b,ModelMap
            modelMap,@ModelAttribute("interim") Interim in) {

}

When I submit the form spring mvc set interimCategory in both beans,

*

*How to tell spring not to set interimCategory of Bcr bean?

*Is this good way to create an html form in spring ?

A: If you don't want to use Spring form tag, you can choose to send your form using JQuery Ajax + send your data inside an HTTP body using POST method, that the body of that HTTP message will be JSON message.
Then you can use the @RequestBody annotation to bind that json to your variable on the controller.


text:
Q: Why import rajawali.*; cannot be resolved! Am i doing something wrong? i need to touch 3d objects in my android. And most of people i asked in forum, they suggesting me to use Rajawali as the framework. [I am using Android Studio]
I look into so many tutorial but i always stuck here:
import rajawali.*;

it shows cannot be resolved.
Then I've downloaded the source code from here MasDennis/Rajawali hoping it could give me a clear view of my mistakes. But i cant even test it / played it in the android studio. (Run test the app in my phone).
Please. Im really trying to figure out. and im stuck just here for almost a week now. If this fix, i can continue with my program. Thanks for the help.
P/s: I forgot to mention this before. I did add the codes in the build gradle. Im following exactly from this tutorial. Im successfully adding the .obj file. However, i cannot continue to any functions that requires me to import rajawali.*;


text:
Q: undefined method `map' for nil:NilClass in render action error flash I have a rails form which takes the rails model FlsCenter and orders them alphabetically to be displayed in a drop down. When none of the fields of the form are filled out, and the form is submitted, the page gets a 500 Server Error in which the following Rails error is displayed:
undefined method `map' for nil:NilClass

Where the map function is in the following view code:
= f.select(:fls_center, @fls_centers.map{|p| [p.name, p.id]}, prompt: "Select a Program Center", selected:@school_application.fls_center)

Where @fls_centers is defined in the new method of my SchoolApplicationController here:
@fls_centers = FlsCenter.order('name ASC')

Here are the relevant controller methods from SchoolApplicationsController
def create
@school_application = SchoolApplication.new(school_application_params)
  if @school_application.save_with_payment
    redirect_to pay_path(id: @school_application.id)
  else
    @school_application.errors.full_messages.each do |msg|
      flash.now[:error] = msg
    end
    render action: "new"
  end
end

And here is my new method:
  def new
    if application_params
      @school_application = SchoolApplication.new(application_params)
    else
      @school_application = SchoolApplication.new()
    end
    Rails.logger.debug(@fls_centers)
    @fls_centers = FlsCenter.order('name ASC')
  end

The only thing I can imagine that is going wrong is that render action: "new" does not execute the variable instantiation inside the new method. I do not know how to amerliorate this situation. Thank you

A: You are executing Rails.logger.debug(@fls_centers) before defining the @fls_centers, So make changes like shown below:
def new
  @fls_centers = FlsCenter.order('name ASC')
  if application_params
    @school_application = SchoolApplication.new(application_params)
  else
    @school_application = SchoolApplication.new()
  end
  Rails.logger.debug(@fls_centers)
end

Hope it helps!

A: You guessed right. The actual new method does not get executed when you call
render action: "new"

You will have to call the variable instantiations all over again:
def create
@school_application = SchoolApplication.new(school_application_params)
  if @school_application.save_with_payment
    redirect_to pay_path(id: @school_application.id)
  else
    @school_application.errors.full_messages.each do |msg|
      flash.now[:error] = msg
    end
    @fls_centers = FlsCenter.order('name ASC')
    render action: "new"
  end
end

If you have a lot of them it might be better to refactor them in a method and call that method in the new method as well as before the render call.


text:
Q: Entity Framework ICollection to List I am trying to do something like this:
 List<Department> t = db.Employees
        .Where(e => e.CompanyId.Equals(12345))
        .Where(e => e.Departments.Any(d => d.IsActive.Equals(true)))
        .Select(e => e.Departments);

But it gives me an error telling me that can't implicitly convert from IQueryable<ICollection<Department>> to List<Department>.
My Linq is a bit rusty. What is the right way to bring this down to the List<Department>

A: You have a queryable collection of a collection of departments (note the plural e.Departments).  As a result, you can use .SelectMany() to flatten your collection and then resolve the IQueryable with .ToList().
List<Department> t = db.Employees
    .Where(e => e.CompanyId.Equals(12345))
    .Where(e => e.Departments.Any(d => d.IsActive.Equals(true)))
    .SelectMany(e => e.Departments).ToList();


text:
Q: What do I do with Vim Bootstrap output file? Using: Ubuntu 20.04 LTS; Neovim (cannot remember initial install method, although it is activated via nvim command)
I was recently pointed toward this web app for creating Vim and Neovim config files. According to any resources I can find, it is supposed to generate a .vimrc file based on the options that you choose. I ran the app, but the output was a file called generate.vim.
What do I do with this file in order to get a config file for Neovim (init.vim?)
If you couldn't tell I am new to Vim. This app is made to limit distractions like config for noobs like myself, but it looks like my level of 'noob' is a bit too much for them...

A: I was able to solve this issue by running the 'generate.vim' file with Neovim (chosen from the list of apps given @ the run/download prompt.) For me, the default app was text-editor, which just displayed the file. However, when I switched 'run app with' to neovim, the prompt just immediately disappeared. Afterward, I noticed that there was an init.vim file in the appropriate directory. When I opened Neovim, the plugin mgr was running, and all settings were changed.


text:
Q: Android Flutter and http get I'm figuring out how to get status code 200 from https://icanhazip.com
This code only works on desktop and android emulator, but it doesn't work on the android mobile. The variable string id178 is always blank . It doesn't even print 'TEST'
setState() should update the variable when you tap
Thank you
This is the manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.test">
   <!-- The INTERNET permission is required for development. Specifically,
     the Flutter tool needs it to communicate with the running application
     to allow setting breakpoints, to provide hot reload, etc.
   -->
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
 runApp(App());
}

class App extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return MaterialApp(
      home: HomePage(),
   );
 }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String id178 = '';

  getMachinesId() async {
    var url = Uri.parse('https://icanhazip.com');
    var res = await http.get(url);
    id178 = '${res.statusCode} TEST ';
  }

  @override
  void initState() {
    super.initState();
    getMachinesId();
  }

 @override
 Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black87,
        title: const Text("TEST !",
        style: TextStyle(
            fontSize: 20,
            fontStyle: FontStyle.italic,
            fontWeight: FontWeight.bold,
            color: Color(0xFFbf9b0a))),
      centerTitle: true,
      ),
      body: Center(
        child: Text(
          "Server Machine: $id178\n",
          style: const TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),

      floatingActionButton: FloatingActionButton(
         onPressed: () {
           setState(() {
             getMachinesId();
           });
         },
         child: const Icon(Icons.verified_sharp),
      ),
  );
 }
}

A: You missed print and set state
getMachinesId() async {
    var url = Uri.parse('https://icanhazip.com');
    var res = await http.get(url);
    id178 = '${res.statusCode} TEST ';
   print(id178);
   setState((){});
  }

A: As far as I know there are three manifest file
src/debug
src/main (release)
src/profile

I've edited the wrong manifest...
Edit:
After you have created new project in visual code, there is a manifest for each subfolder :
android/app/src/main

android/app/src/debug

android/app/src/profile

In terminal window I run :
flutter build apk --release

so the right "AndroidManifest.xml" file is in the "main" folder


text:
Q: unable to install react-open-weather (SPA - AEM ) custom component I was following this documentation To create a custom component(open weather) in SPA and map it to AEM.
I'm following the above documentation to install that component as a npm dependancy using this command 'npm i react-open-weather', but i am getting errors while installing that component, i have tried this command with --force, or --legacy-peer-deps still my problem doesn't get resolved.
I got struck here can anyone help me to get out of this problem.


text:
Q: How to get the status of the Scenario ran in behave Can some one please tell me, how can I get the status of the scenario which ran with behave in python?
I want to get the status (success or error) of the test cases ran in after_scenario method.

A: As of Behave 1.2.6 status is an enumeration, so:
# -file- environment.py
from behave.model_core import Status

def after_scenario(context, scenario):
    print(Scenario.status)

    if scenario.status == Status.failed:
        print('more details:...')

The import is only needed for comparing the status with Status.failed, e.g. to print some more details.
The status is a read-only summary of the scenario's run:

*

*Status.untested: the scenario has not been completely tested yet.

*Status.skipped: one or more steps of this scenario was passed over during testing.

*Status.passed: the scenario was tested successfully.

*Status.failed: one or more steps of this scenario failed.
Changed in version 1.2.6: Use Status enum class (was: string)

See: http://behave.readthedocs.io/en/stable/api.html#behave.model.Scenario.status

A: This is pretty easy to do with behave. The Scenario class has an attribute called status. You can use this in the after_scenario method like so:
# -file- environment.py

def after_scenario(context, scenario):
    print (scenario.status)

This should return one of:

*

*untested:
The scenario was has not been completely tested yet.

*skipped:
One or more steps of this scenario was passed over during testing.

*passed: The scenario was tested successfully.

*failed:
One or more steps of this scenario failed.


text:
Q: Learning Flash Programming for PHP Websites Any pointers where i could start learning flash programming.
Also i would be really grateful if you could point me to place where i could get free templates for the programming
Thanks in advance

A: If you really want to learn Flash (as3) programming then you want to get Essential Actionscript 3 by Colin Moock.
There is a lot of AS3 code out there. You will have to be more specific regarding your goals to really provide an answer. "Flash Programming" is extremely general. Flash IDE, AS3, Flex, etc...

A: Using the AMFPHP framework you will be able to make remote call from actionscript to your php back-end methods. The site has a lot of good example to get you started. Basically, this framework helps you serialize object from the Action Message Format to it's php equivalent. For example, you will be able to send and/or receive arrays inside your actionscript code.
If you want to work with a .NET back-end, FluorineFx is an excellent open-source option. Some very good examples are included in the download package. You can subscribe to mailing-list and receive direct help from Zoli (creator of the framework).
Let us know if that helps you.


text:
Q: Regarding PHP QUERY <?php

$cat_id = $globalClass->getRow("prod_category","`category`='".$get_cat['id']."'");

for($m = 0; $m<count($cat_id); $m++)

{

$product = $globalClass->getRow1("product","`id`='".$cat_id[$m]['prod_id']."'");
if(!empty($product[0]['id']))
{
for($k=0; $k<count($product); $k++)

{

?>

How can i use order by name in ascending order in $product = $globalClass->getRow1("product","id='".$cat_id[$m]['prod_id']."'");

A: As per you info, i can suggest you as below:
$product = $globalClass->getRow1("product","id='".$cat_id[$m]['prod_id']."' order by name asc");


text:
Q: sed: keep certain contents for matched lines I have numerous sequences in one fasta file like the one below (downloaded from UniProtKB):
>sp|P00045|CYC7_YEAST Cytochrome c iso-2 OS=Saccharomyces cerevisiae (strain ATCC 204508 / S288c) GN=CYC7 PE=1 SV=1
MAKESTGFKPGSAKKGATLFKTRCQQCHTIEEGGPNKVGPNLHGIFGRHSGQVKGYSYTD
ANINKNVKWDEDSMSEYLTNPKKYIPGTKMAFAGLKKEKDRNDLITYMTKAAK

Since they are all amino acid sequences for cytochrome c, I care only about the organism (i.e. Saccharomyces cerevisiae for the above entry). So I wish to modify headers of these sequences as below:
>Saccharomyces cerevisiae
MAKESTGFKPGSAKKGATLFKTRCQQCHTIEEGGPNKVGPNLHGIFGRHSGQVKGYSYTD
ANINKNVKWDEDSMSEYLTNPKKYIPGTKMAFAGLKKEKDRNDLITYMTKAAK

Organism names always come after "OS=" and stop when either one of:

*

*space(.*) # strain information

*space..=

is met.
So could anybody give me some clues on how to make it? Thx!

A: You can use this:
sed 's/.*OS=\([^(]*\).*/>\1/' input


text:
Q: Ubuntu would not start I have been using Ubuntu 20.04 for quite a while now and yesterday I wanted to change my python version while following a tutorial (unfortunately I do not remember the name of the site). The only thing I remember is that after entering a specific command (which was a step in the tutorial) not only python but all other files had started to get deleted. I tried to terminate the operation but nothing helped so I decided to turn off the computer. When I tried to turn it on again Ubuntu did not start and the computer was stuck on a default greeting screen (A screen which shows up for a second before the os starts up).
After I had encountered this problem I entered the BIOS and my Ubuntu os was still present in the start-up options.
My question is: it there some way to restore my previous os? Or I need to install Ubuntu again?
(I had already prepared a bootable USB)

A: Tampering with the standard python version of Ubuntu is a fatal error. You need to reinstall.
Boot a live DVD or USB and reinstall. If your live DVD/USB is the same version as the installed Ubuntu version, you will see a "Reinstall" option. This will reinstall the system in the same setup as the existing installation, without formatting the partitions. That way, your user data and user configuration will be preserved.


text:
Q: Gradle error with jar file on command line This is my first time working with gradle so please be patient. I am building a java project and trying to build and compile it with gradle. The code works just fine on an IDE.
I am running into an error on the command line with I run the command below:
java -jar build\libs\*****.jar

the project builds just fine with:
gradlew build

The error I am getting is:
Exception in thread "main" java.lang.NullPointerException: source
    at java.base/java.util.Objects.requireNonNull(Objects.java:233)
    at java.base/java.util.Scanner.<init>(Scanner.java:595)
    at java.base/java.util.Scanner.<init>(Scanner.java:581)
    at com.***.MortgagePlan.handleData(MortgagePlan.java:20)
    at com.***.MortgagePlan.main(MortgagePlan.java:10)

I am wondering how to fix this error. I have a main class, a customer class along with a text data file in one folder. The build.gradle looks like this:
plugins{
    id 'java'

}

jar{
    manifest {
        attributes 'Main-Class': 'com.***.MortgagePlan'
    }
}

My code requires me to import the scanner, input stream and an arraylist. Any ideas?
ps. the * are not the actual names of my files/ directories. I have blocked out sensitive information

A: You might want to check if your build system and/or IDE is running on the same JVM version as the java command. If those are mismatched, certain features may work in the IDE but not in deployment.


text:
Q: Creating a random ordered list from an ordered list I have an application that takes the quality results for a manufacturing process and
creates graphs both to show Pareto charts of the bad, and also to show production throughput.
To automate the task of testing these statistical procedures I would like to deterministically be able to add records into the database and have the quality tech go to certain graphs and compare to a known good graph. But, I also would like to simulate the results so they would go into the database as if a user was running through the testing process.
One idea I have had is to fill a list with i number good, j number bad1, k number bad 2, etc. And then somehow randomly sort the list before insertion into the database.
So, my question, is there a standard algorithm to take a sorted list of values and create a randomly sorted list?

A: You'll want to use a shuffle algorithm. Make sure to use a proper shuffle algorithm and not a home-baked one, because it may introduce some form of subtle pattern to the data. See this post by Jeff Atwood about the problem with using "random enough" shuffles.

A: Our host has a very good article about card shuffling, I believe some good ideas can be adopted
http://www.codinghorror.com/blog/archives/001008.html

A: Depends on what you need for "randomness".  The easiest way is probably just to through all of the elements into a hash set and iterate over the result.  The order you get will be deterministic, but for most intents and purposes can be considered random.  Alternatively, you can generate random numbers between [0..length] of the list, picking out elements and pushing them onto a new list.  Assuming that list removal is constant time, the result would be a random list generated with O(n) efficiency.

A: Random rnd = new Random();
List<int> orderedList = new List<int>();
List<int> randomList = new List<int>();
while (orderedList.Count != 0)
{
    int index = rnd.Next(0, orderedList.Count);
    randomList.Add(orderedList[index]);
    orderedList.RemoveAt(index);
}

A: A simple answer is to have an array or vector, loop once through it, and for each position visited, pick an element at random from the remainder of the list and swap it with the current element.
You need a reasonable random number generator for this.

A: the way i used to do this was to have a loop that ran a number of times that would generate two random numbers between 0 and the length of the list, then swap those two elements.


text:
Q: Beautiful soup - html parser returns dots instead of string visible on web I'm trying to get the number of actors from: https://apify.com/store which is under the following HTML:

895results

When I send get request and parse response with BeautifulSoup using:
r = requests.get(base_url)
soup = BeautifulSoup(r.text, "html.parser")
return soup.find("span", class_="ActorStore-statusNbHitsNumber").text

I get three dots ... instead of the number 895
the  element is ...
How can I get the number?

A: If you inspect the network calls in your browser (press F12) and filter by XHR, you'll see that the data is loaded dynamically via sending a POST request:

You can mimic that request via sending the correct json data. There's no need for BeautifulSoup you can use only the requests module.
Here is a complete working example:
import requests

data = {
    "query": "",
    "page": 0,
    "hitsPerPage": 24,
    "restrictSearchableAttributes": [],
    "attributesToHighlight": [],
    "attributesToRetrieve": [
        "title",
        "name",
        "username",
        "userFullName",
        "stats",
        "description",
        "pictureUrl",
        "userPictureUrl",
        "notice",
        "currentPricingInfo",
    ],
}
response = requests.post(
    "https://ow0o5i3qo7-dsn.algolia.net/1/indexes/prod_PUBLIC_STORE/query?x-algolia-agent=Algolia%20for%20JavaScript%20(4.12.1)%3B%20Browser%20(lite)&x-algolia-api-key=0ecccd09f50396a4dbbe5dbfb17f4525&x-algolia-application-id=OW0O5I3QO7",
    json=data,
)

print(response.json()["nbHits"])

Output:
895

To view all the JSON data in order to access the key/value pairs, you can use:
from pprint import pprint
pprint(response.json(), indent=4)

Partial output:
{   'exhaustiveNbHits': True,
    'exhaustiveTypo': True,
    'hits': [   {   'currentPricingInfo': None,
                    'description': 'Crawls arbitrary websites using the Chrome '
                                   'browser and extracts data from pages using '
                                   'a provided JavaScript code. The actor '
                                   'supports both recursive crawling and lists '
                                   'of URLs and automatically manages '
                                   'concurrency for maximum performance. This '
                                   "is Apify's basic tool for web crawling and "
                                   'scraping.',
                    'name': 'web-scraper',
                    'objectID': 'moJRLRc85AitArpNN',
                    'pictureUrl': 'https://apify-image-uploads-prod.s3.amazonaws.com/moJRLRc85AitArpNN/Zn8vbWTika7anCQMn-SD-02-02.png',
                    'stats': {   'lastRunStartedAt': '2022-03-06T21:57:00.831Z',
                                 'totalBuilds': 104,
                                 'totalMetamorphs': 102660,
                                 'totalRuns': 68036112,
                                 'totalUsers': 23492,
                                 'totalUsers30Days': 1726,
                                 'totalUsers7Days': 964,
                                 'totalUsers90Days': 3205},


text:
Q: Any wordpress development tool to query its functions? I'm developing Wordpress advanced sites. I have to do a lot of functionalities programmatically, and I need to call a lot of Wordpress functions to access to database with specific queries, get data of users, sanitizing inputs, etc. Now I'm debuggin my code getting results in debug files with file_put_contents function or printing it in error_log. But this is very slow and impractical.
I want to have some advice from advanced users about if exists some development tool to access wordpress functions more organized and efficient than I'm doing.
For example. I want to have array of post with post_type = 'custom_post' In my code I do an WP_Query with neededs arguments and later I dump it to file with file_put_contents function and read it to show result.
I'm looking for tool to can write the same WP_Query and get the result faster. Like a SQL query in PHPMyadmin, where you make a query and get the result.
Or I want to know which is the result of sanitizing function of string, can call sanitizing_function('my string') and check the result instantly without print it in file or log.
I don't know if some tool do what I´m looking for.
Thank you so much


text:
Q: Java regression testing (with AWT involved) possible without stealing desktop focus? I've got regression tests of a Java system that don't bring up any graphical elements but do make use of the AWT event thread.  Is there any way I can set things up to run this test suite in the background on my workstation without it constantly grabbing focus from whatever else I'm working on?  (I'm running this on a mac.)

A: Try running java with -Djava.awt.headless=true parameter. This should work for you if you are not using any graphical elements.  Hopefully, it will prevent the program from grabbing focus while it is running.
java -Djava.awt.headless=true
Here are some links with more information:
http://www.macosxhints.com/article.php?story=20071208235352641

A: You could execute these tests with a virtual desktop, virtual machine (like VMWare) or virtual frame buffer. I'm not sure about Mac, but on Linux it works great with xvfb.

A: If your on a Mac:
Run Tests - Without Focus Loss!


text:
Q: Core Data Relationship Not Persisting I am attempting to add an entity to a set but it is not persisting after the application is closed. My relationship looks like this:

I create a new Task like this:
 guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    // 1
    let managedContext =
        appDelegate.persistentContainer.viewContext

    // 2
    let entity =
        NSEntityDescription.entity(forEntityName: "Task",
                                   in: managedContext)!

    let task = NSManagedObject(entity: entity,
                                insertInto: managedContext)

    // 3
    task.setValue(cell.taskTextField.text, forKeyPath: "name")

    // 4
    do {
        try managedContext.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }

I add the task to a group entity like this:
 groups[0].mutableSetValue(forKey: "tasks").add(task)

Where groups is a NSManagedObject array whose value is loaded in viewDidLoad: like so:
   //1
    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "Group")

    //3
    do {
        groups = try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }

The groups populate properly, I have all the groups I created. But no relationships are present. This prints nothing:
  let set = groups[0].mutableSetValue(forKey: "tasks")
    for tasks in set{
        print(tasks)
    }

This code prints the tasks provided I don't open and close the app. For some reason the data is not persisting when the app is closed. Any Ideas? Thanks

A: Make sure you're saving your context all the way back to up the persistent store (not just the parent context).


text:
Q: CodeIgniter Ion auth customize I try to make an app. I'm using Ion Auth for it.
What I mean is I want to make use of the library.
Current structure of the app:

*

*Posts -ID(pk), Title, Desc,
post_author, post_date

*Comments
-Comment_id(pk), Comment_post_id, comment_author, comment_content

*Backend

Let's say my name is Lisa, Lisa submit a post. It uses the current login and save it to Posts table. It should save Id or name? I do not know how to integrate it with my program.

A: You might want to check out my standard CI project on github to get an idea of how to use it since it sounds like you're fairly new to this.
http://github.com/benedmunds/CodeIgniter-Standard-Project
Good luck with your project.


text:
Q: Ruby on Rails: how to use OAuth2::AccessToken.post? OAuth2::AccessToken.post() method is specified like this in the documentation:
(Object) post(path, opts = {}, &block)
I'm trying to pass some arguments, but seems that I*m doing it wrong:
response = token.post('/oauth/create.js', {:title => "title", :description => "desc"})

The parameters are never reaching the method, values are always nil. So, what is the correct way of using the post method with arguments? And what is that &block?
I'm also getting WARNING: Can't verify CSRF token authenticity. This might be contributing to the problem as well. The case is that I'm using OAuth api from the outside of the app. OAuth 2 is implemented via Doorkeeper gem.
Update: The CSRF warning is gone now after I defined scopes. Also I manage to use this post() method with arguments by providing the as part of the url: "?title=test&...". Still would be nice to know how to use this method as documented.

A: You can use the block to pass parameters to post request:
token.post('/oauth/create.js') do |request|
  request.params['title'] = "something"
end

OAuth2 gem uses faraday, the request object is a faraday request, so you might want to check other ways to pass parameters along with the request
faraday gem => https://github.com/lostisland/faraday

A: The body in a POST or PUT is accessed via the options body param. No documentation on this. Had to look in the oauth client code itself to discover this:
https://github.com/intridea/oauth2/blob/ebe4be038ec14b3496827d29cb224235e1c9f468/lib/oauth2/client.rb
Your example, with correct body would be:
response = token.post('/oauth/create.js', {body: {:title => "title", :description => "desc"}})


text:
Q: Simple, passive way to remove high frequency interference from low power audio I have used the innards of a Korg Mini-KAOSS Pad to add some amusing effects to one of my electric guitars, but in order to do this I had to remove the original input connectors and wire my pickups directly to the input circuitry.
The input voltage is fine, however I do now have a problem with a high pitched digital sounding whine when using effects. My assumption is that the input connectors probably had some type of rolloff circuitry (almost certainly passive) and in removing these I am getting interference from the high frequency oscillators in the DSP circuitry.
As part of my remediation I am increasing shielding, but realise I probably need to add a filter to remove higher frequencies.
tl;dr - is there a simple circuit (ie probably just an R/C) that I can pop in to roll-off rapidly above the usual frequencies I would get from my guitar strings?

A: Can you show us a picture of exactly what you removed? (and maybe the input circuitry)
Any filtering will likely take place after the input amplifier, so it's possible something else is happening.
It certainly wouldn't hurt to add a simple RC filter just in case though, then if the problem persists you know it's something else.
If you do this I would go for something like Olin suggests but adjust the values for your guitar pickups (e.g something like 100k for R1) which will probably be higher than 600 \$\Omega\$.
For line level connections, old equipment was often matched 600 \$\Omega\$ in/out. Nowadays however it's usually Lo-Z out to Hi-Z in. The Hi-Z input is often 10 k\$\Omega\$, but can be higher. You could measure the resistance across your Mini KAOSS input (be sure to do it after any DC blocking cap if present) to find out exactly what you are working with. YOu could also measure your pickups DC resistance to get a rough idea there too.
I can only see a line in connection, which will probably be expecting a lower impedance signal than your guitar can provide. Have you tried putting your guitar through a preamplifier/DI box?
There may possibly be a DC blocking input cap you may have removed, which might cause strange things to happen.
Here is a clip of a typical guitar amp input to give you an idea of what it expects to see. Note the 1 M\$\Omega\$ input resistor.
I'm no expert on guitar (passive coil) pickups but I think they are commonly around 5-20k (varies with frequency)
A piezo pickup will be much much higher.

A: The frequency of the noise will be important and it would be nice if you had an idea of what it was as this will determine the rate at which you will need to roll off.
In any case a simple Butterworth filter might do the trick. You can implement it in a few ways but as far as I have seen the most popular are the Cauer topology and the Sallen–Key topology.
Cauer is passive, implemented only with RC combinations and Sallen-Key is active, requiring an operational amplifier.

A: Yes, a simple passive low pass filter will likely help.  The problem is it will be somewhat dependent on the source impedance.  The filter can be made more complicated to deal with this in various ways, but here is a simple design that is likely good enough:

R2 and C1 form a simple low pass filter.  The -3dB rolloff frequency of this filter is
f = 1 / 2 * Pi * R * C = 34 kHz
However, that assumes the input voltage has zero impedance.  Any impedance of the input source will be effectively added to the R in the forumula above and lower the filter rolloff frequency.  If you know the guitar pickup impedance, then you can adjust R2 or C1 accordingly.  You want to make the rolloff at least 20 kHz, but still low enough to usefully attenuate the unwanted high frequencies.
Many audio pickups and the like are designed for 600 Ω load.  R1 is there to present a reasonable load to the input signal and also to make its impedance somewhat predictable to the R2/C1 filter.  You have to check what load your pickups really want.  As I said, 600 Ω wouldn't be surprising but it could easily be rather different too.  The values in the circuit above are rough examples if indeed the source is around 600 Ω and the input impedance of the amplifier is "high".  I'm trying to show you how this filter works so you can adjust it to whatever your conditions really are.
For the circuit above, the signal impedance as seen by the R2/C1 filter can only be from zero to 620 Ω.  That gives a -3dB rolloff range of 21-34 kHz, which should be good enough.  Note that if the actual source impedance is really much higher than 620 Ω, then R1 will attenuate the signal a lot and you won't get much out.  Again, you need to adjust the values to your actual case.


text:
Q: search and heighlight row in asp.net Search in asp and highlight result in grid view row asp
how can i do that???????????
 <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" Width="600px"
                          AllowPaging="True" PageSize="8"
                          CssClass="Grid"
                          AlternatingRowStyle-CssClass="alt"
                          PagerStyle-CssClass="pgr" DataSourceID="SqlDataSource1"  >
    <AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
                      <Columns>
                          <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
                          <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
                          <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
                          <asp:BoundField DataField="Time" HeaderText="Time" SortExpression="Time" />
                          <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
                      </Columns>

    <PagerStyle CssClass="pgr"></PagerStyle>
            </asp:GridView

A: If grid doesn't filter the rows, you can add a css class in RowDataBound event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;
    if(/*row matches search pattern*/)
    {
        row.CssClass = "HighlightedRow";
    }
}


text:
Q: Reading multiple records from Text file in C# I need some logic/programming help with reading more than one record from a text file. I can read line for line, but I need to stop as soon as the record is finished, push that object to a list, and then continue with a new record until the next one comes up, save to list, etc...
The header of the record always start with G as the first char. The rest if V (Variable), D (Coordinates), M (Insertion Point), etc...
The file contents looks like this: (dummy data)
G FEATURE01 LEVEL01
M -10.5132 10.0000 697.5086
V \~\@ENTITY=LINE
V \~\@PENSTYLE=0
V \~\@PENTHICK=1
D -10.5089 12.0797 697.8155
D -10.4971 13.6198 698.0429
D -10.0399 17.3069 698.5913
D -10.7665 11.6108 699.2279
D -10.6769 15.9840 699.8735
D -10.8229 13.6024 710.4438
G FEATURE02 LEVEL02
M -10.2681 10.0000 700.4186
V \~\@ENTITY=LINE
V \~\@PENSTYLE=0
V \~\@PENTHICK=1
D -10.2269 10.6946 700.4941
D -10.2585 13.1788 700.7637
D -10.2937 15.9480 701.0642
D -10.9494 20.5230 709.1840
D -10.9277 21.4909 709.4517
D -10.8335 23.3862 709.9763
G FEATURE01 LEVEL02
M -15.4500 10.0000 700.4174
V \~\@ENTITY=LINE 0.00 0 0.00 A A
V \~\@PENSTYLE=0 0.00 0 0.00 A A
V \~\@PENTHICK=1 0.00 0 0.00 A A
D -15.5690 12.3042 700.6673
D -15.3502 14.3130 700.8863
D -15.1219 16.7179 701.1480
D -15.0628 17.3409 701.2427
D -15.5481 20.8968 709.2855
D -15.3132 22.9163 709.8470
D -15.1355 23.2957 709.9627
G FEATURE03 LEVEL03
P 0.0000 0.0000 0.0000 270.0000 90.0000
M -12.8612 14.2951 737.6336
V \~\@ENTITY=LINE
V \~\@PENSTYLE=1
V \~\@PENTHICK=1
V @0ver1ay=KOOS
D -13.2715 15.5321 736.5965

So, as from above there is 4 records in the text file.
Any ideas?
Thanks

A: Here is a piece of code that I have tried to put together for clarity rather than robustness etc. it should put you on the right track.
1- I created a simple record class which will be created for each record (lines starting with 'G') and then all subsequent lines are added to this record until a new start of record is encountered in the file.
class Record
{
  public List<string> Lines { get; private set; }
  public Record()
  {
    Lines = new List<string>();
  }
}

2- Then the following code will process the file line by line, creating new records as they occurr and adding each record to a Record collection.
  // Collection to be populated with the record data in the file
  List<Record> records = new List<Record>();

  using (FileStream fs = new FileStream("datafile.dat", FileMode.Open))
  using (StreamReader rdr = new StreamReader(fs))
  {
    string line;

    // Read first line
    line = rdr.ReadLine();
    while (line != null)
    {
      // Check if we have a new record
      if (line.StartsWith("G"))
      {
        // We have a start of a record so create an instance of the Record class
        Record record = new Record();

        // Add the first line to the record
        record.Lines.Add(line);

        // Read the next line
        line = rdr.ReadLine();

        // While the line is not the start of a new record or end of the file,
        // add the data to the current record instance
        while (line != null && !line.StartsWith("G"))
        {
          record.Lines.Add(line);
          line = rdr.ReadLine();
        }

        // Add the record instance to the record collection
        records.Add(record);
      }
      else
      {
        // If we get here there was something unexpected
        // So for now just move on and read the next line
        line = rdr.ReadLine();
      }
    }
  }


text:
Q: Azure graph explorer I would like to try/test Azure AD user creation Graph API using Graph API explorer.

*

*Is there is any restrictions that we can test this API thru application permission only not as signed in user?

*If so, can I register the postman application in Azure AD and call user create graph API thru postman with application permission?

*Does it require premium license to call http connector and Microsoft organisation account instead of Microsoft personal account?

*Is this Graph API explorer can be used for signed in permission mode only?
I am bit confused. Could someone please suggest the best approach on this?

A:
Is there is any restrictions that we can test this API thru
application permission only not as signed in user?

Of course, you need to grant application permissions to the application in Azure AD, then use the client credential flow to obtain the token, and then call the api in postman.

If so, can I register the postman application in Azure AD and call
user create graph API thru postman with application permission?

Of course, I suggest you do the same.

Does it require premium license to call http connector and Microsoft
organisation account instead of Microsoft personal account?

Not needed.

Is this Graph API explorer can be used for signed in permission mode
only?

Yes, Graph explorer can only be used to authorize the user login mode, and it uses delegated permissions by default.


text:
Q: Unable To Keep Textbox Value When Asp.net File Upload On change event call? i am trying to keep Textbox value when i upload image by using hidden fields but after alot of try i am posting this issue that it always refresh textbox and my text box value flushes ??
my code is,
var hv = $('#hidden1').val();
var img = document.getElementById("<%= Btn_Preview.ClientID%>");
img.click();
$('TxtBxDesignation').val() = hv;

actualy i call this script on change event and also calling .click event of preview button to view image on the same time i upload image
<asp:FileUpload runat="server" ID="FU_Img" onchange="FU_Img_onchange(this);" /><br />
                                    <asp:Button ID="Btn_Preview" runat="server" Text="Preview" BorderColor="Transparent"
                                        BackColor="Transparent" OnClick="Btn_Preview_Click" />

but its not working for me and textbox refresh when image upload and if i freez this line
"var img = document.getElementById("<%= Btn_Preview.ClientID%>");"

it works smoothly but for sure no chnage image ???
hopes for your suggestion thanks

A: When a file is selected, on PostBack PostedFile property gets initialized with HttpPostedFile object.Since http request can't maintain state, and PostedFile is initialized with HttpPostedFile Object so it looses it's state.
One way to retain state is to store fileupload object in session and in the post back get the values back from it. Use this code in Page_Load.
if (Session["FileUpload1"] == null && FileUpload1.HasFile)
    {
        Session["FileUpload1"] = FileUpload1;
        Label1.Text = FileUpload1.FileName;
    }

else if (Session["FileUpload1"] != null && (! FileUpload1.HasFile))
{
    FileUpload1 = (FileUpload) Session["FileUpload1"];
    Label1.Text = FileUpload1.FileName;
}

else if (FileUpload1.HasFile)
{
    Session["FileUpload1"] = FileUpload1;
    Label1.Text = FileUpload1.FileName;
}

OR
You may also go for  AJAX AsyncFileUpload control for AJAX based upload and it retains path. Check below URLs on this:
1.) http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx
2.) http://www.aspsnippets.com/Articles/Using-ASP.Net-AJAX-Control-Toolkits-AsyncFileUpload-Control.aspx

A: Maintaining the ViewState
When a form is submitted in ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a  control.
Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to maintain the ViewState, include the directive
      <%@ Page EnableViewState="true" %>

Please visit these VIEWSTATE to learn more about view state

A: Take a look at this thread for a technique used to maintain state across postbacks.


text:
Q: Functions in different C++ classes So, I've started a course on C++, but I have a slight problem when it comes to functions with different classes.
I've learnt to create functions the following way:
string someFunction(){
return "blah";
}

However, with different classes it seems to be different.
I've tried the following and it didn't work:
(Startup.h)
#ifndef STARTUP_H
#define STARTUP_H
#include <string>

class Startup{
    public:
        Startup();
        string getBuild();
    };

#endif

(Startup.cpp)
#include "Startup.h"
#include <iostream>
#include <string>

using namespace std;

string build;

Startup::Startup(){

    build = "1.0.0 Alpha";
    getBuild();

}

string Startup::getBuild(){

    cout << "The build is: " << build << endl;

}

(main.cpp)
#include "Startup.h"
#include <iostream>

using namespace std;

int main(){

    Startup startup;

    return 0;

}

The error message is:

C:\Users\someone\Desktop\C++\Projects\Stuff\Startup.h|8|error: 'string' does not name a type|

Also, I know I could just print out the build in the Startup function but I'm just experimenting right now.

A: The string class is in the std namespace. Use it like this:
class Startup{
    public:
        Startup();
        std::string getBuild();
};

A: Rewrite your class as this:
#ifndef STARTUP_H
#define STARTUP_H
#include <string>

class Startup{
    public:
        Startup();
        std::string getBuild();
    };

#endif

Your code should work now. getBuild doesn't return anything, so give it a return type of void, in both definition and declaration.  Prepend std:: to cout and string as well, explaining your error.

A: Chiming in late here, but what you probably wanted is a combination of stuff:
In .h
#ifndef STARTUP_H
#define STARTUP_H
#include <string>

class Startup{
public:
    Startup();
    std::string getBuild();
  //^^^
private:
    std::string buildName; // store the variable inside the class instead
};

#endif

In .cc
#include "Startup.h"
#include <iostream>
// no need to include <string>, it was included previously

using namespace std; // This makes it so you don't have to write `std::` infront of `string` and `cout`

Startup::Startup(){
    build = "1.0.0 Alpha";
    cout << "The build is: " << getBuild() << endl;
}

// Kind of unnecessary function
string Startup::getBuild(){
    return buildName;
}


text:
Q: C# Access denied to path in a Windows Application I've built a Windows Application using c#, on Windows 7.
Everything was working fine, so I've created a Setup Wizard project and then built it. Once I install the app, I can open it correctly, but when I try to make some action that writes a text file(with logging purposes) it crashes, thrwoing me the following error message:

UnauthorizedAccessException
Access to the path 'C:\Program Files
  (x86)\MSProgram\MSProgram\log.txt' is
  denied.

When I manually give that folder full rights, it works fine. Now, the question is the following:
How do I programmatically give the app rights for writing things in my app's directory? So every person that downloads it doesn't experience the same problem.

A: Generally it's not good practise to write to the Program Files directories, I usually write log file to the AppData folder, which you can get at by using:
var logFilename = Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.ApplicationData), "log.txt")

You will probably want to create a directory in there or give the log file a more descriptive name.  You may also want to consider if multiple instances of your app could be running for the same user.
If you must write to the Program Files directory you will need either run the application with administrator privileges, either using run as administrator, or by requesting higher privileges on your application.  Another possibility would be to setup your installer to give the installing user full folder rights, although how to do this will depend on the installer you are using.
Hope this helps.
Andy

A: Don't.  Applications should not write data into their installation directory directly.  Doing so will make the application work poorly on Windows Vista and Windows 7, since it's not the proper way of saving data.
You should instead use Environment.GetFolderPath, and write into a good location, such as the user's application data folder (Environment.SpecialFolders.ApplicationData).

A: The solution is not to grant rights to that directry but to instead write to a folder that is more suitable for application logs.  The "Program Files(x86)" and "Program Files" is a place for application installation, not logging.
A more appropriate location would be the per user data folders

*

*%AppData%

*%LocalAppData%

Or the result of Environment.GetFolderPath for the following values

*

*SpecialFolder.ApplicationData

*SpecialFolder.LocalApplicationData

*SpecialFolder.CommonApplicationData

A: To add to what Reed Copsey and JaredPar wrote in their answers:
Writing to the "Program Files" or "Program Files (x86)" directories is not advisable, and for good reason. The reason for this is that granting permissions for any application to write and/or change files in these directories is a security problem - it allows program that are "jeopardized" (e.g. your browser, in case it has a security bug) to alter programs files, infecting them with viruses or worms, etc.
Windows has dedicated folders for application and user data, and any program accessing data in these folders is expected to treat it as "untrusted data" due to the lower security restrictions on those folders. One such folder is Environment.SpecialFolders.ApplicationData - as indicated by Reed.


text:
Q: In vbs/hta how do I tell if I reach the end of a word document? I am currently creating a large script to automate a Microsoft word document to pull out tables and put them into a new document. But I need to know when I reach the end of the document so I can move on to the next document.
Set objWord         = CreateObject("Word.Application")
Set objNewDoc       = objWord.Documents.Add()
Set objNewSelection = objWord.Selection
Set objDoc = objWord.Documents.Open( C:/Users/blahdoc.doc )
Set objSelection = objWord.Selection

This isn't the script but its how I defined and opened the documents for reading. I will happily insert more details if and when there needed.
I did look around for similar questions but didn't find any that apply. If you do sorry ahead of time ;)

A: You actually don't need to worry about "reaching the end of the document."  Thankfully, the tables are stored in a Tables collection which is a property of a Word.Document. You can iterate through all the tables like so:
For Each oTable In objNewDoc.Tables
    If Left(oTable.Cell(1, 1).Range.Text, Len(oTable.Cell(1, 1).Range.Text) - 2) = "Some string" Then
        MsgBox "Found one!"
    End If
Next

One issue I ran into when putting this together is that all Cells' Text have an End-of-Cell Marker composed of two characters: a Carriage Return (ascii 13) followed by a BELL (ascii 7).  I used Left to strip those off so I could compare the text against a string value, which is what I understand you are trying to do.