text:
Q: Reference access field through index and keep the correct type I'm converting a existing code from javascript to typescript and I try to not change anything to the logic of the code to avoid regressions. I found myself in a situation where I don't exactly know what to do to make typescript understand that some things are allowed. I tried to reduce the examples to a minimum so I'm sorry if the logic is a little weird.
I have the same kind of problem in 2 places so I group them here. Here is the code and a playgound:
interface Config {
    autoStart: boolean;
    baseUrl: string;
}

let _configTrackers: Partial<{[key in keyof Config]: ((value: Config[key], previous?: Config[key]) => any)[]}> = {};
let settings: Partial<Config> = { autoStart: true };
let _configuration: Partial<Config> = { baseUrl: "/" };

function get<K extends keyof Config>(name: K): Partial<Config>[K] {
    let cb = (value: Config[K], previous?: Config[K]) => { return 1 };
    _configTrackers[name]!.push(cb /* "as any" works here but it's not really what I want */); // error on cb
    // Argument of type '(value: Config[K], previous?: Config[K]) => number' is not assignable to parameter of type '((value: boolean, previous?: boolean) => any) & ((value: string, previous?: string) => any)'.
    // Type '(value: Config[K], previous?: Config[K]) => number' is not assignable to type '(value: boolean, previous?: boolean) => any'.
    //  Types of parameters 'value' and 'value' are incompatible.
    //    Type 'boolean' is not assignable to type 'Config[K]'
    return _configuration[name];
}

function f(_configuration: Partial<Config>, settings: Partial<Config>) {
    let attr: keyof typeof settings;
    for(attr in settings) {
        let previous = _configuration[attr];
        let value = settings[attr];
        _configuration[attr] = value; // error on _configuration[attr]
        // Type 'string | boolean' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'.
        _configTrackers[attr][0](value, previous); // error on value
        // Argument of type 'string | boolean' is not assignable to parameter of type 'never'. Type 'string' is not assignable to type 'never'.
    }
}

The first one is on this line _configTrackers[name]!.push(cb), I would like typescript to understand that it is possible. I tried several types for _configTrackers but I couldn't fund any that worked.
The second one is at _configuration[attr] = value;. I guess Typescript doesn't get that previous and value have the same type ... I have a weird error about "never" that I don't really get. How could I get Typescript to this assignement?
How could I get this code to typecheck without "hacks" like as any?

A: What is causing the errors in function f is Typescript's failure to grasp that the the key which you are accessing from settings and the key which you are setting on _configuration are one and the same.
It assigns the type of both value and _configuration[attr] as string | boolean | undefined which is the union of all property values on Config with undefined included because settings uses Partial.  Even though these two variables have the same type, one is not assignable to the other because the union itself is not assignable to any individual member of the union.
We can fix the error on _configuration[attr] = value by using a generic K for the key.  This causes value and previous to have the type Partial<Config>[K].
function f(_configuration: Partial<Config>, settings: Partial<Config>) {

    function process<K extends keyof Config>(key: K) {
        let previous = _configuration[key];
        let value = settings[key];
        _configuration[key] = value; // success!
        const trackers = _configTrackers[key];
        if ( trackers ) {
            trackers[0](value, previous); // error
        }
    }

    let attr: keyof typeof settings;
    for(attr in settings) {
        process(attr);
    }
}

But we still have problems with the _configTrackers.  Callbacks are rough.  The tracker still ends up with the union of two functions.  It is impossible to call this union because your arguments would need to be assignable to both branches and that is impossible for our two value types boolean and string.
const trackers: Partial<{
    autoStart: ((value: boolean, previous?: boolean | undefined) => any)[];
    baseUrl: ((value: string, previous?: string | undefined) => any)[];
}>[K]

We lose the K when guarding against undefined and it becomes
const trackers: ((value: boolean, previous?: boolean | undefined) => any)[] | ((value: string, previous?: string | undefined) => any)[]

Unless someone has a better suggestion, I think that you will have to make an assertion.


text:
Q: How to add multiple json objects to one json object in PowerShell cls

#function to Execute a stored procedure
function ExecSproc
{
    param ($Conn, $Sproc, $Parameters=@{})

    $MethodName = "ExecSproc"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
    $SqlCmd.Connection = $Conn
    $SqlCmd.CommandText = $Sproc
    foreach($p in $Parameters.Keys){
        [Void] $SqlCmd.Parameters.AddWithValue("@$p",$Parameters[$p])
    }
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmd)
    $DataSet = New-Object System.Data.DataSet
    [Void] $SqlAdapter.Fill($DataSet)
    $SqlConnection.Close()
    return $DataSet.Tables[0]
}

function ExecuteSqlQuery ($SQLQuery, $ConnectionString)
{
    $Datatable = New-Object System.Data.DataTable

    $MethodName = "ExecuteSqlQuery"
    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Connection.ConnectionString = $ConnectionString
    $Connection.Open()
    $Command = New-Object System.Data.SQLClient.SQLCommand
    $Command.Connection = $Connection
    $Command.CommandText = $SQLQuery
    $Reader = $Command.ExecuteReader()
    $Datatable.Load($Reader)
    $Connection.Close()

    return $Datatable
}

function SFSCheck()
{
    $OptionalField1 = ""
    $OptionalField2 = ""
    $SecondaryEmail = ""
    $EvaluationGroupCode = ""
    $DefaultRubricId = ""
    $DefaultWalktoolId = ""
    $EvaluatedInSFS = $true
    $EmploymentStatus = ""
    $Cert = ""
    $PrimaryEvalutor_payrollID = ""
    $SecondaryEvaluator_payrollID = ""
    $Access = ""
    $GoogleEmail = ""

    $PrimaryEvalutor_payrollID = $ManagerEmployeeNumber
    $OptionalField1 = ($EffectiveDate -as [string]).Split(" ")[0]

    $SFS = ExecSproc -Conn $AcctProConnectionString -Sproc SchoologySFSeSchoolGet -Parameters @{JobClassCode=$JobClassCode;Location=$CheckLocation}
    if ([string]::IsNullOrEmpty($SFS))
    {
        Write-Host "No Standards for Success account needed for combination of Job Class Code and location."
    }
    else
    {
        if ($SFS[7] -eq "Y")
        {
            if ($SFS[9] -ne "N")
            {
                $Access = $SFS[9]
                $Cert = $true

                #Check the Action Code to determine the status field
                if ($ActionCode -eq "LEAV")
                {
                    $EmploymentStatus = "Inactive"
                }
                elseif ($ActionCode -eq "TERM")
                {
                    $EmploymentStatus = "Remove"
                }
                elseif($ActionCode -eq "HIRE")
                {
                    $EmploymentStatus = "Add"
                }
                else
                {
                    $EmploymentStatus = ""
                }

                if(-not([string]::IsNullOrEmpty($StateId)))
                {
                    $StateId = $StateId.Substring(4).Trim()
                }

                #$personAsJson = "{SIEN=`"$StateId`";Payroll_id=`"$EmployeeNumber`";Email=`"$EmployeeEmail`";FirstName=`"$FirstName`";LastName=`"$LastName`";Position=`"$LongDescription`";Optional_Field1=`"$OptionalField1`";Optional_Field2=`"$OptionalField2`";Location_id=`"$CheckLocation`";Primary_Evalutor_id=`"$PrimaryEvalutor_payrollID`";Secondary_Evaluator_ids=`"$SecondaryEvaluator_payrollID`";EvalGroup_id=`"$EvaluationGroupCode`";Rubric_id=`"$DefaultRubricId`";Walk_id=`"$DefaultWalktoolId`";isEvaluated=`"$EvaluatedInSFS`";Employment_Status=`"$EmploymentStatus`";isCertified=`"$Cert`";Access=`"$Access`";Google_Email=`"$GoogleEmail`"}"
                $User = New-Object Users
                $User.SIEN = $StateId
                $User.Payroll_id = $EmployeeNumber
                $User.Email = $EmployeeEmail
                $User.FirstName = $FirstName
                $User.LastName = $LastName
                $User.Position = $LongDescription
                $User.Optional_Field1 = $OptionalField1
                $User.Optional_Field2 = $OptionalField2
                $User.Location_id = $CheckLocation
                $User.Primary_Evaluator_id = $PrimaryEvalutor_payrollID
                $User.Secondary_Evaluator_ids = $SecondaryEvaluator_payrollID
                $User.EvalGroup_id = $EvaluationGroupCode
                $User.Rubric_id = $DefaultRubricId
                $User.Walk_id = $DefaultWalktoolId
                $User.is_Evaluated = $EvaluatedInSFS
                $User.Employment_Status = $EmploymentStatus
                $User.isCertified = $Cert
                $User.Access = $Access
                $User.Google_Email = $GoogleEmail

                $json.Add($User)
                #$response = Invoke-RestMethod 'http://example.com/api/SFS' -Method Put -Body $json

                #Write-Host "Adding $FirstName $LastName to Standards for Success file" -ForegroundColor Green
            }
        }
        else
        {
            Write-Host "Account does not need Standards for Success." -ForegroundColor Red
        }
    }
}

$source = @"
public class Users
{
    public string SIEN;
    public string Payroll_id;
    public string Email;
    public string FirstName;
    public string LastName;
    public string Position;
    public string Optional_Field1;
    public string Optional_Field2;
    public string Location_id;
    public string Primary_Evaluator_id;
    public string Secondary_Evaluator_ids;
    public string EvalGroup_id;
    public string Rubric_id;
    public string Walk_id;
    public bool is_Evaluated;
    public string Employment_Status;
    public bool isCertified;
    public string Access;
    public string Google_Email;
}
"@

Add-Type -TypeDefinition $source

$AcctProConnectionString = "Server='167.217.10.172';Database='AccountProvision';trusted_connection=true;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $AcctProConnectionString

$Query = "SELECT TOP 3 * FROM FacultyAduit WHERE CaptureDateTime = '2017-03-16 10:00:00.000' ORDER BY CaptureDateTime DESC"
$AuditData = New-Object System.Data.DataTable
$AuditData = ExecuteSqlQuery -SQLQuery $Query -ConnectionString $AcctProConnectionString
$json = New-Object System.Collections.Generic.List[System.Object]

foreach($row in $AuditData)
{
    $EmployeeNumber = ""
    $FirstName = ""
    $LastName = ""
    $EffectiveDate = ""
    $JobClassCode = ""
    $LongDescription = ""
    $StateId = ""
    $CheckLocation = ""
    $ManagerEmployeeNumber = ""
    $ActionCode = ""
    $EmployeeEmail = ""

    $EmployeeNumber = $Row[2]
    $FirstName = $row[3].ToLower()
    $LastName = $Row[4].Replace(" ", "").Replace("-","").Replace("'","").ToLower()
    $EffectiveDate = $row[7]
    $JobClassCode = $row[16]
    $LongDescription = $Row[18].ToLower()
    $StateId = $Row[28]
    $CheckLocation = $Row[29]
    $ManagerEmployeeNumber = $row[33]
    $ActionCode = $Row[36]
    $EmployeeEmail = $Row[37].ToLower()

    SFSCheck
    Write-Host ""
}

$json | ConvertTo-Json

I have a script that generates json user objects such as this:
{
"SIEN" : "",
"Payroll_id" : "",
"Email" : "102_teacher@sandbox.com",
"FirstName" : "102_TEACHER",
"LastName" : "SANDBOX",
"Position" : "",
"Optional_Field1" : "",
"Optional_Field2" : "",
"Location_id" : "B102",
"EvalGroup_id" : "2182",
"Rubric_id" : "2344",
"Walk_id" : "",
"Employment_Status" : "active",
"isCertified" : true,
"Google_Email" : ""
}

However I would like to generate ONE json object that includes all of the user objects that I am generating that looks like this:
{
"Users":
[
    {
        "SIEN":  "",
        "Payroll_id":  "1203",
        "Email":  "hilds@myips.org",
        "FirstName":  "shannon",
        "LastName":  "hild",
        "Position":  "media assistant",
        "Optional_Field1":  "01/09/1989",
        "Optional_Field2":  "",
        "Location_id":  "B094",
        "Primary_Evalutor_id":  "12269",
        "Secondary_Evaluator_ids":  "",
        "EvalGroup_id":  "",
        "Rubric_id":  "",
        "Walk_id":  "",
        "isEvaluated":  "True",
        "Employment_Status":  "Inactive",
        "isCertified":  "True",
        "Access":  "Staff - Certified",
        "Google_Email":  ""
    },
    {
        "SIEN":  "10804749",
        "Payroll_id":  "8895",
        "Email":  "chizerc@myips.org",
        "FirstName":  "cynthia",
        "LastName":  "chizer",
        "Position":  "special education tchr",
        "Optional_Field1":  "08/25/1999",
        "Optional_Field2":  "",
        "Location_id":  "B105",
        "Primary_Evalutor_id":  "558",
        "Secondary_Evaluator_ids":  "",
        "EvalGroup_id":  "",
        "Rubric_id":  "",
        "Walk_id":  "",
        "isEvaluated":  "True",
        "Employment_Status":  "Inactive",
        "isCertified":  "True",
        "Access":  "Staff - Certified",
        "Google_Email":  ""
    }
]
}

I am sending this one json object to an API, but am unsure how to append the users to the one object.  I've tried creating a string and adding everything to one string and converting that string to a json object, however this does not work either.  Any help is much appreciated.

A: You can do by creating an array list, converting the user from JSON to a PSCustomObject by using ConvertFrom-Json, add the user to the list and convert the list back to JSON by using ConvertTo-Json.
$users = [System.Collections.ArrayList]::new();

$userAsJson = '
{
    "SIEN" : "",
    "Payroll_id" : "",
    "Email" : "102_teacher@sandbox.com",
    "FirstName" : "102_TEACHER",
    "LastName" : "SANDBOX",
    "Position" : "",
    "Optional_Field1" : "",
    "Optional_Field2" : "",
    "Location_id" : "B102",
    "EvalGroup_id" : "2182",
    "Rubric_id" : "2344",
    "Walk_id" : "",
    "Employment_Status" : "active",
    "isCertified" : true,
    "Google_Email" : ""
}';
$user = $userAsJson | ConvertFrom-Json;
$null = $users.Add($user);
$null = $users.Add($user);

$result = @{ Users = $users};

$result | ConvertTo-Json;

This produces the following output
{
    "Users":  [
                  {
                      "SIEN":  "",
                      "Payroll_id":  "",
                      "Email":  "102_teacher@sandbox.com",
                      "FirstName":  "102_TEACHER",
                      "LastName":  "SANDBOX",
                      "Position":  "",
                      "Optional_Field1":  "",
                      "Optional_Field2":  "",
                      "Location_id":  "B102",
                      "EvalGroup_id":  "2182",
                      "Rubric_id":  "2344",
                      "Walk_id":  "",
                      "Employment_Status":  "active",
                      "isCertified":  true,
                      "Google_Email":  ""
                  },
                  {
                      "SIEN":  "",
                      "Payroll_id":  "",
                      "Email":  "102_teacher@sandbox.com",
                      "FirstName":  "102_TEACHER",
                      "LastName":  "SANDBOX",
                      "Position":  "",
                      "Optional_Field1":  "",
                      "Optional_Field2":  "",
                      "Location_id":  "B102",
                      "EvalGroup_id":  "2182",
                      "Rubric_id":  "2344",
                      "Walk_id":  "",
                      "Employment_Status":  "active",
                      "isCertified":  true,
                      "Google_Email":  ""
                  }
              ]
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read and parse a Json File in C# in unity Here is the code
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class csharpfile:MonoBehaviour{

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("file.json"))
        {
            string json = r.ReadToEnd();
            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);

        }
    }

    public class Item
    {
        public int millis;
        public string stamp;
        public DateTime datetime;
        public string light;
        public float temp;
        public float vcc;
    }
}

Now i want to parse the file content (file.json)
[
    { "millis": "1000",
      "stamp": "1273010254",
      "datetime": "2010/5/4 21:57:34",
      "light": "333",
      "temp": "78.32",
      "vcc": "3.54" },
]

how would i print content on screen after file parsing and how to write in file .do help.....

A: for printing the deserialized value:
                    string json = file.ReadToEnd();
                    List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
                    foreach (var item in items)
                    {
                        Console.WriteLine(item.millis);
                    }

for writing/serializing:
                var serObj = JsonConvert.SerializeObject(new Item
                {
                    //assign values here
                });

Or
                var stm = new MemoryStream();
                using (var sw = new StreamWriter(stm))
                {
                    var ser = new JsonSerializer();
                    ser.Serialize(sw, new Item());
                }


text:
Q: Google Api create accessible by link SpeadSheet I use script from here to create spread sheet, but it always creates as closed one. I need to create spread sheet that accessible by link, but I cannot find a way to do it.
Here what I mean:
$spreadsheet = new Google_Service_Sheets_Spreadsheet([
            'properties' => [
                'title' => $title,
            ]
        ]);

(taken from link I proposed before)
I creating new spreadsheet, and I assume that I need to do something like that
$spreadsheet = new Google_Service_Sheets_Spreadsheet([
            'properties' => [
                'title' => $title,
                'access' => 'by_link' //pseudo code
            ]
        ]);

How to do it?

A: I believe your goal is as follows.

*

*From it always creates as closed one. I need to create spread sheet that accessible by link, you want to retrieve the URL of the created Spreadsheet.

*In this case, I thought that you might want to publicly share the created Spreadsheet.

*From your script, you want to achieve your goal using googleapis with PHP.

In this case, how about the following modified script?
Modified script:
$service = new Google_Service_Sheets($client); // Please use your script here.

$spreadsheet = new Google_Service_Sheets_Spreadsheet([
    'properties' => [
        'title' => $title,
    ]
]);
$spreadsheet = $service->spreadsheets->create($spreadsheet, ['fields' => 'spreadsheetId']);

// Here, you can see the URL of the created Spreadsheet.
$url = "https://docs.google.com/spreadsheets/d/" . $spreadsheet->spreadsheetId . "/edit";
printf("URL: %s\n", $url);

// Below script publicly shares the created Spreadsheet.
$drive = new Google_Service_Drive($client);
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');  // or writer
$drive->permissions->create($spreadsheet->spreadsheetId, $newPermission);

*

*If you don't want to publicly share the created Spreadsheet, please remove the above script below $drive = new Google_Service_Drive($client);.

References:

*

*Method: spreadsheets.create

*Permissions: create


text:
Q: DropDown Buttons in a side menu items I've made a side menu with items but what I need now is to add another sub menu for each item.
What should I do to accomplish that?
class CustomListTitle extends StatelessWidget{
    //....
    Row(
      children: <Widget>[
      Icon(icon),
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text(text, style: TextStyle(
          fontSize: 16.0
        ),),
      ),
      ],
     ),
    Icon(Icons.arrow_right)
    //....
}

A: I am not exactly sure what you want, but If what you want is basically this:

except inside of you're side menu, then I suggest that you check out ExpansionPanels


text:
Q: Convert Word Art to Text (MS OFFICE WORD) Is there any way to convert Word Art to text in Microsoft office, the same way you can convert text to WordArt?

A: Converting text to WordArt actually inserts the current text in a floating text box with some fancy styles. The inverse conversion is not unambiguous, though, as the text in the floating blocks will lose the absolute positioning info for the floating blocks - e.g. the text is docked 100 px below a specified paragraph, so it appears as part of the next paragraph (actually floating in the middle of the next paragraph flow).
You can however run a macro that will convert all such blocks to text and see if the result would work for you, for example like in the Removing All Text Boxes In a Document article:
Sub RemoveTextBox2()
    Dim shp As Shape
    Dim oRngAnchor As Range
    Dim sString As String

    For Each shp In ActiveDocument.Shapes
        If shp.Type = msoTextBox Then
            ' copy text to string, without last paragraph mark
            sString = Left(shp.TextFrame.TextRange.Text, _
              shp.TextFrame.TextRange.Characters.Count - 1)
            If Len(sString) > 0 Then
                ' set the range to insert the text
                Set oRngAnchor = shp.Anchor.Paragraphs(1).Range
                ' insert the textbox text before the range object
                oRngAnchor.InsertBefore _
                  "Textbox start << " & sString & " >> Textbox end"
            End If
            shp.delete
        End If
    Next shp
End Sub

This basically iterates over all text boxes, gets their text, insert it in the document, and then removes the text boxes.


text:
Q: Django formset factory getting error object has no attribute save Info: I want to upload multiple files while creating new customer. I want to use formset_factory for file update. when i try to submit the form i am getting this error CustomerFileFormFormSet object has no attribute save. can anybody tell me how tell me how can i update multiple files while adding new customer in database?
models.py
class FileData(models.Model):
    """Files Model"""

    customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True)
    title = models.CharField(max_length=100)
    file = models.FileField(upload_to='data', blank=True)

    def __str__(self):
        return self.title

views.py
def CustomerCreate(request):
    """Customer Create View"""

    customer_form = CustomerForm()
    customer_file = formset_factory(CustomerFileForm, extra=1)

    if request.method == 'POST':
        customer_form = CustomerForm(request.POST)
        formset = customer_file(request.POST, request.FILES)

        if customer_form.is_valid() and formset.is_valid():

            customer = customer_form.save(commit=False)
            customer.dealer = request.user
            customer.save()

            file = formset.save(commit=False)
            file.customer = customer
            file.save()

            return redirect('/')

    context = {
        'customer_form': customer_form,
        'formset': customer_file,
    }
    return render(request, "customer/customer-create.html", context)

A: This is the code which is work for me maybe it's good or not but it's working  to save the formset_factory instance. i can use forloop for each formset and save...!
views.py

if customer_form.is_valid() and formset.is_valid():

    customer = customer_form.save(commit=False)
    customer.dealer = request.user
    customer.save()

    for form in formset:
        # extract name from each form and save
        title = form.cleaned_data.get('title')
        docs = form.cleaned_data['doc']
        file_data = FileData(title=title, doc=docs, customer=customer)
        # save file data instance
        file_data.save()


text:
Q: Using the MS Access COUNT DISTINCT function The following query returns the count of requests where AcquisitionDate is within 60 days of RequestDate, along with various other columns.
How can I modify the code to count the number of unique AcquisitionDates within 60 days of RequestDate? I tried to use COUNT DISTINCT but couldn't figure out how it should be used in this case.
SELECT SceneTable.PATH, SceneTable.ROW, SceneTable.ROW, SceneTable.UlLat,
       SceneTable.UlLon, SceneTable.UrLat, SceneTable.UrLon, SceneTable.LlLat,
       SceneTable.LlLon, SceneTable.LrLat, SceneTable.LrLon,
      Sum(Iif((DateDiff("d",[AcquisitionDate],[RequestDate])<60),1,0)) AS Expr1,
       Count(RequestTable.RequestID) AS CountOfRequestID
FROM ((SceneTable INNER JOIN
       SceneAcquisitionTable
           ON SceneTable.SceneID = SceneAcquisitionTable.SceneID) INNER JOIN
       UserSceneAcquisitionTable
           ON SceneAcquisitionTable.SceneAcquisitionID =
              UserSceneAcquisitionTable.SceneAcquisitionID) INNER JOIN
       RequestTable
           ON UserSceneAcquisitionTable.UserSceneAcquisitionID =
              RequestTable.UserSceneAcquisitionID
GROUP BY SceneTable.PATH, SceneTable.ROW, SceneTable.UlLat, SceneTable.UlLon,
         SceneTable.UrLat, SceneTable.UrLon, SceneTable.LlLat, SceneTable.LlLon,
         SceneTable.LrLat, SceneTable.LrLon

Here are sample tables as well as expected results:

A: See this solution about a generic way to implement COUNT DISTINCT in Access


text:
Q: Spring WebClient Configuration Okta OAuth2 I'm building an API Gateway which uses Spring Webflux, Spring Cloud Gateway, Spring Cloud Security & Okta for OAuth2.
Here's my RouteLocator, through which I can call my Foo Microservice.
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder, TokenRelayGatewayFilterFactory filterFactory) {
    return builder.routes()
            .route("foo", r ->
                    r.path("/foo")
                            .filters(f -> f
                                    .rewritePath("/foo", "/api/v1/foo")
                                    .filter(filterFactory.apply()))
                            .uri("lb://foo-service")
            )
            .build();
}

This works perfectly fine.
However, since I need to aggregate the results of different microservices, let's say Foo and Bar, I'm creating a load balanced Spring WebClient bean that I can use to make http calls:
@Bean
@LoadBalanced
public WebClient.Builder webClientBuilder() {
    return WebClient.builder();
}

How can I configure the WebClient to pass the Token on every request the same way as the TokenRelayGatewayFilterFactory does in the RouteLocator?
EDIT:
Here's my updated WebClient bean:
@Bean
@LoadBalanced
public WebClient.Builder webClientBuilder(ReactiveClientRegistrationRepository clientRegistrations,
                                          ServerOAuth2AuthorizedClientRepository authorizedClients) {
    var oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
    oauth.setDefaultOAuth2AuthorizedClient(true);
    oauth.setDefaultClientRegistrationId("okta");
    return WebClient
            .builder()
            .filter(oauth);
}

Now it seems like it is working on the Chrome browser. After logging in on Okta I can access /foo on Foo microservice through Http GET. Although when I try an Http POST on /foo through Postman, (while adding the Authorization header), I'm getting a 302 response that redirects me to an Okta html page.
Funnily enough, using the RouteLocator I don't get any redirection and both GET and POST work through Postman. The redirection seems to be happening only when using WebClient.
Any idea why?
EDIT #2:
My Security config file:
@Configuration
@EnableWebFluxSecurity
class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
                .csrf().disable()
                .authorizeExchange().anyExchange().authenticated()
                .and()
                .oauth2Login()
                .and()
                .oauth2ResourceServer().jwt()
                .and()
                .and().build();
    }

    @Bean
    CorsWebFilter corsWebFilter(){
        CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setAllowedOrigins(List.of("*"));
        corsConfig.setMaxAge(3600L);
        corsConfig.addAllowedMethod("*");
        corsConfig.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);

        return new CorsWebFilter(source);
    }
}

A: Take a look at ServletOAuth2AuthorizedClientExchangeFilterFunction (or the reactive equivalent)
This video covers it in more detail: https://youtu.be/v2J32nd0g24?t=2168


text:
Q: Writing a Path Coverage Tool Currently, one of our production systems is handled by over 3000 programs written between 1986 and now . The code base is written in a non-standard language, which unfortunately lacks modern testing tools.
In a bid to improve our code quality moving forward I have been working to incorporate processes and build tools that will improve development and testing. I have just completely a line coverage tool so that we can help identify dead code + untested code during development.
Now, I would like to start work on adding Path Coverage to the tool.
How should I go about this?
Given that:
1) The line coverage tool acts as a pre-processor that injects code
2) I already have the ability to gather stats I set in said code.
What data should I be recording as the program executes, and how do I interpret it?
How can I represent the results via HTML?
I have already read the question How to get started "writing" a code coverage tool?, which was about Java, however it didn't help (including the paper "Branch Coverage for Arbitrary Languages Made Easy").
Thanks in advance for any guidance given!

A: Path coverage measurement is a tricky subject.  First you have to define what you mean by a path in the first place.  Is a loop executed three times a different path than a loop executed four times?  If so, you have an infinite number of paths.  If not, there are test cases missed even if all paths are covered.
It might be that the better next step is branch coverage: measuring whether every conditional is executed both true and false.  This can be accomplished by recording sequences of line numbers.

A: To do path coverage, you need to get at the program control flow somehow.  An obvious method is to construct a real control flow graph, and then traverse segments of it to pick out "path fragments" (e.g., basis paths) to be used in your path coverage analysis.
(You can attempt to do this by string hacking the source code, but you'll likely fail;
parsing and flow analysis is too complex).
See What's the point of basis path coverage?
for a good stackoverflow discussion on basis paths.
To implement the required path coverage tool, you likely need to really parse the full legacy language completely.  For 3000 programs and a strong requirement for testing, using a industrial strength parser and infrastructure to do this would make sense.
Our DMS Software Reengineering Toolkit can be used to construct not only the parser, but the control flow analysis and the instrumentation required to collect path coverage data.  (The "Branch Coverage for Arbitrary Languages" made this point if all you wanted to do was collect branch coverage data, but there's more to DMS than just parsing).
DMS also has support for constucting control (and data flow) graphs if you need them,
as you apparantly do in this case; see DMS constructed control flow graphs.
DMS has been used to build control and data flow analyzers for C, Java and COBOL,
and has been used to build parsers for some 30+ langauges.  It can handle your legacy language if you are serious about this.
EDIT 10/31/2011:  DMS can now compute control flow for C++, so it would be a great foundation for a C++ path coverage tool.


text:
Q: how to get event of on completion of youtube video in android webview I was able to play youtube video on WebView. I want to finish/close/destroy the WebView automatically when youtube video is completed.
here is my code:
  WebView engine = new WebView(this);
  engine.getSettings().setJavaScriptEnabled(true);
  engine.getSettings().setPluginsEnabled(true);
  engine.loadUrl("http://www.youtube.com/embed/bIPcobKMB94?autoplay=1&rel=0&loop=0");//&enablejsapi=1");
  setContentView(engine);

Actually I was trying to play songs (audio/video) from the playlist when audio is there in playlist it played in my custom player and when youtube video is there is played in WebView and songs are playing one after another automatically onCompletion. Youtube video played in WebView but after the completion of video, webview still open (not going to be destroy/finish). How could I finish WebView and get back to previous activity?

A: Android's webview implementation hides the underlying MediaPlayer related APIs and callbacks. The only situation when the application comes into picture is when a user tries to go full screen (clicking on full screen icon in video embedded in WebView). In this case, onShowCustomView() is called back provided the application has implemented and registered a WebChromeClient callback. There is no way for you to know when a video has finished playing inside a webview.
I know this isn't what you asked: but why not use the youtube app by dispatching an intent to play the url? You can use the startActivityForResult() method which will call back your onActivityFinished() API (you have to implement this callback) with a result code. Will this not work for you?


text:
Q: Firebase Hosting : How to Redirect URLs Based on Origin Domain I have rules as follows, but I want this to only work if origin is any other domain except the current domain.
If my domain is friends.com, everything should go to index, otherwise be handled like below. e.g, if origin is from Google, with a path like friends.com/user, that should call an firebase https function instead of going to index.
{
    "hosting": {
        "public": "y",
        "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
        "rewrites": [{
                "source": "/user",
                "function": "user"
            },
            {
                "source": "/post",
                "function": "post"
            },
            {
                "source": "/*",
                "destination": "/index.html"
            }
        ],
        "headers": [{
            "source": "/css/**",
            "headers": [{
                "key": "Cache-Control",
                "value": "max-age=0"
            }]
        }]
    }
}


text:
Q: Solving Inequalities with variables in the denominator Ok so I've got an exam in 4 hours and I can't ever figure out these problems.
Here's the problem I'm struggling with now:
$$\frac{x}{3x - 5} \leq \frac{2}{x - 1}.$$
I've learned this so many times but my brain just cannot intuitively understand how these work. I can't cross-multiply because I don't know if the binomials are negative or not. If someone could just give a quick explanation of how to solve this sort of thing I'd really appreciate it.

A: $1.$ Find out where you have equality. This involves simplifying to a quadratic equation. In your case you will I think end up with $x^2-7x+10=0$, which has the roots $x=2$ and $x=5$.
$2.$ Find the singularities, where your expression is not defined. These are $x=1$ and $x=5/3$.
$3.$ The points $x=1$, $x=5/3$, $x=2$, and $x=5$ are the only places where the inequality might reverse. These $4$ points divide the number line into $5$ regions. For each region, pick a convenient test point and check whether the inequality holds at that point. If it holds at the test point, it holds for the whole region. If it fails, then it fails for the whole region.
$4.$ Write down your conclusions, paying attention to the fact that we will have equality at $2$ and $5$, and that the inequality makes no sense at $x=1$ and $x=5/3$.

A: $\frac{x}{3x-5}-\frac{2}{x-1} ≤0$
$\implies\frac{x(x-1)-2(3x-5)}{(3x-5)(x-1)}≤0$
$\implies\frac{(x-2)(x-5)}{(3x-5)(x-1)}≤0$
(1)$(x-2)(x-5)≤0$ and $(3x-5)(x-1)>0$
or (2) $(x-2)(x-5)≥0$ and $(3x-5)(x-1)<0$
(1)$\implies 2≤x≤5$ and ($x<1$ or $x>\frac{5}{3})\implies 2≤x≤5$.
(2)$\implies (x≥5$ or $x≤2)$ and $1<x<\frac{5}{3}\implies 1<x<\frac{5}{3}$.
Taking union of regions, we get $1<x≤5$
The formula used :
$(x-a)(x-b)≤0$ where $a≤b\implies a≤x≤b$
and  $(x-a)(x-b)≥0$ where $a≤b\implies x≤a$ or $x≥b$


text:
Q: Проблема спарсить из XML с помощью BS4 Помогите пожалуйста с такой проблемой.
У меня есть xml файл с такой структурой:
<?xml version="1.0">
<extract_cadastral_plan_territory>
  <details_statement>
    <group_top_requisites>
      <organ_registr_rights></organ_registr_rights>
      <date_formation>2022-12-02</date_formation>
      <registration_number>****-***/****-*********</registration_number>
    </group_top_requisites>
  </details_statement>
  <details_request>
    <date_received_request>2022-12-02</date_received_request>
    <date_receipt_request_reg_authority_rights>2022-12-02</date_receipt_request_reg_authority_rights>
  </details_request>
  <cadastral_blocks>
    <cadastral_block>
      <cadastral_number>52:18:0010180</cadastral_number>
      <area_quarter>
        <area>1.1</area>
        <unit>059</unit>
      </area_quarter>
      <land_record>
        <object>
          <common_data>
            <type>
              002001001000
              <value>Земельный участок</value>
            </type>
            <cad_number>52:18:0010180:1</cad_number>
          </common_data>
          <subtype>
            01
            <value>Землепользование</value>
          </subtype>
        </object>
        <params>
          <category>
            <type>
              003002000000
              <value>Земли населенных пунктов</value>
            </type>
          </category>
          <permitted_use>
            <permitted_use_established>
              <by_document>Жилой частный сектор</by_document>
            </permitted_use_established>
          </permitted_use>
          <permittes_uses_grad_reg>
            <reg_numb_border>52:00-7.1</reg_numb_border>
          </permittes_uses_grad_reg>
          <area>
            <value>438</value>
            <inaccuracy>7</inaccuracy>
          </area>
        </params>
        <address_location>
          <address_type>
            01
            <value>Установленный</value>
          </address_type>
          <address>
            <address_fias>
              <level_settlement>
                <fias>6a7510ae-0e9d-4e74-a36f-57fe370a5149</fias>
                <okato>22401382000</okato>
                <kladr>52000001000103800</kladr>
                <oktmo>22701000001</oktmo>
                <postal_code>603040</postal_code>
                <region>
                  52
                  <value>Нижегородская область</value>
                </region>
                <city>
                  <type_city>г</type_city>
                  <name_city>Нижний Новгород</name_city>
                </city>
              </level_settlement>
              <detailed_level>
                <street>
                  <type_street>пер</type_street>
                  <name_street>Сочинский</name_street>
                </street>
                <level1>
                  <type_level1>уч</type_level1>
                  <name_level1>1</name_level1>
                </level1>
              </detailed_level>
            </address_fias>
            <readable_address>Российская Федерация , Нижегородская обл, городской округ город Нижний Новгород , г Нижний Новгород, пер Сочинский, земельный участок 1</readable_address>
          </address>
        </address_location>
        <cost>
          <value>1010106.84</value>
        </cost>
      </land_record>
    </cadastral_block>
  </cadastral_blocks>
</extract_cadastral_plan_territory>

Не удается получить площадь объекта (именно из файла), использую вот такой код:
from bs4 import BeautifulSoup
from pathlib import Path

file_path = r"C:\Users\shirshov\Desktop\2"

fg = '''<?xml version="1.0">
<extract_cadastral_plan_territory>
  <details_statement>
    <group_top_requisites>
      <organ_registr_rights></organ_registr_rights>
      <date_formation>2022-12-02</date_formation>
      <registration_number>****-***/****-*********</registration_number>
    </group_top_requisites>
  </details_statement>
  <details_request>
    <date_received_request>2022-12-02</date_received_request>
    <date_receipt_request_reg_authority_rights>2022-12-02</date_receipt_request_reg_authority_rights>
  </details_request>
  <cadastral_blocks>
    <cadastral_block>
      <cadastral_number>52:18:0010180</cadastral_number>
      <area_quarter>
        <area>1.1</area>
        <unit>059</unit>
      </area_quarter>
      <land_record>
        <object>
          <common_data>
            <type>
              002001001000
              <value>Земельный участок</value>
            </type>
            <cad_number>52:18:0010180:1</cad_number>
          </common_data>
          <subtype>
            01
            <value>Землепользование</value>
          </subtype>
        </object>
        <params>
          <category>
            <type>
              003002000000
              <value>Земли населенных пунктов</value>
            </type>
          </category>
          <permitted_use>
            <permitted_use_established>
              <by_document>Жилой частный сектор</by_document>
            </permitted_use_established>
          </permitted_use>
          <permittes_uses_grad_reg>
            <reg_numb_border>52:00-7.1</reg_numb_border>
          </permittes_uses_grad_reg>
          <area>
            <value>438</value>
            <inaccuracy>7</inaccuracy>
          </area>
        </params>
        <address_location>
          <address_type>
            01
            <value>Установленный</value>
          </address_type>
          <address>
            <address_fias>
              <level_settlement>
                <fias>6a7510ae-0e9d-4e74-a36f-57fe370a5149</fias>
                <okato>22401382000</okato>
                <kladr>52000001000103800</kladr>
                <oktmo>22701000001</oktmo>
                <postal_code>603040</postal_code>
                <region>
                  52
                  <value>Нижегородская область</value>
                </region>
                <city>
                  <type_city>г</type_city>
                  <name_city>Нижний Новгород</name_city>
                </city>
              </level_settlement>
              <detailed_level>
                <street>
                  <type_street>пер</type_street>
                  <name_street>Сочинский</name_street>
                </street>
                <level1>
                  <type_level1>уч</type_level1>
                  <name_level1>1</name_level1>
                </level1>
              </detailed_level>
            </address_fias>
            <readable_address>Российская Федерация , Нижегородская обл, городской округ город Нижний Новгород , г Нижний Новгород, пер Сочинский, земельный участок 1</readable_address>
          </address>
        </address_location>
        <cost>
          <value>1010106.84</value>
        </cost>
      </land_record>
    </cadastral_block>
  </cadastral_blocks>
</extract_cadastral_plan_territory>'''

for path in Path(file_path).rglob('*.XML'):
    with open(path, 'r',encoding='utf-8') as parse:
        xml = parse.read()
        soup = BeautifulSoup(xml, features="xml")
        print(soup.select_one('permitted_use_established by_document'))
        print(soup.select_one('area value'))

Тут я попробовал структуру файла засунуть в переменную и у меня получилось, но не получается из файла xml. Также попробовал за место "soup = BeautifulSoup(xml, features="xml")" использовал "soup = BeautifulSoup(xml, features="lxml")", тогда выдает "<by_document>Жилой частный сектор</by_document>", но не выдает "438".Есть предположение, что проблема в кодировки xml файла, т.к. когда копирую текст из переменной (который в visual studio code написан) и вставляю в блокнот с сохранением в xml тогда ищет без проблем, но при пересохранении оригинального xml файла через блокнот ни чего не дает. Может быть в этом проблема. Пробовал переустановить python, visual studio code, lxml,bs4, результата нет.

A: Получилось с другой кодировкой
for path in Path(file_path).rglob('*.XML'):
    with open(path, 'r',encoding='utf-8-sig') as parse:
        xml = parse.read()
        soup = BeautifulSoup(xml, features="xml")
        print(soup.select_one('permitted_use_established by_document'))
        print(soup.select_one('area value'))

A: Попробуйте так,дописать .text:
with open(file_path, 'r', encoding='utf-8') as file:
    xml = file.read()
soup = BeautifulSoup(xml, features="xml")
print(soup.select_one("by_document").text)
print(soup.select_one("area value").text)

Вывод:

Жилой частный сектор

438


text:
Q: how to populate a list of values in a drop down I have two select dropdowns. If I select values from one dropdown, the other should be populated with corresponding values.
<g:select name="firstText" from="${eventsList}" noSelection="['':'-Choose the From Date-']" onchange="categoryChanged(this.value)" />
            <label>WayBill Id</label>
            <select id="bill">
                <option>Select Bill</option>
             </select>

During the onchange function, I am making an AJAX call to a controller and getting the values
This is my ajax function
function categoryChanged(categoryId) {
    alert(categoryId)
    $.ajax({
        url:"<g:createLink url="[action:'categoryChanged',controller:'jsonComparison']" />",
        asnyc: false,
        data: {dateValue:categoryId},
        success: function(data){
            //var retrievedValue = JSON.parse(data);
            alert("inside the success ajax function"+data)

            //$("#wayBill1").val(retrievedValue.value1)
            //$("#wayBill1").html(retrievedValue.value1)
            //$('#wayBill1 :selected').text();
            var select = $('#bill');
            select.find('option').remove();
            $.each(retrievedValue,function() {
                    $('<option>').val(data).text(data).appendTo(select);

           });

        }
    });
}

The alert alert("inside the success ajax function"+data) is firing with the values but not able to display it in the second dropdown. The values are liist of values like [0000-00.00,0001-00.00,0002-00.07]
This is my controller class
def categoryChanged(){
        String firstParameter = params?.dateValue
        def reply
        def wayB = []
        wayB = JsonComparison.findAllByDateValue(firstParameter)
        println "wayBill id: "+wayB.Bill
        //reply = [status:true, value1:"${wayB.Bill}"]
        render wayB.wayBill as List

    }

am i rendering it correctly as JsonComparison.findAllByDateValue will be returning list of values or else i am doing it wrong while displaying it. Once i receive the response the second select becomes empty and it is not placing the values into it

A: the way you are adding options into dropdwon is to be corrected. Please see if following code helps!!!
function categoryChanged(categoryId) {
    alert(categoryId)
    $.ajax({
        url:"<g:createLink url="[action:'categoryChanged',controller:'jsonComparison']" />",
        asnyc: false,
        data: {dateValue:categoryId},
        success: function(data){
            var retrievedValue = JSON.parse(data);
            alert("inside the success ajax function"+data)

            //$("#wayBill1").val(retrievedValue.value1)
            //$("#wayBill1").html(retrievedValue.value1)
            //$('#wayBill1 :selected').text();
            var select = $('#bill');
            select.find('option').remove();

            for(i=0;i<retrievedValue.length;i++)
            {
             $('<option/>', {
              value: retrievedValue[i],
              html: retrievedValue[i]
             }).appendTo('#bill select');
            };

        }
    });
}

A: The problem is here:
$.each(retrievedValue,function() {
   $('<option>').val(data).text(data).appendTo(select);
});

You try to iterate the 'undefined' and fill each option with an entire set of returned data.
Also I would recommend to cast the returned list in you controller into JSON:
render wayB.wayBill as JSON

And then parse this JSON with JS when populating the dropdown:
$(data).each(function() {
    $('<option>').val(this).text(this).appendTo(select);
});


text:
Q: Android Database: Multiple Instances of one Database Table Let's say I am planning on creating an app that tracks locations for various indicated periods of time, and stores them in a database.
I'd only need one table version with schema consisting of an _id, longitude, latitude, and time. I do not want to store each instance in the same table.
Considering I will be logging many (an unknown number) different instances of this one table, how do I go about creating my database class?

A: not sure why would you want to have multiple tables of same kind inside your database but the solution will be to create a new table each instance or some predetermined number of instances. Each table name will be different as you cannot have duplicate tables in your database. You can also have another table in your database which keeps the track of table names you create. so for example lets start with table1.
you have an SQL statement
Create Table Table1 (
    _id integer PRIMARY KEY AUTOINCREMENT,
    Long real not null,
    Lat real not null,
      Time real not null
);

Use this SQL as template and just change the Table name from Table1 to Table2, Table3, Table#
and also insert into another table some info about the table you create.
This is one way to do it.
Hope you got some idea's.


text:
Q: 'express' is not recognized as an internal or external command, operable program or batch file I did npm install -g express and still for some reason getting this error. Is anyone having the same issue?

A: Found out that express now wants you to use express-generator. So instead of npm install -g express it is npm install -g express-generator.

A: run this:
sudo npm install -g express-generator

In express(version 4), command line tool isn't bundled together, so the express command won't be recognized until you install the express generator.

A: I solved this similar issue by adding NPM global modules to my path variable.
Try add C:\Users<youruser>\AppData\Roaming\npm to your path.


text:
Q: Using class encoding for prediction? I was wondering if you can use class encoding, specifically OneHotEncoder in Python, for prediction, if you do not know all the future feature values?
To give more context. I am predicting whether or not a fine will be paid in the future based upon the location, issuing office & amount (and potentially other features if I can get it to work). When I do onehotencoding on my training set it works great (For 100k rows of data my test accuracy is around 92%, using a 75/25 split).
However, when I then introduce the new data, there are locations and 'offices' the encoder never saw. Therefore, new features were not created. This means that in my training set, I had 2302 columns when I built my model (random forest), while when predicting using the real data, I have 3330 columns, therefore, the model I built is no longer valid. (note, I am also looking at other models as the data is so sparse)
How do you handle such a problem when class encoding? Can you only class encode if you have tight control on your future feature values?
Any help would be much appreciated. Apologies if my terminology is wrong, I am new to this and this is my first post on stackoverflow.
I can add code if it helps however I think it is more the theory which is relevant here.

A: There are two things to keep in mind when using OneHotEncoding.

*

*The number of classes in a column is important. If a class is missing from the test set but present in the train set, it won't be a problem. But if a class is missing from the train set and present in the test set, the encoding will not be able to recognize the new class. This seems to be the problem in your case.

*Secondly, you should use the same encoder to encode the train and test split. This way the number of columns in the train and test splits will be the same (2302 != 3330 columns), but in the case of any additional classes in the test set, the user can specify how to deal with missing values. Have a look at the documentation.

A possible way to deal with your issue would be to do the OneHotEncoding on the entire dataset and then split the data 75/25. This will work considering you wont have any new training data later.


text:
Q: Datatype .innerHTML I´m getting a NaN out of this script, is it a data type problem and how do i solve it?

Present the result like this
               <button onclick="calc()">Calc</button>

A: You have to get the value from the element.
var profile = document.getElementById("profil").value;

A: With .getElementById you get a DOM Element.
Supposing "profil" and "hour" are input elements, you want to obtain their values:


text: Q: How to enable sync between computers on ubuntu 16 In Ubuntu 15.04 LTS , Ubuntu Software Center had an option "Sync between computers.." to sync list of packages on my desktop with Ubuntu One account. but in Ubuntu 16.04 LTS, Ubuntu Software lacks this option . How do I access this option?


text:
Q: How to remove images (v2.1.0) How do you remove an image from the registry in IBM Cloud Private 2.1.0?  In 1.2 you could remove an image from the UI.  How is it done in the current version?

A: I've written a script to help with removal of images via CLI.  It will allow you to remove images within your ICP registry based on jq CLI contains patterns. This script is intended to be run on your ICP master node.  Save off the snippet, chmod +x, update the vars for your creds and enjoy!

Example Invocations:
./remove-registry-image.sh label
Result :: Removes all images which include that label in the namespace or image
   ./remove-registry-image.sh namespace/image-label
Result :: Removes a specific image-label located in namespace

#!/bin/bash
# ----------------------------------------------------------------------------------------------------\\
# Description:
#   A basic script port to delete registry images on an ICP Cluster
#   Fork of https://gist.github.com/mohamed-el-habib/26d26dddaf3dcefcc0e6bdd8a15bd681
#   Reference: https://www.ibm.com/support/knowledgecenter/en/SSBS6K_2.1.0/apis/docker_registry_api.html
#
#   usage ./remove-registry-image.sh filterString
#
#   ./remove-registry-image.sh nameSpace/textString
#
# ----------------------------------------------------------------------------------------------------\\

set -e

##########
# Colors##
##########
Green='\x1B[0;32m'
Red='\x1B[0;31m'
Yellow='\x1B[0;33m'
Cyan='\x1B[0;36m'
no_color='\x1B[0m' # No Color
beer='\xF0\x9f\x8d\xba'
delivery='\xF0\x9F\x9A\x9A'
beers='\xF0\x9F\x8D\xBB'
eyes='\xF0\x9F\x91\x80'
cloud='\xE2\x98\x81'
crossbones='\xE2\x98\xA0'
litter='\xF0\x9F\x9A\xAE'
fail='\xE2\x9B\x94'
harpoons='\xE2\x87\x8C'
tools='\xE2\x9A\x92'
present='\xF0\x9F\x8E\x81'
#############

export ICPUSER=admin
export ICPPW=admin

# Get the variables
clear

echo -e "${tools}   Welcome to the delete registry script for an IBM Cloud Private Cluster v2 Docker Registry"

if [ "${OS}" == "rhel" ]; then
  sudo yum install epel-release -y
  sudo yum install jq -y
else
  sudo apt-get -qq install jq -y
fi

dockerRegistry='mycluster.icp'
dockerRegistryPort='8500'
user="$ICPUSER:$ICPPW"
imagesFilter="$1"

# get the list of images names that match the filter
CATALOG_TOKEN=$(curl --cacert $HOME/.kube/kubecfg.crt -u ${user} -ks "https://${dockerRegistry}:8443/image-manager/api/v1/auth/token?service=token-service&scope=registry:catalog:*" | jq -r '.token')
images=$(curl --cacert $HOME/.kube/kubecfg.crt -ks -H "Authorization: Bearer ${CATALOG_TOKEN}" "https://${dockerRegistry}:${dockerRegistryPort}/v2/_catalog" | jq -r '.repositories[]? | select(. | contains("'${imagesFilter}'")) ')

for image in $images ; do

    # get the list of tags for each image
    TAG_TOKEN=$(curl --cacert $HOME/.kube/kubecfg.crt -u ${user} -ks "https://${dockerRegistry}:8443/image-manager/api/v1/auth/token?service=token-service&scope=repository:${image}:*" | jq -r '.token')
    tags=$(curl --cacert $HOME/.kube/kubecfg.crt -ks -H "Authorization: Bearer ${TAG_TOKEN}" "https://${dockerRegistry}:${dockerRegistryPort}/v2/${image}/tags/list" | jq -r .tags[]?)

    for tag in $tags ; do

        echo "${image}:${tag}"
        # get the digest of the image:tag
        digest=$(curl -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -v --cacert $HOME/.kube/kubecfg.crt -ks -H "Authorization: Bearer ${TAG_TOKEN}" "https://${dockerRegistry}:${dockerRegistryPort}/v2/${image}/manifests/${tag}" 2>&1  | grep -e "Docker-Content-Digest:*" | awk '{ sub(/\r/,"",$3) ; print $3 }')
        if [ -z $digest ] ; then
            echo "${image}:${tag} not found"
        else
            echo -e "${litter}  Deleting ${image}:${tag}:${digest}"
            curl -XDELETE -w "[%{http_code}]\n" --cacert $HOME/.kube/kubecfg.crt -ks -H "Authorization: Bearer ${TAG_TOKEN}" "https://${dockerRegistry}:${dockerRegistryPort}/v2/${image}/manifests/${digest}"
        fi
        echo "...."
    done
done

if [ -n "${images}" ]; then
  echo -e "${fail}   No images matching provided filterString (${imagesFilter}) found"
else
  echo -e "${beers}   Congrats!  All images matching chosen filterString (${imagesFilter}) have been deleted"
fi

A: Yes, in 2.1.0 removing an image can't be done by UI. UI will have that feature back in future release.
For upcoming release, You would be able to do this from API. Knowledge Center document will have updated information for this.

A: from docker CLI directly, list them first:
docker images

remove one of them:
docker rmi -f the-image-id

remove all of them:
docker rmi -f $(docker images -a -q)


text:
Q: Cant connect to Tomcat6 running on Ubuntu Server 11.10 I am trying to stand up tomcat6 and just view the default page.  Everything is installed and running correctly (or so it seems).  I start the server
sudo /etc/init.d/tomcat6 start

and everything starts up fine.
 * Starting Tomcat servlet engine tomcat6
   ...done.

When I run a netstat, I can see that it is listening like expected on port 8080.
tcp        0      0 127.0.0.1:8005          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:28017           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:43521         0.0.0.0:*               LISTEN
tcp        0      1 192.168.1.65:40912      65.5.149.13:25          SYN_SENT
tcp        0      0 192.168.1.65:22         99.44.242.76:50769      ESTABLISHED
tcp        0    272 192.168.1.65:22         99.44.242.76:50552      ESTABLISHED
tcp6       0      0 :::22                   :::*                    LISTEN
udp        0      0 0.0.0.0:68              0.0.0.0:*

But anytime I try to go to the X.X.X.X:8080, the page times out because the server is not responding.  I look in the logs and there are no errors.  I would be happy to post the logs, but they just have normal start up stuff.  So I know that the server is running, and I know that I am pointed at the right place, but in between the 2 something is configured wrong.  Please point me in the right direction.

A: Are you accessing remotely to that server? Try to check if there is any proxy, subnet or something that makes the packages not to reach the destination.
First try to access to the server locally.
"http://Localhost:8080"
Then, from another computer check if ping works. if not, check if both are in the same domain
ADDED:
However if you have access to start tomcat you should be to test it locally:
remotelly:
traceroute -p 8080 your.server.ip

on the server:
traceroute -p 8080 localhost


text:
Q: Comparison between TextInputFormat vs Avro I am a bit new to Hadoop and its file formats. I have a below query related to it.
In a 4 datanode cluster only one datanode is having all the data that needs to be processed for any problem (its a very large volume of data, that needs to be processed in parallel using MapReduce Framework) and rest of the 3 datanodes are empty. So based on the data locality how differently Avro and TextInputFormat will act on the data to consume/parse it in a faster than other.
I know the basic feature/ advantages of Avro over TextFileFormat
**Compact** − To make the best use of network bandwidth, which is the most scarce resource in a data center.
**Fast** − Since the communication between the nodes is crucial in distributed systems, the serialization and deserialization process should be quick, producing less overhead.
**Extensible** − Protocols change over time to meet new requirements, so it should be straightforward to evolve the protocol in a controlled manner for clients and servers.
**Interoperable** − The message format should support the nodes that are written in different languages.

But I am looking for an Answer in a more specific and descriptive way to answer this particular situation. I will appreciate your help in advance.


text:
Q: mypy type checking for variables that are indirectly declared in later `elif` Consider the following code, in which a variable x is referenced before it is declared. When it is declared, it is declared indirectly from y.
for i in range(10):
    if i < 3:
        state = 'earlier'
    elif i < 7:
        state = 'middle'
    else:
        state = 'later'
    # do actions based on state
    if state == 'later':
        print(x)
    elif state == 'middle':
        x = y
        print(y)
    elif state == 'earlier':
        y = 2

mypy gives the following error for this code:
$ mypy stackoverflow.py
stackoverflow.py:10: error: Cannot determine type of 'x'

How can I appropriately annotate this code so that mypy can correctly determine the type of x?
My question is not how to refactor the code. I know that things like changing the order of the if state == ... blocks would fix the problem, but I need to keep them in the current order for various reasons. The question is how to make mypy figure out types when given this structure.

A: Can you just declare it first with some value good for initialization? Like you do with static typed languages like C.

A: I would break this loop into 3 separate loops, for clarity if for no other reason.
for i in range(3):
    y = 2

for i in range(3,7):
    x = y
    print(y)

for i in range(7,10):
    print(x)

This eliminates the need for state altogether, as now the order of the loops themselves determines what state you are in.
An alternate method, if you don't like the hard-coded endpoints and would rather refer to interval sizes instead:
from itertools import islice

itr = iter(range(10))

for i in islice(itr, 3):
    y = 2

for i in islice(itr, 4):
    x = y
    print(y)

for i in itr:
    print(x)


text:
Q: GORM doesn't create ForeignKey column I'm trying to setup relation between two models on PostgreSQL database using Go and gorm.
Here is my code, first model:
Trip.go
package model

import "github.com/jinzhu/gorm"

// Trip models
type Trip struct {
    gorm.Model
    TripName        string
    TripDescription string
}

Second model:
TripKeyPoints.go
package model

import "github.com/jinzhu/gorm"

// TripKeyPoint models
type TripKeyPoint struct {
    gorm.Model
    KPName        string
    KPDescription string
    TripID        Trip
}

Part of code from a file which runs migrations and initializes all
    db.DropTableIfExists(&User{}, &model.Trip{}, &model.TripKeyPoint{})
    db.AutoMigrate(&User{}, &model.Trip{}, &model.TripKeyPoint{})
    db.Model(&model.TripKeyPoint{}).AddForeignKey("trip_id", "trips(id)", "CASCADE", "CASCADE")

Users models is just an addon but I leave it in this snippet.
Due to many tests, I drop tables at the beginning.
Here is what I receive when i run the code:
?[35m(C:/golang_lab/golang-gorm-tutorial/users.go:36)?[0m
?[33m[2019-09-21 18:40:34]?[0m ?[31;1m pq: column "trip_id" referenced in foreign key constraint does not exist ?[0m

And yeah that's true, when I log into postgres in table trip_key_points there isn't column with a foreign key.
What I need to do, I want to have one TRIP object and then assign other TripKeyPoints.
Any idea what why? Or how can I force GORM to create this column?

A: I explicitly define foreign key column:
// TripKeyPoint models
type TripKeyPoint struct {
    gorm.Model
    KPName        string
    KPDescription string
    TripID        uint `gorm:"TYPE:integer REFERENCES trips"`
}

A: try to edit your struct like this :
// TripKeyPoint models
type TripKeyPoint struct {
    gorm.Model
    KPName        string
    KPDescription string
    TripID        Trip `gorm:"foreignkey:TripId"`
}


text:
Q: How can I fix memory leak in my Codeigniter app running PHP with Pthreads ? Fatal Error: Allowed memory size of 2147483648 bytes exhausted I am running a CodeIgniter App on top of Nginx and PHP-FPM .
PHP was manually compiled with ZTS and Pthreads support
I am trying to run the pending tasks from the App with a cron (php spark task:run tasks) in CLI and getting this error every time :
Fatal error: Allowed memory size of 2147483648 bytes exhausted (tried to allocate 3347974853963771560 bytes) in /home/nginx/domains/mydomain.com/app/Commands/Task.php on line 62

Here is the code related to the error :
require APPPATH . 'Vendor/autoload.php';
    $UserId = $Task->task_destination;
    $ClientSettings = [
        'base_uri'  =>  'https://www.example.com',
        'cookies'   =>  $cookie_jar = new FileCookieJar(

LINE 62! APPPATH . 'Vendor/abc/app-php/sessions/' . $Account->account_username . '/' . $Account->account_username . '-cookies.dat',
            false
        )
    ];

There seems to be some memory leaking issues related to pthreads as the tasks are using its multithreading.
Things I have tried so far to fix the issue :
1) I set a memory limit of 2GB RAM in PHP CLI .ini file
2) I have tried forcing the memory size by running php -d memory_limit=2048M before the spark command
3) I have tried to change the memory directly in Codeigniter
It's getting really frustrating and at this point I don't even know if this is a code issue or a server side issue , does anyone have a clue on what might be wrong ? Thanks


text:
Q: incorrect output in PyCharm This is my homework. When I run this code, I should get an output like " result
[(arrivaltime:Mon Mar 9 14:10:00 2020, user:mary, session:42, event:click, usrfield:13)] " but I got an incorrect output which is " [<main.Log object at 0x0000000000522100>] " I do't understand where the problem is. Can anyone help, please?
import time
import random

class Log:
    def __init__(self, arrivaltime, user, session, event, usrfield):
        self.arrivaltime = arrivaltime
        self.user = user
        self.session = session
        self.event = event
        self.usrfield = usrfield

    def getArrivaltime(self):
        return self.arrivaltime

    def getUser(self):
        return self.user

    def getSession(self):
        return self.session

    def getEvent(self):
        return self.event

    def getUsrfield(self):
        return self.usrfield

    def _str_(self):
        return "(arrivaltime:%s, user:%s, session:%d, event:%s, usrfield:%d)" %
(time.ctime(self.arrivaltime),
                                                                             self.user,
                                                                             self.session,
                                                                             self.event,
                                                                             self.usrfield)

    def _repr_(self):
        return "(arrivaltime:%s, user:%s, session:%d, event:%s, usrfield:%d)" %
(time.ctime(self.arrivaltime),
                                                                             self.user,
                                                                             self.session,
                                                                             self.event,
                                                                             self.usrfield)

def randomLogs(n):
    stringmaxlen = 3
    sessionmax = 1000
    events = ['eventA', 'eventB', 'eventC', 'eventD', 'eventE']
    arrivalmin = int(time.mktime(time.strptime('Mon Jan 1 12:00:00 2020')))
    arrivalmax = int(time.mktime(time.strptime('Mon Mar 1 12:00:00 2020')))
    usrfieldmax = 10000
    chars = 'abcdefghijklmnprstuvyz'
    logs = []

    for i in range(1, n + 1):
        arrival = random.randint(arrivalmin, arrivalmax)
        user = ''
        for x in range(0, stringmaxlen):
            user += random.choice(chars)
        session = random.randint(0, sessionmax)
        event = random.choice(events)
        usrfield = random.randint(0, usrfieldmax)
        log = Log(arrival, user, session, event, usrfield)
        logs.append(log)
    return logs

def registerEqualQuery(logs, field):
    def query(val1):
        res = []
        for (index, log) in enumerate(logs):
            if getattr(log, field)() == val1:
                res.append(log)
        return res

    if field not in ['getArrivaltime', 'getUser', 'getSession', 'getEvent', 'getUsrfield']:
        raise Exception('field name not found')
    return query

l1 = Log(int(time.mktime(time.strptime("Mon Mar 09 12:00:00 2020"))), "john", 23, "signin", 0)
l2 = Log(int(time.mktime(time.strptime("Mon Mar 09 14:10:00 2020"))), "mary", 42, "click", 13)
l3 = Log(int(time.mktime(time.strptime("Tue Mar 10 11:00:32 2020"))), "john", 23, "signout", 0)
l4 = Log(int(time.mktime(time.strptime("Wed Mar 11 22:10:00 2020"))), "viz", 350, "follow", 1)
l5 = Log(int(time.mktime(time.strptime("Fri Mar 13 03:33:02 2020"))), "admin12", 44, "signin", 0)
mylogs = [l1, l2, l3, l4, l5]
q1 = registerEqualQuery(mylogs, "getUser")
result = q1("mary")
print(result)

A: _str_ should be __str__ and _repr_ should be __repr__ for the program to override the functions.


text:
Q: TinyMCE and multiple CSS selectors on the parent css file handling I got a problem with TinyMCE when it comes to parent site CSS selectors.
My TinyMCE opens an iframe. I add the parent css to the tinyMCE via content_css property, no problem from there.
Now imagine that i got a css style like this:
.mysite.default .content h1 {
   ...
}

.mysite.default .info h4 {

}

The problem comes when i want to access to .content h1 or .info h4.
As by default, by adding to the body the class .mysite.default, if you got an h1 or h4, those won't be applied of course due to the selector .content and .info in the middle.
So inside the iframe's body i would be able to set styles only for
.mysite.default h1 { ... }

.mysite.default h4 { ... }

Is there a good strategy to have this kind of flexibility?
Problem is that I don't have only one h1 or h4 or span styling, I may got many of them, that's why I need a flexible selector strategy for this...
I can't just copy all the styles of the parent dynamically at runtime, because what if one of the parent selectors has a border, margins, padding (because it might be a parent div wrapper container with some unique styling) ?
So it's not that easy as saying, "hey add every parent style and that's all", because the child will have extra borders, extra margins when starting to edit that div.

A: If I understand you correctly, you should be able to use
.mysite.default * h1 { ... }

to select all h1s inside other tags: the * wildcard covers any wrapping tag/class/id.
Hope that is helpful...!


text:
Q: What is the difference between "compound" and "complex" sentences? And what is the difference between coordinating and subordinating conjunctions? Is one kind of sentence (compound or complex) characterized by either a coordinating or subordinating conjunction, while the other kind is characterized by the other?

A: Yes, this is a good place. It's simple, really.
There are two ways to combine clauses. One of them is simply stacking together sentences, like

*

*He went to the store and he bought some bread and he drove home but he left it in the car.
This is a compound sentence (not "compound clause", by the way); it contains only clauses that are linked together by the coordinating conjunctions and, or, and but. Compound sentences can be reduced by Conjunction Reduction, producing, for instance

*

*He went to the store and bought some bread and drove home but left it in the car.
Compound sentences are easy; all the sentences are on the same level as main clauses, and none of them modify another clause.
Complex sentences — the other way to combine clauses — are not easy. A complex sentence has at least one subordinate clause, and there are a lot of different kinds of subordinate clause, each with their own set of rules and their own set of idioms and connotations.

A: COMPOUND SENTENCES:-
Having one or more main clauses.
SIMPLE SENTENCES:-
Having a main clause.
COMPLEX SENTENCES:-
Having one main and two or three subordinate clauses.


text:
Q: What is the idiomatic way to refer to a singleton list constructor in Haskell? Short form: is there a more idiomatic way to write (\a->[a]) ?
Long form: For any data type Foo a, if I have a function f :: Foo a -> b and I need to write something like...
wrapAndF a = f $ Foo a

...I can make it point-free by writing
wrapAndF = f . Foo

But if my function g :: [a] -> b operates on lists and my wrapper looks like this...
wrapAndG a = g [a]

...what is the most idiomatic way to write it point-free? I know I can write an explicit lambda:
wrapAndG = g . (\x->[x])

or, mirroring the use of the constructor in the Foo example, use the list constructor (:), but then I have to flip the arguments:
wrapAndG = g . flip (:) []

...but what is the idiomatic way to refer to the singleton list constructor function? I expected to find a standard function with signature a -> [a], but I couldn't find it on Hoogle or Data.List.
There is of course the alternative of simply not writing it point-free (and that is certainly a valid answer) but since passing type constructors around as wrapper functions seems really useful, it felt odd that I couldn't find a standard function to wrap a value into a list, so I figured I may be missing something.

A: Just found the answer, thanks to pointfree.io, which was linked to in another question. A nice, point-free way to write wrapAndG is
wrapAndG = g . return

This uses the fact that lists are instances of Monad.

A: Echoing the comments by user2407038 and chi, (:[]) is a fine way of spelling it if you want something specific to lists:
wrapAndG = g . (:[])

A: For lists pure does what you want:
wrapAndG = g . pure


text:
Q: How can I compress images,so that google pagespeed test won't recommend to compress that image again? Whenever I run pagespeed test , it gives possible optimization of images in bytes & percentage like,
  Compressing and resizing https://example.com/…ts/AMP.jpg?6750368613317441460 could save 530KiB (91% reduction).
Compressing https://example.com/…AMP.png?12287830358450898504 could save 4.4KiB (31% reduction).
I am using ImageMagick to compress the images.
I have tried  convert AMP.gif_or_png -strip  [-alpha Remove] OUTPUT.png  for png images  and
 convert INPUT.jpg -sampling-factor 4:2:0 -strip [-quality 85] [-interlace JPEG] [-colorspace RGB] OUTPUT.jpg

for jpg images, but none of the above commands gives me the same reduction as suggested by google pagespeed.
 So, let me know if i am missing any parameters or I have passed wrong values of parameters.
The pack of compressed contents are available on google pagespeed page but,I want to compress images using ImageMagick
 or any other sources .

A: If you are looking for a commercial tool, JPEGmini can be used. You can also use imagemin if you are going to use Grunt task runner. You can also use command lines tools that are provided with imagemin such as jpeg-tran and opti-png, and they are open source as well.

A: May be, there is no tool available to do your task dynamically,You should do some calculations or if your doing your task with any language then there are many inbuilt classes are available so  you can use these classes to compress images, like in java Imagescalr, Thumbnail or ImageWriteParam or you can go with Matlab also.

A:
Compressing and resizing https://example.com/…ts/AMP.jpg?6750368613317441460 could save 530KiB (91% reduction).

530 KiB reduction is quite a lot. Verify that the image size is congruous. I mean, if you have a 400x200 image and you show it at 200x100, then serving it at the correct resolution (or resolutions) could be what PageSpeed is after.
For PNG images, often color reduction is possible: if you have a 12 colors image (e.g. a schematic), having it in 24-bit, 8-bit or 4-bit format makes a significant difference, while changing nothing in what people see once it's displayed. Good call removing unneeded alpha channel, though.
The rest you can do with tools like pngopt, pngcrush or advpng. JPEG quality parameter or suitable tools (tinyjpg, or google 'JPEG compression optimizer') can be used to improve JPEG size. There are some tools that are capable of selectively encoding different areas of the image, or rewrite a PNG palette to leverage zLib compression features.
Another possibility with JPEG is using the progressive format, that allows quickly displaying a raw image, and refine it iteratively. More overall bandwidth but also more apparent speed (less browser support also; check it out).
It is not automatic that any of this can be done with ImageMagick - after all, ImageMagick is not directly tasked with file manipulation but with image manipulation. It may well be that its file-compression functions are not as complete or as advanced as other tools'.

A: You can download a compression pack from that page with your images and code optimized to their liking...it is pretty much the best image compression available.

A: I would recommend thumbor.org. It's a open source imaging service which you can simply start using a docker container on Amazon Elastic Beanstalk. It has some pretty nice features like smart cropping and face detection.
To start it, just create a elastic beanstalk environment with docker as predefined configuration. Then you provide a JSON-File with following content in the application version tab.
{
  "AWSEBDockerrunVersion": "1",
  "Image": {
    "Name": "apsl/thumbor"
  },
 "Ports": [
    {
      "ContainerPort": "8000"
    }
  ]
}

You can then configure thumbor with elastic beanstalk environment variables. For optimizing JPG you should add the jpegtran optimizer.
OPTIMIZERS=['thumbor.optimizers.jpegtran']
We use it at Storyblok.com to optimize the images and Google Pagespeed is happy with the result: https://www.storyblok.com/docs/Guides/how-to-resize-images


text:
Q: Ошибка в строчках с break do{
answer = prompt(getStatus() + ' [хотите карту ещё? 1 - да, иначе - нет'); //с помощью promt задаётся вопрос у игрока (выводится строчка)
if (answer == '1') { // если ответ 1,то продолжается игра и
    player.push(getCard()); //  добавляется игроку карта
}
alert(getStatus()); // показывается текущее состоянии игры
} while(answer == '1'); // должны ввести 1,чтоб продолжить игру
    sum = getSum(player); // получение суммы очков,сумма запоминается
    if (sum > 21) { // смотрим сумма больше 21
        alert('Перебор'+ getStatus()); // показывается перебор
        break; // break  выпроваживает нас из этого цикла и мы заканчиваем игру
    } else if (sum == 21) { // если нет перебора,но сумма равна 21
        alert('Black Jack!' + getStatus()); // то выводим блэк джек
        break; // выводим из игры
    }
}
} else { // игрок закончил брать карты
         // теперь карты берёт дилер
         while (getSum(dealer) < 17) { // если сумма карт у дилера <17
            dealer.push(getCard()); // функция pus добавляет ещё одну карту дилеру
};

Пишет, что ошибка в строчке break.
Хром называет ошибку:

Uncaught SyntaxError: Illegal break statement

Но я не понимаю, что она обозначает. Может есть лёгкие способы, программы, которые доступно разъясняют, в чём именно заключается ошибка?

A: Вы запутались в фигурных скобках. Возможно, Вы хотели сделать так:
player.push(getCard());  // Игроку добавляется карта
alert(getStatus());  // Показывается текущее состоянии игры
player.push(getCard());
alert(getStatus());

answer = prompt(getStatus() + ' [хотите карту ещё? 1 - да, иначе - нет');   // С помощью promt задаётся вопрос у игрока (выводится строчка)

while (answer == '1') {  // Должны ввести 1,чтоб продолжить игру
    player.push(getCard());

    alert(getStatus());  // Показывается текущее состоянии игры

    sum = getSum(player);  // Получение суммы очков, сумма запоминается
    if (sum > 21) {  // Смотрим, сумма больше 21
        alert('Перебор'+ getStatus());  // Показывается перебор
        break;  // Выпроваживает нас из этого цикла и мы заканчиваем игру
    } else if (sum == 21) {  // Если нет перебора,но сумма равна 21
        alert('Black Jack!' + getStatus());  // то выводим блэк джек
        break;  // Выводим из игры
    }

    answer = prompt(getStatus() + ' [хотите карту ещё? 1 - да, иначе - нет');   // С помощью promt задаётся вопрос у игрока (выводится строчка)
}

// Проверка результата игрока
if (sum >= 21) {
    // Игра закончена
} else {  // Игрок закончил брать карты
    while (getSum(dealer) < 17) {  // Карты берёт дилер
        dealer.push(getCard());
    }
}
// Сравнение результатов игрока и дилера


text:
Q: Making href (anchor tag) request POST instead of GET? Employee1

when i click the Employee1 link, GET request goes to server. I want to make it POST instead of GET request.
Is there a way i can change default GET behaviour of href?
Note:- I know it can be done where we can call javascript function on hyperlink click , then create form and submit it. But i am looking where we can mention
some attribute in anchor tag to make POST request instead of GET request?

A: Using jQuery it is very simple, assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)
 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one
 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

A: To do POST you'll need to have a form.
<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.
Some tricks: Make a link use POST instead of GET and How do you post data with a link
Edit: to load response on a frame you can target your form to your frame:
<form action="employee.action" method="post" target="myFrame">


text:
Q: Location directive in nginx for root only, nested in / I have a proxy_pass working on / and want certain config only apply to root.
I've tried
location / {
   proxy_pass http://foo.com/
}

location = / {
   subs_filter 'foo' 'bar';
}

But i'm getting a 404 from foo.com - how would i make the subs_filter only apply to the root?

A: To nginx, only "the" one matching location block is used; in the question this means that for the url / there is no proxy_pass - it'll treat the request as a request for a file in the (default if not configured) root.
There is an example in the documentation very similar to the question:
location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}

Applying that to the question the only thing missing is to add proxy_pass to the = / location block, i.e.
location / {
   proxy_pass http://foo.com/
}

location = / {
   proxy_pass http://foo.com/
   subs_filter 'foo' 'bar';
}


text:
Q: QPX express API is returning error 403 Guys I'm using the google console to test qpx express api and i constantly get back this 403 error.
403 Forbidden

- Hide headers -

cache-control:  private, max-age=0
content-encoding:  gzip
content-length:  260
content-type:  application/json; charset=UTF-8
date:  Mon, 30 Mar 2015 08:42:13 GMT
expires:  Mon, 30 Mar 2015 08:42:13 GMT
server:  GSE
vary:  Origin, X-Origin

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured. The API (QPX Express API) is not enabled for your project. Please use the Google Developers Console to update your configuration.",
    "extendedHelp": "https://console.developers.google.com"
   }
  ],
  "code": 403,
  "message": "Access Not Configured. The API (QPX Express API) is not enabled for your project. Please use the Google Developers Console to update your configuration."
 }
}

my request is this...
POST https://www.googleapis.com/qpxExpress/v1/trips/search?key={YOUR_API_KEY}

{
 "request": {
  "passengers": {
   "adultCount": 1
  },
  "slice": [
   {
    "destination": "LCY",
    "origin": "ATH",
    "date": "2015-08-27"
   }
  ]
 }
}

as defined by the qpx doc...
my project has the qpx api enabled.What am i missing here..????

A: The message is quite clear, the reason is indicated: accessNotConfigured.
Please, review again your API enabled:

*

*from Google Developer Console, choose your Project.

*choose API & Auth/APIs option

*select the tab "Enabled APIs"

*check QPX Express Airfare API and enable it

A: SOLVED.
The problem was tha I used android key instead of a Browser key that was required fro my application.
That is why qpx api was blocking my request.
STEPS.
Inside APIs & auth ---> credentials
created a browser key and left referers blank so it is by default set to any refers allowed.


text:
Q: Requiring workflow class in workflow starter code I have a simple question regarding the architecture of my Amazon Simple Workflow / AWS Flow for Ruby app. For background, I have a simple workflow with one activity running in an AWS Flow for Ruby layer on Opsworks. I have a separate REST API running in a Rails App Server layer on Opsworks that I would like to kick off the workflow.
The code in the REST API that kicks off the workflow:
1: domain = AWS::SimpleWorkflow.new.domains['my_domain']
2: workflow_client = AWS::Flow::workflow_client(domain.client, domain) {{from_class: MyWorkflowClass}}
3: workflow_client.start_execution(input_1: @input1, input_2: @input2)

My assumption is that my workflow and REST API code bases could be separate and that the only common component would be the aws-flow Ruby gem and require 'aws/decider'. However, I'm finding that my REST API also needs to have require 'PATH_TO_MY_WORKFLOW_CLASS'. When I remove that line of code from the code file in my REST API that kicks off the workflow, I get the following error:
undefined method `_options' for nil:NilClass; ["/Users/MyName/.rvm/gems/ruby-2.0.0-p247/gems/aws-flow-2.2.1/lib/aws/decider/utilities.rb:183:in `interpret_block_for_options'", "/Users/MyName/.rvm/gems/ruby-2.0.0-p247/gems/aws-flow-2.2.1/lib/aws/decider/implementation.rb:73:in `workflow_client'"
(error at line 2 above)

Am I mistaken? Do I really need to require MyWorkflowClass in my workflow starter app (i.e. my REST API) or am I doing something wrong? I've scoured the documentation and could not find a clear answer to this. All the samples that I can find do indeed have the workflow class included in the workflow starter code, but I'm not sure if it's because they are bundled as a simple sample or if it's because it's the way it's supposed to be. The reason why I am not taking the samples at face value is because requiring the workflow class in the workflow starter code does not make any sense to me. It binds the two apps way too tightly for my taste.

A: I posted an issue on the aws-flow-ruby sdk and got the answer from an Amazon Engineer. In short, you can use the :from_class option or the :prefix_name and :execution_method options together.

There are two ways of starting the workflow in code
1) Using the aws sdk directly.
In this case, your code doesn't need to know anything about the workflow class. You just need the domain, workflow type (name and version) and the workflow id.
It will look something like -
require 'aws-sdk-v1'
swf = AWS::SimpleWorkflow.new.client
swf.start_workflow_execution(
  domain: "HelloWorld",
  workflow_type: {
    name: "HelloWorldWorkflow",
    version: "1.0"
  },
  workflow_id: "foo",
  input: ....,
  ....other options (optional)...
)

As you can see above, this doesn't require the workflow class at all.
2) Using the aws-flow gem (which is what you are doing above).
There are two ways of using the workflow client provided by the aws-flow gem to start an execution. You can either use the client as a generic client and not tie it to any workflow class or you can use the :from_class option to fetch options from a particular workflow class. To use the from_class option, you need to have the class in the ObjectSpace (hence you need to require the workflow file).
With from_class -
require 'aws/decider'
domain = AWS::SimpleWorkflow.new.domains['my_domain']
workflow_client = AWS::Flow::workflow_client(domain.client, domain) {{from_class: "MyWorkflowClass"}}
workflow_client.start_execution(input_1: @input1, input_2: @input2)

Without from_class -
require 'aws/decider'
domain = AWS::SimpleWorkflow.new.domains['my_domain']
workflow_client = AWS::Flow::workflow_client(domain.client, domain) {{
  prefix_name: "YourClassName",
  execution_method: "workflow_method_name",
  version: "1.0",
  ...other options...
}}
workflow_client.start_execution(input_1: @input1, input_2: @input2)

The recommended way to start a workflow execution is to use aws-flow WorkflowClient instead of using the SDK directly.

Additional notes with respect to the input accepted by a workflow:

The SDK and the console will only take strings as input. This can be a free form string but if your workflow is written using ruby flow, this string should be a serialized form of your input so that the WorkflowWorker can deserialize the input when it picks up the task and convert it into ruby objects (in this case a hash).
When you use the ruby flow WorkflowClient, the client will automatically serialize your input hash (or any other input) into a string before sending it to SWF. aws-flow by default uses a YAML based data converter to do this (It can be overridden).
If you just want to see what your input hash will look like as a string, you can do the following -
AWS::Flow::FlowConstants.default_data_converter.dump(input_hash)

You can then use this serialized input to start a workflow using the SDK or the console.


text:
Q: Directory Structure within TreeView VB Started to look at the Treeview control.
Is there anyway to tie the Tree View control into a Directory structure on the Web Server using Visual basic?
I have a lot of legacy files, which are updated and added often. Obviously I could code the structure in XML but this would be laborious and hard to train out to the end user.
I guess it would be a dynamic creation of an XML file perhaps?

A: Here's an elementary sample that I created awhile ago when learning to play with the TreeView. I have now converted the code to VB.NET using an online converter for your benefit.
It recursively walks the directory tree starting from the root of the virtual directory and creates nodes for each sub-directory or file encountered. I think this is exactly what you needed.
For visual separation, I had used icons to differentiate files from folders (folder.gif and file.gif). You can remove that parameter if you want.
Complete ASPX follows (You can paste it into a new page and it should run):

<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Page.IsPostBack Then
      Dim rootDir As New DirectoryInfo(Server.MapPath("~/"))

      ' Enter the RecurseNodes function to recursively walk the directory tree.
      Dim RootNode As TreeNode = RecurseNodes(rootDir)

      ' Add this Node hierarchy to the TreeNode control.
      Treeview1.Nodes.Add(RootNode)
    End If
  End Sub

  Private Function RecurseNodes(ByVal thisDir As DirectoryInfo) As TreeNode
    Dim thisDirNode As New TreeNode(thisDir.Name, Nothing, "Images/folder.gif")

    ' Get all the subdirectories in this Directory.
    Dim subDirs As DirectoryInfo() = thisDir.GetDirectories()
    For Each subDir As DirectoryInfo In subDirs
      thisDirNode.ChildNodes.Add(RecurseNodes(subDir))
    Next

    ' Now get the files in this Directory.
    Dim files As FileInfo() = thisDir.GetFiles()
    For Each file As FileInfo In files
      Dim thisFileNode As New TreeNode(file.Name, Nothing, "Images/file.gif")
      thisDirNode.ChildNodes.Add(thisFileNode)
    Next

    Return thisDirNode
  End Function
</script>

<html>
<head>
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
      <asp:treeview ID="Treeview1" runat="server"></asp:treeview>
    </form>
</body>
</html>

A: A custom sitemap provider is a good bet.
There is a good article on 4guys title "Examining ASP.NET 2.0's Site Navigation - Part 4 "


text:
Q: Apache2 timeout For several weeks now, I've been experiencing timeout problems with Apache2 making my application inacessible. It's an e-commerce website developed in PHP (stack : PHP7.2-FPM, PostgreSQL, Apache2.4.25, Debian 9).
When the site does not respond, it takes a good twenty seconds before displaying the timeout on the browser side. The service status are all good: apache2, database and I have no logs that could help me.
The only leads I have :

*

*Apache2/PHP configuration, I increased the timeout value bit it didnt't change anything
<Proxy "unix:/var/run/php/php7.2-fpm-app.sock|fcgi://localhost">
    ProxySet timeout=1200
</Proxy>

*Apache2 version. I have the same problem on another site (basic wordpress) with exactly the same behavior (timeout without specific logs behind, all services UP etc). And Apache2 version of this website is Apache2.4.25
I have a lot of other sites with the same Apache2 configuration, on more recent versions and no problem.
Does this speak to anyone ? Any ideas or anything ? :)


text:
Q: What is the correct WEB-INF path for precompiled JSPs? My Gradle and Maven builds seems to put precompiled JSPs within different packages.  The Maven build have them in WEB-INF/classes/jsp/WEB_002dINF, while the Gradle build have them in WEB-INF/classes/org/apache/jsp/WEB_002dINF.  Are either fine?
Will the compiled JSPs be used on both Tomcat and Jetty, regardless on how they were built?
Here are the relevant parts of my build scripts:
Maven:
<profile>
    <id>precompileJsps</id>
    <activation>
        <property>
            <name>precompileJsps</name>
            <value>true</value>
        </property>
    </activation>
    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-jspc-maven-plugin</artifactId>
                <version>${version.mortbay.jetty}</version>
                <executions>
                    <execution>
                        <id>jspc</id>
                        <goals>
                            <goal>jspc</goal>
                        </goals>
                        <configuration>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>

Gradle:
jasper {
    compilerSourceVM = "1.7"
    compilerTargetVM = "1.7"
    outputDir = file("${buildDir}/jasper")
}

task precompileJsps(type: Compile) {
    if (System.properties['precompileJsps'] == "true") {
        dependsOn tomcatJasper
    } else {
        enabled = false
    }
    group = 'build'
    description = 'Translates and compiles JSPs'
    classpath = configurations.tomcat + sourceSets.main.output + sourceSets.main.runtimeClasspath
    sourceCompatibility = jasper.compilerSourceVM
    targetCompatibility = jasper.compilerTargetVM
    destinationDir = file("$buildDir/classes/main")
    source = jasper.outputDir
    dependencyCacheDir = file("${buildDir}/dependency-cache")
}
war.dependsOn precompileJsps

(This question was moved from https://stackoverflow.com/questions/19906475/how-do-i-verify-that-precompiled-jsps-are-used-in-tomcat-and-jetty)

A: No. Each container has its own JSP compiler, internal classes used inside the compiled JSPs, and mapping between JSPs and class files.
You don't get a different result because one build uses Maven and the other one uses Gradle. You get a different result because one build uses the Jetty compiler and the other one uses the tomcat compiler.