text:
Q: Is there any workaround for MSVC producing `Internal compiler error` for this code? For some reason the below code gives me fatal error C1001: Internal compiler error. with MSVC 19.27, but not with Clang. Any idea how to write it so that the static_assert can be done also on MSVC?
template <typename T, int N, typename K, int M>
constexpr int countIdentifersNotInArray(const T(&identifiers)[N], const K(&array)[M]) {

 auto find = [&array](const unsigned char value) {
        for (const auto& a : array) {
            if (a == value) {
                return true;
            }
        }
        return false;
    };

    int count = 0;
    for (const auto& value : identifiers) {
        if (!find(value)) {
            ++count;
        }
    }
    return count;
}

constexpr bool testIt() {
    return countIdentifersNotInArray({ 0x01, 0x02 }, { 0x01 });
}

int main() {
    static_assert(testIt());
    return 0;
}

I would like to use this in a an environment where stl is not available, so solutions without that are most interesting.

A: As the comment has pointed out, this is an MSVC bug and you should definitely report to Microsoft.
By removing multiple lines until it stops crashing the compiler, I believe the cause is the range-for loops. So, since they're arrays with known size, you can workaround with the classic indexed loops:
template <typename T, int N, typename K, int M>
constexpr int countIdentifersNotInArray(const T(&identifiers)[N], const K(&array)[M]) {

    auto find = [&array](const auto value) {
        for (int i = 0; i < M; i++) {
            if (array[i] == value) {
                return true;
            }
        }
        return false;
    };

    int count = 0;
    for (int i = 0; i < N; i++) {
        if (!find(identifiers[i])) {
            ++count;
        }
    }
    return count;
}

It works on MSVC.


text:
Q: How to higlight button color when hover the mouse after a click? I'm doing a piano application thought to be played on mobile devices (Android). All the piano keys are UI buttons that have the "property" pressed color to a grey one in order to properly indicate when a piano key is emiting sound.
My current problem is that when I first click on a key and after that I drag the mouse over the following keys, only the first one that I clicked is getting the change of color (the idea is that the change of color duration finishes when other key starts sound and then the new key where I pass the mouse-finger gets the grey color).
I also tryied setting the higlighted color property to the same color as the pressed color with the Navigation parameter to none (if it's set to automatic it happens some kind of bug that the color is getting "stuck" until I make sound another key), but the result it's still the same.
EDIT:
I update the issue with some progress thath I made:
I'm trying to change the pressed color with a script thanks to the events Pointer enter and exit (both events are placed on a Event trigger in every button).
Code:
public class ChangeKeyColor : MonoBehaviour{

    public Button button;

    void Start()
    {

    }

    void Update()
    {

    }

    public void EnterKey () {
        Debug.Log("Enter the key");
        ColorBlock colors = button.colors;
        colors.normalColor = new Color(179, 179, 179, 255);
        //colors.highlightedColor = new Color32(179, 179, 179, 255);
        button.colors = colors;
    }

    public void ExitKey()
    {
        Debug.Log("Exits the key");
        ColorBlock colors = button.colors;
        colors.normalColor = Color.white;
        //colors.highlightedColor = new Color32(255, 255, 255, 255);
        //colors.pressedColor = Color.white;
        button.colors = colors;
    }

}

The only improvement that I obtained is that now when I'm dragging the mouse (maintaning it) the first button returns to white color, but I think that this is happening because now I only setted to gray color the pressed color option...
Does anyone know why the pressed color change that I'm making in the script isn't happening? When I drag the mouse to another key isn't considered as a pressed button?
Regards!

A: I'm not sure if you are still looking for the answer, but I finally had some time to try it myself.
What I did is changing color and debug-logging transform's name instead of playing sound.
My code for Images/Buttons (attached to each Image, I didn't use Button components):
using UnityEngine;
using UnityEngine.UI;

public class ChangeColor : MonoBehaviour {

public Color activeColor, notActiveColor;
private Image thisImage;

void Awake () {
    thisImage = GetComponent<Image>();
}

public void OnPointerClick()
{
    Activate();
}

public void OnPointerEnterAndDown()
{
    if (Input.GetKey(KeyCode.Mouse0))
    {
        Activate();
    }
}

public void OnPointerExit()
{
    thisImage.color = notActiveColor;
}

private void Activate()
{
    Debug.Log(transform.name);
    thisImage.color = activeColor;
}
}

EventTrigger settings:

And this is what it looks like in the end:

A: (This should be a comment, but it's a little long, so reply me and I'll update the answer)
I don't know why are you having this problem, I do the simple test creating 2 UI Buttons and setting the highlighted color to red, and the pressed to blue.
By default (there's no script attached to anything) the behaviour is the follow:
1.If I press (and mantain) the click on a button, that button is blue, when I release the "pression", the button keeps red.
2.While this first button is red, if I drag the mouse over the second button, this will be also red.
3.If now I press on the second button, the first behaviour applies to the second button, and the first one will be white again.
This is the following behaviour that you want, according to what I understood.
So, if this is not the desired behaviour, tell us more about what you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Initializing user profile on user creation with the same form with Devise 3.2 Rails 4.1 Each user in the application has a profile that has to be filled out by the user when registering. The user and profile classes are as follows:
user.rb:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable
  has_one :profile
end

profile.rb:
class Profile < ActiveRecord::Base
  belongs_to :user
end

the view form:
= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f|
  = f.input :email, required: true, autofocus: true
  = f.simple_fields_for :profile do |pf|
    = pf.input :name
    = pf.input :bio
  = f.input :password, required: true
  = f.input :password_confirmation, required: true
  = f.button :submit

The problem is that the profile object needs to be initialized before the form is rendered.
I decided to override the new method of the Devise::RegistrationsController:
class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :configure_permitted_parameters
  def new
      build_resource({})     # copied from super
      resource.build_profile # my custom initialization code
      respond_with self.resource # copied from super
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << { profile_attributes: [:name, :bio] }
  end
end

This doesn't seem to be very DRY since I am duplicating the code in the super new method. I might also break things if the super controller method new changes when the gem is upgraded. Any better way to override the resource (user) creation without duplicating code?

A: You can try to only change the User model:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable
  has_one :profile
  accepts_nested_attributes_for :profile

  def profile
    super || build_profile
  end
end


text:
Q: using arraylist for instance of a class I am in this Java class and I am basically trying to be an overachiever but I have spent most of the time trying to figure out things and its not working.
I am creating an ArrayList of the Temperature class.
List<Temperature> templist = new ArrayList<Temperature>();
Temperature t1 = new Temperature ();

for (number of loops user wants)
{
 templist.add(t1)
}

But my Temeperature class has both the number and the scale. So when I dispay t1 it looks this
Temperature [degrees=43.0, scale=F]

how to I utilized my getDegrees() and getScale() method to just extract just the degrees and scales separately. also i need to get a min, max and avg. I know how to do that using for loop but since there are instance of classes involved can that still possible ?
So basically this is what i have
Temperature.java
import java.util.Scanner;

/*
 * This class represents a temperature value.
 */
    public class Temperature {

private double degrees;
private char scale;
Scanner s = new Scanner (System.in);

public Temperature (){
this.degrees = 0 ;
this.scale = 'F' ;
    }

public double getDegrees() {
    return degrees;
}

//public double getDegreesF(){
//  return degrees;
//}

public double getDegreesC(Temperature temperature)

{
         if (scale == 'C')
             return degrees;
         else if (scale == 'F')
           degrees = ((degrees - 32)*(5)/(9));
           return degrees;

}

public void setDegrees(double degrees) {
    this.degrees = degrees;
}

public char getScaleC() {
     scale = 'C';
    return scale;
}

    public void setScale(char scale) {

    while  ((scale != 'C') && (scale !='F') )

       {

        System.out.println("Please enter correct value");
        scale = s.next().charAt(0);
      }

    this.scale = scale;
}

@Override
public String toString() {
    return "Temperature [degrees=" + degrees + ", scale=" + scale + "]";
}

    }

 Test Temperature.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class TestTempreture {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int numberoftimes = 0 ;

        Scanner s = new Scanner (System.in);

        Temperature t1 = new Temperature ();
        List<Temperature> templist = new ArrayList<Temperature>();

        for (int i = 0; i < numberoftimes; i ++  )

        {

            t1.setDegrees(s.nextInt());
            t1.setScale(s.next().charAt(0));
            templist.add(t1);

        }

        System.out.println(templist.get(0));

A: The problem is, ArrayList doesn't know how to calculate min, max, and average. You could use a loop in your main code, or you could use composition...
public class AllTemps {
    private static final ArrayList<Temperature> temps = new ArrayList<Temperature>();
    private Temperature min = null;

    public AllTemps() { }

    public boolean add(Temperature t) {
        updateMin(t);
        return temps.add(t);
    }

    // Here you would implement any other methods to access the ArrayList that you need

    private void updateMin(Temperature t) {
        if (min == null) {
            min = t;
        } else {
            if(min.getDegrees() > t.getDegrees()) min = t;
        }
    }
}

And then you can implement calculating the max, average, etc. the same way.


text:
Q: SQL date string split How could I split a date range like this

20120301-20120331

into two different dates in T-SQL? The data appears in a column called date_range.
Thanks!

A: Assuming SQL Server:
DECLARE @string VARCHAR(17) = '20120301-20120331';

SELECT
    CONVERT(DATETIME, LEFT(@string, 8)),
    CONVERT(DATETIME, RIGHT(@string, 8));

From a table:
SELECT
    CONVERT(DATETIME, LEFT(column_name, 8)),
    CONVERT(DATETIME, RIGHT(column_name, 8))
FROM dbo.table_name;


text:
Q: Librosa.display immediately disappears I am following some example code from Librosa documentation in order to display a spectrogram of a STFT. The problem is that the spectrogram never appears, when I run the program in a terminal window, I briefly see a program launch (the same as would launch on a call to plt.show()) but it disappears immediately.
Do I need to explicitly call a method to show the img object in the code below? If not, what could be causing the plot to not show?
# read the .wav file
audio, sample_rate = librosa.load("/Users/user/Desktop/voice.wav")

# perform stft using librosa module
audio_stft_1000 = np.abs(librosa.stft(audio, n_fft=1000))
audio_stft_3000 = np.abs(librosa.stft(audio, n_fft=3000))

# create plots according to docs linked above
fig, ax = plt.subplots()

img = librosa.display.specshow(librosa.amplitude_to_db(audio_stft_1000,
                                                       ref=np.max),
                               y_axis='log', x_axis='time', ax=ax)

ax.set_title('Power spectrogram')
fig.colorbar(img, ax=ax, format="%+2.0f dB")

A: Very simple solution:
plt.show()


text:
Q: Validating AWS Cognito JWT in a ASP.NET Core 6 gRPC service The JWT (id) token provided by AWS cognito is not passing token validation on my gRPC service, I keep getting unauthenticated as the response.
Does this have something to do with the default JwtBearer options?
gRPC service Program.cs:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder();

builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenLocalhost(5000, o => o.Protocols = HttpProtocols.Http2);
});

builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_bX1jng7q2",
        ValidateIssuerSigningKey = true,
        ValidateIssuer = true,
        ValidateLifetime = true,
        ValidAudience = "2c744fhbdu94inn8u4sv4kg0ft",
        ValidateAudience = true,
        RoleClaimType = "cognito:groups"
    };
    options.MetadataAddress = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_bX1jng7q2/.well-known/openid-configuration";
});

builder.Services.AddAuthorization();
builder.Services.AddGrpc();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.MapGrpcService<GreeterService>();

app.Run();

Client:
try
{
    var greeterClient = new Greeter.GreeterClient(channel);

   // id token
    string id_token = "eyJraWQiOiJ4Qkk0MUNXYjdPUGtROGk2RWlhK1hQWlpjZ0ZcL0dOSFIwbFYyTTdLNVJhND0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI4M2FhY2U1Mi05NTJjLTQyMmEtODdkYy1iOWI1MDkyNGNmYjkiLCJjb2duaXRvOmdyb3VwcyI6WyJBZG1pbiJdLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaXNzIjoiaHR0cHM6XC9cL2NvZ25pdG8taWRwLnVzLWVhc3QtMS5hbWF6b25hd3MuY29tXC91cy1lYXN0LTFfYlgxam5nN3EyIiwiY29nbml0bzp1c2VybmFtZSI6IjgzYWFjZTUyLTk1MmMtNDIyYS04N2RjLWI5YjUwOTI0Y2ZiOSIsIm9yaWdpbl9qdGkiOiI0MzQyZWJmNi0zYzQ4LTQ1YjEtODY1NC1kYTg1ZDQ1OGMyMDMiLCJhdWQiOiIyYzc0NGZoYmR1OTRpbm44dTRzdjRrZzBmdCIsImV2ZW50X2lkIjoiMDgyZDNlZDQtZTJlNy00OGRhLWJjOWYtZjgzMjY5NjAxZmQ0IiwidG9rZW5fdXNlIjoiaWQiLCJhdXRoX3RpbWUiOjE2NDg3MjgwMzgsImV4cCI6MTY0ODczMTYzOCwiaWF0IjoxNjQ4NzI4MDM4LCJqdGkiOiJkNzdlZTM3Yi1iMjA3LTRlZDctOTU3ZS1hY2E0OWE1ZmU0YWMiLCJlbWFpbCI6InNoYW1lZWwuZmF6dWxAbWFpbC5jb20ifQ.acGpo3owsd7gEvRtSTCijcRoIz4MP4MN8JUxBgM8mD8Oo-LBQam2uM2NxTtEygfx6MIWJMc9tNylv4GMm53bdrqBXCFeuYGiCdvdP4FvdFKkgwBV6Bzw7t0orN-P0zyrouDKW4NWIz2lUBvaOWE8j_fSdMhSsOlbbByDZH6mrNgugSWIXaF_frwIn2SjhMPnK4VO07uTdXMBiGvgkWH0JJidlU_vc9hjU33f";

// access token
    string access_token = "eyJraWQiOiJPOWlVVWpWVjkrTTdZMXE4c0dieG9RWTNrUXB4S3oyNEZXbERiekN2Nm5zPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiI4M2FhY2U1Mi05NTJjLTQyMmEtODdkYy1iOWI1MDkyNGNmYjkiLCJjb2duaXRvOmdyb3VwcyI6WyJBZG1pbiJdLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtZWFzdC0xLmFtYXpvbmF3cy5jb21cL3VzLWVhc3QtMV9iWDFqbmc3cTIiLCJjbGllbnRfaWQiOiIyYzc0NGZoYmR1OTRpbm44dTRzdjRrZzBmdCIsIm9yaWdpbl9qdGkiOiIyNTBlNDAzMi1lNmE1LTQwMzYtOWMyMC1hZDhmNTBjYTk1YjUiLCJldmVudF9pZCI6ImE4YmZhYWJlLTBkMjYtNDYzNC04M2YwLWM2YTc5OWM4YTEzZiIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiYXdzLmNvZ25pdG8uc2lnbmluLnVzZXIuYWRtaW4iLCJhdXRoX3RpbWUiOjE2NDkwNjMxOTAsImV4cCI6MTY0OTA2Njc5MCwiaWF0IjoxNjQ5MDYzMTkwLCJqdGkiOiI0YzhlYjg3OC04OTM0LTRkNTAtYWM2ZS0wZDZkYmYwNDY3YjYiLCJ1c2VybmFtZSI6IjgzYWFjZTUyLTk1MmMtNDIyYS04N2RjLWI5YjUwOTI0Y2ZiOSJ9.NTMlSa2xpQvMrmzqWYjK6449G9Hvp97JqhjsSE7dmNY5lo62XypyEpji6mCFCWlyD-b6om0mHmYNNknrG0UuD5dodMEI9AHK2u42jxzeQEndwkIEY827VUAOlHztdO3F4rsvT_P0TZmj4_3CvOladmd9KlW8ppWK5ZoFWUFniaFJOxUdfi6A-lBnJX2TxL1eEvLrLs6M5-HBOWLi8AekMsCc0aUrHPVzVTi9LUIjGXWmd6IkiG6HikC";

    var headers = new Metadata();
    headers.Add("Authorization", $"Bearer {access_token}");

    var greeterResponse = await greeterClient.SayHelloAsync(new HelloRequest { Name = "John Doe" }, headers);

    Console.WriteLine("Response Recieved: {0}", greeterResponse.Message);

}
catch (RpcException ex)
{
    Console.WriteLine("{0} :: {1}", ex.StatusCode, ex.Message);
}

Exception: System.Exception: Status(StatusCode="Unauthenticated", Detail="Bad gRPC response. HTTP status code: 401")
---> Grpc.Core.RpcException: Status(StatusCode="Unauthenticated", Detail="Bad gRPC response. HTTP status code: 401")

Also, just so you know, this is just a test pool and the ids listed above are not sensitive as mentioned here

A: Use TokenValidationParameters.IssuerSigningKeyResolver:
builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKeyResolver = async (s, securityToken, identifier, parameters) =>
    {
        // get JsonWebKeySet from AWS
        ConfigurationManager<OpenIdConnectConfiguration> configurationManager =
                    new ConfigurationManager<OpenIdConnectConfiguration>(parameters.ValidIssuer + "/.well-known/jwks.json", new OpenIdConnectConfigurationRetriever());
                OpenIdConnectConfiguration openIdConnectConfiguration = await configurationManager.GetConfigurationAsync(CancellationToken.None).ConfigureAwait(false);
        return openIdConnectConfiguration.SigningKeys;
    },
        ValidIssuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_bX1jng7q2",
        ValidateIssuerSigningKey = true,
        ValidateIssuer = true,
        ValidateLifetime = true,
        ValidAudience = "2c744fhbdu94inn8u4sv4kg0ft",
        ValidateAudience = true,
        RoleClaimType = "cognito:groups"
    };
});

Or the raw way:
builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
    {
        // get JsonWebKeySet from AWS
        var json = new WebClient().DownloadString(parameters.ValidIssuer + "/.well-known/jwks.json");
        // serialize the result
        var keys = JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
        // cast the result to be the type expected by IssuerSigningKeyResolver
        return (IEnumerable<SecurityKey>)keys;
    },
        ValidIssuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_bX1jng7q2",
        ValidateIssuerSigningKey = true,
        ValidateIssuer = true,
        ValidateLifetime = true,
        ValidAudience = "2c744fhbdu94inn8u4sv4kg0ft",
        ValidateAudience = true,
        RoleClaimType = "cognito:groups"
    };
});

See more: How to validate AWS Cognito JWT in .NET Core Web API using .AddJwtBearer()

A: In .NET 6 =>
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
                    {
                        var keys = new HttpClient().GetFromJsonAsync<JsonWebKeySet>(parameters.ValidIssuer + "/.well-known/jwks.json");
                        return (IEnumerable<SecurityKey>)keys;
                    },
                    ValidIssuer = "https://cognito-idp.{REGION}.amazonaws.com/{USER_POOL_ID}",
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateLifetime = true,
                    ValidAudience = "{APP_CLIENT_ID}",
                    ValidateAudience = true
                };
            });

A: This is what worked for me on .NET 6
I created an extension method
public static async Task AddAuthenticationSupport(this IServiceCollection services, ConfigurationManager configurationManager)
{
    var validIssuer = configurationManager["ModuleConfiguration:Infrastructure:Cognito:ValidIssuer"];
    var validAudience = configurationManager["ModuleConfiguration:Infrastructure:Cognito:ClientId"];

    var httpClient = new HttpClient();
    var webKeySetJson = await httpClient.GetStringAsync($"{validIssuer}/.well-known/jwks.json");

    services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
                    {
                        var jsonWebKeySet = new JsonWebKeySet(webKeySetJson);
                        return jsonWebKeySet?.GetSigningKeys();
                    },
                    ValidIssuer = validIssuer,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    AudienceValidator = (audiences, securityToken, validationParameters) =>
                    {
                        //This is necessary because Cognito tokens doesn't have "aud" claim. Instead the audience is set in "client_id"
                        var castedToken = securityToken as JwtSecurityToken;
                        var clientId = castedToken?.Payload["client_id"]?.ToString();
                        return validAudience.Equals(clientId);
                    }
            };
            });

    services.AddAuthorization();
}

and then just added the following line on Program.cs
await builder.Services.AddAuthenticationSupport(builder.Configuration);

A: By searching for the error message, it is obvious that there is a problem with the token value, which causes the verification to fail.
And the most important point, when I read the post, I ignored the id token you use to access the service. I'm familiar with Azure AD and I think you should use an access token to access.This should be the key to solving this problem.

A: Like Leo reported... but you don't need to download the jwks.json
 services.AddAuthentication(o =>
    {
        o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
    {
        var awsOptions = config.GetSection("AWS").Get<AWSOptions>();

        var validIssuer = string.Format("https://cognito-idp.{0}.amazonaws.com/{1}", awsOptions.RegionId, awsOptions.UserPoolId);

        options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();

        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = validIssuer,
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateLifetime = true,
            ValidateAudience = true,
            RoleClaimType = "cognito:groups",
            AudienceValidator = (audiences, securityToken, validationParameters) =>
            {
                //This is necessary because Cognito tokens doesn't have "aud" claim. Instead the audience is set in "client_id"
                var castedToken = securityToken as JwtSecurityToken;
                var hasAud = castedToken.Claims.Any(a => a.Type == "client_id" && a.Value == awsOptions.ClientId);
                return hasAud;
            }

        };
        //for debugging
        // options.Events = new JwtBearerEvents()
        // {
        //     OnTokenValidated = async (v) =>
        //   {
        //       return;
        //   },
        //     OnForbidden = async (forbiddenContext) =>
        //     {
        //         System.Diagnostics.Debug.Write(forbiddenContext.ToString());
        //     },

        //     OnAuthenticationFailed = async (AuthenticationFailedContext ctx) =>
        //   {
        //       System.Diagnostics.Debug.Write(ctx.Exception.ToString());
        //       var t = new Random().Next();
        //       var ex = ctx.Exception;
        //   }
        // };

        options.Authority = validIssuer;
        options.Audience = awsOptions.ClientId;

    });
    services.AddAuthorization();


text:
Q: awk script to return results recursively I have a data set as below (t.txt):
827 819
830 826
828 752
752 694
828 728
821 701
724 708
826 842
719 713
764 783
812 820
829 696
697 849
840 803
752 774

I have second file as below (t1.txt):
752
728
856
693
713
792
812
706
737
751
745

I am trying to extract column 2 elements of the second file from the first data set using a for loop.
I have tried :
for i in `cat t1.txt`
do
awk -F " " '$1=i {print $2}' t.txt > t0.txt
done

Desired output is :
694
820
774

Unfortunately I am getting a blank file.
I have tried to do it manually like : awk -F " " '$1==752 {print $2}' t.txt > t0.txt
Results obtained are
694
774

How can I do it for the entire t1 file in one go?

A: Simplest way: using join
$ join -o 1.2 <(sort t.txt) <(sort t1.txt)
694
774
820

join requires the files to be lexically sorted on the comparison field (the default field one). The -o option instructs join to output the 2nd field from the 1st file.
With awk
$ awk 'NR==FNR {key[$1]; next} $1 in key {print $2}' t1.txt t.txt
694
820
774

That remembers the keys in t1.txt, then loops over t.txt (when the accumulated record number NR is not equal to the file's record number FNR), if the first field occurred in t1, print the second field.


text:
Q: Java httpServer basic authentication for different request methods I'm using a very simple httpServer in Java for an api rest with GET, POST, PUT and DELETE. I'm using Basic Authentication and I have a couple classes Authentication.java and Authorisation.java which I use to authenticate and check permissions for the users.
So, the thing is that I want all users (authenticated) to be able to GET information from my api rest, but only users with certain privileges to be able to POST, PUT and DELETE. So how can I do that?
This is what I got
public class Server {

  private static HttpServer server;

  public static void start() throws IOException {

    server = HttpServer.create(new InetSocketAddress(8000), 0);
    HttpContext ctx = server.createContext("/users", new UserHandler());
    ctx.setAuthenticator(new ApiRestBasicAuthentication("users"));

    server.start();
  }

}

And this is my ApiRestBasicAuthentication
public class ApiRestBasicAuthentication extends BasicAuthenticator {

  private UserAuthentication authentication = new UserAuthentication();

  public ApiRestBasicAuthentication(String realm) {
    super(realm);
  }

  @Override
  public boolean checkCredentials(String user, String pwd) {
    int authCode = authentication.authenticate(user, pwd);
    return authCode == UserAuthentication.USER_AUTHENTICATED;
  }

}

As this is now, check credentials is only checking if the user is authenticated.
But I'd like to check, if the method is POST, DELETE or PUT I should also check the specific credentials. But how can I get the method in my ApiRestBasicAuthentication? I'm doing that in my handler class
public void handle(HttpExchange httpExchange) throws IOException {
    String method = httpExchange.getRequestMethod();
    if ("post".equalsIgnoreCase(method)) {
      createUser(httpExchange);
    } else if ("get".equalsIgnoreCase(method)) {
      readUsers(httpExchange);
    } else if ("put".equalsIgnoreCase(method)) {
      updateUser(httpExchange);
    } else if ("delete".equalsIgnoreCase(method)) {
      deleteUser(httpExchange);
    }
  }

Maybe this is supposed to be done some other way.
Any ideas?
Many thanks.

A: A simple way to do it would be to change your
ApiRestBasicAuthentication  like:
public class ApiRestBasicAuthentication extends BasicAuthenticator {

  private UserAuthentication authentication = new UserAuthentication();

  public ApiRestBasicAuthentication(String realm) {
    super(realm);
  }

  @Override
  public Authenticator.Result authenticate(HttpExchange exch) {
      Authenticator.Result result=super.authenticate(exch);
      if(result instanceof Authenticator.Success) {
          HttpPrincipal principal=((Authenticator.Success)result).getPrincipal();
          String requestMethod=exch.getRequestMethod();
          if( ADD SOME LOGIC HERE FOR PRINCIPAL AND REQUEST METHOD) {
              return new return new Authenticator.Failure(401);
          }
          return result;

      }
  }

  @Override
  public boolean checkCredentials(String user, String pwd) {
    int authCode = authentication.authenticate(user, pwd);
    return authCode == UserAuthentication.USER_AUTHENTICATED;
  }

}

And add some logic there for requests/users that you want to fail the authenticator. I have shown you here how to get the method in the authenticate method but you need to specify the types of credentials.

Another solution would be if you check the source code of BasicAuthenticator you can see how it implements authenticate method and you can create your own implementation in a similar way instead of extending BasicAuthenticator and use the get method instead of just the username and password. You can see the source code here and I am sure you will be able to find your way around ;)
Usually in enterprise application you can use some external security management system - for example if you use Spring (the de facto standard in the current java web apps) you can use spring security and do such security patterns and filters in a more declarative way

A: While the above answers might be valid for you, I think you should also consider using defined roles and security-constraints which can be defined in your web.xml and used in the REST Resource using @RolesAllowed annotation. This then allows you to specifically allow permissions for methods individually or at the REST resource/class level.
In web.xml, this looks something like this:-
<security-role>
        <role-name>SERVERTOSERVER</role-name>
    </security-role>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>REST API description</web-resource-name>
            <url-pattern>/<path name>/*</url-pattern>
            <http-method>GET</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description>Only allow users
        from following roles</description>
            <role-name>SERVERTOSERVER</role-name>
        </auth-constraint>
    </security-constraint>

The following links have some examples: Purpose of roles tags in tomcat-users.xml? ,
https://www.thecoderscorner.com/team-blog/hosting-servers/17-setting-up-role-based-security-in-tomcat/
In case helpful, here is another type of solution for a Jersey based application:  https://howtodoinjava.com/jersey/jersey-rest-security/

A: There might be many ways to solve this issue. Here is one of my proposal:

*

*Create a User Object with fields that you want and one field called something like "role". Lets say only "admins" are allowed to do make Http requests other than "GET" while "regular" users can only do "GET". Many ways to do this but one way is to make the "role" field String and assign values to it using an ENUM, so that it's easy to change later and only specific terms are used. But you don't have to do that. Write get and set method for the fields you create and that you might need later, and definitely for role.

*You need to make sure that class containing the handle(HttpExchange httpExchange) is able to see the currently logged in user, and refer to the User object associated with them. Then you need to modify the method so that

if(loggedInUser.getRole().equals("admin")){
  //allow whatever method
} else {
  // allow "GET" or give some denied permission error
}

Since other implementations have not been provided, I can't give a more detailed answer or be sure that this will work for you.

A: I think what you should create an AuthenticationInterceptor and by-pass GET the requests there and correspondingly apply authentication mechanism for rest non-GET requests.
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  private ApiRestBasicAuthentication apiRestBasicAuthentication;

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    switch (request.getMethod()) {
      case "GET" :
        // by-passing all GET requests
        return true;

      default :
        return apiRestBasicAuthentication.checkCredentials(username, password);
    }
  }

}


text:
Q: How to apply css style to popup title element of label I have a form label as follows:
Email Address: *

I want to apply a different style to my popover 'title' element (#000).
Not the 'Email Address:' label that shows on the form (which is #fff).
Thought I may be able to do the following, but it doesn't work:
label#jform_email-lbl[type="title"] {
    color: #000;
}

****EDITED**
The answer is as follows - for anyone else trying to find the right css:**
div.tip .tip-title {
   color: #E77600 !important;
   font-weight: bold;
}
div.tip .tip-text {
   color: #979797 !important;
   font-weight: bold;
}

A: Later edit, i understood the question :
<!DOCTYPE html>

Email Address: *


text:
Q: Volume of spheres in higher dimensions? What is the volume of spheres in higher dimensions?

A: Let $\kappa_n$ be the volume of the unit $n$-sphere $B_n$ and write the points of $B_n$ in the form $(x,y,{\bf z})$ with ${\bf z}\in{\mathbb R}^{n-2}$. For given $(x,y)\in B_2$ one has $|{\bf z}|^2\leq 1-r^2$, where $r:=\sqrt{x^2+y^2}$. These ${\bf z}$ fill an $(n-2)$-sphere of radius $\sqrt{1-r^2}$, and the $(n-2)$-dimensional volume of this sphere amounts to $\kappa_{n-2}(1-r^2)^{(n-2)/2}$. Therefore we get $$\kappa_n=\int_{B_2}\kappa_{n-2}(1-r^2)^{(n-2)/2}{\rm d}(x,y)=2\pi \kappa_{n-2}\int_0^1 (1-r^2)^{(n-2)/2}\>r\>dr={2\pi\over n}\>\kappa_{n-2}\ .$$
By means of this this recursion formula and using the known values $\kappa_1=2$, $\kappa_2=\pi$ one easily obtains the $\Gamma$-formula quoted in other answers.

A: $$V_n = \frac{\pi^{n/2}}{\Gamma(n/2+1)}$$
As posted earlier here.

A: Did you try the obvious?

A: Start with an unrelated integral
$$I = \int_{-\infty}^\infty \cdots \int_{-\infty}^\infty e^{(-x_1^2+x_1^2+\cdots x_n^2) } dx_1 dx_2 \cdots dx_n = \pi^{n/2}$$
This should be easy to easy if you notice that this can be factored as a product of n integrals each in the variable $x_i$ and that $\int_{-\infty}^\infty e^{-x^2}dx =\sqrt{\pi}$
Now try to calculate the same integrate by making a change to polar coordinates. These new coordinates will have one $r$ coordinate and $n-1$ angular coordinates $\{\theta_i\}$
$$I = \int e^{(-x_1^2+x_1^2+\cdots x_n^2) } dV_n =$$
To express the volume element in the new coordinates you can either use inference from lower dimensions (or if you're a physicist, a dimensional argument) and say that $$V = C_n r^n \Rightarrow dV_n = nC_n r^{n-1}dr$$
or you can explicitly compute the Jacobian to show that $|J(r,\theta_1,\cdots,\theta_n)|= r^{n-1} \cos^{n-2}\theta_1\cos^{n-3}\theta_2 \cdots \cos \theta_{n-2} $
so
$$I = \int_0^\infty e^{-r^2} nC_nr^{n-1} dr = C_n\frac{n}{2} \Gamma (\frac{n}{2}) = C_n\left(\frac{n}{2}\right)! $$
$$ C_n = \frac{\pi^{n/2}}{\left(\frac{n}{2}\right)!} $$
$$V_n =  \frac{\pi^{n/2}}{\left(\frac{n}{2}\right)!}  r^n$$
on a sidenote, you also get the surface area from $dV_n = S_n(r) dr$
$$S_n(r)= \frac{(2\pi)^{n/2}}{\Gamma (\frac{n}{2})} r^{n-1}$$


text:
Q: How to Add a filter to single.php only in wordpress? I want to add nofollow rel to tag cloud on single post only. This function code in functions.php works fine but I couldn't figure it out how to restrict it to single.php only.
function szub_nofollow_tag($text) {
return str_replace('<a href=', '<a rel="nofollow" href=',  $text);
}

add_filter('wp_tag_cloud', 'szub_nofollow_tag');

Could you please tell me how to do it??

A: http://codex.wordpress.org/Function_Reference/is_singular
Should do the trick, remember to use it inside the function itself as I don't think WordPress knows if it's true/false while parsing functions.php
function szub_nofollow_tag($text) {
    if ( is_singular() )
        return str_replace('<a href=', '<a rel="nofollow" href=',  $text);
    else
        return $text;
}

add_filter('wp_tag_cloud', 'szub_nofollow_tag');


text:
Q: Embedding in Keras Which algorithm is used for embedding in Keras built-in function?
Word2vec? Glove? Other?
https://keras.io/layers/embeddings/

A: The short answer is neither. In essence, an embedding layer such as Word2Vec of GloVe is just a small neural network module (fully-connected layer usually) that projects higher, sparse dimensionality into a lower, n-dimensional vector.
When you insert a fresh random embedding layer in Keras into your neural network, Keras will construct a dense learnable matrix of shape [input_dim, output_dim].
Concretely, let's say that you're inserting an Embedding layer to encode integer scalar month information (12 unique values) into a float vector of size 3. In Keras, you're going to declare your embedding as follows:
import numpy as np
import keras
from keras.models import Sequential, Model
from keras.layers import Embedding, Input
x = Input(shape=(1000,)) # suppose seq_len=1000
embedding = Embedding(12+1, 3, input_length=1000)(x)
model = Model(inputs=x, outputs= embedding) # Functional API
model.summary()

Your embedding layer would have a summary as follows:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 1000)              0
_________________________________________________________________
embedding_1 (Embedding)      (None, 1000, 3)           39
=================================================================
Total params: 39
Trainable params: 39
Non-trainable params: 0
_________________________________________________________________

Notice that the learnable parameters are 39 = 13*3 (the +1 is needed by Keras to encode values that don't belong to any of the 12 unique months - just in case).
Also notice that while the input shape to embedding is shaped (None, 1000), the output of the embedding is shaped (None, 1000, 3). This means the very small dense weight matrix of size [13, 3] is applied to each of the 1000 input time-steps. Which means, every month integer input of 0-11 will be converted into a float vector of size (3,).
This also means that when you do backpropagation from the final layer into the embedding layer, the gradient to each of the 1000 time-steps embedding output will also flow (in a time_distributed manner) to the small neural network weights (which is, essentially, the embedding layer) of size [13,3].
Please also refer to official Keras documentation for Embedding layer: https://keras.io/layers/embeddings/.

A: None of the above. It is by default initialised randomly embeddings_initializer='uniform'.
There is a tutorial on how to use existing embeddings.


text:
Q: Scale Everything On Pygame Display Surface So I'm making a 2D pixel art game in pygame and as you could assume, all my sprite textures appear very small. I'm wondering if there's a way I can globally scale everything up in my game without either having to scale each sprite up individually or messing up the coordinates. Every sprite will move on a grid: one unit is 16x16 pixels and when my player sprite moves, for example, it will just move over in a direction 16 pixels.
Here's my main script:
import sys
from pygame.locals import *
import pygame

from game.sprites import Ghost

pygame.init()

WINDOW_WIDTH = 640
WINDOW_HEIGHT = 640
DES_WIDTH = 64
DES_HEIGHT = 64

COL_BG = (46, 48, 55)
COL_FG = (235, 229, 206)

X = 1000
Y = 1000

win = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Through The Doors")

running = True
paused = False

# INITIALIZE SPRITES
player = Ghost()

all_sprites = pygame.sprite.Group()
all_sprites.add(player)

clock = pygame.time.Clock()

while running:
    clock.tick(30)

    if not paused:
        win.fill(COL_BG)
        all_sprites.update()
        all_sprites.draw(win)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    keys = pygame.key.get_pressed()

    if keys[pygame.K_RIGHT]:
        player.go_right()
    elif keys[pygame.K_LEFT]:
        player.go_left()
    elif keys[pygame.K_UP]:
        player.go_up()
    elif keys[pygame.K_DOWN]:
        player.go_down()

    pygame.display.flip()

pygame.quit()

I do have more sprites I am going to load in, but I would like to resolve the scaling issue first.

A:
I'm wondering if there's a way I can globally scale everything up in my game without either having to scale each sprite up individually [...]"

No there is no way. You have to scale each coordinate, each size and each surface individually. PyGame is made for images (Surfaces) and shapes in pixel units. Anyway up scaling an image will result in either a fuzzy, blurred or jagged (Minecraft) appearance.

Is there a way I could make a separate surface and just put that on top of the base window surface, and just scale that?

Yes  of course.
Create a Surface to draw on (win). Use pygame.transform.scale() or pygame.transform.smoothscale() to scale it to the size of the window and blit it to the actual display Surface (display_win):
display_win = pygame.display.set_mode((WINDOW_WIDTH*2, WINDOW_HEIGHT*2))
win = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT))

while running:
    # [...]

    if not paused:
        win.fill(COL_BG)
        all_sprites.update()
        all_sprites.draw(win)

    # [...]

    scaled_win = pygame.transform.smoothscale(win, display_win.get_size())
    # or scaled_win = pygame.transform.scale(win, display_win.get_size())
    display_win.blit(scaled_win, (0, 0))
    pygame.display.flip()

Minimal example:  repl.it/@Rabbid76/PyGame-UpScaleDisplay


text:
Q: Evaluate the integral: $\int_{0}^3\frac{dx}{5x+1}$ $\int_{0}^3\frac{dx}{5x+1}$
So I cannot evaluate this integral because we do not have any rules for taking the anti-derivative of a quotient of functions. Thus, we need to separate this into two separate fractions before we can take the anti-derivative.
How do we do this?
$\frac{1}{5x+1}$ I can't transfer the binomial to the top unless I can do the following, and if so please make me aware that I am right.
$\frac{(5x+1)^{-1}}{1}$
Is this "illegal math"

A: A minor point: It is unnecessary to write $\frac{(5x+1)^{-1}}{1}$ with a $1$ in the denominator. For any number $a$ it is always true that $a = \frac{a}{1}$ so we write simply $(5x+1)^{-1}$.
As for your main question, you probably know by know that you should make the substitution $5x+1 = t$. You are correct that there is no specific rule to integrate the quantity that you have. So what you want to do is pattern-match what you have to an integral form that you recognize. Ideally you recall that the derivative of $\ln(x)$ is $\frac{1}{x}$, and in that capacity you recognize the integral $\int \frac{1}{x} \text{d}x$. This is why the substitution $5x+1 = t$ is useful, because it converts your problem into one that you can easily anti-differentiate. Plugging in this substitution yields $$\int_0^3 \frac{1}{t} \text{d}x$$ but before continuing there are still two things to address. $(1)$ We need $\text{d}t$ not $\text{d}x$, as we are now trying to integrate with respect to $t$, and $(2)$ the integral limits from $0$ to $3$ were meant for your original quantity, not your substituted quantity. These will need to change to match your $t$ substitution.
Getting $\text{d}t$ is pretty easy. Take $5x+1 = t$ and differentiate both sides. You'll get $$5\text{d}x = 1\text{d}t \implies \text{d}x = \frac{1}{5}\text{d}t$$
For the new limits again take $5x+1 = t$. When $x = 0$ we have $5(0) +1 = t \implies t = 1$ and when $x = 3$ we have $5(3)+1 = t \implies t = 16$, so your new limits of integration are from $1$ to $16$. We now have everything we need to set up the new integral. $$\begin{align} \int_0^3 \frac{1}{5x+1}\text{d}x &\equiv \int_1^{16} \frac{1}{t}\left(\frac{1}{5}\text{d}t\right) \\ &= \frac{1}{5} \int_1^{16} \frac{1}{t}\text{d}t \end{align}$$
If this process is new to you, take note. It's (probably) the most common method you will use to solve integrals: Pattern-match your integral to one that you know how to anti-differentiate, make a substitution, solve for your infinitesimal in terms of the substitution, solve for the new limits of integration and lastly integrate.

A: Notice, let $5x+1=u\implies 5dx=du$ $$dx=\frac{du}{5}$$
For lower limit $x=0\implies u=5(0)+1=1$
For upper limit $x=0\implies u=5(3)+1=16$
Now, substituting the corresponding values, we get
$$\int_{0}^{3}\frac{dx}{5x+1}=\int_{1}^{16}\frac{1}{u}\frac{du}{5}$$
$$=\frac{1}{5}\int_{1}^{16}\frac{du}{u}$$ $$=\frac{1}{5}[\ln|u|]_{1}^{16}$$
$$=\frac{1}{5}[\ln|16|-\ln|1|]=\frac{1}{5}[\ln|16|-0]$$ $$=\color{}{\frac{1}{5}\ln(16)}=\color{}{\frac{1}{5}\ln(2^4)}$$ $$=\color{red}{\frac{4}{5}\ln 2}$$

A: Hint:
with the substitution $5x+1=t$ you have $5dx=dt$ and the integral becomes:
$$
\int \dfrac{1}{5}\cdot \dfrac{dt}{t}
$$
can you integrate?

A: Let $5x+1 = t\;,$ Then $d(5x+1) = dt\Rightarrow \displaystyle \frac{d}{dx}(5x+1)dx = dt$
So we get $$\displaystyle 5dx=dt\Rightarrow dx = \frac{1}{5}dt$$ and changing limit
We get $$\displaystyle \frac{1}{5}\int_{0}^{16}\frac{1}{t}dt = \frac{1}{5}\left[\ln |t|\right]_{1}^{16} = \frac{1}{5}\left[\ln|16|-\ln|1|\right] = \frac{1}{5}\ln(16)$$

A: No it isn't illegal to do that, it is the same thing.  To solve sub $u=5x+1$ then $du=5dx$ which means $1/5du=dx$  Your integral becomes $\frac 1 5\int_{1}^{16}\frac{du}{u}$ and use the fact that $\int\frac {du} u=ln x$, should be absolute value of x in that last expression.


text:
Q: Schedule deployment change set I have the need to make a changeset once a week from develpment enviroment to test enviroment. Is it possible to schedule this action?
I would like to create a batch job to do this but I can't find anything about that. Any suggestion?
Thanks in advance.

A: You can use the Force.com Migration Tool (ant) and write a small script to do this.
The steps would be:

*

*ant retrieve from the source org

*ant deploy to the target org

You would need somewhere to run this, such as Jenkins or Travis or anywhere that allowed you to run a recurring task.
The issue you are likely to encounter is what kind of metadata you want to move and what clashes will occur. Think of things like Assignment Rules with specific users mentioned that don't exist in the target or Profiles that refer to packages that exist in one org but not the other.
There are commercial offerings, like the company I run, which will do this for you. Check out Gearset if you want to move the burden of this process to somebody else, but there are others that will do it and you can roll it yourself using Jenkins and ant


text:
Q: When I used the lookup tool on this it came back as malware, can anyone confirm that for me? My phone is is not working quite right, it's slow, the battery is crap all of a sudden and weird things are going on. Apps that I had previously deleted showing back up. Old accounts coming back. Deleted texts showing back up. I have an Apple ID that I have never used, my ex tried to set it up behind my back to mess with me but he's not real bright and couldn't do it, but he got far enough that I've been stuck with it and never able to use it, and all of a sudden it's receiving email, my email. So, I ran a system diagnostic, actually a few of them, and I know enough that I can tell there's something going on I just don't know what exactly.
I uploaded the files to iCloud and opened them on my Mac intending to run on that and when I tried to open one it froze and and after a day of it telling me there were no safari windows and if I wanted the I had to position them myself, which I don't even understand let alone know how to do. So just hot that back today finally.
The following is an excerpt from the security diagnostic file:
modelid : iPhone11,8,     inHeartbeatWindow : 0,      staticKeyEnforced : 0, peerRecentlyOptedIn : 0, ktCapable : 0, build : 20D67, inResetWindow : 0, transparencyVersion : 54, failure : {
code = "-238";
domain = TransparencyErrorVerify;
}, ktSoftFailure : 1, errorCode : -238, product : iPhone OS, ktEnvironment : 0, errorDomain : TransparencyErrorVerify, peerEverOptedIn : 0 }
2023-02-21 20:28:01 +0000 EventSoftFailure:      `your text`ktIDSValidatePeerCompleteEvent - Attributes: {peerOptIn : 0, selfOptInChangeDate : -1, selfOptIn : 0, sldd : (


text:
Q: In Google Analytics, how can I find top 5 days sorted by number of visitors? Is there an easy way of finding the 5 most visited days?
I want a report on this format:

Date         Visitors
dd-mm-yyyy   320
dd-mm-yyyy   301
dd-mm-yyyy   256
dd-mm-yyyy    99

A: Since apparently only programming questions are allowed, here is the needed API call to retrieve the data programmatically:
https://www.googleapis.com/analytics/v3/data/ga?ids=gaXXX&start-date=2016-01-01&end-date=today&metrics=ga%3Ausers&dimensions=ga%3Adate&sort=-ga%3Ausers&max-results=5
Demo can be seen in the Query Explorer


text:
Q: How do I make Chef wait for the app deployment before moving files? I have the following Chef recipe
aws_s3_file "/usr/share/tomcat/webapps/system.war" do
  bucket "mybucket"
  remote_path "builds/system_latest.war"
  aws_access_key_id node[:aws_access_key_id]
  aws_secret_access_key node[:aws_secret_access_key]
end

service "tomcat" do
  action [:restart]
end

aws_s3_file "/usr/share/tomcat/webapps/system/WEB-INF/application.properties" do
  bucket "mybucket"
  remote_path "config/application.properties"
  aws_access_key_id node[:aws_access_key_id]
  aws_secret_access_key node[:aws_secret_access_key]
end

It works fine every time I run it, except if the machine is a fresh one.
When it is a fresh machine, I get:

Errno::ENOENT
  ------------- No such file or directory - /usr/share/tomcat/webapps/system/WEB-INF/application.properties

I think that it happens because tomcat is not done deploying the application, so the folder does not exist when this statement is run.
I imagine that moving files around when an application is deployed is a normal procedure. How can I do that and guarantee that Chef is going to wait until the deploy is done?

A: Write some code (probably in either Ruby or Bash) to query if Tomcat is done, when put it in a while loop.
ruby_block 'wait for tomcat' do
  block do
    true until ::File.exists?('/usr/share/tomcat/webapps/system/WEB-INF')
  end
end


text:
Q: Is possible to get facebook user access token without user interaction? I want that my Php script (myscript.php ) that i have deployed on a public host gets the Facebook user access token (with my facebook account) from Facebook. I don't want user interaction with login procedure where to inser user and pass. Is it possibile and how can be made? I understand the SDK is not useful for this scenario.
For now my script is:

    require_once ('../php-graph-sdk-5.x/src/Facebook/autoload.php');

    $fb = new \Facebook\Facebook([
    'app_id' => 'myappid',
    'app_secret' => 'mysecret',
    'default_graph_version' => 'v2.10',]);

    $helper = $fb->getRedirectLoginHelper();
    $accessTokenEntity=$helper->getAccessToken();
    try {
        $accessTokenEntity=$helper->getAccessToken();
        $response = $fb->get('/me', $accessTokenEntity->getValue());
     }

    catch (\Facebook\Exceptions\FacebookResponseException $e) {

    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
    }
     catch (\Facebook\Exceptions\FacebookSDKException $e)
        {
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
        }

    $me = $response->getGraphUser();
    echo 'Logged in as ' . $me->getName();

Copied from gitub example but i think it s not good for my scenario.
And the output is
"Fatal error: Call to a member function getValue() on null in ..."


text:
Q: Finding the position of a person on a grid, when you know the $(x,y)$ coordinates of transmitters and the signal strength at the person I have a $100\times100$ grid. I have a transmitter on each corner, $4$ in total.
$$\begin{array}{rl}\text{Transmitter (a) is at}&(0,0);\\
\text{(b) is at}&(100,0);\\
\text{(c) is at}&(0,100);\\
\text{(d) is at}&(100,100).\end{array}$$
The user is able to measure the signal power from each transmitter.
I need to determine roughly where the user is on the grid knowing that the power/distance from the user to...
$$\begin{array}{rl}\text{transmitter (b) is}&53\\
\text{transmitter (c) is}&51\\
\text{transmitter (d) is}&72\end{array}$$
There is a margin for error on the transmitter power/distance as I translate itf from decibels into distance on the grid: there is about a $20\%$ margin for error.
It's not important, but I translate the signal power to roughly $1$ unit of distance for argument's sake.
What is the equation I need to apply to these values to get a rough $(x,y)$ coordinate for the user?
Trying to remember back to when I was in school, I vaguely remember getting the points where circles intersect and averaging them out or something like that.

A: One approach is to consider this as a probabilistic inverse problem. It may be overkill for purely theoretical purposes where there is a geometric formula for the exact solution, but this is how I would do it in a real-world situation where there is uncertainty. The following framework is probably how it's actually done for real GPS devices.
Probabilistic/Bayesian theory:
Define things as follows:

*

*Call the unknown point location $p=(x,y)$,

*the measurement locations $m_1,m_2,m_3$, ($m_1=(x_{m1},y_{m1})$, etc)

*the measured distances $d=(d_1,d_2,d_3)$,

*and the measurement noise $\eta = (\eta_1,\eta_2,\eta_3)$.

Then the situation can be encapsulated via the following equation:
$$d=g(p)+\eta,$$
where $g(p):=(||m_1-p||,||m_2-p||,||m_3-p||)$. Based on measurements of $d$, we want to estimate $p$. The continuous density version of Bayes' theorem tells us that
$$f_P(p|d)=\frac{f_D(d|p)f_P(p)}{f_D(d)}.$$
Let's break down what this means piece by piece:

*

*$f_P(p|d)$ is the posterior probability density for your reciever to be at location $p$, taking into account that you measured the distances to be $d$.

*

*Our goal is to find either the whole distribution $f_P(p|d)$, or maybe just certain properties of it like the expected value, maximum liklihood point, variance, etc.

*The expected value and maximum liklihood point of the posterior $f_P(p|d)$ would be good "best guesses" for where the reciever is, and the variances would say how certain you are of that guess.

*$f_D(d|p)$ is the likelihood that you would measure a set of distances $d$ if the true reciever point was $p$, taking into account the noise.

*

*Considering a slight rearrangement of the model equation, $\eta=d-g(p)$, we can express the liklihood as
$$f_D(d|p)=\rho_{\eta}(d-g(p))$$
where $\rho_{\eta}$ is the probability distribution of the noise $\eta$.

*The noise distribution $\rho_\eta$ has to be modeled based on your knowledge of the measurement device - more on this later.

*$f_P(p)$ is the prior probability distribution on the reciever location - how likely you think it is to be in certain location before you even measure the distances.

*

*For example, if any location is as likely as any other, $f_P(p)$ would be a uniform distribution on the box.

*$f_D(d)$ is the prior probability distribution on the distance measurements $d$.

*

*Since $f_D(d)$ doesn't depend on $p$, it's basically just a normalization constant.

*Properties of $f_D(d)$ are important in theory to show that the bayesian framework is legitimate, but in practice you can just ignore it. It won't effect the mean, maximum liklihood point, variance, etc.

Now lets address the modeling issues mentioned above. It might be reasonable to say that the measurements are mean-zero normally distributed random variables with standard deviations $\sigma_1, \sigma_2,\sigma_3$ for the distance measurements $d_1, d_2$, and $d_3$ respectively, and the prior distribution is uniform on the box. Then the liklihood is,
$$f_D(d|p)=e^{-\sigma_1^{-2}(d_1-||m_1-p||)^2-\sigma_2^{-2}(d_2-||m_2-p||)^2-\sigma_3^{-2}(d_3-||m_3-p||)^2},$$
so the posterior is,
$$f_P(p|d)=N\begin{cases}e^{-\sigma_1^{-2}(d_1-||m_1-p||)^2-\sigma_2^{-2}(d_2-||m_2-p||)^2-\sigma_3^{-2}(d_3-||m_3-p||)^2}, & p \text{ is in the box} \\ 0 & p \text{ not in the box}\end{cases}$$
where $N$ is some fixed normalization constant.
Extracting information from the posterior:
Given the posterior distribution, there are a few things you might want to do.
Drawing samples:
First, you might want to draw samples from it. Markov-chain monte carlo is a good way to do this since it works without you knowing the normalization constant. MCMC also has advantages for high-dimensional problems, but that doesn't matter since this problem is small. However if you have thousands of measurement devices and thousands of points then such considerations will be important.
Best guess for reciever location:
Second, you might want to find the maximum liklihood point - in other words the point $p$ where $f_P(p|d)$ is maximized. To do that, solve the constrained convex optimization problem,
\begin{align}min_p & ~ \sigma_1^{-2}(d_1-||m_1-p||)^2+\sigma_2^{-2}(d_2-||m_2-p||)^2+\sigma_3^{-2}(d_3-||m_3-p||)^2 \\ \text{such that } & p \text{ is in the box}\end{align}
Uncertainty quantification:
Third, you might want to find the uncertainty. A quick and dirty way to do this is to draw a few, say 5, samples from the posterior and then take their variance. A more sophisticated way is to take the trace of the inverse of the hessian of the optization functional. It turns out that the inverse of the hessian is the covariance of a gaussian approximation to the posterior, though a proof of this is somewhat involved.
For an explanation on Bayesian inversion for a similar but easier example, you might read the excellent explanatory paper, "Estimating parameters in physical models through Bayesian inversion: a complete example" by Allmaras et. al.
Summary: The situation can be framed as a probabilistic inverse problem, where noise-corrupted measured distances are known and the recievers' position is unknown. Under this framework, Bayes' theorem provides a formula for the posterior probability density for the receiver position, based on (1) the prior probability densities, (2) the noise distribution, and (3) the measured data. If the prior is modeled as a uniform distribution and the noise is gaussian, then the posterior takes a particularly simple form. Samples from the posterior can be drawn with Markov chain monte carlo, and the posterior maximum liklihood point can be found by solving a computationally easy convex optimization problem.
Edit: I did a quick code up of the above maximum likelihood calculation in python using an off-the-shelf optimization routine from scipy, and it seems to work well.
Code: (I release this to the public domain if you want to use it. Doesn't use gradient information)
import numpy as np
from scipy.optimize import minimize
from math import sqrt
from math import pow
import matplotlib.pyplot as plt

def recieverMAPpoint(d1,d2,d3):
    #coordinates of constraints box
    m1x=100.; m1y=0.
    m2x=0.; m2y=100.
    m3x=100.; m3y=100.
    #measurement undertainty=20%
    s1=.2*d1; s2=.2*d2; s3=.2*d3
    #optimization functional J
    def J(p):
        x=p[0]; y=p[1]
        r1=d1-sqrt(pow(m1x-x,2)+pow(m1y-y,2))
        r2=d2-sqrt(pow(m2x-x,2)+pow(m2y-y,2))
        r3=d3-sqrt(pow(m3x-x,2)+pow(m3y-y,2))
        return pow(r1/s1,2) + pow(r2/s2,2) + pow(r3/s3,2)
    #constraints box B
    B = ({'type': 'ineq',
      'fun' : lambda p: np.array([p[0], p[1]])},
     {'type': 'ineq',
      'fun' : lambda p: np.array([100-p[0], 100-p[1]])})
    #minimize J over B
    res = minimize(J,np.array([50,50]),constraints=B,options={'disp': True},method='SLSQP')
    #plot constraints box
    plt.plot([0,100,100,0,0],[0,0,100,100,0],color='black')
    #plot distance circles
    c1=plt.Circle((m1x,m1y),radius=d1,ec='blue',fc='none')
    c2=plt.Circle((m2x,m2y),radius=d2,ec='blue',fc='none')
    c3=plt.Circle((m3x,m3y),radius=d3,ec='blue',fc='none')
    plt.gca().add_patch(c1); plt.gca().add_patch(c2); plt.gca().add_patch(c3)
    #plot optimal point
    plt.plot(res.x[0],res.x[1],'ro')
    plt.axis([-20,120,-20,120])
    plt.show()
    return res.x

Test Cases:
Example from original post:
>>> recieverMAPpoint(53,51,72)
Optimization terminated successfully.    (Exit mode 0)
            Current function value: 6.47506375609
            Iterations: 9
            Function evaluations: 36
            Gradient evaluations: 9
array([ 48.3354663 ,  50.77404997])

Measurements error overestimates distance:
>>> recieverMAPpoint(70,100,40)
Optimization terminated successfully.    (Exit mode 0)
            Current function value: 0.241068422167
            Iterations: 12
            Function evaluations: 48
            Gradient evaluations: 12

Measurement error underestimates distance:
>>> recieverMAPpoint(30,100,70)
Optimization terminated successfully.    (Exit mode 0)
            Current function value: 0.472436673945
            Iterations: 13
            Function evaluations: 52
            Gradient evaluations: 13
array([ 85.47617804,  27.93369774])

Distance measurements exact:
>>> recieverMAPpoint(80.6,67.1,92.2)
Optimization terminated successfully.    (Exit mode 0)
            Current function value: 1.20656973089e-07
            Iterations: 11
            Function evaluations: 44
            Gradient evaluations: 11
array([ 30.012965  ,  39.98444119])

Optimal point on edge of box (constraint active):
>>> recieverMAPpoint(60,120,130)
Optimization terminated successfully.    (Exit mode 0)
            Current function value: 0.526683755534
            Iterations: 13
            Function evaluations: 52
            Gradient evaluations: 13
array([  3.96901773e+01,  -1.76150977e-13])


text:
Q: Can I use CHAR datatype for multiple codepages? As the topic says.
I'm expecting data deliveries from various SQL Databases and (Excel) flat files with most likely different locales into my MS SQL Database.
Can I use CHAR and VARCHAR datatypes in my staging DB or do I need to switch to NCHAR / NVARCHAR?
My gut tells me I need NCHAR/NVARCHAR but I couldn't find a definite answer.
For brevity's sake let's assume all incoming data only contains latin letters and numbers (no korean text or similar)


text:
Q: Laptop occasionally won't run on battery power until I remove and reinstert the battery I have a Toshiba Satellite S55-B5280.
Occasionally, the laptop will stop running on battery power. Meaning, if the AC adapter is unplugged, the laptop won't turn on; while the laptop is turned on, if I unplug the AC adapter, it shuts down immediately.
Once it gets into this state, it continues until I remove and reinstert the battery, which reliably fixes it. After the problem is fixed, the laptop runs fine on battery and the battery life is normal.
At first I suspected it may be an issue with the physical connection at the battery connector, but the laptop sometimes enters this state while sitting undisturbed on a table.
What could be the cause? Is it more likely to be a fault in the battery, the laptop's power circuitry, or the battery connector?
edit: upower shows a battery voltage of 16.7 V. Laptop has stopped running on battery entirely.
edit: I tested the battery with a multimeter, and 16.7 V is accurate. I'm not sure if that rules out the battery as a problem or not.
I tested the two fuses PF1 and PF2 (white rectangles with a "Y" on them in the photo below), and they are both short (which I assume means they are good):

You can see above one of the fuses, there is a zero ohm link, possibly named PR74. This connects to the pulldown to enable the battery. If I insert the battery (AC power unplugged) and measure the voltage at PR74, it is 3.1 V. Then, I try pressing the laptop power button, and PR74 remains 3.1 V. I'm not sure if this might indicate a problem.
PR74 connects to R671 (bottom right), which is 1kohm. I'm not sure where it goes after that.

A: I'd say there is an issue with the motherboard (laptop's power circuitry). When issues like this appear, I call up warranty service and describe the problem. Their only answer is to replace the motherboard.
Is your laptop still under warranty? Are there any firmware updates for the motherboard?


text:
Q: Optimizing indexes I just began optimizing my schemas with indexes (pretty late I guess).
I never dealt with huge dataset but I'll be soon coping with about 1 to 5 millions rows.
Here is the schema I'm using right now for testing:
CREATE TABLE `object`
(
  `otype` VARCHAR(255),
  `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
  `domain` VARCHAR(255),
  `created_at` INT,
  `updated_at` INT,
  `deleted_at` INT,
  `category` VARCHAR(31), /* genre, type, category */
  `status` VARCHAR(15)
)ENGINE=InnoDB;
ALTER TABLE `object` ADD UNIQUE KEY `object` ( `otype`, `id` );
CREATE INDEX `id` ON `object` ( `otype`, `id` );
CREATE INDEX `object_id` ON `object` ( `id` );
CREATE INDEX `object_domain` ON `object` ( `domain` );
CREATE INDEX `object_category` ON `object` ( `category` );
CREATE INDEX `object_status` ON `object` ( `status` );

CREATE TABLE `offer`
(
id BIGINT UNSIGNED,
`category` VARCHAR(31), /* genre, type, category */
amount DECIMAL(12,3)
)ENGINE=InnoDB;
ALTER TABLE `offer` ADD FOREIGN KEY ( `id` ) REFERENCES object( `id` ) ON UPDATE CASCADE ON DELETE CASCADE;
CREATE INDEX `offer_id` ON `offer` ( `id` );
CREATE INDEX `offer_category` ON `offer` ( `category` );

And this is the query I'm trying to optimize: I'm reporting it twice because I was experimenting if using indexes filtering just the first table was faster than filtering both the tables and I guess I was right: aren't I?
mysql> select SQL_NO_CACHE count(*) from object, offer where object.id = offer.id and object.category = "bid" and status = "pending" order by created_at;
+----------+
| count(*) |
+----------+
|   499510 |
+----------+
1 row in set (2.06 sec)

mysql> explain extended select SQL_NO_CACHE count(*) from object, offer where object.id = offer.id and object.category = "bid" and status = "pending" order by created_at;
+----+-------------+--------+------+-------------------------------------------------+-----------------+---------+------------------+--------+----------+------------------------------------+
| id | select_type | table  | type | possible_keys                                   | key             | key_len | ref              | rows   | filtered | Extra                              |
+----+-------------+--------+------+-------------------------------------------------+-----------------+---------+------------------+--------+----------+------------------------------------+
|  1 | SIMPLE      | object | ref  | PRIMARY,object_id,object_category,object_status | object_category | 96      | const            | 498729 |   100.00 | Using index condition; Using where |
|  1 | SIMPLE      | offer  | ref  | offer_id                                        | offer_id        | 9       | testme.object.id |      1 |   100.00 | Using index                        |
+----+-------------+--------+------+-------------------------------------------------+-----------------+---------+------------------+--------+----------+------------------------------------+
2 rows in set, 1 warning (0.01 sec)

mysql> select SQL_NO_CACHE count(*) from object, offer where object.id = offer.id and offer.category = "bid" and status = "pending" order by created_at;
+----------+
| count(*) |
+----------+
|   499510 |
+----------+
1 row in set (3.78 sec)

mysql> explain extended select SQL_NO_CACHE count(*) from object, offer where object.id = offer.id and offer.category = "bid" and status = "pending" order by created_at;
+----+-------------+--------+--------+---------------------------------+----------------+---------+-----------------+--------+----------+------------------------------------+
| id | select_type | table  | type   | possible_keys                   | key            | key_len | ref             | rows   | filtered | Extra                              |
+----+-------------+--------+--------+---------------------------------+----------------+---------+-----------------+--------+----------+------------------------------------+
|  1 | SIMPLE      | offer  | ref    | offer_id,offer_category         | offer_category | 96      | const           | 498792 |   100.00 | Using index condition; Using where |
|  1 | SIMPLE      | object | eq_ref | PRIMARY,object_id,object_status | PRIMARY        | 8       | testme.offer.id |      1 |   100.00 | Using where                        |
+----+-------------+--------+--------+---------------------------------+----------------+---------+-----------------+--------+----------+------------------------------------+
2 rows in set, 1 warning (0.00 sec)

I studied different articles and the mysql index page which states:

They are used only for equality comparisons that use the = or <=> operators (but are very fast) [...] The optimizer cannot use a hash index to speed up ORDER BY operations

*

*Since I'll probably move to mysql cluster, does it make sense to switch from InnoDB to NDB engine and use HASH indexes on "category" and "status" columns?

*I read how btrees stores data. If most of my queries involve a "WHERE category = x AND status = y", should I add 3 different indexes: one on category, one on status, and one on the combination of both?

*"show warnings" doesn't show anything useful about what mysql is trying to warn me about: what's wrong with my query?
mysql> show warnings \G
*********************** 1. row ***********************
  Level: Note
   Code: 1003
Message: /* select#1 */ select sql_no_cache count(0) AS count(*) from testme.object join testme.offer where ((testme.object.id = testme.offer.id) and (testme.object.category = 'bid') and (testme.object.status = 'pending'))
1 row in set (0.00 sec)
4 Can the following:
CREATE INDEX `object_category_status` ON `object` ( `category`, `status` );
CREATE INDEX `object_category` ON `object` ( `category` );
CREATE INDEX `object_status` ON `object` ( `status` );

be reduced with the following for the very same result?
CREATE INDEX `object_category_status` ON `object` ( `category`, `status` );
CREATE INDEX `object_status` ON `object` ( `status` );

Thanks for your time!

A: I will answer each the the three questions
QUESTION #1

Since I'll probably move to mysql cluster, does it make sense to switch from InnoDB to NDB engine and use HASH indexes on "category" and "status" columns?

ANSWER TO QUESTION #1
Hash indexes are for one-to-one lookups. Hash indexes are only available for the MEMORY Storage Engine (See my May 17, 2011 post Why does MySQL not have hash indices on MyISAM or InnoDB?)
QUESTION #2

I read how btrees stores data. If most of my queries involve a "WHERE category = x AND status = y", should I add 3 different indexes: one on category, one on status, and one on the combination of both?

ANSWER TO QUESTION #2
You do not want single column indexes. MySQL could still use them if there are no compound index present. It will make MySQL work harder generating results by merging lookups from two separate indexes,
You are way better off with a compound index, an index on both category and status.
In your particular case

*

*the index could be (status,category) if you order categories within a status.

*the index could be (category,status) if you order status values under a category (if the number of status values is high)

*Since you do an ORDER BY within a (status,category) combination, your compound would benefit even further from one or both of these combined indexes

*

*(status,category,created_at)

*(category,status,created_at)

*Please see my posts on using compound indexes

*

*Sep 18, 2012 : How are multiple indexes used in a query by MySQL? (Discusses INDEX_MERGE briefly)

*Apr 11, 2014 : Why is MySQL not using the index with the higher cardinality?
QUESTION #3

"show warnings" doesn't show anything useful about what mysql is trying to warn me about: what's wrong with my query?

ANSWER TO QUESTION #3
Without seeing the actual warning message, I can't tell you. Note this: You ran EXPLAIN twice on the same query and got two slightly different results. This was due to the choose of keys. InnoDB tends to take guess by passing through index pages inside the BTREE nodes of the indexes and chooses based on cardinality.
In your case, you should run just once
OPTIMIZE TABLE object;

This will defrag the table and generate a clean set of index statistics.
You could slightly improve the query by writing it as an INNER JOIN
select SQL_NO_CACHE count(*) from object
inner join offer on object.id = offer.id
where object.category = "bid"
and status = "pending"
order by created_at;

You should also think about the fact that offer no PRIMARY KEY.
You should run this query
SELECT COUNT(1),id,category from offer
GROUP BY id,category HAVING COUNT(1) > 1;

If you get no results back, then that can be your PRIMARY KEY. Thus, the offer table should be
CREATE TABLE `offer`
(
    id BIGINT UNSIGNED,
    `category` VARCHAR(31), /* genre, type, category */
    amount DECIMAL(12,3),
    PRIMARY KEY (id,category)
) ENGINE=InnoDB;


text:
Q: how to get scope for "this" in typescript I have the following class:
module ModuleName {
    export class ClassName {

        constructor() {
            this.bindEvents();
        }

        bindEvents() {
            var self = this;
            $("#save-button").off("click")
                .click(() => {
                    self.classFunction();
                });
        };

        classFunction(){
        }
    }
}

I would expect the self variable now to contain a reference to the class. (The compile even tells me it does!)
However, when the js is loaded on the client it cannot find the function, bevause self points to the window object instead of the class.
How can I implement this so that I have a reference to my class?
generated js:
        ClassName.prototype.bindEvents= function () {
            var self = this;
            $("#save-button").off("click")
                .click(function () {
                self.classFunction();
            });
        };

A: Using arrow function will solve your problem.
const bindEvents = () => {
 // your code
}

ES6 does not autobind 'this' to the class syntax, while inside a normal function.
Using arrow function will refer 'this' to class.


text:
Q: How to make pivot table in SQL Server in my case? I wants to display the record by same column. I don't know how describe the question also.
I have a table called SoldQtyTable
ItemNo    Weeks    Years    QtySold    AsOfWeekOnHand
----------------------------------------------------
1           1        2017      5         3
2           1        2017      2         5
3           1        2017      66        70
1           2        2017      4         33

I wants to display like below
ItemNo    Years    [1QtySold]    [1_OnHand]    [2QtySold]    [2_OnHand]
-----------------------------------------------------------------------
1          2017       5               3            4            33
2          2017       2               5
3          2017      66               70

I tried in this way. But It doesn't work
select
    PVT1.ItemID,
    PVT1.StoreID,
    PVT1.Years,
    isnull([1],0) as [1QtySold], isnull([2],0) as [2QtySold],
    isnull([1_OnHand],0) as [1_OnHand], isnull([2_OnHand],0) as [2_OnHand]
from
(
    SELECT
        ItemID,
        StoreID,
        Years,
        Weeks,
        AsOfWeekOnHand
    FROM
        SoldQtyTable
) L
PIVOT
(
    SUM(AsOfWeekOnHand)
    FOR Weeks IN ( [1_OnHand], [2_OnHand])
) AS PVT1
LEFT JOIN
(
    SELECT
        ItemID,
        StoreID,
        Years,
        Weeks,
        QtySold
    FROM
        SoldQtyTable
) L
PIVOT
(
    SUM(QtySold)
    FOR Weeks IN ( [1soldQty], [2soldQty]
) AS PVT2 on PVT2.ItemID = PVT1.ItemID and PVT1.Years = PVT2.Years
where
    PVT1.years = 2017

A: I find conditional aggregation so much simpler:
SELECT ItemID, Years,
       SUM(CASE WHEN weeks = 1 THEN QtySold END) as QtySold_1,
       SUM(CASE WHEN weeks = 1 THEN AsOfWeekOnHand END) as AsOfWeekOnHand_1,
       SUM(CASE WHEN weeks = 2 THEN QtySold END) as QtySold_2,
       SUM(CASE WHEN weeks = 3 THEN AsOfWeekOnHand END) as AsOfWeekOnHand_2
FROM SoldQtyTable
GROUP BY ItemID, Years
ORDER BY ItemID, Years;

A: If you want to PIVOT multiple columns, you can achieve that by doing UNPIVOT first and then doing PIVOT on just one value column as described in this answer.
SELECT ItemID,
      StoreID,
      Years,
      [1_QtySold],
      [1_AsOfWeekOnHand] AS [1_OnHand],
      [2_QtySold],
      [2_AsOfWeekOnHand] AS [2_OnHand]
FROM
(
    SELECT
        ItemID,
        StoreID,
        Years,
        Weeks + '_' + col AS col,
        [value]
    FROM
    (
        SELECT
            ItemID,
            StoreID,
            Years,
            CAST(Weeks as varchar) Weeks,
            AsOfWeekOnHand,
            QtySold
        FROM
            SoldQtyTable
        WHERE Years = 2017 -- your original filter PVT1.years = 2017
     ) src
     UNPIVOT
     (
        VALUE
        FOR col in (AsOfWeekOnHand, QtySold)
     ) unpiv
) s
PIVOT
(
  SUM([value])
  FOR col IN ([1_AsOfWeekOnHand], [1_QtySold], [2_AsOfWeekOnHand], [2_QtySold])
) unpiv
ORDER BY StoreID

Here is the SQL Fiddle.


text:
Q: Outputting a double in exponential notation I am converting a VB6 application to C#. My C# code is:
double a = 0.1345;
double b = 56.0;
double c = 40574.0;
double d = a * (b / c);
Console.WriteLine(d);

as per VB the above code should return 1.856361216542613e-4
but my application is returning 0.000185636121654261.
I need the value as it is having e notation.

A: You just nedd to use ToString() with proper format:
Console.WriteLine(d.ToString("e"));

More formats on: MSDN
EDIT:
To increase a precion, you need to specify it after e:
Console.WriteLine(d.ToString("e16"));
//1.8563612165426135e-004

Unfortunately, there is no way to get rid of 00 before 4 in exponent. Here is explanation:

The case of the format specifier indicates whether to prefix the
  exponent with an "E" or an "e". The exponent always consists of a plus
  or minus sign and a minimum of three digits. The exponent is padded
  with zeros to meet this minimum, if required.

Source: MSDN
EDIT2:
In order to get rid of padding in exponent, you could write the following format:
 Console.WriteLine(d.ToString("0.##############e+0"));


text:
Q: Update a column everytime a new row is added to a dataframe I have a dataframe df1 that looks like this:
    use_id  user_id platform    platform_version    device
0   22782   26980   ios         10.2                iPhone7
1   22783   29628   android     6.0                 Nexus 5
2   22784   28473   android     5.1                 SM-G903F
3   22785   15200   ios         10.2                iPhone7
4   22786   28239   android     6.0                 ONE E1003
5   22787   12921   android     4.3                 GT-I9505
6   22788   28714   android     6.0                 SM-G930F
7   22789   28714   android     6.0                 SM-G930F
8   22790   29592   android     5.1                 D2303
9   22791   28775   ios         10.2                iPhone6

and a second dataframe df2 (subset of df1):
    use_id  user_id   device       date_created
0   22782   26980     iPhone7      2018/12/12
1   22783   29628     Nexus 5      2019/01/15
2   22784   28473     SM-G903F     2019/01/23
3   22785   15200     iPhone7      2019/01/23
4   22786   28239     ONE E1003    2019/01/23

I want to identify the new rows in df1 not present in df2, append them to df2 and then update the 'date_created' column with the entry date.
So df2 will be similar to this:
    use_id  user_id   device       date_created
0   22782   26980     iPhone7      2018/12/12
1   22783   29628     Nexus 5      2019/01/15
2   22784   28473     SM-G903F     2019/01/23
3   22785   15200     iPhone7      2019/01/23
4   22786   28239     ONE E1003    2019/01/23
5   22787   12921     GT-I9505     2019/05/22
6   22788   28714     SM-G930F     2019/05/22
7   22789   28714     SM-G930F     2019/05/22
8   22790   29592     D2303        2019/05/22
9   22791   28775     iPhone6      2019/05/22

I was able to get the difference of both dataframes using merge():
mergedStuff = pd.merge(df1['use_id', 'user_id', 'device'], df2, on=['use_id', 'user_id', 'device'], how='outer', indicator=True).loc[mergedStuff['_merge'] == 'left_only']

and then append the new rows to df2:
df2 = df2.append(mergedStuff, ignore_index=True)

But I am struggling how to add the created date like below only for new appended rows.
df2['date_created'] = pd.datetime.now()
Is there a simple way to achieve this?

A: You can use pandas built in datetime functionality to add the date created field to df1 prior to merging.
df1['date_created'] = pd.Timestamp.now()
#to keep just the date part
df1['date_created'] = df1['date_created'].dt.date

A: Use a left join to merge the two frames and set indicator to True:
df_merged=pd.merge(df1,df2,how='left',indicator=True)

Filter out the rows contained in the left frame only
df_merged=df_merged.loc[df_merged['_merge']=='left_only']

df_merged['Created']=pd.Timestamp.now()


text:
Q: How do I run specs for the activeadmin gem I am trying to run the specs for a local clone of the activeadmin gems current master.
I am using ruby 2.2.2 and have bundled successfully.
When I try to run one of the specs like so:
bundle exec rspec spec/unit/filters/humanized_spec.rb

I am getting the following error:

The git source https://github.com/jruby/activerecord-jdbc-adapter is not yet checked out. Please run `bundle install` before trying to start your application
Coverage report generated for RSpec to /Users/aljoscha/gem/activeadmin/coverage. 0.0 / 0.0 LOC (100.0%) covered.
/Users/aljoscha/gem/activeadmin/spec/rails_helper.rb:13:in `require': cannot load such file -- active_record (LoadError)
    from /Users/aljoscha/gem/activeadmin/spec/rails_helper.rb:13:in `<top (required)>'
    from /Users/aljoscha/gem/activeadmin/spec/unit/filters/humanized_spec.rb:1:in `require'
    from /Users/aljoscha/gem/activeadmin/spec/unit/filters/humanized_spec.rb:1:in `<top (required)>'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `block in load_spec_files'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `each'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `load_spec_files'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:100:in `setup'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:86:in `run'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:71:in `run'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:45:in `invoke'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.5.4/exe/rspec:4:in `<top (required)>'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/bin/rspec:22:in `load'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/bin/rspec:22:in `<main>'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `eval'
    from /Users/aljoscha/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `<main>'

which I cannot make sense of.
Especially since activerecord-jdbc-adapter is not even in the Gemfile.
What am I missing?

A: Try prepending your command with bundle exec:
bundle exec rspec spec/unit/filters/humanized_spec.rb

It looks like you have a local version discrepancy causing issues.
If not, did you follow all of the steps listed on their contributing readme?

If you are still stuck, you may be experiencing an issue with bundler itself.  First, try updating bundler then reinstalling gems and attempt to run rspec.  If that doesn't work you may need to delete the bundle cache folder and start over.

A: I'm going to re-answer to emphasize how to test a gem using appraisal as mentioned in CONTIBUTING:
bundle exec appraisal install
bundle exec appraisal rails_50 rspec spec/unit/filters/humanized_spec.rb

Thank you for your interest in Active Admin.


text:
Q: Creating one graph from two or more different worksheets I'm in the process of creating a macro which creates an xy graph from data chosen using input boxes. I've run into two problems (one major and one minor).

*

*I am given an error message whenever I try to select data from a different worksheet. How can I make the macro able to use data from several different worksheets? (I suspect that the problem is under the comment, "Set additional y values with input box", but I'm not sure)
The error message is "Run-time error 1004: Selection method of range class failed", and it refers to the line

myAddTitle.OFFEST(1, 0).Select

after I try to select data from a new worksheet for my second series.

*No matter what I set as the name for series 1, the legend always says Series 1. How can i make it correspond to myYTitle?

Any suggestions would be greatly appreciated! Thank you!
'''
Sub InsertFSC()
'
'
'
'
`With ActiveSheet
'
' Set x values with input box
Dim myXCell As Range
Dim myXSeries As Range
Dim myXTitle As Range
Set myXTitle = Application.InputBox("Please select the heading of the column which contains
your desired X values:", "Select title cell", Type:=8)
myXTitle.OFFSET(1, 0).Select
Set myXCell = Selection
Range(myXCell, myXCell.End(xlDown)).Select
Set myXSeries = Selection
'
'
' Set y values with input box
Dim myYCell As Range
Dim myYSeries As Range
Dim myYTitle As Range
Set myYTitle = Application.InputBox("Please select the heading of the column which contains your desired Y values:", "Select title cell", Type:=8)
myYTitle.OFFSET(1, 0).Select
Set myYCell = Selection
Range(myYCell, myYCell.End(xlDown)).Select
Set myYSeries = Selection
'
'
' Create Blank Graph
Dim chartObj As ChartObject
Dim DataChart As Chart
Set chartObj = ActiveSheet.ChartObjects.Add(Top:=10, Left:=325, Width:=600, Height:=300)
Set DataChart = chartObj.Chart
DataChart.ChartType = xlXYScatterSmooth
'
'
' Remove auto-plotted data
Do While DataChart.SeriesCollection.Count > 0
DataChart.SeriesCollection(1).Delete
Loop
'
'
' Add first data series
With DataChart.SeriesCollection.NewSeries
    .Name = myYTitle
    .XValues = myXSeries
    .Values = myYSeries
End With
'
'
'
' Formatting
' Display a message box with yes/no and question icon - want to continue?
If MsgBox("Would you like to add another Y data series to your graph?", vbQuestion + vbYesNo + vbDefaultButton2, "Continue?") = vbYes Then
     MsgBox "The user clicked Yes"
'
'
'
' BEGIN THE LOOP of selecting additional Y values until user selects NO
Do Until answer = vbNo
'
' Set additional y values with input box
Dim myAddCell As Range
Dim myAddSeries As Range
Dim myAddTitle As Range
Set myAddTitle = Application.InputBox("Please select the heading of the column which contains the Y values you want to add:", "Select title cell", Type:=8)
myAddTitle.OFFSET(1, 0).Select
Set myAddCell = Selection
Range(myAddCell, myAddCell.End(xlDown)).Select
Set myAddSeries = Selection
'
'
' Add the new data to graph
With DataChart.SeriesCollection.NewSeries
   .Name = myAddTitle
   .XValues = myXSeries
   .Values = myAddSeries
End With
'
'
' Display message box with yes/no and question icon
answer = MsgBox("Would you like to continue and select another Y data series?", vbQuestion + vbYesNo + vbDefaultButton2, "Continue?")
' END OF LOOP
Loop
Else
     MsgBox "The user clicked No"
End If
'
'
'
' Add a chart title and axis labels with input box
With DataChart
    .HasTitle = True
    .ChartTitle.Text = Application.InputBox("Please enter a chart title", "Chart Title Name", Type:=2)
' Add X Axis title
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = myXTitle
' Add Y Axis title with input box?
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = Application.InputBox("Please enter the Y axis title", "Y axis Name", Type:=2)
End With
'
'
End With
End Sub

'''

A: Try this:
Sub InsertFSC()

    Dim xVals As Range, yVals As Range, allYVals As Collection
    Dim chartObj As ChartObject
    Dim DataChart As Chart

    Set allYVals = New Collection

    Set xVals = GetRange("Please select the heading of the column which contains your desired X values:")
    If xVals Is Nothing Then Exit Sub 'cancelled xvals selection
    'loop and collect Yvalue column(s)
    Do
        Set yVals = GetRange("Please select Y values column header (or cancel if done):")
        If Not yVals Is Nothing Then
            allYVals.Add yVals
        Else
            Exit Do 'user is done selecting
        End If
    Loop

    If allYVals.Count = 0 Then Exit Sub 'didn't get any yvalues selected

    'add the chart
    Set chartObj = ActiveSheet.ChartObjects.Add(Top:=10, Left:=325, Width:=600, Height:=300)
    Set DataChart = chartObj.Chart
    DataChart.ChartType = xlXYScatterSmooth

    ' Remove auto-plotted data
    Do While DataChart.SeriesCollection.Count > 0
        DataChart.SeriesCollection(1).Delete
    Loop
    'loop over the collected y values ranges and add a series for each one
    For Each yVals In allYVals
        With DataChart.SeriesCollection.NewSeries
           .Name = yVals.Cells(1).Value
           .XValues = xVals.Offset(1, 0).Resize(xVals.Rows.Count - 1) 'move/resize to exclude header
           .Values = yVals.Offset(1, 0).Resize(xVals.Rows.Count - 1)
        End With
    Next
End Sub

'return a user-selected range or Nothing
Function GetRange(msg As String)
    Dim rv As Range
    On Error Resume Next
    Set rv = Application.InputBox(msg, "Select title cell", Type:=8)
    On Error GoTo 0
    If Not rv Is Nothing Then
        Set rv = rv.Parent.Range(rv, rv.End(xlDown))
    End If
    Set GetRange = rv
End Function

If this is for general use, you should add some checks on the user-selected ranges - eg. make sure the range is not empty, only one column is selected, that the range doesn't span an entire column (or does not exceed some sensible size limit), and that the X and Y ranges are the same size.


text:
Q: XAML text and Binding in one Textblock Is there a way to make a Texblock with a normal text and a Binding in the same Text Proberty?
It should look like this :
<TextBlock  Text="Text {Binding SomeBinding}" />

A: Nope.
You should use a IValueConverter at this point.
If you don't know how to use an IValueConverter, the official tutorial by Microsoft will be helpful.


text:
Q: parallel processing of python script I have a python script which takes one input at a time and process it .
I want to run script parallel with different inputs at a same time . Like 50 or 100 times but with different inputs feed from txt file .
i execute script like:
python script.py -d url1

then
python script.py -d url2

then
python script.py -d url3

and instead of input one argument at a time , i want to feed those url from a text file and process them in parallel .
I tried this script running in bash shell using gnu-parallel but bash script not runs python shell and thus errors.
the code is as follows---
#!/usr/bin/env bash
doit() {
    host="$1"
    ~/script/python script1.py -d $host
      }
   export -f doit

   cat "$1" | parallel -j50 -k doit

contents of txt file---
url1.com
url2.com
url3.com
--------
url1000.com
url_any.com

A: With GNU Parallel, like this:
parallel --dry-run -a arguments.txt python script.py

which assumes your arguments are one per line in "arguments.txt".
Use parallel -k ... to keep outputs in order, if required.
Use parallel --bar ... to get a progress bar.

A: An alternative to GNU Parallel is to use Python subprocess to execute the command repeatedly.
This is an example using Python 2.7.
First your code will need to read the text file to assign all the arguments to a list.
with open('<Arguments text file location>') as f:
    arguments = f.read().splitlines()

Then you use a loop to run the command once for each argument using subprocess.
import subprocess
procs = []
for argument in arguments:
    cmd = 'python script.py %(argument)' % {'argument': argument}
    procs.append(
        subprocess.Popen(cmd, shell=True)
    )
exit_codes = [p.wait() for p in procs]


text:
Q: Can't update node I'm trying this to update my node version, in order to be able to install i18next,
but I get this error:
Error: Cannot find module 'readable-stream'
at Function._resolveFilename (module.js:337:11)
at Function._load (module.js:279:25)
at Module.require (module.js:359:17)
at require (module.js:375:17)
at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/sha/index.js:3:48)
at Module._compile (module.js:446:26)
at Object..js (module.js:464:10)
at Module.load (module.js:353:31)
at Function._load (module.js:311:12)
at Module.require (module.js:359:17)
If you need help, you may report this log at:
<http://github.com/isaacs/npm/issues>
or email it to:
<npm-@googlegroups.com>
System Darwin 11.4.2
command "node" "/usr/local/bin/npm" "install" "-g" "n"
cwd /Users/personalcomputer/Desktop
node -v v0.6.18
npm -v 1.3.5

Additional logging details can be found in:
/Users/personalcomputer/Desktop/npm-debug.log
not ok code undefined
not ok code 1

How can I solve this?
Thanks


text:
Q: Autofac, accessing ContainerBuilder from random component I am playing with Autofac and let's pretend i have a component (DLL) in my application that is using Logging. How and where to log will be defined by main App. So it registers ILog interface with Autofac.
Problem is how my component can get access to ContainerBuilder object to resolve ILog?
I can always initialize my component with IContainer but that defeats the purpose. I would just pass ILog interface to component instead of IContainer.

A: If I understand where you are with this correctly - it's worth reading up on the "Composition Root" for how to think about this in general. The short answer is "you don't access Containers from components."
https://blog.ploeh.dk/2011/07/28/CompositionRoot/
As you say, your component shouldn't know anything about Autofac - that actually goes for all of your code except a small section in your main application. So how does the ILog find its way to your component? From that Mark Seemann post:
"This means that all the application code relies solely on Constructor Injection"
That's a good general rule to make your code cleaner, even if you weren't using a DI framework. So in your situation, say you have a very simple app like this:
class Program
{
    static void Main(string[] args)
    {
        var component = new Component();    // we want logging to happen inside here
        component.DoStuff();
        Console.ReadKey();
    }
}

You actually just want to add your ILog as a dependency on your Component and then inject that as close as possible to your app-entry point:
public class Component
{
    private readonly ILog _logger;

    public Component(ILog logger)
    {
        _logger = logger;
    }

    public void DoStuff()
    {
        _logger.Log("this is a test");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var container = GetContainer();
        using (var scope = container.BeginLifetimeScope())
        {
            var test = scope.Resolve<Component>();          // this is potentially the only place we need to resolve anything
            test.DoStuff();
        }
        Console.ReadKey();
    }

    private static IContainer GetContainer()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<Component>();
        builder.RegisterType<Logger>()
            .As<ILog>();
        var container = builder.Build();
        return container;
    }
}