text:
Q: Formatting MySQL query results let me start off with the fact that i'm still kind of new to php/mysql.
I'm trying to build a system that can be used to record jobs completed for customers that keeps track of job numbers, customer name, equipment, dates, and employee's assigned to the task.
I have a table setup to handle the employee's assigned, but I can't seem to figure out how to format the results the way I would like.
There could be multiple employee's assigned to the same job over several days. So I setup a table like:
job_ID  |  employee_name  |  date_worked  |  hours_worked
  1     |      Dave       |   2010-1-2    |     4.5
  1     |      Dave       |   2010-1-3    |     4.0
  1     |      Mike       |   2010-1-2    |     6.0
  2     |      Bill       |   2011-5-7    |     8.0
  2     |      Bill       |   2011-5-8    |     6.5
  2     |      Dave       |   2011-5-7    |     4.0
  2     |      Dave       |   2011-5-8    |     4.5

What i'm looking to do with the results is output it like:
    Job # = 1
    Employee  |  2010-1-2  |  2010-1-3  |
      Dave    |     4.5    |     4.0    |
      Mike    |     6.0    |      0     |

    Job # = 2
    Employee  |  2011-5-7  |  2011-5-8  |
      Bill    |     8.0    |     6.5    |
      Dave    |     4.0    |     4.5    |

Can anyone offer advice?
EDIT
Ok, so I guess I left out some information.
I have a table (job_list) that is used to keep records.
This table records the job_id, client, equipment, location, call date, response date, completion date, etc.
Then I have a table (employee_list) that lists all employees by id, and name.
The idea behind the table I posted earlier was to be the table that just records who was where, on what day, and for how long.
I've amended the table i posted to have employee_id.
And I would like to display the results in php to look like the output i posted.  I just don't know how to do it.
What other information can I provide?  Apologies for my lack of understanding on what I need to post :-/
And if my approach is completely horrible, I did say I'm still new to this...

A: This is basically a PIVOT but MySQL does not have a PIVOT function so you will need to replicate it using an aggregate function and a CASE statement.  If you know all of the values that you want to transform your query will be similar to this:
select employee_name,
  sum(case when date_worked = '2010-01-02' then hours_worked else 0 end) `2010-01-02`,
  sum(case when date_worked = '2010-01-03' then hours_worked else 0 end) `2010-01-03`
from yourtable
group by employee_name

See SQL Fiddle with Demo
The result is:
| EMPLOYEE_NAME | 2010-01-02 | 2010-01-03 |
-------------------------------------------
|          Bill |          0 |          0 |
|          Dave |        4.5 |          4 |
|          Mike |          6 |          0 |

If you have an unknown number of values, then you can use a prepared statement to generate this dynamically:
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when date_worked = ''',
      date_worked,
      ''' then hours_worked else 0 end) AS `',
      date_worked, '`'
    )
  ) INTO @sql
FROM yourtable;

SET @sql = CONCAT('SELECT employee_name, ', @sql, '
                  FROM yourtable
                   GROUP BY employee_name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See SQL Fiddle with Demo
Both will produce the same result.


text:
Q: facebook registration plug in custom fields not working I'm having a few problems with this. First, the iframe will only render the "name" field and none of the others, even those that are not custom. I read somehwere that the fb:registraiton tag might be better to use for custom fields, but I don't know how to make that work since I can't find any examples of it using custom fields. This is my code:
<iframe src="https://www.facebook.com/plugins/registration?
             client_id=39672055*******&
             redirect_uri=http://mydomain.com/signedRequest.php&fb_only=true&fields="[
 {'name':'name'}, //only the name field will render
 {'name':'email'},
 {'name':'location'},
 {'name':'gender'},
 {'name':'password'},
 {'name':'neighborhood','description':'In What Neighborhood Do you Live?','type':'text', 'view':'prefilled'}
]"
        scrolling="auto"
        frameborder="no"
        style="border:none"
        allowTransparency="true"
        width="100%"
        height="330">
</iframe>

A: I found this solution from another stack question. The issue for me seems to have been the opening quote" before the opening brace of the fields attribute. This syntax works:
<iframe src="https://www.facebook.com/plugins/registration.php?
        client_id=MY_APP_ID&
        redirect_uri=MY_CALLBACK_URL&
        fields=[
                { 'name':'name' },
                { 'name':'first_name' },
                { 'name':'last_name' },
                { 'name':'company', 'description':'Company Name', 'type':'text' },
                { 'name':'email' },
                { 'name':'phone', 'description':'Phone Number', 'type':'text' },
                { 'name':'address1', 'description':'Address', 'type':'text' },
                { 'name':'city', 'description':'City', 'type':'text' },
                { 'name':'state', 'description':'State/Region', 'type':'text' },
                { 'name':'zip', 'description':'Zip Code', 'type':'text' }
                ]"
        scrolling="auto"
        frameborder="no"
        style="border:none"
        allowTransparency="true"
        width="100%"
        height="600">
</iframe>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating a Dropdown Based on the Selection of Another Dropdown - replaceWith Not Working I have a couple of drop downs, when a venue is choosen from the first one, it should populate the second drop down with floor values. Using jQuery AJAX I am able to get the selected venue, send that back to my controller and get the data needed for the second drop down. However I am not able to replace the existing drop down with the new data. This is the HTML for the two drop downs:

                        Venue

                            <select class="form-control bs-select" name="venue" id="venue_select"
                                    data-noneSelectedText="No venue selected"
                                    data-validation="required"
                                    data-validation-error-msg-required="Please select a venue"
                                    data-dynamic-visible="true"
                                    data-dynamic-relation="venue"
                            >
                                <option value="0" >Select a Venue</option>

                                @foreach($venues as $venue)
                                    @if(!is_null($venue->name))
                                    <option value="{{$venue->id}}" >{{ $venue->name  }}</option>
                                    @endif
                                @endforeach
                            </select>

                        Location Floor

                            <select class="form-control bs-select" name="floor" id="floor_select"
                                    data-validation="required"
                                    data-validation-error-msg-required="Please select a floor"
                            >
                                <option value="">Select a Floor</option>
                                @foreach($locations as $location)

                                    <option value="{{ $location->floor_id }}"
                                            data-dynamic-relation-for="venue"
                                            data-dynamic-relation-targets="[{{ $location->id }}]"
                                            {{ old('floor_id') === (string) $location->floor_id ? ' selected' : '' }}
                                    >{{ $location->floor }}</option>

                                @endforeach
                            </select>

There is a lot included the HTML for these drop down (I didn't write the code) that appear to be interfering with replaceWith() function. The jQuery code that retrieves the data for the second drop down looks like this:
$('#venue_select').on("change", function(){
    var selectVenueId = this.value
    console.log('Selected venue', selectVenueId);
    _xhr = $.ajax(
        url: $("meta[name='root']").attr("content") + '/app/settings/locations/data',
        type: 'POST',
        headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
           },
        data: {
          venue_id: selectVenueId,
          },
        dataType: 'JSON',
        async: true,
        cache: false,
        error: function (jqXHR, textStatus, errorThrown) {
            _this.SetLoading(false);

            _xhr = null;
        },
        success: function (response) {
            _this.SetLoading(false);

            var locations = response;

            console.log('Locations: ', locations);

            var listItems = '<option value="">Select a Floor</option>';

            for (var i in locations){
                listItems += "<option value='" + i + "'>" + locations[i] + "</option>";
            }

            $('#locations-new .block-content #select_floor select#floor_select').replaceWith('<select class="form-control bs-select" name="floor" id="floor_select"></select>' + listItems + '</select>');

            console.log('listItems: ', listItems);

            _xhr = null;
            }
       });
});

This is what I get on the front end when I run it:

It's not replacing the second dropdown but adding it.
You may have noticed the additional elements in the select tags:
data-dynamic-visible="true"

data-dynamic-relation-for="venue"

They appear to have a bearing on dynamic updating, but no Google searches have turned up any reference to these. There is a dynamicRelation.js file which looks like this:
define([
    "jquery",
    "underscore"
], function(s) {

    var DynamicRelationUiClass = function () {
        // Private vars
        var _this = this;

        // Private functions
        var _onUpdate = function (e) {
            _this.Update(e.currentTarget);
        };

        var _construct = function () {
            $(document).on("change click", "[data-dynamic-relation]", _onUpdate);

            $('[data-dynamic-relation]').each(function () {
                _this.Update(this, 0);
            });
        };

        // Public functions
        this.Update = function(element, duration) {
            if (_.isUndefined(duration)) { duration = 250; }

            element = $(element);

            var relationGroup = element.data("dynamic-relation"),
                currentValue = element.val();

            if (parseInt(currentValue) !== NaN) { currentValue = parseInt(currentValue); }

            $('[data-dynamic-relation-for="' + relationGroup + '"]').each(function () {
                var t = $(this),
                    targets = t.data('dynamic-relation-targets'),
                    found = targets.indexOf(currentValue) !== -1;

                t.prop("disabled", !found);
                if (!found && t.prop("selected")) { t.prop("selected", false); }
            });

            $('.bs-select').selectpicker('refresh');
            $('.multiselect').multiSelect('refresh');
        };

        _construct();
    }

    return DynamicRelationUiClass;
});

I would like any clue to a solution, especially if someone has information of the dynamicVisible feature, or short of that how to get the replaceWith() to work.


text:
Q: Photos being stored on Amazon S3 bucket through Java's AWS SDK gain 1 pixel in height I've encountered this strange issue while trying to transfer images from my Java webserver to my Amazon S3 bucket. I am developing a mobile application for both Android and iOS (with Swift), which allows users to upload images from their device to the server.
The images (Bitmaps for Android, and UIImage for iOS) are both converted to Base 64 before being sent to my webserver (made in Java to conform to HTTP/1.1 standards). The data arrives to the server intact (meaning by printing the base 64 before it is sent, and after it arrives to the server, they are identical). From there I decode the String into a byte array. I have isolated the issue to have something to do with the actual sending process to the Amazon S3 bucket. Take the following snippet for example:
//image is a byte array, and imageid a String
InputStream is = new ByteArrayInputStream(image);
AmazonS3 s3 = new AmazonS3Client();
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType("image/jpeg");
meta.setContentLength(image.length);
s3.putObject(new PutObjectRequest("bucket", "images/" + imageid + ".jpg", is, meta));

This code works fine for Android, where the images upload at 1080x1080 without an issue. However, when I try to upload an image from iPhone, the resolution becomes 1080x1081. Confused by this, I decided to try saving the image locally as well as send it to the server using ImageIO. Strangely enough, using:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(image));
File f = new File("image.jpg"); //Removed file creation for brevity
ImageIO.write(img, "jpg", f);

When I used the "identify" command from Imagick on the local image, the output is:
image.jpg JPEG 1080x1080 1080x1080+0+0 8-bit DirectClass 53.4KB 0.000u 0:00.000

However when I transfer the image from the S3 bucket and do the same thing, I get:
image2.jpg JPEG 1080x1081 1080x1081+0+0 8-bit DirectClass 56.2KB 0.000u 0:00.000

Again, this only occurs with uploads from iOS. The image itself is still valid and opens without an issue. For example:
Face Down Camera Image
(Picture was taken while the camera was facing down, hence the dark image)
I suspect the issue may have something to do with differences in how the images are encoded into Base 64. I use the Bouncycastle library to do the encoding on Android, as well as the decoding on the webserver, and use an NSData function in swift as described below:
let imageData = UIImageJPEGRepresentation(normImg, 0.4)
let base64 = NSString(data: imageData!.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0)), encoding: NSUTF8StringEncoding) as! String

What confuses me the most is how ~3KB of data (which makes sense for 1080 extra pixels at 3 bytes per RGB pixel) seems to just be appearing out of nowhere, and why it seems to be isolated to iOS.
Hopefully I was clear enough with my question and the debugging I have done to provide as much information as possible. If you need any more information, please let me know!
Edit: Just ran a test and uploaded a 1080x1080 image by command line to the S3 bucket. It also adds the extra pixels.
Edit2: Decided to change how the file uploading process worked. It is no longer being converted to base 64, and the NSData of the UIImage is being converted into a byte (UInt8) array and uploaded. The still leads to the same result of having the extra pixel, which rules out my original speculation that it had something to do with the base64 encoding. Android still seems to function properly on the other hand, which leaves me to believe that the binary data of the image is not completely valid for whatever reason. I believe the EXIF data is formatted differently between Android and iOS, though I don't know what would cause this.


text:
Q: How to get a solution without any hard score by optaplanner engine We want to find a way how to avoid hard scores for the optaplanner solutions.
In our enterprise optimization project, it's not allowed to generate a solution with hard constraint scores. But actually the generated results by Optaplanner engine always have some allocations with hard constraint scores. when this situation happens, we will try to move the entity to the null allocation currently instead to clean the hard scores.
The above solution seems not the right way to avoid hard scores. Are there other methods to achieve that goal?

A: It is hard to know what is the issue without having any example of the algorithm configuration and examples of the problem, but hope this helps.
If you get constraint violations (as that is what hard scores are) in your solution it means no feasible solution is being found. This can have a couple of reasons:
* There is no feasible solution to begin with
* The optimisation algorithm doesn't step fast enough or the termination makes it terminate too early.
Depending on the problem at hand it can be hard to verify whether a feasible solution exists, but one could draft a simple problem that is to be solved by Optaplanner to verify whether it can find it (it should be able to). If it doesn't then something is wrong with the modelling or objective function.
For the second point the best way to go forward is to keep track of the score calculation speed, it should preferably be in the thousands of steps per second ( > 1000/sec). If it isn't investigate using Drools or IncrementalScoreCalculator for fasting computation. Also, use the benchmarker module to see if your algorithm is appropriately configured.
Lastly, do you have a local search phase ? A construction phase alone is way more likely to return an infeasible solution as opposed to one with a local search phase.

A: In the user guide, see overconstrained planning. An approach of nullable=true and a medium score penalty on every null assignment should do what you want. See K88's answer too.


text:
Q: Load data Query with regular expression I need to load data that is coming from a csv file to a particular table. I am loading 5 fields of the csv file into the table.  I need to apply regular expression for a particular field value in the csv file. IF it doesnt match i need to reject that record. Is it possible ?
This is my load data query:
LOAD DATA LOCAL INFILE ''/test.csv''
INTO TABLE TEST_TABLE FIELDS
TERMINATED BY '',''
LINES TERMINATED BY ''\n''
    (@FIELD1,@FIELD2,@FIELD3,@FIELD4,@FIELD5)
SET
    FIELD1=STR_TO_DATE(@FIELD1,''%d-%m-%Y''), FIELD2=nullif(@FIELD2,''''),
    FIELD3=nullif(@FIELD3,''''), FIELD4=nullif(@FIELD4,''''),
    FIELD5=nullif(@FIELD5,'''');

If the values that is coming in field4 in csv file is equal to either 200 or 300, i need to consider that record and load other values otherwise i need to reject the record.
Sample file::

1),234232323,STATUS,200,33
2),45454545,STATUS,300,33
3),646546445,STATUS,100,33

here 1st and 2nd record should be considered and 3rd record should be rejected.

A: LOAD ...;
DELETE TEST_TABLE WHERE field4 NOT IN (200,300);


text:
Q: API to get android system properties is removed in arm64 platforms I am using __system_property_get() from sys/system_properties.h to get a system property. I am trying to use r10c ndk because I need arm64 toolchain.
__system_property_get() is defined in libc.so. Below is the readelf output of libc.so for armv5/armv7a.
readelf -Ws libc.so | grep property_get

       194: 00009100    20 FUNC    GLOBAL DEFAULT    4 __system_property_get
       198: 00009100    20 FUNC    GLOBAL DEFAULT    4 __system_property_get

But, looks like it has been removed for arm64 version! I am getting a linker error saying it is not defined. I analyzed all the shared libraries of arm64 but none of them have that symbol.
Is there an alternate API to get the system property in the native code?
Thank you!

A: In older NDKs this was not an officially supported API. It was mistakenly exposed to the 32-bit ABIs early on, but wasn't exposed to the 64-bit ABIs until it was officially supported. Regardless, it is exposed by the system at all API levels, so newer NDKs are able to use this regardless of ABI or minSdkVersion.

A: It's useful API for native apps, just as it is for Java apps, it originates from the native side (see http://rxwen.blogspot.com/2010/01/android-property-system.html), and other Android system code uses it, so it's unlikely to go away soon.
#include <android/log.h>
#include <dlfcn.h>

#if (__ANDROID_API__ >= 21)
// Android 'L' makes __system_property_get a non-global symbol.
// Here we provide a stub which loads the symbol from libc via dlsym.
typedef int (*PFN_SYSTEM_PROP_GET)(const char *, char *);
int __system_property_get(const char* name, char* value)
{
    static PFN_SYSTEM_PROP_GET __real_system_property_get = NULL;
    if (!__real_system_property_get) {
        // libc.so should already be open, get a handle to it.
        void *handle = dlopen("libc.so", RTLD_NOLOAD);
        if (!handle) {
            __android_log_print(ANDROID_LOG_ERROR, "foobar", "Cannot dlopen libc.so: %s.\n", dlerror());
        } else {
            __real_system_property_get = (PFN_SYSTEM_PROP_GET)dlsym(handle, "__system_property_get");
        }
        if (!__real_system_property_get) {
            __android_log_print(ANDROID_LOG_ERROR, "foobar", "Cannot resolve __system_property_get(): %s.\n", dlerror());
        }
    }
    if (!__real_system_property_get) return (0);
    return (*__real_system_property_get)(name, value);
}
#endif // __ANDROID_API__ >= 21

A: Confirming @bleater's answer as a workaround for the unexposed __system_properties_* symbols: dlopen libc and dlsym as needed.


text:
Q: What led Hausdorff to consider the possibility of "unerreichbar" or "weakly inaccessible" cardinals? I would like to know how it was that Felix Hausdorff came to consider the possibility of, if not indeed necessity of, what he was the first to call "unerreichbare" or "unreachable" cardinals, or what we call, somewhat less clearly, "[weakly] inaccessible cardinals" today. To me such a move clearly constitutes a huge leap of imagination, much like the earlier one Cantor made when he proved that not all infinite sets have the same size. [even if that should have been clear already from the elementary proof that there can be no bijection between ANY set and its powerset] I suspect there was something in Hausdorff's very rich research project, mostly on the ordinals at the time, that "compelled" him to hypothesize such, to his day, very "large" cardinals; indeed cardinals much larger than, and "unreachable" from, the entire series of Beth cardinals, [at least from Beth1 to Bethω as were already known at the time]? ... I also haven't yet found much written about what the reception of Hausdorff's unreachable cardinals was by his contemporaries. I assume many of the latter must have thought the notion completely preposterous, but even that I haven't been able to confirm.  Any direction anyone can provide to me about such things will be greatly appreciated!

A: As bof said, I think the notion is actually natural enough that it would be weird to not ask about it. But in fact there is a good reason for Hausdorff to explicitly consider it.
The big question in set theory at the time was of course the continuum hypothesis. In $1904$, Konig had proved an interesting technical result about the continuum, namely $$cf(2^\omega)>\omega$$
(actually he proved something more general). Indeed this was the only nontrivial result about the continuum's cardinality known when Hausdorff wrote his book in $1908$, and as Cohen would observe later the only nontrivial result provable in $\mathsf{ZFC}$ at all. Moreover, Hausdorff had a role in this result: it was extracted from a failed argument against $\mathsf{CH}$ put forth by Konig, whose error was detected by Hausdorff (and independently Konig himself). See here for more on this.
So by the time Hausdorff is writing in $1908$, there's already a known connection between the biggest question around and the notion of cofinality, and Hausdorff himself has been involved in forming this connection. Understanding the role of cofinality in cardinal arithmetic is therefore a very natural topic for him to think about, and among the first questions which arise is: "Are the uncountable regular cardinals exactly the uncountable successor cardinals?" So right there the notion of weak inaccessibility emerges naturally.
(That said I don't know of a source which definitely says that this is why Hausdorff introduced them. But it was definitely "in the air" at the time.)

It's also worth noting that a certain amount of the idea "weakly inaccessible cardinals are really big" took a while to become clear. Specifically, slogans like

weakly inaccessible cardinals are so big we can't prove they exist

are rather common, even if they're fairly misleading (e.g. since we can have $2^\omega$ be weakly inaccessible if weakly inaccessibles are consistent in the first place). Now remember that the idea behind such slogan comes from combining two theorems of Godel, and one communal agreement:

*

*$\mathsf{ZFC}$ captures "what we can prove about set theory."

*$\mathsf{ZFC}$ cannot prove that $\mathsf{ZFC}$ has a model (let alone a transitive model!) unless $\mathsf{ZFC}$ is inconsistent.

*If $\alpha$ is weakly inaccessible, then $L_\alpha\models\mathsf{ZFC}$.
But $\mathsf{ZFC}$ wouldn't even be introduced (let alone essentially universally accepted) in its modern formulation until the late $20$s, while Godel wouldn't prove $(2)$ and $(3)$ until the early $30$s and $50$s respectively.

*

*OK fine, we can easily sidestep $(2)$ above: it would be enough to show instead that $L_\alpha\models$ "There are no weakly inaccessible cardinals" if $\alpha$ is the least weakly inaccessible cardinal, which follows immediately from the appropriate absoluteness of weak inaccessibility. But as far as I'm aware of, even though it's easier that sort of argument post-dated the second incompleteness theorem, so the point about historicity still stands. EDIT: it turns out that my history is a bit off; absoluteness proofs that $\mathsf{ZFC}$ doesn't prove the existence of a strongly inaccessible cardinal were given in the $20$s. Still, this significantly postdates Hausdorff's work.
And finally, observe that point $(3)$ is actually surprisingly subtle. For strong inaccessibility things are very simple: it's almost trivial to show $V_\alpha\models\mathsf{ZFC}$ whenever $\alpha$ is strongly inaccessible. So as soon as we think about absoluteness, or learn the second incompleteness theorem, it's obvious that strongly inaccessible cardinals reach beyond $\mathsf{ZFC}$. However, this argument breaks down for weak inaccessibility: it need not be the case that $V_\alpha\models\mathsf{ZFC}$ if $\alpha$ is weakly inaccessible, and in fact - as noted above - it's possible that $2^\omega$ itself is weakly inaccessible. Instead, some genuine work is needed here: I don't offhand see a way to show that weakly inaccessible cardinals imply the consistency of $\mathsf{ZFC}$ without developing the basic theory of $L$, which is highly nontrivial.
So our modern understanding of the logical strength of weak inaccessibility wasn't available to Hausdorff in $1908$. Of course it's clear from the definition that weakly inaccessible cardinals are pretty big, but there isn't that much evidence at the time that they're particularly special. So I suspect that their reception was much more muted than a reader brought up on the modern story of large cardinals might expect.


text:
Q: Car Racing Game I am currently working on a Car Racing Web game using HTML, CSS and JavaScript.
My work is about to over but I am facing a problem in the game. Let me tell you about the game, there are two cars i.e. White Car and Red Car on a Canvas Element.
The white car is controlled using up, down, left and right arrow keys and the red car is controlled using WASD keys.
My problem is: If I move the white car the red car gets hidden and if i move the red car the white car gets hidden.
The Code is Given Below:

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

      <link rel="stylesheet" type="text/css" href="project84.css">
      <title>Car Racing Game</title>

Car Racing Game

Game Status:

        <canvas id="myCanvas" height="500px" width="700px"></canvas>

          NOTE :  IF THE CARS ARE NOT VISIBLE PRESS ANY ARROW KEY

          *Please Click once on the car before pressing any Arrow Key

            Arrow Keys for White Car

            WASD Keys for Red Car

For output, click the link below:
https://codepen.io/RiYad06/pen/yLMpvLg

A: You need to render all your objects every time.
So when you're handling for example right(), you still need to draw the second car.
 function right() {
  if (car1_x <= 700) {
    car1_x = car1_x + 10;
    console.log(
      "When right arrow is pressed, x = " + car1_x + " | y = " + car1_y
    );
    uploadBackground();
    uploadCar1();
    uploadCar2(); // <<< YOU NEED THIS
  }
  if (car1_x >= 600) {
    console.log("White Car Won!");
    document.getElementById("game_status").innerHTML = "White Car Won!";
  }
}

You can create something like a renderScene() function that you can call in all your handler to avoid repeating yourself too much.

A: You need to invoke upload on 2 cars in the move functions like this:
function up() {
  if (car1_y >= 0) {
    car1_y = car1_y - 10;
    console.log("When up arrow is pressed, x = " + car1_x + " | y = " + car1_y);
    uploadBackground();
    uploadCar1();
    uploadCar2();
  }
}

https://codepen.io/lrazerz/pen/abJGBeY


text:
Q: How do I use `break_` in the package "loops"? Looking into the package loops, I found it very interesting and could be useful. However, there's one part about the package that I don't understand: how am I supposed to use break_?
Let's say I have a function get' :: IO (Maybe Int), with which each call will return a number read from a file, and returns Nothing if the EOF is reached. I'm trying to construct a simple loop where I print each number and break upon EOF.
Now, I know to loop indefinitely I can use forever:
import Control.Monad.Loop as ML
import Control.Monad as M

main = do
    M.sequence . loop $ do
        ML.forever
        return $ do
            mx <- get'
            case mx of
                Nothing -> ???
                Just x  -> print x

But where do I put my break_? It is a LoopT IO Int, so I can only put it in LoopT monad, but isn't it supposed to be called mid interation, instead of when defining loops? This really confuses me.

A: LoopT is a monad transfomer, so you will need to liftIO your print x statement.
Here are some usage examples:
import Control.Monad
import Control.Monad.Trans (liftIO)
import Control.Monad.Loop as ML

-- infinite printing loop
foo :: LoopT IO ()
foo = do
  x <- ML.iterate 0 (+1)
  liftIO $ print x

run_foo = ML.exec_ foo

-- prints 1, 3, 5, 7, 9
bar :: IO ()
bar = ML.exec_ $ do
  x <- ML.iterate 1 (+2)
  if x < 10
    then liftIO $ print x
    else break_

Update
If you want to execute a infinite loop in another monad, I would just use forever from Control.Monad --
import Control.Monad
import Control.Monad.State

myloop = forever $ do
  x <- get
  liftIO $ print x
  put (x+1)

main = runStateT myloop 10 -- start loop at 10

Update 2
Another example using a monadic condition:
findFavoriteNumber = ML.exec_ $ do
  x <- ML.iterate 1 (+1)
  yn <- liftIO $ do putStr $ "is " ++ show x ++ " your favorite number? "
                    getLine
  if yn == "yes"
    then break_
    else return ()

Of course, this loop doesn't return the favorite number - it just keeps asking until the user responds with "yes".

A: Here's a direct translation of your loop to loops style:
module Main where
import Control.Monad.Loop as ML
import Text.Read (readMaybe)
import Control.Exception
import System.IO.Error
import Control.Applicative
import Control.Monad.IO.Class

get' :: IO (Maybe Int)
get' = do
  catchJust (\e -> if isEOFError e then Just () else Nothing)
            (return . readMaybe =<< getLine)
            (const $ return Nothing)

main :: IO ()
main = exec_ $
  ML.forever >> do
    mx <- liftIO get'
    case mx of
      Nothing -> break_
      Just x -> liftIO (print x)


text:
Q: setFormula by using script in Google Sheets I have a little knowledge of javascript I just want to know how to make a script that works in these scenario
I just want to set the second-row with D2:F2, or as long as the first row has a value to be a reference in the formula like in cells: D2={franco!F2:F}; E2={justin!F2:F}; F2 ={aeron!F2:F} and so on...
currently I am using the following codes:
function setFormula() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var rangeList = ss.getRange('d1:f1').getValue();
  var range = ss.getRange('d2:f2');
  range.setValue('={'+rangeList+'!F2:F}');
}

hope that someone can help me with this code. Thank you in advance

A: *

*You want to put the formulas of {franco!F2:F}, {justin!F2:F} and {aeron!F2:F} to the cells "D2", "E2" and "F2", respectively.

*In this case, you want to retrieve the values of franco, justin, aeron from the cells "D1:F1".

*You want to achieve this using Google Apps Script.

I could understand like above. For this, how about this answer? Please think of this as just one of several possible answers.
Sample script:
function setFormula() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var rangeList = ss.getRange('d1:f1').getValues()[0];
  var range = ss.getRange('d2:f2');
  range.setFormulas([rangeList.map(function(e) {return '={'+e+'!F2:F}'})]);
}

*

*At first, the values of franco, justin, aeron are retrieved. Using these values, each formula is creted in the loop with map

*setFormulas uses the 2 dimensional array. Please be careful this.

References:

*

*getRange()

*getValues()

*setFormulas()

*map()


text:
Q: Hide a bunch of Divs after user inactivity I'm using Paul Irish's idle-timer plugin available here : http://paulirish.com/2009/jquery-idletimer-plugin/ .
I want to hide some divs after 5 seconds of inactivity and show them back when user activity's catched .
Here is my code :
$(document).ready(function(){
    $.idleTimer(5000);
    $(document).bind("idle.idleTimer", function(){
        $("#audio_container").fadeOut(1000);
        $(".breadcrumb").fadeOut(1000);
    });
    $(document).bind("active.idleTimer", function(){
        $("#audio_container").fadeIn(1000);
        $(".breadcrumb").fadeIn(1000);
    });
 });

It works perfectly on Firefox / Safari / Mobile Safari , but I can't make it work on Chrome or IE 8 / 9 .
Obviously the onmousemove event is the problem, if I unbind the onmousemove event, it works (But I need it so this is not an acceptable fix for me).
You can find an exemple here :
Best regards,
EDIT :
The mousemouve event is located in the idle-timer plugin .
$.idleTimer = function(newTimeout, elem){

    // defaults that are to be stored as instance props on the elem

    var idle    = false,        //indicates if the user is idle
        enabled = true,        //indicates if the idle timer is enabled
        timeout = 30000,        //the amount of time (ms) before the user is considered idle
        events  = 'mousemove keydown DOMMouseScroll mousewheel mousedown touchstart touchmove'; // activity is one of these events

if I remove the mousemove event from the plugin, it works .

A: if u dont have to use the plugin and hide divs or wathever element after five seconds of inactivity and show it once its active again, i came up with a script like so (tested in chrome,firefox, explorer):
http://jsfiddle.net/e8KXw/1/
(Using an input for demonstration instead of div)
<input type="text" > /* Use div or any element */

Jquery:
var interval = 1;

setInterval(function(){
   if(interval == 5){
       /* if intervall reaches 5 the user is inactive hide element/s */
       $('input').hide();
       interval = 1;
   }
   interval = interval+1;
    console.log(interval);
},1000);

$(document).bind('mousemove keypress', function() {
    /* on mousemove or keypressed show the hidden input (user active) */
    $('input').show();
    interval = 1;
});

Hope its not far from what you are after.
Cheers!


text:
Q: Periodic task and notifications when the application is closed I have been looking for the best way to execute a periodic task every 30/60 seconds which connects to a web service and show a notification depending on the response. This periodic task should keep on executing even if the application is closed (After Destroy).
I have seen these options:

*

*WorkManager: but the minimum time for this is 15 minutes.

*AlarmManager: I have read that the resources consumption would be high for my task frequency.

*Foreground Service: This could be a good option but I don't like the constantly shown notification in this mode.

Are there any other optimal option to resolve this? Which one do you recommend me?


text:
Q: 99% disk IO spikes with Percona So we have a server that has seemingly random spikes in disk I/O, going up to 99.x% at random times and for no obvious reason, staying high for a while, and then going back down. This didn't use to be an issue, but recently the disk I/O has been staying at 99% for extended periods of time, in some cases up to 16 hours.
The server is a dedicated server, with 4 CPU cores and 4 GBs of RAM. It is running Ubuntu Server 14.04.2, running percona-server 5.6 and nothing else major. It is being monitored for downtime and we have a screen permanently showing CPU/RAM/Disk I/O for the servers we deal with. The server is also being regularly patched and maintained.
This server is the 3rd in a chain of replicas, and is there as a fail-over machine. The MySQL data flow is as follows.
Master --> Master/Slave --> Problem Server
All 3 machines have identical specs and are hosted with the same company. The problem server is in a different datacentre to the first & second.
The 'iotop' tool shows us that the disk I/O is being caused by the 'jbd2/sda7-8' process. From what we know this handles the filesystem journalling, and flushing things to disk. Our 'sda7' partition is '/var' and our sda8 partition is /home. Nothing should be reading/writing to /home on a regular basis. Stopping the mysql service results in the disk I/O immediately dropping back down to a normal level so we are fairly certain it is percona that is causing the issue, and this would match with it being the /var partition as this is where our MySQL data directory resides (/var/lib/mysql).
We use NewRelic to monitor all of our servers, and when the disk I/O spikes, we can not see anything that could be causing it. The load average sits at ~2. The CPU usage hovers at ~25%, which NewRelic says is being caused by 'IO Wait' rather than a particular process.
Our mysql configuration file was generated through a combination of the Percona configuration wizard and some settings that are required for our customers app, but is nothing particularly fancy.
MySQL config - http://pastebin.com/5iev4eNa
We have tried the following things to try and resolve the issue:

*

*Ran mysqltuner.pl to see if there was anything obviously wrong. Results look very similar to the results from the same tool on the other 2 database servers, and does not change much between uses.

*Used vmstat, iotop, iostat, pt-diskstats, fatrace, lsof, pt-stalk and probably a few more, but nothing obvious has jumped out.

*Tweaked the 'innodb_flush_log_at_trx_commit' variable. Have tried setting it to 0, 1 & 2, but none seemed to have any effect. This should have changed how often MySQL was flushing transactions to the logs files.

*A mysql 'show full processlist' is very un-interesting when disk-I/O is high, it just shows the slave reading from the master.
Some of the outputs from tools are obviously quite long so I'll give pastebin links, and I couldn't manage to copy-paste the output of iotop, so I've provided a screen capture instead.
iotop

pt-diskstats: http://pastebin.com/ZYdSkCsL
When the disk I/O is high, "vmstat 2" shows us the things being written are mostly because of "bo" (buffer out), which correlates with the disk journalling (flushing buffers/RAM to disk)
http://pastebin.com/E3LWzwjj
"lsof -p mysql-pid" (list open files of a process) shows us that the files being written to are mostly .MYI and .MYD files in the /var/lib/mysql directory, and the master.info and relay-bin and relay-log files. Even without specifying the mysql process(so any file being written on the entire server), the output is very similar (mostly MySQL files, not much of anything else) This confirms for me that it is definitely being caused by Percona.
When disk I/O is high, the "seconds_behind_master" increases. I'm not sure which way round they happen as of yet. "seconds_behind_master" also jumps from normal values to arbitrarily large values temporarily, and then returns to normal pretty much straight away, some people have suggested this could be caused by network issues.
'show slave status' - http://pastebin.com/Wj0tFina
The RAID controller (3ware 8006) does not have any caching abilities; someone also suggested poor caching performance could be causing the issue. The controller has identical firmware, version, revision etc. as cards on other servers for the same customer (albeit webservers), so I'm fairly certain it is not at fault. I have also ran verifications of the array, which came back fine. We also have the RAID checking script which would have alerted us to any changes.
The network speeds are terrible compared to those on the second database server, so I'm thinking that maybe this is a network issue. This also correlates with spikes in bandwidth just before the disk I/O goes high. However, even when the network does "spike", it doesn't spike to a high amount of traffic, just relatively high compared to the average.

Network speeds (generated using iPerf to an AWS instance)
Problem server - 0.0-11.3 sec  2.25 MBytes  1.67 Mbits/sec
Second server  - 0.0-10.0 sec   438 MBytes   366 Mbits/sec
Apart from being slow, the network seems to be fine. No packet loss, but some slow hops between servers
Will be happy to also provide output of any relevant commands but I can only add 2 links to this post as I'm a new user :(
EDIT We got in touch with our hosting provider regarding this issue, and they were kind enough to swap the hard disks for SSDs of the same size. We rebuilt the RAID onto these SSDs, but unfortunately the problem persists.

A: Which version of MySQL server do you use?
After 5.5 you can use the performance_schema to get realtime statistics from the database.
I'd start querying the
 table_io_waits_summary_by_table
 table_io_waits_summary_by_table
 table_lock_waits_summary_by_table

to see what is happening exactly.
An another solution would be if you check the buffer pool usage, it is not possible, that there are cold pages which needed to move to memory?

A: The best way to attack it is to look at http://www.brendangregg.com/linuxperf.html and follow Brendan's advice.
Specifically you want his iosnoop tool that will tell you who access the storage the most. But you'll do yourself a big favor if you read through it to learn his thought process and methodologies as that would benefit you a lot in the long term.


text:
Q: How to style an individual point with Mapbox? I am building a web app based on Mapbox and want to show more information about a subset of points in a table, then be able to select a row in the table (corresponding to a point on the map) and highlight the point on the map by virtue of selecting the row in the table. I selecting the current points on view through a Node.js server, then populating a DataTables table with those points. Ideally, I could then click the row in the DataTable and have the corresponding point styled accordingly. Is there a way to do this? Thank you!

A: You haven't given much information about how your map is set up, but I'm going to assume you have a data source (either GeoJSON or vector tiles) and a layer that is currently displaying all your points. (I'm not sure what ou mean by a "DataTables table").
There are two methods
With a highlight layer
Let's say there is an attribute on every row called placeNumber.
1: Create a highlight layer:
map.addLayer({
  id: 'place-highlight',
  type: 'circle',
  source: mysource,
  paint: {
    'fill-color': 'yellow',
    'circle-radius': '20',
    'fill-opacity': 0.5
  },
  filter: ['==', 'placeNumber', -1]
});

2: Update the filter:
map.setFilter('place-highlight', ['==', 'placeNumber', selectedPlaceNumber]);

With SetFeatureState
To make this work, you need to be able to access the FeatureID of the selected feature.
When the row is clicked:
map.setFeatureState({ source: 'place', id: previousSelectedFeatureId }, { selected: false })
map.setFeatureState({ source: 'place', id: selectedFeatureId }, { selected: true })
previousSelectedFeatureId = selectedFeatureid;

And use the feature state within your paint properties:
paint: {
   'circle-color': ['case',
      ['==', ['feature-state', 'selected'], true], 'yellow',
      'black'
      ]
}

That is, "circle color is yellow for points that have a "selected" feature-state of true, and black otherwise".


text:
Q: Will seaborn.barplot take the matplotlib.pyplot variable without any arguments passed? I'm getting started with machine learning and I've been looking at a machine learning algorithm lately. I've seen seaborn.barplot take plt.figure to display the graph without any argument. How is that possible?
fig = plt.figure(figsize = (7,7))
sns.barplot(x = 'quality',y = 'fixed acidity', data = wineData)

fig is not passed as an argument to sns.barplot but it shows the graph according to figsize.

A:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = np.random.normal(0, 1, 3)
# array([-1.18878589,  0.59627021,  1.59895721])
plt.figure(figsize=(16, 6))
sns.boxplot(x=data);

In order to change the figure size of the seaborn package use matplotlib.pyplot.figure
The seaborn function that draws a bar plot, use matplotlib.pyplot.figure with the figsize keyword

A: In the seaborn barplot code you find the following two lines:
if ax is None:
    ax = plt.gca()

This means, if no axes ax is provided by the user, the current axes from the current figure is taken. The current figure has been created by you with the given figure size. So seaborn plots its barplot to this figure.


text:
Q: Start ClickOnce application through CreateProcess I'm trying to automate a series of GUI controls in a ClickOnce application, however I'm having problems to launch the application through my automation code. What I'd like to do is launch the application with CreateProcess(), so I can have a window handle to execute my controls.
This is my current code (I omitted the path to the app):
import win32process
import win32con

path_to_app = "path_to_application\\application.appref-ms"
startupinfo = win32process.STARTUPINFO()

(hprocess, hthread, dwprocessid, dwthreadid) = win32process.CreateProcess(path_to_app, None, None, None, 0, win32con.NORMAL_PRIORITY_CLASS, None, None, startupinfo)

# Execute controls here

And this is the error I'm getting:

pywintypes.error: (193, 'CreateProcess', '%1 is not a valid Win32 application.')

If I try to directly open the .exe that will eventually run, it fails with a message that I should run through the shortcut (in this case the .appref-ms).
How is it possible to start the application and get its window handle?

A: Generally to get a click once application to run from within another application you have to first run dfsvc.exe from the .Net framework runtime directory. (see https://stackoverflow.com/a/11996812/3803708). Then try running the .appref-ms and hopefully it will work.

A: This code works for me:
import subprocess, time
import pywinauto

p = subprocess.Popen(['cmd.exe', '/c', r'C:\Users\<user_name>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\GitHub, Inc\GitHub.appref-ms'])
time.sleep(5)
app = pywinauto.Application.connect(path='github.exe')
dlg = app.Windows_(visible_only=True)[0]
print dlg.handle

Of course, you need to install

*

*pywinauto 0.4.2 on Python 2.x 32-bit

*or pywinauto-64 if you're on Python 3.x (or your app is 64-bit).

The code was tested on 32-bit github application, Win7 x64, Python 2.6 32-bit (pywinauto-64 clone).


text:
Q: File Pointer Not Being Assigned a Value When Using fopen() I am trying to write a simple C program which will read data from a csv file and perform some calculations on this data.
Unfortunately I have a problem where a file pointer of mine, fptr , is not being assigned a value after calling fopen(). I know this is the case after stepping through VS 2017's debugger. Yet I do not know why this is the case. This is a huge problem and means my program will throw some very nasty exceptions any time I try to read data from the file or close the file.
My code is below:
main.c
#include<stdio.h>
#include <stdlib.h>         // For exit() function
#include"constants.h"       //For access to all project constants

/***************************************************************************************************************
To keep the terminal from automatically closing
Only useful for debugging/testing purposes
***************************************************************************************************************/
void preventTerminalClosure() {
    //flushes the standard input
    //(clears the input buffer)
    while ((getchar()) != '\n');
    printf("\n\nPress the ENTER key to close the terminal...\n");
    getchar();
}

/***************************************************************************************************************
Read the given input file
***************************************************************************************************************/
void readInputFile(char fileName[]) {
    FILE *fptr;
    char output[255];

    //open the file
    if (fptr = fopen(fileName, "r") != NULL) {          //read file if file exists
        //fscanf(fptr, "%[^\n]", output);
        //printf("Data from the file:\n%s", output);
        printf("<--Here-->");
    }else {
        printf("\nERROR 1: File %s not found\n", fileName);
        preventTerminalClosure();
        exit(1);
    }

    fclose(fptr);                       //close the file
}

/***************************************************************************************************************
                                        *   *   *   Main    *   *   *
***************************************************************************************************************/
void main() {
    char testName[MAX_NAME_SIZE];

    printf("Hello World!\n");
    printf("Please enter your name: ");
    scanf("%s", testName);

    printf("It's nice to meet you %s!", testName);

    readInputFile("dummy.txt");

    preventTerminalClosure();   //Debug only

}

I have made sure that my fake file does indeed exist and is located in the correct location. Otherwise my code would hit the else block inside of readInputFile(). That is something I have thoroughly tested.
There is clearly something basic that I am missing which explains this pointer behavior; but what that is, I am not sure. Any help would be appreciated! :)

A: Use parenthesis to enforce order, so that fptr is compared against NULL after it has been assigned value returned by fopen:
FILE *fptr;
char output[255];

//open the file
if ( (fptr = fopen(fileName, "r")) != NULL)


text: Q: Magento translation package doesn't work well After installing Magento , I downloaded a package for translation to Portuguese in this link and replaced the vendor folder for the content I downloaded . Even though I changed the language in my account to Portuguese and cleaned the cache, the translation was not satisfactory. Very little has been translated. The administrator area still has most of the elements in English. The contact us screen and user registration screen are still all in English! I tried to modify the files pt_BR.csv within i18n folders, but it does not seem to have any effect . How could I translate Magento screens effectively?


text:
Q: How would you detect a collision in this 2d game below, using javascript and jQuery? I made a simple game which allows you to move a purple box by pressing the arrow keys. The purple box is inside a blue perimeter. I want to be able to prevent the purple box from being able to breach the blue perimeter and stay inside, which i know involves collisions, however I don't seem to understand how that can be done. Here is the code I have written so far:
        <!DOCTYPE html>

So lets say I am moving the purple box and it happens to touch the blue square. If that happens if has to stop moving in that direction, until it is no longer in contact with the blue square, thus preventing it from escaping the blue square. How would I do this, using JS and jQuery?

A: Take a look into the jquery animate's step function. You have to check if the object has reached the edge at each step of the animation. Something very similar is done here
See the "try it for yourself..." link at the bottom.

A: Hit detection is fairly straight forward, when working with boxes. It sounds like what you're attempting to do is contain 1 movable box (#k) within a static containing box (#bob).
The basic concept is to add some simple logic checks to each of your key up events that check if the position you're thinking of moving to is going to exit the bounds. If the check determines that the new position will exit the bounds, it doesn't bother animating.
Each direction will have a slightly different check.
UP
When attempting to move up all you have to do is check that the moving box's new top bound is greater than 0. You can use jQuery('#k').position().top to determine the movable box's top bound.
Down
When attempting to move down all you have to do is check that the moving box's new bottom bound is less than the containing box's height. You can use jQuery('#k').position().top+jQuery('#k').height() to determine the movable box's bottom bound. And jQuery('#bob').height() to determine the containing box's height.
Left
When attempting to move left all you have to do is check that the moving box's new left bound is greater than 0. You can use jQuery('#k').position().left to determine the movable box's left bound.
Right
When attempting to move right all you have to do is check that the moving box's new right bound is less than the containing box's width. You can use jQuery('#k').position().left+jQuery('#k').width() to determine the movable box's right bound. And jQuery('#bob').width() to determine the containing box's width.

Additional notes

*

*You should probably make #bob position:relative. At the moment position will be calculated relative to the body tag's position not #bob's (they just happen to share the same coordinates right now).

*The reason there is extra logic on "down" and "right" is that position in the DOM is determined based on the top left corner. To compensate for this we must add in the height or width of the object respectively.

Background Information - HTML/jQuery Positioning
A diagram to help illustrate HTML/jQuery positioning:
https://docs.google.com/drawings/d/121mfxpapfmcRD2UV7qoMY5RdoH-4womiheqDHtQ_YWY/edit
Each element's coordinate originates from its top left corner.
In HTML/jQuery the position of an absolutely positioned element is relative to its parent's origin (overlooking position inheritance for simplicity sake at the moment). If its top left corner is the same as its parent's top left corner its position will be (0,0). As it moves away from it's parent's top left corner it's coordinates become the horizontal (x) and vertical (y) gap between the 2 coordinates.


text:
Q: How to read and modify an xml file using vb.net and linq I am able to only read and edit the first claim, however I need the code to do the same in all claims. It has to count line in each claim and write a line number in each line. Below is the xml file;
<ClaimBatch>
  <Claims>
    <Claim>
      <claimGross>4947.7200</claimGross>
      <numLines>2</numLines>
      <Line>
        <lineNo>1</lineNo>
        <benefitAmount>2473.8600</benefitAmount>
        <levy>247.3860</levy>
      </Line>
      <Line>
        <lineNo>2</lineNo>
        <benefitAmount>2473.8600</benefitAmount>
        <levy>247.3860</levy>
      </Line>
    </Claim>
    <Claim>
      <claimGross>549.6800</claimGross>
      <numLines>2</numLines>
      <Line>
        <benefitAmount>274.8400</benefitAmount>
        <levy>48.0976</levy>
      </Line>
      <Line>
        <benefitAmount>274.8400</benefitAmount>
        <levy>48.0976</levy>
      </Line>
    </Claim>
  </Claims>
</ClaimBatch>

Below is the code that I have used so far;
Public Sub writeLineNo()

Dim counter As Integer = 1
    Dim reader As XmlReader = XmlReader.Create("C:\SQLQUERIS\" & cmbschemetxt & " " & dateStr & ".xml")
    xmlDoc = XDocument.Load("C:\SQLQUERIS\" & cmbschemetxt & " " & dateStr & ".xml")

    For Each line In xmlDoc.<ClaimBatch>.<Claims>.<Claim>.<Line>
        If reader.ReadToFollowing("Line") Then
            reader.MoveToContent()
            While reader.ReadToNextSibling("Line")
                line.AddFirst(<lineNo><%= counter %></lineNo>)
                counter += 1
            End While
        End If
    Next
    reader.Close()
    xmlDoc.Save("C:\SQLQUERIS\" & cmbschemetxt & " " & dateStr & ".xml")
End Sub

A: Simply use two For Each loops. One to loop over each <Claim>, and one to loop over each <line> inside each <Claim>.
Given the following XML
Dim xml = <ClaimBatch>
            <Claims>
                <Claim>
                    <claimGross>4947.7200</claimGross>
                    <numLines>2</numLines>
                    <Line>
                        <benefitAmount>2473.8600</benefitAmount>
                        <levy>247.3860</levy>
                    </Line>
                    <Line>
                        <benefitAmount>2473.8600</benefitAmount>
                        <levy>247.3860</levy>
                    </Line>
                </Claim>
                <Claim>
                    <claimGross>549.6800</claimGross>
                    <numLines>2</numLines>
                    <Line>
                        <benefitAmount>274.8400</benefitAmount>
                        <levy>48.0976</levy>
                    </Line>
                    <Line>
                        <benefitAmount>274.8400</benefitAmount>
                        <levy>48.0976</levy>
                    </Line>
                </Claim>
            </Claims>
            </ClaimBatch>

use a nested loop like:
For Each claim in xml.<Claims>.<Claim>
    Dim counter = 1
    For Each line in claim.<Line>
        line.AddFirst(<lineNo><%= counter %></lineNo>)
        counter += 1
    Next
Next

xml is now:


text:
Q: asyncio: loop.run_until_complete(loop.create_task(f)) prints "Task exception was never retrieved" even though it clearly was propagated For some reason this program prints the following warning:
Task exception was never retrieved
future: <Task finished coro=<coro() done, defined at /usr/lib64/python3.4/asyncio/coroutines.py:139> exception=SystemExit(2,)>

even though the exception is clearly retrieved and propagated, as caught SystemExit! is printed to the terminal, and process status code becomes 2.
The same thing happens with Python 2 and trollius.
Am I missing something?
#!/usr/bin/env python3

import asyncio

@asyncio.coroutine
def comain():
    raise SystemExit(2)

def main():
    loop = asyncio.get_event_loop()
    task = loop.create_task(comain())
    try:
        loop.run_until_complete(task)
    except SystemExit:
        print("caught SystemExit!")
        raise
    finally:
        loop.close()

if __name__ == "__main__":
    main()

A: SystemExit seems to be a special case. If, for example, you raise and catch an Exception, you won't see any errors.
The way around this seems to be to manually retrieve the exception using Task.exception():
import asyncio

@asyncio.coroutine
def comain():
    raise SystemExit(2)

def main():
    loop = asyncio.get_event_loop()
    task = loop.create_task(comain())
    try:
        loop.run_until_complete(task)
    except SystemExit:
        print("caught SystemExit!")
        task.exception()
        raise
    finally:
        loop.close()

if __name__ == "__main__":
    main()

EDIT
Actually, all BaseException subclasses will behave this way.

A: I think it's because SystemExit and KeyboardInterrupt are different cases. Normal Exception won't cause the same issue for example.
You can chain the comain coroutine inside another to consume the exception like this:
#!/usr/bin/env python3

import asyncio

@asyncio.coroutine
def comain():
    raise SystemExit(2)

@asyncio.coroutine
def another():
    try:
        yield from comain()
    except SystemExit:
        print ("consumed")

def main():
    loop = asyncio.get_event_loop()
    task = loop.create_task(another())
    try:
        loop.run_until_complete(task)
    except SystemExit:
        print("caught SystemExit!")
        raise
    finally:
        loop.close()

if __name__ == "__main__":
    main()

Here - I am calling another() instead of comain() and inside another() I am handling the exception from comain().


text:
Q: Compute the matrix representation of a linear map with respect to a basis I'm trying to solve this exercise but I'm stuck:
Let $V$ be a vector space over $K$ and let $\mathcal{B} = \{v_1, v_2, v_3, v_4\}$ be a basis of $V$. Let $f: V \rightarrow V$ be a linear map such that:
$$f(v_1) = v_2 - v_3, \quad f(v_2) = 3v_1 - 2v_4, \quad f(v_3) = v_3, \quad f(v_4) = v_1 + v_4.$$
Calculate the matrix $A$ which represents $f$ in the basis $\mathcal{B}$. (Extra: is $A$ nilpotent?)
I tried multiple things. Intuitively, I thought the answer would look something like this:
\begin{bmatrix}\mid&\mid&\mid&\mid\\\ v_2-v_3&3v_1-2v_4&v_3&v_1+v_4\\\ \mid&\mid&\mid&\mid\end{bmatrix}
Which of course works for our usual basis vectors $e_1, e_2, e_3, e_4$, but unfortunately not for other basis vectors.
What I tried next was to calculate the matrix by hand in the case of a $2 \times 2$ matrix and then a specific example with some made-up numbers for a $3 \times 3$ matrix but I wasn't able to see any easy patterns. Surely the intention here is not to solve multiple, big systems of equations to figure out all the entries in the matrix one by one, right? What am I missing here?
Oh and for the extra, my guess is that $A$ is not nilpotent, since no matter how many times we apply $A$, we will always get $v_3$ for $v_3$ and never the zero vector. Is this correct?

Thanks to a comment I came to this solution:
$A = \begin{bmatrix}
0 & 3 & 0 & 1 \\
1 & 0 & 0 & 0 \\
-1 & 0 & 1 & 0 \\
0 & -2 & 0 & 1
\end{bmatrix}$, and I see that this works with the basis $e_1, e_2, e_3, e_4$.
But if I try it with other vectors, obviously it doesn't work. For example, let $v_1 = \begin{pmatrix} 1\\\ 1\\\ 1\\\ 1\end{pmatrix}, \quad v_2 = \begin{pmatrix} 1\\\ 1\\\ 1\\\ 0\end{pmatrix}, \quad v_3 = \begin{pmatrix} 1\\\ 1\\\ 0\\\ 0\end{pmatrix}, \quad v_4 = \begin{pmatrix} 1\\\ 0\\\ 0\\\ 0\end{pmatrix}$
But then $Av_1 = \begin{pmatrix} 4\\\ 1\\\ 0\\\ -1\end{pmatrix} \neq v_2 - v_3$
What am I not understanding here? Shouldn't the solution have to be in terms of the given vectors? Doesn't the solution change if you have different specific vectors?

A: You're looking for a linear map $M$ such that
$$M\begin{pmatrix}v_1&v_2&v_3&v_4\end{pmatrix}=\begin{pmatrix}v_2-v_3&3v_1-2v_4&v_3&v_1+v_4\end{pmatrix}$$ Which is exactly, if we denote the former equality by $MV_1=V_2$
$$M=V_2V_1^{-1},$$ assuming a well-defined inverse. Maybe this helps.

A: Here is definition of coordinate vector (don't skip this part). Matrix Representation of $f$ with respect to ordered basis $B$ is
$$A=[f]_B=\begin{bmatrix}\mid&\mid&\mid&\mid\\\ [f(v_1)]_B & [f(v_2)]_B &[f(v_3)]_B&[f(v_4)]_B\\\ \mid&\mid&\mid&\mid\end{bmatrix}.$$
Since $ f(v_1) = v_2 - v_3$, $f(v_2) = 3v_1 - 2v_4$, $f(v_3) = v_3$, $f(v_4) = v_1 + v_4$, we have $$[f(v_1)]_B=\begin{pmatrix} 0\\ 1\\ -1\\ 0\\ \end{pmatrix}, \quad[f(v_2)]_B = \begin{pmatrix} 3\\ 0\\ 0\\ -2\\ \end{pmatrix}, \quad [f(v_3)]_B = \begin{pmatrix} 0\\ 0\\ 1\\ 0\\ \end{pmatrix}, \quad [f(v_4)]_B = \begin{pmatrix} 1\\ 0\\ 0\\ 1\\ \end{pmatrix}.$$ Thus
$$A= \begin{bmatrix} 0 & 3 & 0 & 1 \\ 1 & 0 & 0 & 0 \\ -1 & 0 & 1 & 0 \\ 0 & -2 & 0 & 1 \end{bmatrix}.$$

We are working in general vector space $V$ with $\dim (V)=4$. So saying $\{e_1,e_2,e_3,e_4\}$ is basis of $V$ don't make sense, unless $V=F^4$.


text:
Q: Error when Updating/Installing software in Eclipse 3.4.2 I am trying to update installed software and install plugins for a fresh install of eclipse 3.4.2.  Whenever I try to update/install I get this error:
"Unexpected error encountered while preparing for the operation.  org.eclipse.core.runtime.AssertionFailedException"
Details:
"Unexpected error encountered while preparing for the operation. null argument:"
log file entry
org.eclipse.core.runtime.AssertionFailedException: null argument:
at org.eclipse.core.runtime.Assert.isNotNull(Assert.java:86)
at org.eclipse.core.runtime.Assert.isNotNull(Assert.java:74)
at org.eclipse.equinox.internal.provisional.p2.metadata.ProvidedCapability.<init>(ProvidedCapability.java:25)
at org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.createProvidedCapability(MetadataFactory.java:189)
at org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataParser$ProvidedCapabilityHandler.<init>(MetadataParser.java:483)
at org.eclipse.equinox.internal.p2.metadata.repository.io.MetadataParser$ProvidedCapabilitiesHandler.startElement(MetadataParser.java:469)
at org.eclipse.equinox.internal.p2.persistence.XMLParser$AbstractHandler.startElement(XMLParser.java:171)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryIO$Parser.parse(MetadataRepositoryIO.java:193)
at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryIO.read(MetadataRepositoryIO.java:56)
at org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.SimpleMetadataRepositoryFactory.validateAndLoad(SimpleMetadataRepositoryFactory.java:116)
at org.eclipse.equinox.internal.provisional.spi.p2.metadata.repository.SimpleMetadataRepositoryFactory.load(SimpleMetadataRepositoryFactory.java:85)
at org.eclipse.equinox.internal.p2.updatesite.metadata.UpdateSiteMetadataRepository.initializeMetadataRepository(UpdateSiteMetadataRepository.java:187)
at org.eclipse.equinox.internal.p2.updatesite.metadata.UpdateSiteMetadataRepository.<init>(UpdateSiteMetadataRepository.java:67)
at org.eclipse.equinox.internal.p2.updatesite.metadata.UpdateSiteMetadataRepositoryFactory.load(UpdateSiteMetadataRepositoryFactory.java:48)
at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:485)
at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:452)
at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:435)
at org.eclipse.equinox.internal.p2.director.SimplePlanner.gatherAvailableInstallableUnits(SimplePlanner.java:196)
at org.eclipse.equinox.internal.p2.director.SimplePlanner.getProvisioningPlan(SimplePlanner.java:235)
at org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil.getProvisioningPlan(ProvisioningUtil.java:210)
at org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction.computeProvisioningPlan(InstallAction.java:80)
at org.eclipse.equinox.internal.provisional.p2.ui.actions.InstallAction.getProvisioningPlan(InstallAction.java:130)
at org.eclipse.equinox.internal.provisional.p2.ui.actions.ProfileModificationAction$1.run(ProfileModificationAction.java:61)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)

What is causing this problem and how do I fix it?

A: I fixed my problem by reinstalling eclipse from the archived package.  I used the same procedure (to my knowledge) to reinstall as I used the first time, but this time with no errors when trying to update and install features.

A: p2 was barely able to run in 3.4.x (and was still with quite a few bugs like this one in early 3.5).
Any chance you can try with a 3.5.1 eclipse installation?


text:
Q: Swap colour in alluvian plot I created an alluvian plot (image below) and would like to just swap the colours so unresolved is red and solved green, but cannot mannage to do that. Already tried also changing the dataframe, it doesn't make a diference.
I used the script:
ggplot(data = D180_PROPOSAL1,
       aes(axis1 = Data, axis2 = Issue,
           y = Frequency)) +
  scale_x_discrete(limits = c("Data", "Issue"), expand = c(.05, .1)) +
  xlab("Assesment at Day 180") +
  geom_alluvium(aes(fill = Unresolved)) +
  geom_stratum() +
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  theme_minimal() +
  ggtitle("Uncertainties in the evaluation of bevacizumab biosimilars",
          "stratified by type of data and type of issue")

Here is the picture of the plot
I also included the dataset in a link Dataset

A: Below you may find a solution to your problem.
What i did is to use the scale_fill_manual() layer function with parameter values = c("Solved" = "#7CAE00", "Unresolved" = "#F8766D"). This will color the alluvium belonging to "Solved" into the default green color ("#7CAE00") and the alluvium belonging to "Unresolved" into the default red color ("#F8766D").
library(readxl)
library(ggalluvial)

# Load the data:
D180_PROPOSAL1 <- readxl::read_excel(path = "D180_PROPOSAL1.xlsx")

# Plot the original figure
p <- ggplot(data = D180_PROPOSAL1,
       aes(axis1 = Data, axis2 = Issue,
           y = Frequency)) +
  scale_x_discrete(limits = c("Data", "Issue"), expand = c(.05, .1)) +
  xlab("Assesment at Day 180") +
  geom_alluvium(aes(fill = Unresolved)) +
  geom_stratum() +
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  theme_minimal() +
  ggtitle("Uncertainties in the evaluation of bevacizumab biosimilars",
          "stratified by type of data and type of issue")

# modify the colors of the alluvium:
# #7CAE00 = default green
# #F8766D = default red
p <- p +
  scale_fill_manual(values = c("Solved" = "#7CAE00", "Unresolved" = "#F8766D"))

plot(p)

The resulting figure is:


text:
Q: Javascript Prompt Box Loops Something is wrong with this code but I can't figure out what it is. The page does not work properly or do what it's supposed to. I need a code that prompts for a password and that limits the attempts to 3. After the third attempt, it needs to have an alert box.
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
    if (answer == "Psycho")
    {
        document.write("These are pictures of my kitten and     her things.");
    }
    else
    {
        answer = prompt("Password: ");
        attempts--;
    }
}
if (attempts = 0)
{
    alert("Incorrect Password");
}
</script>

A: There are a few options to fix your code.
You could return once you're done the work.
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
    if (answer == "Psycho")
    {
        document.write("These are pictures of my kitten and     her things.");
        break;
    }
    else
    {
        answer = prompt("Password: ");
        attempts--;
    }
}
if (attempts == 0)
{
    alert("Incorrect Password");
}
</script>

Or, I would return early if you've failed
<script>
var attempts = 4;
var answer = prompt("Password: ");
while (attempts > 0 && answer != "Psycho")
{
    answer = prompt("Password: ");
    attempts--;
}

if (attempts == 0)
{
    alert("Incorrect Password");
}
else
{
    document.write("These are pictures of my kitten and     her things.");
}
</script>

A: You have a couple of issues. You should check entry after the user enters in the prompt. Or the last entry will not be checked. Next issue is you are not exiting the loop. Another issue is the fact that = is assignment so inside the if you are assigning zero, not checking to see if it is zero.

var attempts = 3;
while (attempts > 0) {
  var answer = prompt("Password: ");
  if (answer == "Psycho") {
    document.write("These are pictures of my kitten and her things.");
    break;
  }
  attempts--;
}
if (attempts == 0) {
  alert("Incorrect Password");
}


text:
Q: I haven't been long as Imagine that I'm talking to my friend. That's the dialog is very casual. Can I say

I haven't been long as a programmer.

in the sense that I work as a a programmer not very far. Is it suitable for informal discussion?

A:
I haven't been long as a programmer

This sounds like you are not very tall when you are a programmer, or something. The correct idiom is

I haven't been a programmer for long.

A: If you wish to emphasize on the time period, it would be best to use

I haven't spent a lot of time programming.

Otherwise the construct mentioned before is also great.


text:
Q: Create Vagrant file via PowerShell I have these lines which I would like to add to Vagrant file which I would like to create via PowerShell
Vagrant.configure("2") do |config|
config.vm.communicator = "winrm"
config.vm.box = "Win_10_V.box"
config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--usb", "on"]
    vb.customize ["modifyvm", :id, "--usbehci", "on"]
    vb.customize ['usbfilter', 'add', '0', '--target', :id, '--name', 'SmartCard', '--vendorid', '0x096E', '--productid', '0x0007']
    vb.gui = true
end
end

I tried this PowerShell cmdlet but it doesn't work because of multiple " symbols.
New-Item "D:\VV\Vagrantfile" -type file -force -value "Vagrant.configure("2") do |config|
config.vm.communicator = "winrm"
config.vm.box = "W_1.box"
config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--usb", "on"]
    vb.customize ["modifyvm", :id, "--usbehci", "on"]
    vb.customize ['usbfilter', 'add', '0', '--target', :id, '--name', 'SmartCard', '--vendorid', '0x096E', '--productid', '0x0007']
    vb.gui = true
end
end"

Here is error output
New-Item : A positional parameter cannot be found that accepts argument '2) do |config|
config.vm.communicator = winrm
config.vm.box = Win_10_V.box
config.vm.provider virtualbox do |vb|
    vb.customize [modifyvm, :id, --usb, on]
    vb.customize [modifyvm, :id, --usbehci, on]
    vb.customize ['usbfilter', 'add', '0', '--target', :id, '--name', 'SmartCard', '--vendorid', '0x096E', '--productid', '0x0007']
    vb.gui = true
end
end'.
At line:1 char:1
+ New-Item "D:\VV\Vagrantfile" -type file -force -value "Vagrant.configu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

I know that I have positional parameters but I need them in my Vagranfile

A: The problem is that the double-quote in the value you pass (just before the 2) is terminating the string that you're passing as the value. Re-write is using a here-string:
$value = @"
"Vagrant.configure("2") do |config|
config.vm.communicator = "winrm"
config.vm.box = "W_1.box"
config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--usb", "on"]
    vb.customize ["modifyvm", :id, "--usbehci", "on"]
    vb.customize ['usbfilter', 'add', '0', '--target', :id, '--name', 'SmartCard', '--vendorid', '0x096E', '--productid', '0x0007']
    vb.gui = true
end
end
"@

New-Item "D:\VV\Vagrantfile" -type file -force -value $value

This will allow you to have embedded quotes within the string.


text:
Q: grep - print file name fails to process I Have a logs like this. Which processes number of .bill.file format files. In case of any issues with processing an SEVERE message followed by INFO will be printed which has detail about file path
SEVERE  2016-02-09 00:45:18 [process number] rocessRunner.process Exception during process 123.bill.file
SEVERE  2016-02-09 00:45:18 [process number]
...
...
INFO    2016-02-09 00:45:18 [process number] Runner. Closing input  /var/run/data/123.bill.file

My requirement is to get to the path of files which gives exception.

A: grep is not really suited for a condition based match like the requirement you have but more suited for awk which can process multiple pattern match on multiple lines. Here per your input, we first match the string starting with SEVERE and when the next match of INFO comes, we print the last column which likely contains the file you are looking for.
awk '/^SEVERE/{flag=1; next} flag && /^INFO/{print $NF; flag=0}' file


text:
Q: git revert a specific commit avoiding a merge I would like to remove a specific commit on a git repository in order to be able to remove a "fix" applied to my software.
There it is an EMC :
#!/bin/bash
rm -rf TEST .git
mkdir TEST
git init
echo "info 1" > TEST/file.txt
git add TEST/
git commit -m "Initial Commit"
echo "info 2" >> TEST/file.txt
git add TEST/
git commit -m "Commit Fix 1 on file"
echo "info 3" >> TEST/file.txt
git add TEST/
git commit -m "Commit Fix 2 sur file"

the result of file.txt will be
info 1
info 2
info 3

And I would like to obtain the file without the line "info 2". The git revert will generate conflict, and I would like to avoid manage those conflicts. That is to say doing like the commit "Commit Fix 1 on file" would have never append.
I tried revert or rebase without any luke, so if you have another idea, I will be glade to have some help.
Sincerely,

A: To revert a particular commit, you need to identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes.

A: $ git reset HEAD^^
$ change your file to delete the info 2
$ git add .
$ git commit -m "Commit Fix 2 sur file"


text:
Q: ASP.NET Core MVC Encrypt/Decrypt QueryString Values I'm using ASP.NET Core 2.0 MVC, C#, Entity Framework Core Code First and SQL Server 2016.
I created a web form and all of my CRUD operations are working fine. However, I need some help on Encrypting / Decrypting the Querystring values that get passed to the Confirmation, Edit and Delete Views.
On my Index page I would also like to Encrypt the EmployeeID when a user hovers over the Edit and Delete links to those Action Methods. I don't want them to be visible on the Index Page.
Please see my code that I have below.
Models
public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int DepartmentID { get; set; }
    public Department Department { get; set; }

    public int AppointmentID { get; set; }
    public Appointment Appointment { get; set; }
}

public class Department
{
    public int DepartmentID { get; set; }
    public string Name { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

public class Appointment
{
    public int AppointmentID { get; set; }
    public string TimeSlot { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

DbContext
public class WinTenDbContext : DbContext
{
    public WinTenDbContext(DbContextOptions<WinTenDbContext> options) : base(options)
    { }

    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Appointment> Appointments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .HasKey(e => e.EmployeeID);

        modelBuilder.Entity<Employee>()
            .Property(e => e.FirstName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        modelBuilder.Entity<Employee>()
            .Property(e => e.LastName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        modelBuilder.Entity<Department>()
            .HasKey(d => d.DepartmentID);

        modelBuilder.Entity<Department>()
            .Property(d => d.Name)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);

        modelBuilder.Entity<Appointment>()
            .HasKey(a => a.AppointmentID);

        modelBuilder.Entity<Appointment>()
            .Property(a => a.TimeSlot)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);
    }
}

ViewModels
public class EmployeeFormVM
{
    public int EmployeeID { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    [Display(Name = "First Name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please select your Department")]
    [Display(Name = "Department")]
    public int DepartmentID { get; set; }

    public IEnumerable<Department> Departments { get; set; }

    [Required(ErrorMessage = "Please select your Appointment")]
    [Display(Name = "Appointment")]
    public int AppointmentID { get; set; }

    public IEnumerable<Appointment> Appointments { get; set; }
}

EmployeesController
public class EmployeesController : Controller
{
    private readonly WinTenDbContext _context;

    public EmployeesController(WinTenDbContext context)
    {
        _context = context;
    }

    //// GET: Employees
    //public async Task<IActionResult> Index()
    //{
    //    var winTenDbContext = _context.Employees.Include(e => e.Appointment).Include(e => e.Department);
    //    return View(await winTenDbContext.ToListAsync());
    //}

    public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
    {
        ViewData["CurrentSort"] = sortOrder;
        ViewData["FirstNameSortParm"] = sortOrder == "fname" ? "fname_desc" : "fname";
        ViewData["LastNameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "lname_desc" : "";
        ViewData["DeptNameSortParm"] = sortOrder == "deptname" ? "deptname_desc" : "deptname";
        ViewData["DateSortParm"] = sortOrder == "time_slot" ? "time_slot_desc" : "time_slot";

        if (searchString != null)
        {
            page = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        ViewData["CurrentFilter"] = searchString;

        var employees = from s in _context.Employees.Include(e => e.Appointment).Include(e => e.Department)
                        select s;

        if (!String.IsNullOrEmpty(searchString))
        {
            employees = employees.Where(s => s.LastName.Contains(searchString)
                                   || s.FirstName.Contains(searchString));
        }

        switch (sortOrder)
        {
            case "fname":
                employees = employees.OrderBy(s => s.FirstName);
                break;
            case "fname_desc":
                employees = employees.OrderByDescending(s => s.FirstName);
                break;
            case "lname_desc":
                employees = employees.OrderByDescending(s => s.LastName);
                break;
            case "deptname":
                employees = employees.OrderBy(s => s.Department.Name);
                break;
            case "deptname_desc":
                employees = employees.OrderByDescending(s => s.Department.Name);
                break;
            case "time_slot":
                employees = employees.OrderBy(s => s.Appointment.AppointmentID);
                break;
            case "time_slot_desc":
                employees = employees.OrderByDescending(s => s.Appointment.AppointmentID);
                break;
            default:
                employees = employees.OrderBy(s => s.LastName);
                break;
        }

        int pageSize = 10;
        return View(await PaginatedList<Employee>.CreateAsync(employees.AsNoTracking(), page ?? 1, pageSize));
    }

    // GET: Employees/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees
            .Include(e => e.Appointment)
            .Include(e => e.Department)
            .SingleOrDefaultAsync(m => m.EmployeeID == id);
        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // GET: Employees/Confirmation/5
    public async Task<IActionResult> Confirmation(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees.Include(d => d.Department).Include(a => a.Appointment)
            .SingleOrDefaultAsync(m => m.EmployeeID == id);

        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // GET: Employees/Create
    public IActionResult Create()
    {
        var departments = _context.Departments.ToList();
        var appointments = _context.Appointments.Include(x => x.Employees).Where(x => !x.Employees.Any()).ToList();

        var viewModel = new EmployeeFormVM
        {
            Departments = departments,
            Appointments = appointments
        };

        return View(viewModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(EmployeeFormVM employee)
    {
        if (ModelState.IsValid)
        {
            var emp = new Employee();
            {
                emp.FirstName = employee.FirstName;
                emp.LastName = employee.LastName;
                emp.DepartmentID = employee.DepartmentID;
                emp.AppointmentID = employee.AppointmentID;
            }

            // Query DB to check if Employee exists with same First/Last Name
            Employee existingEmployee = await _context.Employees.SingleOrDefaultAsync(m => m.FirstName == employee.FirstName && m.LastName == employee.LastName);
            if (existingEmployee != null)
            {
                // Display Error if duplicate employee
                ModelState.AddModelError(string.Empty, "An employee with this name has already registered. Please contact the Service Desk for any scheduling conflicts.");
                employee.Departments = _context.Departments.ToList();
                //employee.Appointments = _context.Appointments.ToList();
                employee.Appointments = _context.Appointments.ToList();
                return View(employee);
            }

            // Query DB to check if appointment has already been assigned to an employee
            Employee existingAppointment = await _context.Employees.SingleOrDefaultAsync(m => m.AppointmentID == employee.AppointmentID);
            if (existingAppointment != null)
            {
                // Display error if the appointment was already chosen
                ModelState.AddModelError(string.Empty, "This appointment has already been taken. Please select another timeslot.");
                employee.Departments = _context.Departments.ToList();
                //employee.Appointments = _context.Appointments.ToList();
                employee.Appointments = _context.Appointments.ToList();
                return View(employee);
            }

            _context.Add(emp);
            await _context.SaveChangesAsync();
            //return RedirectToAction(nameof(Index));

            var newlyCreatedId = emp.EmployeeID;
            return RedirectToAction(nameof(Confirmation), new { id = newlyCreatedId });
        }
        return View(employee);
    }

    // GET: Employees/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employeevm = new EmployeeFormVM();
        {
            Employee employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);

            if (employee == null)
            {
                return NotFound();
            }

            employeevm.EmployeeID = employee.EmployeeID;
            employeevm.FirstName = employee.FirstName;
            employeevm.LastName = employee.LastName;

            // Retrieve list of Departments
            var departments = _context.Departments.ToList();
            employeevm.Departments = departments;
            // Set the selected department
            employeevm.DepartmentID = employee.DepartmentID;

            // Retrieve list of Appointments
            var appointments = _context.Appointments.ToList();
            employeevm.Appointments = appointments;
            // Set the selected department
            employeevm.AppointmentID = employee.AppointmentID;
        }
        return View(employeevm);
    }

    // POST: Employees/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(EmployeeFormVM vmEdit)
    {
        if (ModelState.IsValid)
        {
            Employee employee = _context.Employees.SingleOrDefault(e => e.EmployeeID == vmEdit.EmployeeID);

            if (employee == null)
            {
                return NotFound();
            }

            employee.FirstName = vmEdit.FirstName;
            employee.LastName = vmEdit.LastName;
            employee.DepartmentID = vmEdit.DepartmentID;
            employee.AppointmentID = vmEdit.AppointmentID;

            try
            {
                _context.Update(employee);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(vmEdit.EmployeeID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(vmEdit);
    }

    // GET: Employees/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees
            .Include(e => e.Appointment)
            .Include(e => e.Department)
            .SingleOrDefaultAsync(m => m.EmployeeID == id);
        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // POST: Employees/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);
        _context.Employees.Remove(employee);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool EmployeeExists(int id)
    {
        return _context.Employees.Any(e => e.EmployeeID == id);
    }
}

Create View
@using (Html.BeginForm("Create", "Employees"))
    {
        @Html.ValidationSummary(true, "", new { @class = "validation-summary-errors" })

            @Html.LabelFor(e => e.FirstName)
            @Html.TextBoxFor(e => e.FirstName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.FirstName)

            @Html.LabelFor(e => e.LastName)
            @Html.TextBoxFor(e => e.LastName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.LastName)

            @Html.LabelFor(d => d.DepartmentID)
            @Html.DropDownListFor(d => d.DepartmentID, new SelectList(Model.Departments, "DepartmentID", "Name"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(d => d.DepartmentID)

            @Html.LabelFor(a => a.AppointmentID)
            @Html.DropDownListFor(a => a.AppointmentID, new SelectList(Model.Appointments, "AppointmentID", "TimeSlot"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(a => a.AppointmentID)

            <button type="submit" class="btn btn-primary">Submit</button>

    }

Edit View
@using (Html.BeginForm("Edit", "Employees"))
    {

            @Html.LabelFor(e => e.FirstName)
            @Html.TextBoxFor(e => e.FirstName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.FirstName)

            @Html.LabelFor(e => e.LastName)
            @Html.TextBoxFor(e => e.LastName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.LastName)

            @Html.LabelFor(d => d.DepartmentID)
            @Html.DropDownListFor(d => d.DepartmentID, new SelectList(Model.Departments, "DepartmentID", "Name"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(d => d.DepartmentID)

            @Html.LabelFor(a => a.AppointmentID)
            @Html.DropDownListFor(a => a.AppointmentID, new SelectList(Model.Appointments, "AppointmentID", "TimeSlot"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(a => a.AppointmentID)

        @Html.HiddenFor(e => e.EmployeeID)

            <button type="submit" class="btn btn-primary">Submit</button>

    }

Confirmation View

Thank you @Html.DisplayFor(model => model.FirstName) @Html.DisplayFor(model => model.LastName)!

Your @Html.DisplayFor(model => model.Appointment.TimeSlot) appointment has been booked. If you need to reschedule this appointment, please call the Service Desk at x1380.

A: @Max is right. IDataProtectionProvider is what you want to look at.
IDataProtectionProvider can be used on windows or unix.
It's true it can't be used as a clientside javascript library but there are ways to still leverage it.
The simplest approach is to encrypt the ID before sending the view's html to the browser and including the encrypted ID in an html data- attribute, etc, where your client javascript can get access to it to post back (or used in a query string if you so choose) with the edit or delete request.
Below is an example of how to use the IDataProtectionProvider in a controller to encrypt and decrypt an id.
 public class HomeController : Controller{
     IDataProtector dataProtector;

     public HomeController(IDataProtectionProvider provider){
         dataProtector = provider.CreateProtector(GetType().FullName);
     }

    [HttpGet]
    public IActionResult Get() {
        int id = 1234;

        string encryptedId = dataProtector.Protect(id.ToString());

        int decryptedId = 0;
        if(int.TryParse(dataProtector.Unprotect(encryptedId), out decryptedId) == false){
            throw new Exception("Invalid cypher text");
        }

        //at this point decryptedId contains the decrypted value.

   }

Please note that when this dataProtector is created above it uses GetType().FullName as the encryption "purpose".  This is a common practice that appears in the .net core framework code.  The "purpose" is used as additional context data when doing the encryption and is essentially used to derive a purpose specific subkey for encrypting/decrypting data.  In this case since I set it to GetType().FullName it will be the fully qualified name of the controller.  That's great if you are encrypting and decrypting from withing the same controller, it will work no problem.  BUT, if you want to encrypt in one controller and decrypt in a different controller (or any other class for that matter), then the important thing to know is that purpose string passed to  in this line dataProtector = provider.CreateProtector(purpose); MUST be the same for the dataProtector used to decrypt as it was for the dataProtector used to encrypt.  (i.e. it can't be the class name if the class used to decrypt is different than the one used to encrypt).
Additionally, this is a article that you may find useful: https://www.mikesdotnetting.com/Article/295/encryption-and-decryption-in-asp-net-core


text:
Q: Signout/Switch Twitter user using SocialAuthAdapter in Android I'm using SocialAuthAdapter lib in Android and I'm trying to switch Twitter user without success. What happens is after doing the following I do not get LogIn screen, but instead it signs in previous user:
adapter.getCurrentProvider().logout();
adapter.authorize(_parentActivity, Provider.TWITTER);

A: use the signout method provided by latest socialauth android sdk.  The method above not clear cookies

A: adapter.signOut(HomeActivity.this, Provider.TWITTER.toString());