Entity Framework commands not recognized

Question: I'm using ASP.NET Core MVC and for some reason the package manager console in visual studio 2015 or the command prompt window will not recognize any Entity Framework commands like 'Enable-Migrations' 'dnx ef database update' etc..
I never had any issues with EF migrations in any other project where iv'e been using MVC 5 with Entity Framwork 6
I also tried restarting Visual Studio like many answers recommended but that didn't work for me.
The error message I get for enabling migrations is:
PM> Enable-migrations
Enable-migrations : The term 'Enable-migrations' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ Enable-migrations
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Enable-migrations:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Comment: Please post the text of the error message, not a screenshot of it. My eyes aren't good enough to read that anymore.
Comment: @CraigW. Sorry about that, I added the text instead of screenshot.
Comment: The package might have not installed successfully. EF tools I believe are installed/enabled as part of the package install and if that didn't succeed correctly, you may not be able to get access to the commands.
Comment: @HarikrishnaMenonA I installed the latest Entity Framework from nuget so it's there, but still won't work.
Comment: Please, don't use MVC6 tags anymore. It's for a future version of ASP.NET MVC based on the old webstack (MVC5). ASP.NET Core is a complete new and incompatible, portable version based on .NET Core. Use [tag:asp.net-core-mvc] and/or [tag:asp.net-core] tags instead and your question is more likely to be found by people who can help you with the issue
Comment: Are you using entity framework or EntiryFramework core? And did you install the tools (rc2) or commands (rc1/dnx)?
Answer: First "dnx" command won't work if you installed the Entity Framewok Core or are using a Asp.Net Core application, you need to use the .Net Core CLI commands instead, and "enable-migrations" is not part of the commands list anymore.
So to add a migration to your project you need to use the following command in the command line opened from the root of your src folder:
dotnet ef migrations add {MigrationName}

There are many other commands, find out about them more by typing the following in the command line:
dotnet ef database --help

dotnet ef dbcontext --help

dotnet ef migrations --help

This is assuming that you already installed the EF Core and EF Core Tools in your project, you should have these two references in your project.json:
Under dependencies:
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0"
Under tools:
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
All the previous information is related to the Entity Framework Core under a ASP.Net Core application.
If you want to work with ASP.Net Core and the Entity Framework 6, it is also possible but that does require a few extra steps and a little plumbing to get it working seamlessly (kind of), specially if you want to make use of ASP.NEt Identity with EntityFramork 6.
Let me know if that is what you are looking for or if what I mentioned applies to your current situation and if it solves things.
I'll try my best.


When testing a method, can you mock variables on singletons which that method refers to?

Question: I've got a method that I'd like to test with JUnit/Mockito.
The method takes in one Integer, numberOfRowsThatTheUserWants.
The method then compares that value, against another value totalNumberOfRowsInDB and will return the requested number of rows(randomly picked). If the user requests more than is available, they'll just get the total that are available.
All is fine up to this point.
The problem I have, is testing this methods behaviour.
totalNumberOfRowsInDB is a variable held on a singleton. My reason for doing this was because it would be set at startup and would not change during the execution of the application, and I wanted to avoid constant unneccssay calls to the DB to constantly count the rows when it would never change.
Testing works if I make my tests assume there is a total of 10 rows (as that is what I have on the actual base), however I don't want my tests to be dependent on my scrub data, because if I add a few more rows, it'll break the tests.
Question : How can I modify(mock) a static variable that resides INSIDE of the method I'm actually trying to test? I'm completely open to suggestions / advice on how to improve my design if its awfully wrong...
This is a little demo to show a simplified version of my issue:
public class MockMe
{
    public static void main(String[] args)
    {
        // Setting to 5, but this comes from user input
        Integer numberOfRowsThatTheUserWants = 5;
        MockMe myMockMe = new MockMe();
        myMockMe.myMethod(numberOfRowsThatTheUserWants);
    }

    private void myMethod(Integer numberOfRowsThatTheUserWants)
    {
        if(numberOfRowsThatTheUserWants > MySingleton.getInstance().getTotalRowsOnDB())
        {
            System.out.println("You've requested more than is available, so I'll just give you all I've got instead");
        }
        else
        {
            System.out.println("Here are your " + numberOfRowsThatTheUserWants + " rows as requested, sir!");
        }
    }
}

class MySingleton
{
    private static MySingleton mySingleton;
    private int totalRowsOnDB;

    private MySingleton()
    {
        //private constructor to prevent instantiation
    }

    public int getTotalRowsOnDB()
    {
        return totalRowsOnDB;
    }

    public static MySingleton getInstance()
    {
        if (mySingleton == null)
        {
            mySingleton = new MySingleton();
            // this is actually set by SELECT COUNT(*) FROM TABLENAME but setting to 10 for purposes of demo
            //DBManager dbManager = new DBManagerImpl();
            //mySingleton.totalRowsOnDB = dbManager.getTotalRows();
            mySingleton.totalRowsOnDB = 10;
        }
        return mySingleton;
    }
}

Comment: You mean to make the test dependent on "real" data? i.e., the actual number of rows in the table?? It's not clear what exactly you want to 'mock' but if you are going to want real and non-scrubbed data, I think you are going jump the boundary of "pure unit testing" - it depends on which camp you come from - if the unit under test is to be tested in isolation with no connection to the "outside world" whatsoever, then you'll just have to "mock" the values but if you do want it to be based on actual count, you'll be in the realm of integration testing (as per the pursists' POV)
Answer: Using reflection, you can modify a private field:
Field field = MySingleton.class.getDeclaredField("totalRowsOnDB");
field.setAccessible(true); // "Cheat" by setting it to "not private"
field.set(MySingleton.class, 5); // Set it to whatever you like

Answer:
My reason for doing this was because it would be set at startup and would not change during the execution of the application

In such case, I'd recommend to expose setter for this property, then your class would be definitely more "testable". Writing singleton for such purpose is not very good idea in my opinion.
Anyway, for modifying private fields in class for unit tests (for example autowired in the production code) you can use for example org.springframework.test.util.ReflectionTestUtils (or write your own reflection solution based on their code).


How to edit/open Google Sheet using API?

Question: I'm using API to get access_token and now I need to open Google Sheet.
I'm sending  "Authorization: Bearer ya29.a0AV...." together with link: "https://docs.google.com/spreadsheets/u/0/d/[DocumentFileID]/edit" and I get HTML document back (~200kb). I'm using libcurl for that.
The problem is - missing are some css and js files and I see document just partially. Is there any way to open/edit Google Sheet using API?
I know for the option to just open https://docs.google.com/spreadsheets/u/0/d/[DocumentFileID]/edit in the new browser tab, but in that case I need to manually login to Google and that's what I try to avoid, because I want to use API to login and to open/edit a Sheet.
I also know for the option to share a document but I also try to avoid that. I'm writing application to customers who can access they own documents once they confirmed API usage.
Answer: I think you may have misunderstood what the google sheets api can do

The Google Sheets API is a RESTful interface that lets you read and modify a spreadsheet's data.

It gives you access to the data, it does not allow you to open the google sheets web application.  Your going to have to code your own google sheets type app if you want users to open sheets directly.
Comment: no it is not. Thats not what the api is for.
Comment: If you are logged into Google and if you know the documentID, you can directly open the document. I want to do the same using API, is that possible?
Comment: I understand. Too bad.
Comment: Linda, I added openid into scope, when using oAuth2 and it seems it works, I'm logged into Google and I can veiw documents. Is that something expected?
Comment: If yes, how to use id_token? I know how to get new id_token after expiration, but can not figure out how to use new fresh id_token to authenticate again (after user logged off).
Comment: open id is signin.  its not the same thing as oauth2,  id tokens cant be refreshed you need to login the user again for signin.
Comment: Each time I call https://accounts.google.com/o/oauth2/token/client_id=[ClientId]&client_secret=[clientSecret]&refresh_token=[refreshToken]&grant_type=refresh_token
I get new, fresh "id_token" (together with "access_token" and some other values).
When I check "id_token" on https://jwt.io, I see it have new expiration time, which means, it is new id_token. What is use of this new, fresh id_token if it can not be used to signin, please?
Comment: The id token denotes to your application that its signed in.   A user has signed in to your application using their google account.
Comment: OK thanks, I will signin user again on same way as first time with scope=openid.
Please tell me how to check is the user signed?
Comment: you have an id token the user is signed in to your application.
Comment: I have id_token but user logged of in the meantime. How to check is the user still logged or not?


How am I updating an div every 10 seconds with Ajax when the div is on same page

Question: I'm using Laravels framework to develop an social network. I just wanna know how to update my div every 10 seconds etc (the status div)
On my home.blade.php page am I using an extend function to my default template which looks like this:

@include('templates.partials.navigation')

    @include('templates.partials.alerts')
    @yield('content')

As you see I'm including content and in my timeline.blade.php it looks like this:
    @extends('templates.default')

@section('content')

            @if (!$statuses->count())

There's nothing in your timeline.

            @else
                @foreach ($statuses as $status)

                        user->username']) }}">
                            user->getNameOrUsername() }}" src="{{ $status->user->getAvatarUrl() }}">

user->username']) }}">{{ $status->user->getNameOrUsername() }}

{!! $status->body !!}

                                created_at }}">
                                @if($status->user->id !== Auth::user()->id)

 $status->id]) }}">Like

                                @endif

{{ $status->likes->count() }} likes

                            @foreach ($status->replies as $reply)

                                        user->getNameOrUsername() }}" src="{{ $reply->user->getAvatarUrl() }}">

{{ $reply->user->getNameOrUsername() }}

{{ $reply->body }}

{{ $reply->created_at->diffForHumans() }}

                                            @if(Auth::user()->hasLikedStatus($reply))

 $reply->id]) }}">Unlike

                                            @elseif($reply->user->id !== Auth::user()->id)

 $reply->id]) }}">Like

                                            @endif

{{ $reply->likes->count() }} likes

                            @endforeach

                            <form role="form" action="{{ route('status.reply', ['statusId' => $status->id]) }}" method="post">

has("reply-{$status->id}") ? ' has-error': '' }} ">
                                    <textarea name="reply-{{ $status->id }}" class="form-control" rows="2" placeholder="Reply to this status" style="resize:none"></textarea>
                                    @if($errors->has("reply-{$status->id}"))
                                        {{ $errors->first("reply-{$status->id}") }}
                                    @endif

                                <input type="submit" value="Reply" class="button-reply btn btn-default btn-sm ui green basic button">
                                <input type="hidden" name="_token" value="{{ Session::token() }}">
                            </form>

                @endforeach
                {!! $statuses->render() !!}
            @endif

@stop

So how am I refreshing the div without making an actually reload of the whole page, like the load() ajax method?
Comment: Possible duplicate of [AJAX jQuery refresh div every 5 seconds](http://stackoverflow.com/questions/25446628/ajax-jquery-refresh-div-every-5-seconds)
Comment: To execute a function every a specified time you need to use setInterval(...) look here : http://www.w3schools.com/jsref/met_win_setinterval.asp but as said before by @rnevius I think the question is duplicated
Answer: You won't be able to do this in laravel alone. You will have to use javascript with setInterval as mentioned above. http://www.w3schools.com/jsref/met_win_setinterval.asp
With jQuery it will look something like this
setInterval(function(){
$.ajax({
    url:'some url here to get the contents of your div'
}).done(function(response){
    $(".container").html(response);
});}, 10000);

I haven't tested this so don't quote me on this.


How clean the javascript object by replace() in javascript

Question: I have a object in this format
{"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"email@example.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}","business_name":"Soporte Devy"}

Which is not easily readable is there any way i can clean this object and see like this
business_name: Sport Devy
name: hong kong

I just want to clean the object and convert it into representable form
Answer: You could write a function to transform it into the format you want.  I am not sure if you specifically want it as a string or as a different object.  I am outputting a string but you could modify this to return an object if that is what you need.

function formatDisplay(obj) {
   const bname = obj.business_name;
   const customer = JSON.parse(obj.customer || "{}");
   const name = customer && customer.name;
   /* If you need object:
   return {
     business_name: bname,
     name: name
   };
   */
   return [
    "business name: "+ bname,
    "name: " + name,
   ].join("\n");
};

const data = {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"email@example.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}","business_name":"Soporte Devy"};

console.log(formatDisplay(data));
Answer: const obj = {
  "paymethod_id": 1,
  "business_id": 76,
  "delivery_type": "1",
  "driver_tip": 0,
  "delivery_zone_id": 6569,
  "delivery_datetime": null,
  "location": {
    "lat": 18.7675049,
    "lng": -103.1445221
  },
  "deliveryOptionmodal": {
    "id": 3,
    "value": "Sin contacto/Dejar orden en la puerta",
    "$$hashKey": "object:272"
  },
  "delivery_cost_new": 10,
  "products": {
    "name": "Product"
  },
  "customer_id": 35,
  "customer": "{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"firstname.lastname@example.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}",
  "business_name": "Soporte Devy"
}

business_name can be read directly from the object - obj.business_name. customer node needs to parsed into javascript object; for that you can use JSON.parse(obj.customer)


How would I find the gradient of a best-fit line for input values on a scatterplot

Question: Based on this example, the below code plots a scatterplot to which double values can be input via a spinner. I'd like to plot a line of best fit on the scatter plot in order to calculate the gradient and find an average for the values which the value I get for gradient. I'd like it to be output onto a text box when a button is pressed. Help would be greatly appreciated.
package Grava;

        import javafx.application.Application;
        import javafx.geometry.Pos;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.TextField;
        import javafx.scene.control.*;
        import javafx.scene.image.Image;
        import javafx.scene.layout.BorderPane;
        import javafx.scene.layout.HBox;
        import javafx.stage.Stage;
        import org.jfree.chart.ChartFactory;
        import org.jfree.chart.JFreeChart;
        import org.jfree.chart.fx.ChartViewer;
        import org.jfree.chart.plot.XYPlot;
        import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
        import org.jfree.data.statistics.Regression;
        import org.jfree.data.xy.XYSeries;
        import org.jfree.data.xy.XYSeriesCollection;

public class ScatterAdd extends Application {

    private final XYSeries series = new XYSeries("Voltage");
    private final XYSeries trend = new XYSeries("Trend");
    private final XYSeriesCollection dataset = new XYSeriesCollection(series);

    ChoiceBox<String> domainLabels = new ChoiceBox<>();
    ChoiceBox<String> rangeLabels = new ChoiceBox<>();

    private JFreeChart createChart() throws Exception {
        /*
        JFreeChart chart = createChart();
        domainLabels.getSelectionModel().selectedItemProperty().addListener((ov, s0, s1) -> {
            chart.getXYPlot().getDomainAxis().setLabel(s1);
        });
        rangeLabels.getSelectionModel().selectedItemProperty().addListener((ov, s0, s1) -> {
            chart.getXYPlot().getRangeAxis().setLabel(s1);
        });
        XYPlot plot = createChart().getXYPlot();
        XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer();
        r.setSeriesLinesVisible(1, Boolean.TRUE);
        r.setSeriesShapesVisible(1, Boolean.FALSE);
        this part gives me an error when i create it in the createChart() method
        */

        return ChartFactory.createScatterPlot("VI Characteristics", "Current", "Voltage", dataset);

    }

    @Override
    public void start(Stage stage) throws Exception {

        Image image = new Image("Grava.logo.png");
        stage.getIcons().add(image);

        var equation = new TextField();

        series.addChangeListener((event) -> {
            double[] coefficients = Regression.getOLSRegression(dataset, 0);
            double b = coefficients[0]; // intercept
            double m = coefficients[1]; // slope
            double x = series.getDataItem(0).getXValue();
            trend.add(x, m * x + b);
            x = series.getDataItem(series.getItemCount() - 1).getXValue();
            trend.add(x, m * x + b);
            dataset.addSeries(trend);
            equation.setText("y = " + m + " x + " + b);

        });

        domainLabels.getItems().addAll("Current", "Seconds");
        domainLabels.setValue("Current");

        rangeLabels.getItems().addAll("Voltage", "Metres");
        rangeLabels.setValue("Voltage");

        var xSpin = new Spinner<Double>(-10000000.000, 10000000.000, 0, 0.1);
        xSpin.setEditable(true);
        xSpin.setPromptText("Xvalue");

        var ySpin = new Spinner<Double>(-10000000.000, 10000000.000, 0, 0.1);
        ySpin.setEditable(true);
        ySpin.setPromptText("Yvalue");

        var button = new Button("Add");
        button.setOnAction(ae -> series.add(xSpin.getValue(), ySpin.getValue()));

        HBox xBox = new HBox();
        xBox.getChildren().addAll(domainLabels);

        HBox yBox = new HBox();
        yBox.getChildren().addAll(rangeLabels);

        var enter = new ToolBar(xBox, xSpin, yBox, ySpin, button, equation);
        BorderPane.setAlignment(enter, Pos.CENTER);

        BorderPane root = new BorderPane();
        root.setCenter(new ChartViewer(createChart()));
        root.setBottom(enter);

        stage.setTitle("ScatterAdd");
        stage.setScene(new Scene(root, 720, 480));
        stage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

Answer: As shown here, call Regression.getOLSRegression() and display the result. You can do this in your Add button handler, as suggested in your question, or in a SeriesChangeListener, as shown below. This fragment simply prints the equation of the line, but you can update the display as desired.
private final XYSeries series = new XYSeries("Voltage");
private final XYSeries trend = new XYSeries("Trend");
private final XYSeriesCollection dataset = new XYSeriesCollection(series);
…
// https://stackoverflow.com/a/61398612/230513
series.addChangeListener((event) -> {
    double[] coefficients = Regression.getOLSRegression(dataset, 0);
    double b = coefficients[0]; // intercept
    double m = coefficients[1]; // slope
    System.out.println("y = " + m + " x + " + b);
});

Note that the series will need at least two values, and it should be added to the collection only once. In particular,

Don't recreate the dataset in createChart()

Don't recreate the choice boxes in start()

Add a TextField to the toolbar and invoke setText() in the change listener; the displayed equation will update as points are added.

Create an XYSeries named  trend and add into the dataset, then update the series in the change listener.
  var equation = new TextField();
  series.addChangeListener((event) -> {
      …
      equation.setText("y = " + m + "x + " + b);
      double x = series.getDataItem(0).getXValue();
      trend.clear();
      trend.add(x, m * x + b);
      x = series.getDataItem(series.getItemCount() - 1).getXValue();
      trend.add(x, m * x + b);
  });

Comment: How would i implement the getOLRegression() method into my code to plot a scatterplot. please
Comment: As your code may have evolved, please [edit] your question to include a [mre] that shows your revised approach.
Comment: I've amended my question with a minimal reproducible example however it doesn't plot the line of best fit or add a button to give the gradient. could i please have some help.
Comment: I've elaborated above; you should then be able to add/update a second series as shown [here](https://stackoverflow.com/a/61398612/230513).
Comment: How would I add a button which brings up a visible line of best fit please.
Comment: Same as the example: add a series with two points calculated from the equation.
Comment: I've ammended my code with an attempt to add a line of best fit however I cant get the line of best fit to show up please could I have some help.
Comment: You'll need a second series for the trend line, which should be updated in the listener.
Comment: I've ammended the code to make a minimal reproducible example, I've attempted to create a second series trend but when I try to create plot and chart in the createchart() method i get met with the error saying exception in the start method I have tried creating plot and chart in the start method however the best fit line doesnt appear . thanks for your help so far
Comment: In `start()`, invoke `addChangeListener()` only _after_ you've added some data and invoked `createChart()`; otherwise the the listener will fire before it has anything to work with.
Comment: thank you the best fit line appears so does the equation of the line however after inputting 2 points an error comes up 'exception in application start method' but the application still works fine just the error comes up in intelij
Comment: I suspect the repeated addition of `trend` to the `dataset`, seen [here](https://stackoverflow.com/q/74889977/230513). If not, [edit] your question to to show your current approach and the error you encounter.
Comment: thanks for your help trashgod how would I make this best fit line curved and implement this with the getPowerRegression() method.
Comment: Same way, but open a new question; note, you'll need more than two points for the curve.


What are the underlying mechanics of Ammo bag and Medic kit in Payday 2?

Question: Very similar to this question, except for Payday 2 instead: Do medic and ammo bags run out after a certain number of uses, or after a certain amount of health/ammo dispensed?
I'm trying to figure out how the Ammo bag and Medic kit work in Payday 2 so that I can optimize use of them. I haven't been able to find any reliable information about their underlying mechanics - but I have discovered plenty of conflicting accounts. I suspect some of it may be from early beta.
It appears as though the Ammo bag depletes based on the amount of ammo picked up. It's certainly something more complicated than a simple number of uses... sometimes it disappears after two uses, sometimes after many. I'm not clear on whether or not it is helpful to deplete secondary ammo before using the ammo bag, or if this simply uses up twice as much of the ammo bag. If it's simple a quantity based thing - then optimal use would probably be to only use your most effective ammunition, and recharge as often as viable.
It appears that the medic kit may be a number of charges as it was in Payday: The Heist. This would mean optimal strategy is to only use it when very low on health.
Can anyone confirm, contradict, or elaborate on these hypotheses?
Comment: I think both bags have 4 uses, for the heal bag i'm almost 95% certain, since i've seen it been used 4 times. But the ammo bag i've also seen been used 4 times, what could happen is that someone reloads takes from the bag, fires and reloads then takes from the bag aswell removing 2 charges. The game is based on 4 player coop so I think 4 is the magic number here.
Answer: Steam user Faildozer has written a very detailed guide, "
PAYDAY 2: The Numbers" ("taken from the game files"). Here is what he has to say about ammo packs, supporting your theory:

The ammo bag starts out with 4 uses, some further info about how usage is counted by the game:

It's not split between primary and secondary ammo; there's just one pool of ammo that weapons draw from
How much ammo drawn from the bag is based on a percentage of how much ammo you've used so an empty AK draws just as much as an empty M308 which draws just as much as an empty Crosskill and so on
A default bag holds enough ammo for exactly 4 full refills (400% ammo if you want to think of it as a percentage)
The Enforcer skill that increases the capacity of the ammo bag gives you 50% more ammo per bag (so 6 full refills/600% ammo)
The game will always prioritize filling up your secondary first before your primary, so if both your primary and secondary are completely out of ammo, and the bag has exactly 1 full refill left (or 100% ammo) then your secondary will be refilled completely and your primary will still be empty

Medic bags do get used up after 2 uses (without upgrades). Similar to Left4Dead, you die for good if you go down too often, but healing from a med kit resets this counter. So saving them for teammates that went down multiple times already might be worth it.
Comment: This does not seem to be true, ammo bags start out with 3 full refills. Not 4. Acing Ammo Specialist raises it to 5 full refills.


Need to join a lambda function (python) to CloudFormation template in YAML, How can i achieve this?

Question: I'm stuck trying to embed the lambda into this CF template. Lambda is coded on python and CF in YAML, im having a hard time converting the lambda to Yaml.
A little bit of help here would be appreciated. I need to add the lambda to the CF template. Any explanation will be also useful.
<code>AWSTemplateFormatVersion: 2010-09-09
Description: CH CloudFormation template for Deploy and Init of DynamoDB Table
Parameters:
  dbTableName:
    Type: String
    Default: ClientOrders
    Description: Enter the name used for DynamoDB Table
  phoneNumber:
    Type: String
    Default: 1115551111
    Description: Enter your phone number

Resources:
  OrdersTable:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      TableName: !Ref dbTableName # !Join [ "-", [ !Ref "AWS::StackName", !Ref dbTableName ] ]
      AttributeDefinitions:
        - AttributeName: PhoneNumber
          AttributeType: S
        - AttributeName: OrderNumber
          AttributeType: S
      KeySchema:
        - AttributeName: PhoneNumber
          KeyType: HASH
        - AttributeName: OrderNumber
          KeyType: RANGE
      TimeToLiveSpecification:
        AttributeName: ExpirationTime
        Enabled: true
      ProvisionedThroughput:
        ReadCapacityUnits: '10'
        WriteCapacityUnits: '5'
    DependsOn:
      - DynamoDBQueryPolicy
  DynamoDBQueryPolicy:
    Type: 'AWS::IAM::Policy'
    Properties:
      PolicyName: DynamoDBQueryPolicy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: 'dynamodb:*'
            Resource: '*'
      Roles:
        - !Ref OrdersTableQueryRole
  OrdersTableQueryRole:
    Type: 'AWS::IAM::Role'
    Properties:
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - dynamodb.amazonaws.com
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /

  phoneRecord:
    DependsOn:
      - OrdersTable
    Type: 'Custom::CrtUpdDltDynamodbDocumentLambda'
    Properties:
      ServiceToken: !GetAtt dynamoSetupLambda.Arn
      DynamoTableName: !Ref dbTableName # !Join [ "-", [ !Ref "AWS::StackName", !Ref dbTableName ] ]
      # DynamoKeyProperty: PhoneNumber
      DynamoItem: !Sub |
        [{
          "PhoneNumber": "784578745",
          "OrderNumber": "11547854",
          "someKey": "someValue"
        },
        {
          "PhoneNumber": "${phoneNumber}",
          "OrderNumber": "11545154",
          "someKey": "someValue"
        }]
  dynamoSetupLambda:
    Type: AWS::Lambda::Function
    Properties:
      Description: custom resource function invoked for intitial configuration of dynamodb
      Handler: index.lambda_handler
      Timeout: 300
      MemorySize: 128
      Role: !GetAtt 'OrdersTableQueryRole.Arn'
      Runtime: python3.8
      Code:
        ZipFile: |
          import json, boto3, os, threading, logging
          import cfnresponse
          def setup_stack(tableName, dynamoItems):
              dynamodb_client = boto3.resource("dynamodb", region_name=os.environ['AWS_REGION'])
              try:
                  dynamodb_client_table = dynamodb_client.Table(tableName)
                  with dynamodb_client_table.batch_writer() as batch:
                      for message in dynamoItems:
                          batch.put_item(
                              Item=message
                          )
              except Exception as exc:
                  print(exc)
          # def remove_stack(tableName): # will need to clear maybe?
          #     dynamodb_client = boto3.resource(tableName, region_name=os.environ['AWS_REGION'])
          #     dynamodb_client_table = dynamodb_client.Table(table_name)
          #     continue
          def timeout(event, context):
              logging.error('Execution is about to time out, sending failure response to CloudFormation')
              cfnresponse.send(event, context, cfnresponse.FAILED, {}, None)
          def lambda_handler(event, context):
              print('Received event: %s' % json.dumps(event))
              # make sure we send a failure to CloudFormation if the function is going to timeout
              timer = threading.Timer((context.get_remaining_time_in_millis()
                      / 1000.00) - 0.5, timeout, args=[event, context])
              timer.start()

              status = cfnresponse.SUCCESS
              try:
                  dynamoItems = event['ResourceProperties']['DynamoItem']
                  dynamoTable = event['ResourceProperties']['DynamoTableName']
                  if event['RequestType'] == 'Delete':
                      print("Not going to remvove yet")
                      # remove_stack(dynamoTable)
                  else:
                      setup_stack(dynamoTable, json.loads(dynamoItems))
              except Exception as e:
                  logging.error('Exception: %s' % e, exc_info=True)
                  status = cfnresponse.FAILED
              finally:
                  timer.cancel()
                  cfnresponse.send(event, context, status, {}, None)
</code>
Lambda:
<code>    from __future__ import print_function
import boto3
from boto3.dynamodb.conditions import Key, Attr
import json
dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):
    #print(event)
    PhoneNumber=event['Details']['ContactData']['Attributes'].get('PhoneNumber',"Not Available")
    table = dynamodb.Table('ClientOrders')
    try:
      response = table.query(
        KeyConditionExpression=Key('PhoneNumber').eq(PhoneNumber)
        )
    except ClientError as e:
        print(e.response['Error']['Message'])
        return {
                "Success":"False",
                "Reason":e.response['Error']['Message']
               }
    else:
        #item = response['Item']
        print("GetItem succeeded:")
        print(json.dumps(response))
        print(response['Items'])
        if "Items" in response:
            return{
                "Success":"True",
                "PhoneNumber":response["Items"][0]["PhoneNumber"]
                }
        else:
            return {
                "Success":"False",
                "Reason":"No Records Found"
            }
</code>
Thanks in advance!
Comment: At first glance this looks good, can you share the error message you're getting?
Comment: You haven't explained what's wrong? Why it does not work? What is expected outcome? What errors do you get?
Answer: I solved it, you need to use ZipFile and mantain the format from the CF template. I was checking if was valid through the CF designer builder but i would suggest to try to run it anyway and in case of errors analyze it.


Microsoft SQL Server multiple locks

Question: I'm currently running Microsoft SQL Express Server.
When one user performs a query without committing it, it locks the entire table.
The problem is that malicious users might "ruin" the database by doing so on purpose.
How can I prevent this from happening?
Comment: Need more info. What sort of query is it? How are they running the query without committing it?
Comment: Is this a programmer or a user locking the table? Are you waiting for the user to perform an action before you call commit?
Comment: They use pyodbc, perform res = con.execute('insert into mytable...'), at that point the table is locked until they res.commit().
Comment: These are programmers, they can at any point decide to lock that table. Is it possible to set a lock timeout on a table or something like that?
Answer: You need to understand database isolation levels http://en.wikipedia.org/wiki/Isolation_(database_systems). Most likely you are running queries as seralizable which will have that effect. Try submitting some code.

Microsoft SQL Server multiple locks


Vaadin Touchkit or mgwt

Question: I am evaluating possibilities to create mobile hybrid Apps with GWT and Apache Cordova / PhoneGap. I already build a small prototype with mgwt and liked it, but I would like to research a few other possibilities before starting the project. Therefore I took a look at Vaadin and its AddOn Touchkit.
I have the following questions:

Is it possible to use the Vaadin Touchkit Addon in a Client-Side Application which does not need a permanent server connection?
In the mobile chapter of the documentation an example is shown that is a Server-Side Application, as far as I understand it and therefore would need a server connection for each UI event. Please correct me if I'm wrong, I have no experience with Vaadin.

Is there any difference between a "normal" GWT App and a Client-Side Vaadin App?

Does it has any advantages to use Vaadin Touchkit instead of mgwt?

In general is Vaadin Touchkit comparable to mgwt and if yes which are the main differences?
Answer:
You can build a Vaadin TouchKit applications that work offline. The "Parking Demo" shows this: http://demo.vaadin.com/parking/ (Source code here : https://github.com/vaadin/parking-demo) By default, default the application is online, but for the data entry the app uses offline (client-side-only) approach.
If you are building a client-side Vaadin app you would still use the TouchKit widgets. Until version 3 TouchKit widgets have followed the iOS native widgets, but v4 introduces new styles that are more device agnostic and better suitable also for Android devices.
The most prominent difference (and advantage, if you wish) of Vaadin TouchKit is however the default server-side programming approach. It is very quick to build mobile optimized web applications - especially if you already have an existing Java web application and business logic in place. For client-side apps the visible difference is the look-and-feel of the Touchkit and mgwt widgets.
Generally this is also where it boils down to: If you are quite ok
to have parts of the application running online (data on server) and
need the offline-mode is only needed for some parts of application,
Vaadin TouchKit is very quick and efficient way to build decent looking apps. On the other hand, mgwt
gives you direct start on the client-side-only applications and is
maybe better optimized for that.

You had already found out that both suffer from the sandboxing of HTML5 applications. While camera and location APIs are available a solution like phonegap is still needed to really integrate with the device and match native applications.

Vaadin Touchkit or mgwt


Can't SSH into Ubuntu Desktop from Windows laptop via ethernet cable

Question: I have an Ubuntu 18.04 LTE Desktop and a Windows 10 laptop. I would like to SSH from windows 10 via Cygwin (or whatever else is convenient) into the Desktop but would prefer to use an ethernet cable for direct connection between the two, as opposed to wifi. Using SSH to the wireless local IP address works fine but I cannot get it to work via ethernet.
Here is the info for my Ubuntu Desktop
$ ifconfig -a
enp69s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.1  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::6961:bda5:85a6:4150  prefixlen 64  scopeid 0x20<link>
        ether a8:a1:59:18:6c:b4  txqueuelen 1000  (Ethernet)
        RX packets 86049  bytes 7681993 (7.6 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 215  bytes 27497 (27.4 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device memory 0xb7600000-b761ffff

enp71s0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether a8:a1:59:18:6c:b2  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

gpd0: flags=4240<POINTOPOINT,NOARP,MULTICAST>  mtu 1500
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 500  (UNSPEC)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 4129  bytes 488109 (488.1 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 4129  bytes 488109 (488.1 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlp70s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.0.57  netmask 255.255.255.0  broadcast 10.0.0.255
        inet6 2601:2c5:c780:e3f0:142a:9cd:ee13:3f75  prefixlen 64  scopeid 0x0<global>
        inet6 2601:2c5:c780:e3f0:817e:ff1:3daf:22e1  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::af6e:ce97:8156:93db  prefixlen 64  scopeid 0x20<link>
        inet6 2601:2c5:c780:e3f0::8abc  prefixlen 128  scopeid 0x0<global>
        ether 24:41:8c:95:cc:cf  txqueuelen 1000  (Ethernet)
        RX packets 167161  bytes 75026317 (75.0 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 78430  bytes 18079733 (18.0 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp69s0 is the ethernet cable connecting to my laptop. In my Cygwin terminal, connecting through the wireless router works fine:
ssh email@example.com

But when I attempt to ssh to the address 192.168.1.1 it does not. In fact, when I type ping 192.168.1.1 it would say Connection timed out. I would prefer to use a direct connection, so any help or advice would be helpful. Thanks!
EDIT: Problem fixed after changing the IP address of enp69s0 from 192.168.1.1 to another value 192.168.1.3. Didn't realize that 192.168.1.1 is usually reserved for the router.
EDIT2: Added my own answer
Comment: Are the two computers directly connected to each other by Ethernet cable, or are they connected via a router or a switch? What is the Ethernet IP address of the Windows computer. The 192.168.1.1 is usually reserved for the router.
Comment: Please [Edit] your Question and show us `ip route`. Can you `ping -I enp69s0 192.168.1.1`?
Comment: Feel free to write your own answer. Or I can convert my comment to an answer. In either case you should accept the answer as correct with the green  check mark ✅. This will help others.
Comment: Hi guys, the problem indeed was having my ubuntu IP address set as 192.168.1.1. Changing it to 192.168.1.3 fixed my problem (my windows IP address was 192.168.1.2)
Answer: Problem fixed after changing the IP address of enp69s0 from 192.168.1.1 to another value 192.168.1.3. Didn't realize that 192.168.1.1 is usually reserved for the router.


vector states from elementary tensors $h\otimes k\in H\otimes K$ separate all of $\mathbb{B}(H\otimes K)$

Question: In the book "C* algebras and finite dimensional approximations",there is a statement in the proof of lemma4.1.8,$A\otimes B\subset\mathbb{B}(H\otimes K)$ and vector states from elementary tensors $h\otimes k\in H\otimes K$ separate all of $\mathbb{B}(H\otimes K)$,Who can give me a little hints on how to prove the statement,thanks!
Answer: All you need to show is that if $T\in B(H\otimes K)$ satisfies $T(h\otimes k)=0$ for all $h\in H$, $k\in K$, then $T=0$.
This is straighforward: given $\xi\in H\otimes K$, we may write
$$
\xi=\sum_{k,j} \alpha_{kj}\,e_k\otimes f_j
$$
for orthonormal bases $\{e_k\}$ of $H$ and $\{f_j\}$ of $K$. Then, since $T$ is bounded,
$$
T\xi=\sum_{k,j} \alpha_{kj}\,T(e_k\otimes f_j)=0.
$$
So $T=0$.
Comment: No, they have the form $$\langle a\left(\sum_j h_j\otimes k_j\right),\sum_j h_j\otimes k_j\rangle =\sum_{s,j} \langle a(h_j\otimes k_j),h_s\otimes k_s\rangle.$$
Comment: i don't understand the meaning of vector states from elementary tensors.My thought:For any $T\in B(H\otimes K)$ ,we can find a vector state $\phi$ such that  $\phi(T)\neq 0$ .
Comment: Sorry, I'm not sure what you are asking. You mean to ask what a vector state is?
Comment: Yes.what is the definiton of vector state.
Comment: A vector state is a state of the form $a\longmapsto \langle a\xi,\xi\rangle$ for a unit vector $\xi$.
Comment: By the definition,does it mean that vector states from elementary tensors $h\otimes k\in H\otimes K$ has the form $a\longmapsto \langle ah\otimes k,h\otimes k\rangle$?


How to disable form button until function has fully complete

Question: So everything in script works perfectly. However there is an issue in this part of the code:
var min = 1;
while (min < 200) {
    var max = min + 30;

    scan(fruitID, min, max);

    var min = max;
}

What I want from this loop:

Computes max value
Calls scan() function
Waits until the ajax in scan has successfully gotten the data, and displayed it up on the screen.
Computes min value
Repeats the loop

The mistake is in step 3. It doesn't wait for ajax to get the data back and process it. It just straight away repeats the loop. How do I make the loop wait until the scan() function has fully finished.

$(document).ready(function() {

    $('#submit').click(function(e){
    e.preventDefault();

    $("#submit").attr("disabled", true);
    $("#submit").html("Verifying Username");
    var fruitName = $("#fruit-name").val();

    $.ajax({
        type: "POST",
        url: "verify-input.php",
        dataType: "json",
        data: {fruitName:fruitName},
        success : function(data){
            if (data.code == 200){
                $("#submit").html("Running Scan");
                var fruitID = data.fruitId;
                //alert("Fruit ID: " + fruitID);

                var min = 1;
                while (min < 200) {
                    var max = min + 30;

                    scan(fruitID, min, max);

                    var min = max;
                }

            } else {
                $("#submit").attr("disabled", false);
                $("#submit").html("Submit");
                $(".display-error").html("
"+data.msg+"
");
                $(".display-error").css("display","block");
            }
        }
    });

    });
});

function scan(vFruitId, min, max) {

    $.ajax({
        type: "POST",
        url: "scanner.php",
        dataType: "json",
        data: {vFruitId: vFruitId, min: min, max: max},
        success : function(data){
            data.forEach((item, idx) => {
              $("#results").append(`

calories: ${item.sweetness}

sweeteness: ${item.calories}

bitterness: ${item.bitterness}

              `);
      })
        }
    });

}
<form>
  Fruit (only correct input is: banana)

  <input type="text" id="fruit-name" name="fruit" value="banana">

  <button type="submit" id="submit" value="Submit">Submit</button>
</form>

Comment: since scan is asynchronous, you'll need to handle the asynchrony - since jquey ajax returns a promise-like object, you could use that promise. make success callback `async function (data)` ... then `await scan(fruitID, min, max);` and finally in `scan` you `return $.ajax({`
Answer: note: your original code does not re-enable the form button, so the question title is a bit misleading
The solution is to use the Promise-like object returned by $.ajax
The following code uses arrow notation like in the question, but does not use async/await so would work anywhere the code in the question works

$(document).ready(function () {

    $('#submit').click(function (e) {
        e.preventDefault();

        $("#submit").attr("disabled", true);
        $("#submit").html("Verifying Username");
        var fruitName = $("#fruit-name").val();

        $.ajax({
            type: "POST",
            url: "verify-input.php",
            dataType: "json",
            data: {
                fruitName: fruitName
            },
            success: function (data) {
                if (data.code == 200) {
                    $("#submit").html("Running Scan");
                    var fruitID = data.fruitId;
                    //alert("Fruit ID: " + fruitID);

                    function runscan(min) {
                        return scan(fruitID, min, min+30)
                        .then(() => {
                            min = min + 30;
                            if (min < 200) {
                                return runscan(min);
                            }
                        });
                    }
                    runscan(1)
                    .then(() => {
                        // all done here
                    });

                } else {
                    $("#submit").attr("disabled", false);
                    $("#submit").html("Submit");
                    $(".display-error").html("
" + data.msg + "
");
                    $(".display-error").css("display", "block");
                }
            }
        });

    });
});

function scan(vFruitId, min, max) {
    return $.ajax({
        type: "POST",
        url: "scanner.php",
        dataType: "json",
        data: {
            vFruitId: vFruitId,
            min: min,
            max: max
        },
        success: function (data) {
            data.forEach((item, idx) => {
                $("#results").append(`

calories: ${item.sweetness}

sweeteness: ${item.calories}

bitterness: ${item.bitterness}

              `);
            })
        }
    });

}

Alternatively, using async/await, the main success code can be written

success: function(data) {
  if (data.code == 200) {
    $("#submit").html("Running Scan");
    (async function() { // `success` can't be async, because jquery doesn't like that
      var fruitID = data.fruitId;
      //alert("Fruit ID: " + fruitID);
      var min = 1;
      while (min < 200) {
        await scan(fruitID, min, min + 30);
        min = min + 30;
      }
    })();
  } else {
    $("#submit").attr("disabled", false);
    $("#submit").html("Submit");
    $(".display-error").html("
" + data.msg + "
");
    $(".display-error").css("display", "block");
  }
}

Important note: you still MUST return $.ajax in function scan as per first code snippet
Comment: Can you show me how to do this with a while loop instead? I'm not really understanding the `=>` syntax
Comment: firstly, you can't use while loop with asynchronous calls unless you use async/await .... anyway, you use the `=>` syntax in your code, so why don't you understand it? - where I've used `() => {` use `function() {` basically the same thing in this code ... and the second snippet that uses async/await uses your while loop (written a little more succinctly) anyway
Comment: Could you explain the async and await one. I put async in front of my first function (as you shown above) and the await on when I call the scan function. I return the `$ajax` in the scan function. However, I can see that it never makes a call to my `scanner.php`
Comment: check your browser console - are you sure you tagged the success callback function `async` - saying you put it in front of your first function suggests you did it wrong
Comment: There is nothing i my console.
Comment: does `$("#submit").html("Running Scan");` execute - add some console logs through your code to see what is and isn't running
Comment: It does not execute
Comment: hmmm, and there's no errors at all in your browser developer tools console - but the first request does take place
Comment: The first request (to `verify-input.php`) takes place. Then it doesn't execute `running scan` text and there is no errors. before async and await, it worked fine
Comment: then don't use async/await version, try the first version - not sure why async/await would fail to work, but then, jQuery is jQuery and prone to break for no reason
Comment: @Jackie - I've updated the async/await version - jquery probably doesn't like the success callback to be `[object AsyncFunction]` rather than `[object Function]` - so I've put the async/await stuff inside an IIFE


XML Schema (XSD) restriction pattern allowing only ISO 646 invariant subset (i.e. ASCII)?

Question: Can anyone see why my xsd restriction is not working?
Update: I tried the exact same xsd as below but in the regex I changed the ( and ) to [ and ].
The version with square brackets works perfectly in the regex testers I tried but produces a schema validation error in the XSD. Yes, oXygen seems to be saying that a regex wrapped in [] is not allowed in an otherwise valid XSD.
So is it XML schema or oXygen that does not support the square-bracketed expression?
Or is it some other reason?
Related (?) question: XSD restriction pattern for accented characters
The aim is to validate only strings conforming to the following 2 content models:

"tokenized":

<xs:simpleType name="Tokenized500Type">
    <xs:restriction base="xs:string">
      <xs:maxLength value="500"/>
      <xs:minLength value="1"/>
      <xs:pattern value="\S+( \S+)*"/>
    </xs:restriction>
  </xs:simpleType>
and

(with the tokenization included as the base type) the ASCII character set:

<xs:simpleType name="TransliteratedStringType">
    <xs:annotation>
        <xs:documentation> can only contain non-control characters drawn from the "invariant subset"
            of ISO 646 (i.e. ASCII). </xs:documentation>
    </xs:annotation>
    <xs:restriction base="example:Tokenized500Type">
        <xs:pattern
            value="(!|"|%|&|'|\(|\)|\*|\+|,|-|.|\/|0|1|2|3|4|5|6|7|8|9|:|;|<|=|>|\?|A|B|C|D|E|F|G|H|I|J|K|L| |M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|_|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)+"
        />
    </xs:restriction>
</xs:simpleType>
I've tested the tokenization separately and it does seem to fit all the use cases it's meant for (removing any unneeded whitespace and restricting string length).
I can't figure out why the ASCII restriction is not working.
I thought perhaps some kind of mapping from characters with diacritics to the equivalent without, but turns out it's allowing other specially characters too, e.g. ß. Is it possible that ß is really mapped to ss? or sz?
Do I need to escape all the characters as unicode code points?
Or is there some kind of error in my use of xs:restriction?
Testing using:
 - oXygen XML Editor (regex inside XSD)
 - http://regexr.com/ (regex only)
Test strings:
Dr. Bäcker
Dr. Baecker
...and portions of:
ŦŲƯY̨Ƴąɓçđɗęħįƙłøơşșţțŧųưy̨ƴÁÀÂÄǍĂĀÃÅǺĄÆǼǢƁĆĊĈČÇĎḌĐƊÐÉÈĖÊËĚ
ĔĒĘẸƎƏƐĠĜǦĞĢƔáàâäǎăāãåǻąæǽǣɓćċĉčçďḍđɗðéèėêëěĕēęẹǝəɛġĝǧğģɣĤḤĦIÍÌİÎÏǏĬĪĨĮỊIJĴĶƘĹĻŁĽĿ'NŃN̈ŇÑŅŊÓÒÔÖǑŎŌÕŐỌØǾ
ƠŒĥḥħıíìiîïǐĭīĩįịijĵķƙĸĺļłľŀ'nńn̈ňñņŋóòôöǒŏōõőọøǿơœŔŘŖŚŜŠŞȘṢẞŤŢṬŦÞÚÙÛÜǓŬŪŨŰŮŲỤƯẂẀŴẄǷÝỲŶŸȲỸƳŹŻŽẒŕřŗſśŝšşșṣßťţṭŧþúùûüǔŭūũűůųụưẃẁŵẅƿýỳŷÿȳỹƴźżžẓ
Comment: A couple of observations: The ASCII pattern is missing the space () and you should not include a bare > (>).
More importantly, it should be possible to represent the printable ASCII as "[ -~]+".
Comment: I like that range, but please note that a basic issue appears to be `[]` versus `()` - see update above!
Comment: Hi @SMeyer - I tried escaping the space with   (I think you missed an x in your comment above?), but still getting the XSD validation error: InvalidRegex: Pattern value '([!|"|%|&|'|\(|\)|\*|\+|,|-|.|\/|0|1|2|3|4|5|6|7|8|9|:|;|<|=|>|\?|A|B|C|D|E|F|G|H|I|J|K|L| |M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|_|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z])+' is not a valid regular expression. The reported error was: 'This expression is not supported in the current option setting.'.
Comment: @SMeyer I don't think that spaces need to be escaped in XML, or is that a regex thing? Please see https://www.w3.org/TR/xml11/#sec-predefined-ent for XML; the regex testers I've tried accepted the literal space.
Comment: There was a missing x, good catch. Yes, the space does not have to be escaped. Though it shouldn't hurt either. I just wanted to be clear which one I'm talking about.
Comment: Note that [] denotes a list of characters. On the other hand, () is a subexpression. As such, "(A|B|C)+" is equivalent to "[ABC]+". In your explicit list, there might be a character that should be escaped but isn't. Have you tried my range from the first comment?
Comment: If you propose one final answer I will test it and get back to you.
Answer: If you want to restrict a string to the printable ASCII characters,
you can simply denote a Unicode range like this:
"[ -~]+"

The range for ISO-646 is a bit more complicated, because it is not a continuous sequence:
"[ -"%-?A-Z_a-z]+"

In your explicit list of characters, you most likely are using an incorrectly escaped character, which causes the error.
Comment: The link is included in the answer, i.e. http://en.wikipedia.org/wiki/ISO/IEC_646
Comment: Thanks!  I checked the list of escaped characters in XML, it's covered already in this expression.

The unicode range above seems to work so far.

Could you link to a reference where I can check that all the ISO 646 characters listed in the original regex (an no more) are covered by the range ` -~`?
Comment: ...Maybe I left the `.` unescaped?

...Apparently also the schema validation engine (Saxon) doesn't like escaped `/`... and *this* was the XSD validation error
Comment: Sorry, I didn't realize that ISO-646 is different from the printable ASCII set. I added the range for that too.
Comment: I would still need to point to the documentation to verify the specific code range(s) though - the explicit regex is better because it's self-documenting
Answer: The error message from Saxon tells you exactly what is wrong:
Schema processing failed: Syntax error at char 31 in regular expression: Escape character '/' not allowed

That is to say, the rules for regular expressions in XSD 1.0 do not allow "/" (because "/" isn't special in regular expressions, it doesn't need to be escaped, and XSD doesn't allow characters to be escaped in these circumstances - this is a way of reserving them for future use).
Now I have some questions for you:

Did you get this error message?
If not, how were you running the validation?
If you did get it, why did you ignore it?
Comment: No, I didn't get the message.

I think it got lost probably under some other errors; oXygen does that sometimes.

Had I gotten it, I sure wouldn't have ignored it! It's a perfect error message.

Thanks!
Answer: I would love to give the answer to the other poster here, but the unescaped . was only half the problem.
The / must not be escaped either, given I'm using an XML editor (as stated) based on Saxon, which throws an error for characters that don't need to be escaped.
Full answer here (off-SE): https://www.oxygenxml.com/forum/topic13779.html#p40565
Comment: Adrian's answer is correct except that it suggests that disallowing "\/" is a Saxon quirk, which isn't the case - it's defined in the XSD 1.0 specification.
Comment: Yes, I guess it could read that way. Or it could read "because it's Saxon, you get the exact implementation of the XSD 1.0 spec, which disallows \/".


Recursive sequences general term

Question: Find general term for nth term of the sequence
$$a_{n+2}=a_{n+1}+a_n+n^2, a_1=1, a_2=2$$ How to approach this type of questions? I am looking for a specific answer but also more general insight about solving such questions would be appreciated.
Comment: Have you tried a generating function approach?
Comment: Are you familiar with characteristic equation?
Comment: Yes, but this must be solvable with use of them and thus would appreciate answer without them
Comment: not exactly i am not familiar with this method
Answer: I probably made some error computing this but the general approach can help
$$a_{n+2}=a_{n+1}+a_n+n^2\\a_{n+1}=a_n+a_{n-1}+(n-1)^2\\a_{n+2}-a_{n+1}=a_{n+1}-a_{n-1}+2n-1\\a_{n+2}=2a_{n+1}-a_{n-1}+2n-1\\a_{n+1}=2a_n-a_{n-2}+2n-3\\a_{n+2}-a_{n+1}=2a_{n+1}-2a_n-a_{n-1}+a_{n-2}+2\\a_{n+2}=3a_{n+1}-2a_n-a_{n-1}+a_{n-2}+2\\a_{n+1}=3a_n-2a_{n-1}-a_{n-2}+a_{n-3}+2\\a_{n+2}-a_{n+1}=3a_{n+1}-5a_n+a_{n-1}+2a_{n-2}-a_{n-3}\\a_{n+2}=4a_{n+1}-5a_n+a_{n-1}+2a_{n-2}-a_{n-3}$$
Hence you can do the characteristic equation now
Answer: Hint: The general solution is the sum of the solution of the corresponding homogeneous equation $a_{n+2}=a_{n+1}+a_n$  and a partial solution
 which you may  looking  in the form of a polynomial  of degree  $2$  with  uncnown  coefficients.
The situation is very close  to solution of the linear  differental equations.
Comment: this polynomial will be $n^2+3$ or what? Could you tell me what will be this polynomial equation?
Comment: i am still waiting for the answer

Recursive sequences general term


Why is this Symbolic Execution with Z3 resulting in an error?

Question: I am trying to generate test cases using a symbolic execution logic based on the SMT Solver Z3.
I have the following code.
void foo(int a, int b, int c){
    int x = 0, y = 0, z = 0;
    if(a){
        x = -2;
    }

    if (b < 5){
        if (!a && c) { y = 1; }
        z = 2;
    }

    assert(x + y + z != 3);
}

Now, an error occurs during the SMT Solving process and the resulting error log is like below.
(set-option :produce-unsat-cores true)
(set-option :produce-models true)
(set-option :produce-proofs true)
(define-sort bot () Int)

(declare-const sv_1 Int)
(declare-const sv_5 Int)
(define-fun strcmp ((a String) (b String)) Int (ite (= a b) 0 1))

(assert (! (not (= sv_1 0)) :named __a0))
(assert (! (< sv_5 5) :named __a1))
(assert (! (not (not (= sv_1 0))) :named __a2))
(assert (! (not (not (= (+ (+ (bvneg 2) 0) 2) 3))) :named __a3))
(check-sat)
(get-unsat-core)
(get-model)

I have done some testing with this code.
If I do not use x, y, z in the assert function, there is no error.
If the first 'if statement' is true (i.e. a != 0), then the program will never enter the 'if (!a && c) statement. If I erase one of these 'if statements', the there is no error. But I do not understand why this error is occurring. Could anyone explain to me why Z3 is not being able to solve this? Thank you.
Comment: I don't know anything about z3, but if you call foo(0, 0, 1) then you get x=0, y=1, z=2 which fails the assert.
Comment: @Paul Hankin It is strange because when I just have assert(0==1), the symbolic execution successfully generates test cases (multiple sets of a,b, c)  which cover all the branches
Answer: You didn't tell us what exact error you're getting, so I'm assuming it comes from z3 and not from some other part of your toolchain. Let's run the SMTLib program you posted through z3. When I do that, z3
tells me that there's a "sort mismatch:"
(error "line 13 column 38: operator is applied to arguments of the wrong sort")

And this is because you've the line:
(assert (! (not (not (= (+ (+ (bvneg 2) 0) 2) 3))) :named __a3))

and in particular the expression (bvneg 2). The function bvneg is bit-vector negation, but 2 is an Integer, not a bit-vector value. You want to use regular negation instead. So, change that line to:
(assert (! (not (not (= (+ (+ (- 0 2) 0) 2) 3))) :named __a3))

With that change, z3 says:
unsat
(__a3)
(error "line 16 column 10: model is not available")

Great; so now you have unsat, and the unsat-core is __a3. The error in the last line can be ignored, it arises because you called get-model but the problem is unsatisfiable, and thus there is no model to display.
Now, you might wonder why this is unsat, perhaps you expected it to be satisfiable? You haven't told us how you converted your C function to SMTLib, and it appears that you used some unnamed tool to do so, perhaps one of your own creation. The tool clearly has a bug in it, as it created the bvneg expression that we fixed above, maybe it's not to be trusted as much! But let's see why z3 thinks this problem is unsat.
It boils down to these two lines that your tool generated:
(assert (! (not (= sv_1 0)) :named __a0))
(assert (! (not (not (= sv_1 0))) :named __a2))

Let's simplify these by dropping the annotations, and for clarity I'll rename sv_1 to a, since that seems to be the origin of the variable. This gives us:
(assert (not (= a 0)))
(assert (not (not (= a 0))))

Let's simplify a bit:
(assert (distinct a 0))
(assert (not (distinct a 0)))

(In SMTLib, (distinct x y) means (not (= x y)).)
And now we see the problem; you have two assertions the first one says a is not 0, and the second says it's not the case that a is not 0. Clearly, these two assertions conflict each other, and this is why z3 tells you unsat.
There's actually another source of conflict as well. The other assertion simplifies to:
(assert (not (not (= (+ (+ (- 0 2) 0) 2) 3)

which, if you do the arithmetic, says:
(assert (= 0 3))

which is clearly not true. (And this is why z3 tells you your unsat core is __a3; which is the root-cause of why the whole set of assumptions is unsatisfiable. Note that unsat-cores are not unique, and z3 does not guarantee it'll give you a minimal set. So it could've told you (__a0 __a2) as well as the unsat-core; but that's a separate discussion.)
So, z3 is doing the right thing given your generated SMTLib (after the correction mentioned above.)
Why your tool generates this SMTLib for the C-program is something we cannot help you with unless you tell us more about how you generated that output, or what this intermediate tool actually does. My rough guess is that it's actually generating a bunch of test cases, and eventually it comes to a point where it says "I don't have any more test cases to generate" so everything is actually fine; but there seems to be some issue with why it would generate the (get-model) call; or why it would do the bvneg call which is incorrect. But otherwise, you'll have to consult with the developers of the tool that generates this SMTLib for you for further debugging.


XML Data Binding in Java MicroEdition

Question: I have a J2ME Application in which i need to bind my XML response in J2ME.Will you please help me in this case?How to bind XML Data Binding in J2ME?
Comment: Is that XML the response returned by a SOAP WS?
Comment: No,its response obtained by Http Get/Post method.
Comment: Are you talking about using this:  import org.xmlpull.v1.XmlPullParser
Answer: It seems that what you want is to unmarshall an XML file to a Java class. If so, I have shared a generic way at my blog. It uses two classes to implement it. The code of the first class is:
public class XMLTag {
  // if you do not have enough memory, use lazy
  // instantiation on these attributes
  private Hashtable attributes = new Hashtable();
  private Vector childs = new Vector();

  public void setAttributeValue(String attribute, String value) {
    if (attribute != null && value != null) {
      attributes.put(attribute, value);
    }
  }

  public String getAttributeValue (String attribute) {
    return (String) attributes.get(attribute);
  }

  public void addChild (XMLTag child) {
    childs.addElement(child);
  }

  public Enumeration getChilds () {
    return childs.elements();
  }

  public XMLTag getChildAt (int index) {
    return (XMLTag) childs.elementAt(index);
  }
}

Below is the source code of the second class:
class XMLBinder extends org.xml.sax.helpers.DefaultHandler {

  private Hashtable map = new Hashtable();
  private Stack stack = new Stack();
  private XMLTag rootElement;

  private String attribute;
  private StringBuffer value = new StringBuffer();

  /**
   * @param map with String keys and XMLTag values
   */
  public XMLBinder(Hashtable map) {
    Enumeration e = map.keys();
    while (e.hasMoreElements()) {
      Object key = e.nextElement();
      Object tag = map.get(key);
      if (validateMapping(key, tag)) {
        this.map.put(key, tag);
      } else {
        throw new IllegalArgumentException("key " + key);
      }
    }
  }

  private boolean validateMapping (Object key, Object tag) {
    return key instanceof String
           && tag instanceof Class
           && XMLTag.class.isAssignableFrom((Class) tag);
  }

  public XMLTag unmarshall (InputStream in) throws IOException {
    try {
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
      parser.parse(in, this);
      return rootElement;
    } catch (Exception ex) {
      throw new IOException("caused by " + ex);
    }
  }

  public void startElement(String uri, String localName, String qName,
      Attributes attributes) throws SAXException {
    Class tag = (Class) map.get(qName);
    if (tag != null) {
      try {
        XMLTag newTag = (XMLTag) tag.newInstance();
        addAttributesToXMLTag(attributes, newTag);
        stack.push(newTag);
      } catch (Exception e) {
        throw new SAXException("caused by " + e);
      }
    } else {
      attribute = qName;
    }
  }

  private void addAttributesToXMLTag (Attributes attributes, XMLTag newTag) {
    if (attributes != null) {
      for (int i = attributes.getLength() - 1; i >= 0; i--) {
        String attrName = attributes.getQName(i);
        String attrValue = attributes.getValue(i);
        newTag.setAttributeValue(attrName, attrValue);
      }
    }
  }

  public void characters(char[] ch, int start, int length) {
    if (attribute != null) {
      value.append(ch, start, length);
    }
  }

  public void endElement(String uri, String localName, String qName)
      throws SAXException {
    if (stack.isEmpty()) {
      throw new SAXException("no mapping for " + qName);
    }
    if (attribute != null && attribute.equals(qName)) {
      XMLTag parent = (XMLTag) stack.peek();
      parent.setAttributeValue(attribute, value.toString());
      attribute = null;
      value.setLength(0);
    } else {
      XMLTag child = (XMLTag) stack.pop();
      if (stack.isEmpty() == false) {
        XMLTag parent = (XMLTag) stack.peek();
        parent.addChild(child);
      } else {
        rootElement = (XMLTag) child;
      }
    }
  }
}

To prevent the use of Class.forName we use a map with tags and classes. The key is a String with the tag name and the value is a Class that extends XMLTag. For example, reading an RSS feed would use below classes:
class RSS extends XMLTag {
  Channel channel;
  public void addChild(XMLTag child) {
    if (child instanceof Channel) {
      channel = (Channel) child;
    }
  }
}
class Channel extends XMLTag {
  public void addChild(XMLTag child) {
    if (child instanceof Item) {
      super.addChild(child);
    }
  }
}
class Item extends XMLTag {
}

And the following map:
Hashtable map = new Hashtable();
map.put("rss", RSS.class);
map.put("channel", Channel.class);
map.put("item", Item.class);

The binder can then be used:
XMLBinder binder = new XMLBinder(map);
rss = (RSS) binder.unmarshall(in);

Update after comments
For your xml sample you need to create the following classes:
class DataTable extends XMLTag {
  XsSchema xsSchema;
  DiffgrDiffgram diffgrDiffgram;
  public void addChild(XMLTag child) {
    if (child instanceof XsSchema) {
      xsSchema = (XsSchema) child;
    }
    else if (child instanceof DiffgrDiffgram) {
      diffgrDiffgram = (DiffgrDiffgram) child;
    }
  }
}
class XsSchema extends XMLTag {
}
class DiffgrDiffgram extends XMLTag {
}

and use the following map
Hashtable map = new Hashtable();
map.put("DataTable", DataTable.class);
map.put("xs:schema", XsSchema.class);
map.put("diffgr:diffgram", DiffgrDiffgram.class);

Comment: Thanx.But will you please tell me one thing;Actually i have a procedure in .Net Webservice in which i have different operators and now i am using that procedure in my J2me Application via Http GET/POST.Problem is that the response i am getting is multiple nodes XML.I have use XMLParser for rest of the responses but in this it is not applicable because it contains multiple nodes as there are so many operators.So what am i supposed to do?Do what you have suggested before or something else?Please tell me.Hope u got my point.
Comment: If you required then i will send you the response String?Let me know.
Comment: Sorry, but I did not get your point. Please, update your question with this String.
Comment:
Comment:
Comment:
Comment:

1
AIRCEL
Comment:
2
AIRTEL

"
Comment: this is what i obtain in my String(StrResponse) through Http GET/POST in j2me application.Now i have to parse this XML.i have used XML Parser for other responses but what should i do in this case as this XML format contains multiple Nodes?
Comment: Your XML contains one root tag DataTable and two childs: xs:schema and diffgr:diffgram. You can create one class for each one of them.
Comment: Ok.Will you please elaborate what you haveanswered?Can you give any example?
Answer: JiBX seems to support J2ME. See the following related JIRA issue: [#JIBX-110] Having a J2ME compatible official jibx release.
Once downloaded, you'll have to ant-build the j2me jars using the j2me target (ant j2me from the build directory where build.xml is sitting). You can just build it with a standard javac, no need for a specialized compiler (see this discussion in the JiBX users list).

XML Data Binding in Java MicroEdition


What's the appropriate cable type along exposed rafters?

Question: This is a followup to my previous, more general question.
I installed (exposed) 2"x4" studs at strategic locations. These provide a mounting point for metal boxes, and EMT carries the wire up from the crawlspace, through the metal boxes, and up to ceiling height.
Example: (click for full-size)

I want to wire light fixtures in the ceilings. Bending EMT between fixtures' boxes is one option, but because of the unusual shape of the ceiling, I think I'd rather use something flexible. I believe the options are:

NM cable (aka Romex).
AC cable (aka BX).
MC cable.

I think NM is prohibited by code because the rafters are exposed - the cable needs to be protected, right?
Which is the right choice?
Answer: Jay, I think you can use NM for this application as long as you do not cross beam. Cross beam refers to bridging between collar ties or floor joists across the bottom of said members, as opposed to drilling mid member and lacing the cable through the holes or following parameter beams and extending inward for each fixture along sides of 2X4's
My first choice would be BX or greenfield plastic coated flex raceway. EMT would be great, but maybe a little impracticable for your application.


How to fix problems with ejecting USB after running Steam

Question: Steam runs great from my USB (no lag, relatively short load time, sometimes even remembers my account so I don't have to put in the security code). However, after every time I play (CS:GO, btw), I try to eject the USB but it tells me that it is still in use. Even after closing all tabs and all programs it tells me this.
I thought I found a quick fix by pressing "Exit Steam" in the same location where you can eject USBs, but this only worked a couple times. After that, when I exited Steam I was still unable to eject. How can I consistently eject my USB to prevent any problems to my computer or my flash drive?
Comment: I wonder if a background process is hiding and still running, causing the USB to say it is still in use.  Have you looked through your process list to see if any Steam ones were running still?
Answer: Steam is most likely still running in the background. If any games are downloading stop or pause them. Then, try to exit steam. If you still cannot eject your flash drive, open task manager and abort any steam processes happening in the background. That should fix any issues you have with ejecting your drive.


How do I build an existing CDK module in a new code pipeline stage?

Question: I have an old CDK module that I would like to build with a new module using an AWS code pipeline. So far I've followed this workshop and ended up with a working code pipeline that fetches the source code from CodeCommit, builds the project, and updates the pipeline. The next stage I would like in the pipeline is one where the old CDK module is built, and this is where finding examples that use CDK 2 is proving to be difficult
In addition to the workshop I've found examples like this video, and this video.
These are the files I'm working with:
cdk-codepipeline:
#!/usr/bin/env node
import 'source-map-support/register'
import * as cdk from 'aws-cdk-lib'
import { PipelineStack } from '../lib/pipeline-stack'

const app = new cdk.App();
new PipelineStack(app, 'PipelineStack');

pipeline-stack.ts:
import { Stack, StackProps } from 'aws-cdk-lib'
import { Construct } from 'constructs'
import {IRepository, Repository} from "aws-cdk-lib/aws-codecommit";
import {CodeBuildStep, CodePipeline, CodePipelineSource} from "aws-cdk-lib/pipelines";
import {exec} from "child_process";
import {BuildArtifactsStage} from "./stages/build-artifacts-stage";

export class PipelineStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const self = this
    const branchName: string = 'my-branch-name'

      const repository: IRepository = Repository.fromRepositoryName(self, 'SourceCode','my-repo-name')

      const pipeline = new CodePipeline(self, 'Pipeline', {
        pipelineName: `my-repo-name-${branchName}`,
        crossAccountKeys: false,
        selfMutation: true,
        synth: new CodeBuildStep('Synth', {
          input: CodePipelineSource.codeCommit(repository, branchName),
          installCommands: ['npm install -g aws-cdk'],
          commands: ['cd cdk-codepipeline','npm ci', 'npm run build', 'npx cdk synth', 'cd ..'],
          primaryOutputDirectory: 'cdk-codepipeline/cdk.out',
        }),
      })

      const buildArtifactsStage = pipeline.addStage(new BuildArtifactsStage(self, 'BuildArtifacts'))

  }
}

build-artifacts-stage.ts:
import {Stage, StageProps} from "aws-cdk-lib"
import {Construct} from "constructs"
import {BuildArtifactsStack} from "./build-artifacts-stack";

export class BuildArtifactsStage extends Stage {
    constructor(scope: Construct, id: string, props?: StageProps) {
        super(scope, id, props);

        const buildArtifactsStack = new BuildArtifactsStack(this, 'BuildArtifactsStack')
    }
}

Below in the commands: is the logic I would like to be executed in the fourth Stage of my code pipeline.
build-artifacts-stack.ts:
import {Stack, StackProps} from "aws-cdk-lib";
import {Construct} from "constructs";
import {CodeBuildStep} from "aws-cdk-lib/pipelines";

export class BuildArtifactsStack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props);

        new CodeBuildStep('BuildOldCdkModule', {
            commands: ['cd ../old-cdk-module', 'npm ci', 'npm run build'],
        })
    }
}

Comment: You don't need examples, just check the docs. You can add steps before or after the stacks deployment with this: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.pipelines.StageDeployment.html#addwbrpoststeps
Answer: We are exploring very similar use cases. I am no cdk expert, but hopefully this can be useful.
The example in the workshop seems to have just one cdk project that is changed from deploying the app directly (old version) to deploying the pipeline which deploys the application (same cdk app, just new version):

Next, since the purpose of our pipeline is to deploy our application stack, we no longer want the main CDK application to deploy our original app. Instead, we can change the entry point to deploy our pipeline, which will in turn deploy the application.
To do this, edit the code in bin/cdk-workshop.ts

I stumbled upon the following example which seems to be more in line with what you are doing, since it has the codepipeline in a separate cdk app. Hopefully it can give you some pointers. However, note that the example is cdk1:
https://medium.com/andy-le/building-a-dynamic-aws-pipeline-with-cdk-5d5426fc0493


LINQ many-to-many relationship, how to write a correct WHERE clause?

Question: I use many-to-many relationship for my tables.
There is a query:
var query = from post in context.Posts
        from tag in post.Tags where tag.TagId == 10
        select post;

Ok, it works fine. I get posts having the tag specified by id.
I have a collection of tag ids. And i want to get posts having every tag in my collection.
I try the following way:
var tagIds = new int[]{1, 3, 7, 23, 56};

var query = from post in context.Posts
        from tag in post.Tags where tagIds.Contains( tag.TagId )
        select post;

It doesn't work. The query returns all posts having ANY one of the specified tags.
I want to get a clause like this but dynamicaly for any count of tags in the collection:
post.Tags.Whare(x => x.TagId = 1 && x.TagId = 3 && x.TagId = 7 && ... )

Comment: possible duplicate of [How do I retrieve items that are tagged with all the supplied tags in linq?](http://stackoverflow.com/questions/3478874/how-do-i-retrieve-items-that-are-tagged-with-all-the-supplied-tags-in-linq)
Answer: You shouldn't project each post's tags in the outer query; rather, you need to use an inner query which performs the check for the outer filter. (In SQL, we used to call it a correlated subquery.)
var query =
    from post in context.Posts
    where post.Tags.All(tag => tagIds.Contains(tag.TagId))
    select post;

Alternate syntax:
var query =
    context.Posts.Where(post =>
        post.Tags.All(tag =>
            tagIds.Contains(tag.TagId)));

Edit: Correcting per Slauma's clarification. The version below returns posts which contain, at least, all the tags in the tagIds collection.
var query =
    from post in context.Posts
    where tagIds.All(requiredId => post.Tags.Any(tag => tag.TagId == requiredId))
    select post;

Alternate syntax:
var query =
    context.Posts.Where(post =>
        tagIds.All(requiredId =>
            post.Tags.Any(tag =>
                tag.TagId == requiredId)));

Edit2: Corrected above per Slauma. Also including another alternative making full use of query syntax below:
// Project posts from context for which
// no Ids from tagIds are not matched
// by any tags from post
var query =
    from post in context.Posts
    where
    (
        // Project Ids from tagIds that are
        // not matched by any tags from post
        from requiredId in tagIds
        where
        (
            // Project tags from post that match requiredId
            from tag in post.Tags
            where tag.TagId == requiredId
            select tag
        ).Any() == false
        select requiredId
    ).Any() == false
    select post;

I've used .Any() == false to simulate the NOT EXISTS operator in Transact-SQL.
Comment: +1 for being the only one who matches on only **ALL** tagIds, not just **ANY**
Comment: That is true, I just assumed that you knew something I did not.  Even so, mattytommo is still incorrect, as your original idea (if it had worked) would not have resulted in only the posts with ALL tags being returned.  +1 since your updated answer has the longer linq I prefer and the alternate and is well written.
Comment: Well, you can't really say whether he was correct or not, since it would have depended on whether the hypothetical `Contains(IEnumerable)` was logically equivalent to an `Any` or an `All`. I'd assumed it would be equivalent to an `All` (as in "contains subset").
Comment: Ah, with `Any` it even looks better! The last code snippet looks strange. For me it's a good example that extension method syntax is easier to read as soon as queries become more complex. I would clearly prefer the version with the "indentation cascade" (but indent differently) :)
Comment: @mattytommo Are you sure about that?  It looks to me like he is getting all posts.  Edit: He just added the post.Tags.All block which should do the trick, but Tejs had that first.
Comment: @Trisped, no he's matching **ALL** id's in the tagIds list, not just **ANY**
Comment: Actually, I'd originally assumed a non-existent overload of `Contains`; the code wouldn't have compiled.
Comment: OK, I agree, now seeing it, it's also pretty easy :) (I honestly thought @scottm's solution would be the only way). If you replace now `post.Tags` by `post.Tags.Select(t => t.TagId)` then it even compiles. Nonetheless +1!
Comment: @Slauma: Thanks for pointing that out. My fault for not testing before submitting. All code samples should at least compile now.
Comment: @Slauma: Yes, I agree that the purely query syntax one looks convoluted, although it's close to what one would traditionally have had to write in SQL. It might be possible to make it look better using joins…
Answer: This is actually pretty easy to do:
var tags = context.Posts.Where(post => post.Tags.All(tag => tagIds.Contains(tag)));

Comment: He wants matching **ALL**, not just the 1
Comment: Updated then simply using the `All` extension.
Comment: This would return posts where *all* tags occur in the tagIds list. For example: tagIds = ("C#","Java") and a post which has only the tag "C#". Your query would return this post. But he wants: "to get posts having **every tag** in my collection". I.e.: Only the posts which are tagged with "C#" **and** "Java". Perhaps, not that pretty easy to do? :)
Comment: @Slauma: It's the same level of difficulty (or "pretty easiness") – you just need to swap the collections on which the `All` and `Contains` calls are made. I've left [both versions](http://stackoverflow.com/a/10505638/1149773) for comparison.
Answer: Another option is to intersect the two lists if you want the collection of tags to ONLY contain the set you specify and no others:
var query = from post in context.Posts
  let tags = post.Tags.Select(x => x.Id).ToList()
  where tags.Intersect(tagIds).Count() == tags.Length
  select post;

Comment: Wouldn't you want `tags.Intersect(tagIds).Count() == tagIds.Length` ?
Comment: I wouldn't be sure that the `ToList()` inside of `let` works with LINQ to Entities. (I'd expect "cannot translate into store expression" exception, also `tags` wouldn't be an `IQueryable` anymore.) In my opinion without the `ToList()` it was fine.
Answer: Try it with Any.
var query = from post in context.Posts
    from tag in post.Tags where tagIds.Any(t => t == tag.TagId )
    select post;

Comment: He wants matching **ALL**, not just the 1


Configuring GPG in Kmail

Question: Having done a fresh install I need to set this up again. We could do with an up to date guide. This might encourage more people to use encryption and signing.
I already have a keyring, but others need to know how to do that. That should probably be a separate question. I use KGPG to manage my keys.
In Kmail I know you need to set the default signing and encryption keys on your Identity.
When I try to sign an email it complains that signing failed without asking for my pass-phrase. What am I missing? How should I configure cryptography in Kmail?
Comment: What is the exact error when it fails?
Comment: Signing failed: Bad passphrase
Comment: Do you have pinentry (`pinentry-qt4`) installed? If so, by any chance does the password dialog pop up for a moment and immediately close itself once it gains focus?
Comment: did anyone happen to solve this? I have exactly the very same issue...
Answer: You need to put
<code>use-agent
</code>
in your ~/.gnupg/gpg.conf
I know because Seahorse used to put a blank file there and break things for people using GNOME & KDE together.  I wrote the patch that made it properly copy the skeleton file, but that wasn't until 2009.
Comment: I've done that and gpg-agent is installed. How do I make sure it is running?
Comment: ps -ef | grep agent
Comment: It's running. And I had pinentry-qt4 already.
Comment: Maybe I just needed another restart, but it's working now. Pinentry is popping up for my passphrase

Configuring GPG in Kmail


Initialization of Json Array values to existing ajax function on document ready

Question: I have an working ajax function passing values from an array. The thing is, as i will have loads of translations, i want to create a json file with all the translations and then turn it accessible to my main ajax function. The thing is, my values are not loading on document ready, just when i change the language.
My function i18n it´s not loading o document ready and it gives me an error "Uncaught TypeError: Cannot read property 'en' of undefined". I tried to execute my updateForecast function inside of i18n one, it loads the values on document ready but then i´m in loop.
What i´m doing wrong? For a quick reference, you can see the working example here - https://dl.dropboxusercontent.com/u/23044665/test/index.html
<code> $(function(){

        //
        // Translations
        //
        var trans;
        function i18n (key, value) {

                    $.getJSON("translations.json", function(json){
               trans = json[0];
            });

            if ( trans != 'undefined' && trans[language] != 'undefined' && trans[language][key] != 'undefined') {
                return  trans[language][key]
            }

            return value;
        }

            function updateForecast() {

            var forecast = "http://api.openweathermap.org/data/2.5/forecast/daily?id=" + city_id + "&units=" + units + "&cnt="+ (parseInt(forecast_days)+1) +"&lang=en";

            // Define Ajax Call
            $.ajax({
                url: forecast,
                async: true,
                dataType: 'json',
                success: function(data) {

                     // Execute Translation function
                i18n();

                    var firstItem = data.list[0];
                    var secondItem = data.list[0].weather[0];

                alert(trans[language].weather[secondItem.id]);

               },
               error: function( data ) {
                 alert( "ERROR:");
               }
            });

        }

        updateForecast(); // for init update!

    });
</code>
Comment: you really need to do a far better job of explaining with more precision and some code what your issue is
Comment: You´re right, sorry!! I´ve updated my post with a more detailed explanation of my problem!!! :)
Answer: Ok, i solved the problem. Instead of using this getJSON inside of my i18n function
<code>    $.getJSON(url, function(json){
       trans = json[0];
    });
</code>
I used an ajax call like this one with the parameter async:false.
<code>    $.ajax({
        url:url,
        async: false,
        dataType: 'json',
        success: function(json) {
            trans = json[0];
        }
    });
</code>
And voilá, my json data was loaded on document ready and treated by my main function updateForecast.
And again thanks a lot to who tried to help me.
Answer: collect all the data in JS Array(needs well categorized data ), then use  'JSON.Stringify' to get data in JSON format ., now you can pass the data through the AJAX call/post
Comment: if you want to load data dynamically just go ahead and try with jquery as follows: $(document).on('someSelector', 'someEvent', 'someData');
Comment: I want to make all data accessible. If you click on my link, on document ready, you´ll see a console error saying "Uncaught TypeError: Cannot read property 'en' of undefined.". Then, if you select language on select box all my data loads as expected, and no console error anymore! Why? By the way thanks for your comment!
Comment: i don't get why someone gave a -ve flag on my answer... my answer was just an idea to use JSON.Stringify
Comment: Wasn´t me! By the way, your comment was really construtive you shown me something that i never heard!! :)
Comment: @Legues ... i didn't mean its you... don't be offended.. and i am using it in my project... i know you might not heard about it but i figured it out as i work closely with JS and knockoutJS


What Are The Default Values of `glReadBuffer/glDrawBuffer(s)` for an FBO?

Question: glReadBuffer(...)/glDrawBuffer(...)/glDrawBuffers(...) access part of a framebuffer's state.
For reading the default framebuffer, this is GL_FRONT or GL_BACK.  However, the documentation doesn't say what it is for FBOs.  The only thing I found was an offhand comment here stating that the default is GL_COLOR_ATTACHMENT0 (which is what I would guess).  Can I rely on that?
For writing, I didn't immediately find any claims what what color buffers are enabled.
Answer: You can usually track down the answer for such questions in the OpenGL specification.  Assuming the value you care about is consistent across OpenGL versions (often the case for initial values, seldom the case for minimum values).
In this case, in the GL 4.5 specification, check out the following:

glReadBuffer(...) initial value: (default framebuffer: GL_FRONT iff single-buffered, GL_BACK iff double-buffered) (FBO: GL_COLOR_ATTACHMENT0) (see page 506)
glDrawBuffer(...) initial value: (see glDrawBuffers(...))
glDrawBuffers(...) initial value: (default framebuffer: fragment color 0 goes to GL_FRONT iff single-buffered, GL_BACK iff double-buffered) (FBO: fragment color 0 goes to GL_COLOR_ATTACHMENT0) (both: fragment colors other than 0 go to GL_NONE) (see page 497)


let users switch between different fonts in an android app

Question: I was looking for a complete answer over 2 days searching here and there but no chance.
I'm new in android by the way .
I want 3 different fonts in my app which will be in Settings activity and there will be three buttons or radio buttons for each font so that users can choose the font they like and after tapping the save button the font of all activities will change.
Here is what I know:
place fon.ttf in fonts folder in assets
I know how to set a font to a textView using typeface.
I see the answer provided here Android: Want to set custom fonts for whole application not runtime
but nothing teaches me what I need learn.
please give me a code if it is possible
or tel me what should I do
thanks
Answer: In your settings activity, when the user selects a font size, save it to preferences as an integer
Then, in your activity where you need the font size, grab the value from prefs, and set the text size accordingly.
Here's an example
MainActivity.java
public class MainActivity extends Activity {
    public int fontSize = 0;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        //grab all textViews
        TextView tv = (TextView) findViewById(R.id.your_text_view_id);

        SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(MainActivity.this);

        fontSize = prefs.getInt("pref_fontSize", 12);

        tv.setTextSize(fontSize);

    }

}

If you need further assistance, post your Settings code, and your Activity code
Answer: Put your different fonts in asset folder.
Now when you want to change your font in app, select the desired font from asset. Make sure fonts are in ttf format. Here is a example -
public void setFont(String FONTNAME) { //Just the font name. Don't add ttf at end

    Typeface tf = Typeface.createFromAsset(getAssets(),FONTNAME + ".ttf");
    //Select font from asset folder
    //Make sure that the font with that name exists in asset folder

    textview.setTypeface(tf);
    //Set it to textview or any text field
    //Do it muliple times if you have many textfields

    //Also create different methods in other activities to set the font to them
    //and then call then from here

}

If you want to display the same font to the user everytime they open the app, use shared preference to save the font name. Then in onCreate method, check if the font exists through shared preferance and if it does, then call the above method to set it.
Comment: you could also try to add an id to the paramteters of this function, pass it the font and the id of the view, put it in a utility class and use it all over the app


doesn't support architecture 'arm64, doesn't support architecture 'armhf'

Question: When I try to update, I am having this issue:
$ sudo apt-get update
Hit:2 http://ports.ubuntu.com xenial InRelease
Hit:3 http://ports.ubuntu.com xenial-security InRelease
Ign:1 http://packages.erlang-solutions.com/debian xenial InRelease
Hit:4 http://ports.ubuntu.com xenial-updates InRelease
Hit:6 http://ports.ubuntu.com xenial-backports InRelease
Hit:5 http://packages.erlang-solutions.com/debian xenial Release
Reading package lists... Done
N: Skipping acquire of configured file 'contrib/binary-arm64/Packages' as repository 'http://binaries.erlang-solutions.com/debian xenial InRelease' doesn't support architecture 'arm64'
N: Skipping acquire of configured file 'contrib/binary-armhf/Packages' as repository 'http://binaries.erlang-solutions.com/debian xenial InRelease' doesn't support architecture 'armhf'

The output of lscpu:
ubuntu@ubuntu:~$ lscpu
Architecture:          aarch64
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    1
Core(s) per socket:    1
Socket(s):             4
CPU max MHz:           1512.0000
CPU min MHz:           100.0000
Hypervisor vendor:     (null)
Virtualization type:   full

Comment: I have added `lscpu` output. @Melebius
Answer: The packager does not publish packages for arm64 or armhf in that repository, only i386 and amd64.
If you want this software for Arm, you can either ask the vendor to compile it for arm, or if it's open source, recompile it yourself.
Comment: I am not clear your second comments, can you explore me please @vidarlo
Comment: If it's open source software you can compile it for ARM yourself. If you don't have the source code, you have to ask the vendor to do this.