text:
Q: Error in gsub(vn[i - 1], paste0("(", vars[[i - 1]], ")"), vars, fixed = TRUE) : invalid 'pattern' argument I have been trying to built a decision tree and saved it as .yaml with the editor notepad++ as follows:
name: myTree
variables:
    costIM:3
    costKR250:2
    costKR500:1.5
    pdump:0.6
    pnodump:0.4
    cost0:(500*costIM)
    cost1a:(250*costIM+250*(costKR250+0.5*costKR250))
    cost2a:(250*costIM+250*2*costKR250)
    cost3a:(250*costIM+250*(costKR250+2*costKR250))
    cost4a:(250*costIM+250*costKR250)
    cost1b:(500*(costKR250+0.5*costKR250))
    cost2b:(500*2*costKR250)
    cost3b:(500*(costKR500+2*costKR500))
    cost4b:(500*costKR500)
    p13:1/3
type: decision
500IM:
    payoff: cost0
250IMand250KR:
    type: chance
    DumpingCharge:
        p: pdump
        type: chance
        50%:
            p=p13
            payoff:cost1a
        100%:
            p=p13
            payoff:cost2a
        200%:
            p=p13
            payoff:cost3a
    NoDumpCharge:
        p: 1-pdump
            payoff:cost4a
500KR:
    type: chance
    DumpingCharge:
        p: pdump
        50%:
            payoff:cost1b
        100%:
            payoff:cost2b
        200%:
            payoff:
    NoDumpCharge:
        p: pnodump
            payoff:cost4b

Nevertheless when I try to plot it in R whith this code:
library(yaml)
tree = yaml.load_file(input ="C:\\Users\\camil\\OneDrive\\Desktop\\change.yaml")
result =dtree(yl = tree)
plot(result, final = T)

as I run "result..." I get this error: "Error in gsub(vn[i - 1], paste0("(", vars[[i - 1]], ")"), vars, fixed = TRUE) :   invalid 'pattern' argument"
What am I missing or doing wrong?
The same code worked for loading and plotting other decision trees in .yaml

A: Probem solved: there were some missing spaces after ":".
yaml always require a space after :


text:
Q: Form data is not uploaded and alert not working I'm new to Javascript and followed a tutorial to make a pop form. The data filled by the user was supposed to appear in the console and that doesn't happen. I would also like to create an alert for when people click on the submit button so I added the last few lines that you'll see in the JavaScipt code, but it's not working as well. Hope that this is detailed enough and that someone can help me.
Here is the HTML

                I'd love to chat with you about your upcoming project.

                Fill out the form bellow to get in touch. Either for a budget information or to book a meeting to discuss
                any ideas that you might have, you can contact me for any
                clarification you need. I'll get back to you in 2-3 days.

                  <button id="show-modal">Open Form</button>

Ask away

        <form id="submit">
          <input type="text" placeholder="Name" name="name" />
          <input type="email" id="email" placeholder="Email" name="email"/>
          <input type="text" placeholder="Subject" name="subject" />
          <textarea placeholder="Message" name="message"></textarea>
          <button class="submit">Submit</button>
        </form>

And JavaScript
document.getElementById("show-modal").addEventListener("click", function() {
  document.querySelector(".modal").style.display = "flex";
});

function closeMe() {
  document.querySelector(".modal").style.display = "none";
}

document.querySelector("#show-modal").addEventListener("submit", event => {
  event.preventDefault();
  toggleModal();
  let formData = new FormData(document.querySelector("#show-modal"));
  console.log(
    "Name:" + formData.get("name"),
    "Email:" + formData.get("email"),
    "Subject:" + formData.get("subject"),
    "Message:" + formData.get("message")
  );
});

document.getElementById("#show-modal").addEventListener("submit", function() {
  alert("Thank you for your message!");
});

Here is the page if you want to have a look: https://giacomosorbi.github.io/joanaoli09-module-i/contact.html

A: Change the code to:
(Removed toggleModal() as there is no defination for it)

document.getElementById("show-modal").addEventListener("click", function() {
  document.querySelector(".modal").style.display = "flex";
});

function closeMe() {
  document.querySelector(".modal").style.display = "none";
}

document.querySelector("#submit").addEventListener("submit", event => {
  event.preventDefault();
  let formData = new FormData(document.querySelector("#submit"));
  console.log(
    "Name:" + formData.get("name"),
    "Email:" + formData.get("email"),
    "Subject:" + formData.get("subject"),
    "Message:" + formData.get("message")
  );
  alert("Thank you!!!");
});

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

                I'd love to chat with you about your upcoming project.

                Fill out the form bellow to get in touch. Either for a budget information or to book a meeting to discuss
                any ideas that you might have, you can contact me for any
                clarification you need. I'll get back to you in 2-3 days.

                  <button id="show-modal">Open Form</button>

Ask away

        <form id="submit">
          <input type="text" placeholder="Name" name="name" />
          <input type="email" id="email" placeholder="Email" name="email"/>
          <input type="text" placeholder="Subject" name="subject" />
          <textarea placeholder="Message" name="message"></textarea>
          <button class="submit">Submit</button>
        </form>

A: First of all, move

Second, your addEventListener("submit",... should be on form element, not on modal button-

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to watch the value change in Typescript I have a string variable e.g. createId:string in Angular component.ts
How to add a breakpoint when this variable change value?

A: One way is to add a breakpoint in a setter:
   public set createdId(val:string){
      debugger;
      this._createdId=val;
   }
   public get createdId(){
      return this._createdId;
   }


text:
Q: Can I run the #new and #create methods of my #game controller on my home page? I am creating a counter for a card game and would like to have a "New Game" button directly on my homepage, meaning without passing on the #new-game view.
My #game model doesn't need any information to be created (e.g: name...) so no form on a #new-game view needed to create it. The app is currently working but I have to pass on my #new-game view before a #game can be created.
I am struggling with the logic of the #new and #create actions of my #game controller taking place on my #home view (#pages controller).
Can anybody help ?
Thanks a lot
Here's my #game controller :
  def new
    @game = Game.new
    @game.biddings.build
  end

  def create
    @game = Game.new(game_params)
    @game.save

    redirect_to game_path(@game)
  end

My #page controller :
class PagesController < ApplicationController
  skip_before_action :authenticate_user!, only: [:home]

  def home
  end
end

And my #home view :

BIENVENU SUR COINCH'COUNT !

Coinch'Count est un compteur de points simplifié pour la coinche.

    <%= link_to 'Nouvelle partie', new_game_path, class: 'regular-btn' %>

    <%= link_to 'Liste de toute les parties', games_path, class: 'transp-btn' %>

The idea being to have the first link_to directly creating a #game instance and redirecting to the #game show.

A:
Can I run the #new and #create methods of my #game controller on my
home page?

No. Each request in Rails will only ever run one controller action so its a nonsensical goal.
What you really want to do is just add a form or a link on your pages/home.html.erb view that sends a POST request to /games.
You can do this with button_to which creates a form that just contains a single button:
# these all generate the exact same HTML
<%= button_to("Create game", Game.new) %>
<%= button_to("Create game", games_path, method: :post) %>
<%= button_to("Create game", controller: :games, action: :create) %>

This will work even if the client has turned JS off as its just a standard HTML form.
You can also use link_to with the method option:
# these all generate the exact same HTML
<%= link_to("Create game", Game.new, method: :post) %>
<%= link_to("Create game", games_path, method: :post) %>
<%= link_to("Create game", controller: :games, action: :create, method: :post) %>

This adds a data-method="POST" attribute to the link. Rails UJS defines a event handler for elements with this data attribute which will create a form and post it to the server so that a POST request is sent instead of GET.
If there are any JS errors that prevent the handler from working (like Rails UJS not being loaded) the default browser action of sending a GET request will happen instead so make sure you check the browser console if you run into problems.

A: You can try to declare your link as a "post", and use the creation path games_path :
<%= link_to 'Nouvelle partie', games_path, method: :post, class: 'regular-btn' %>

It will work because, as you said, you don't have any mandatory parameter:

My #game model doesn't need any information to be created


text:
Q: After updating ASP.NET Core 1.1 to ASP.NET Core 2.0 ,Return statement SignIn(ticket.Principal, ticket.AuthenticationScheme);is giving 500 error I recently updated my project to ASP.NET core 2.0 from ASP.NET core 1.1 .I'm using openiddict for authentication.
This is my controller which is responsible for  request/response.
[HttpPost("token")]
public async Task<IActionResult> TokenAsync(OpenIdConnectRequest request)
{
    try
    {
        var ticket = await _service.ExchangeTokenAsync(request);

        return SignIn(ticket.Principal, ticket.Properties,ticket.AuthenticationScheme);;

    }
    catch (Exception ex)
    {
        return BadRequest(new OpenIdConnectResponse
        {
            Error = OpenIdConnectConstants.Errors.ServerError,
            ErrorDescription = ex.Message
        });
    }
}

this return statement
return SignIn(ticket.Principal, ticket.Properties,ticket.AuthenticationScheme);

is throwing 500 internal server error. The code works perfectly up-to this return statement but while executing this return statement getting 500 internal server error.
This is my Startup of file methods.
public void ConfigureServices(IServiceCollection services)
{
    var connectionString = Configuration["ConnectionStrings:ApplicationDbContext"];

    services.AddEntityFrameworkNpgsql();

    services.AddDbContext<ApplicationDbContext>(
        opts =>
        {
            opts.UseNpgsql(connectionString, b => b.MigrationsAssembly("MenuSystem.Repository"));
            opts.UseOpenIddict();
        }
    );

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    var validIssuer = Configuration["Token:Issuer"];
    services.AddAuthentication()
        .AddJwtBearer(cfg =>
        {
            cfg.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = validIssuer,
                IssuerSigningKey = securityKey,

                ValidateIssuer = !String.IsNullOrEmpty(validIssuer),
                ValidateAudience = false,
                ValidateLifetime = true,
                ValidateActor = false,
                ValidateIssuerSigningKey = true
            };
        });

    services.AddOpenIddict(options =>
    {
        // Register the Entity Framework stores.
        options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
        options.AddMvcBinders();
        options.EnableTokenEndpoint("/api/account/token");
        options.UseJsonWebTokens();
        options.AllowPasswordFlow();
        options.AllowCustomFlow("urn:ietf:params:oauth:grant-type:facebook_access_token");
        options.AllowCustomFlow("urn:ietf:params:oauth:grant-type:google_access_token");
        options.AllowCustomFlow("urn:ietf:params:oauth:grant-type:microsoft_access_token");
        options.DisableHttpsRequirement();
        options.AddSigningKey(securityKey);

    });

    services.Configure<IdentityOptions>(options =>
    {
        // Password settings
        options.Password.RequireDigit = true;
        options.Password.RequiredLength = 8;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = true;
        options.Password.RequireLowercase = false;

        // Lockout settings
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
        options.Lockout.MaxFailedAccessAttempts = 10;

        // User settings
        options.User.RequireUniqueEmail = true;
    });

    services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
    {
        builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
    }));

    // Add framework services.
    services.AddMvc(options =>
    {
        options.Filters.Add(new GlobalExceptionFilter());
    });

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, RoleManager<IdentityRole> roleManager)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseAuthentication();
    app.UseCors("CorsPolicy");

    app.UseMvc();
}

Here is Debug Log
   info: Microsoft.AspNetCore.Mvc.SignInResult[1]
Project>       Executing SignInResult with authentication scheme (ASOS) and the following principal: System.Security.Claims.ClaimsPrincipal.
Project> info: Microsoft.AspNetCore.Mvc.SignInResult[1]
Project>       Executing SignInResult with authentication scheme (ASOS) and the following principal: System.Security.Claims.ClaimsPrincipal.
Project> info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Project>       Executed action Project.Controllers.AccountController.TokenAsync (Project) in 15632.6224ms
Project> info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Project>       Executed action Project.Controllers.AccountController.TokenAsync (Project) in 15632.6224ms
Project> fail: Microsoft.AspNetCore.Server.Kestrel[13]
Project>       Connection id "0HL852SU6TGOD", Request id "0HL852SU6TGOD:00000004": An unhandled exception was thrown by the application.
Project> System.InvalidOperationException: The authentication ticket was rejected because the mandatory subject claim was missing.
Project>    at AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerHandler.<SignInAsync>d__6.MoveNext()
Project> --- End of stack trace from previous location where exception was thrown ---

A: This answer is copied from original answer https://stackoverflow.com/a/44845552
The error you're seeing is caused by the fact your ClaimsPrincipal doesn't have the mandatory sub claim, as indicated by the exception message
To fix that, you have two options: manually adding the sub claim or asking Identity to use sub as the name identifier claim
Add the sub claims to the principal returned by await _signInManager.CreateUserPrincipalAsync(user);...
// Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
// OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
// subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
if (string.IsNullOrEmpty(principal.FindFirstValue(OpenIdConnectConstants.Claims.Subject)))
{
    identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Subject, await _userManager.GetUserIdAsync(user)));
}

... or ask Identity to use sub as the name identifier claim:
   services.Configure<IdentityOptions>(options =>
{
    options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
    options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
    options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});


text:
Q: Filter on showColumn & distinct inside my power apps formula I have this formula which is working correctly:-
ClearCollect(
     colUniqueDates,
     AddColumns(
         RenameColumns(
             Distinct(
                 'Grant Applications',
                 Title
             ),
             "Result",
             "Title"
         ).Title,
         "Level",
         1
     )
 );

but i wanted to add filter to is, as follow:-

but i got name is not recognized, any advice?

A: The table that is returned by the AddColumns call in your expression only has two columns: "Title" (which was renamed from "Result" in the result of the Distinct function) and "Level" (which was added by the AddColumns function). There is no "CurrentState" column in that table, which is why you see this error.
Assuming that the original table / data source 'Grant Applications' has this "CurrentState" column, you can move the filtering to where you still have that column in your table, something along the lines of the expression below:
ClearCollect(
     colUniqueDates,
     AddColumns(
         RenameColumns(
             Distinct(
                 Filter(
                     'Grant Applications',
                     CurrentState = "1" Or CurrentState = "0"),
                 Title
             ),
             "Result",
             "Title"
         ),
         "Level",
         1
     )
 );


text:
Q: Elegant way to convert string to dict and back Is there an elegant one-liner to convert this type of string to dict?
I googled now for an hour, but without several loops of splitting strings I can't get it to work.
Input  = "2:9, 6:90, 7:60"
Output = {'2': 9, '6': 90, '7': 60}

I would also need the reverse operation from dict to string.

A: Performance wise most efficient will be normal for loop:
my_string = "2:9, 6:90, 7:60"
my_dict = {}
for s in my_string.split(', '):
     k, v = s.split(":")
     my_dict[k] = int(v)

where my_dict will contain:
>>> my_dict
{'2': 9, '7': 60, '6': 90}

To get back the same string, you can perform .join() on dict.items() as:
>>> ", ".join("{}:{}".format(k, v) for k, v in my_dict.items())
'2:9, 7:60, 6:90'

Or, you can also type-cast the dict to string and do some formatting on it like:
>>> str(my_dict)[1:-1].replace(": ", ":").replace("'", "")
'2:9, 7:60, 6:90'

A: You can use ast.literal_eval and put brackets at each end of the string although your keys will be ints not strings.
from ast import literal_eval

Input  = "2:9, 6:90, 7:60"

Output = literal_eval(f"{{{input}}}")

{2: 9, 6: 90, 7: 60}

To fix the output to be string keys just convert them by hand
Output = dict(zip(map(str, Output), Output.values()))

{'2': 9, '7': 60, '6': 90}

Without importing any libraries you would need to use str.split
Output = dict(s.split(':') for s in Input.split(', '))

{'2': '9', '6': '90', '7': '60'}

Although now your values are strings so you'd need to fix that.
Output = dict(zip(Output, map(int, Output.values())))

{'2': 9, '7': 60, '6': 90}

A: Well without asking questions, if you want a one liner that makes the key a string and the value an int:
dict([[j[0].strip(), int(j[1])] for j in [i.split(':') for i in Input.split(',')]])


text:
Q: How to refine the visual properties of nodes in a GEXF file with NetworkX? Is there a way to use NetworkX to refine the visual properties of a GEXF file after processing it with Gephi? That is, I would like to use Gephi to calculate different network metrics and use them to set the visual properties of network nodes first and then use NetworkX to add some complementary visual properties. An important example of the latter is the use of a specific color palette for nodes according to their cluster membership.
Let's create an example network:
import networkx as nx
G = nx.karate_club_graph()
G.nodes(data=True)

We now have this type of data for each node:
{0: {'club': 'Mr. Hi'}

Next, let's lay out the network and define the visual node properties in Gephi and then re-read the data:
Here is an example of the GEXF file exported from Gephi:
      <node id="0" label="0">
        <attvalues>
          <attvalue for="0" value="Mr. Hi"></attvalue>
          <attvalue for="weighted degree" value="16.0"></attvalue>
          <attvalue for="modularity_class" value="0"></attvalue>
        </attvalues>
        <viz:size value="37.5625"></viz:size>
        <viz:position x="-93.93568" y="73.28415"></viz:position>
        <viz:color r="104" g="173" b="54"></viz:color>
      </node>

Now, let's read the network and see what we have:
G_layout = nx.read_gexf('karate_club_with_visuals.gexf')
G_layout.nodes(data=True)

Do note that you have to (manually) change the XML root node for the GEXF file to be able to read it with NetworkX.
{'0': {'club': 'Mr. Hi', 'Weighted Degree': 16.0, 'Modularity Class': 0, 'label': '0'},

The metrics produced with Gephi are available in the NetworkX data structure. However, the visual information is missing.
Nevertheless, we are able to define a color for a particular node:
G_layout.nodes['0']['viz'] = {'color': {'r': 255, 'g': 0, 'b': 0, 'a': 0}}

When opening the network again in Gephi we will notice one red node with all the previously defined visuals missing.
To conclude, is there a way to preserve the visual information when post-processing network data in GEXF with NetworkX?


text:
Q: Why does SmtpClient fail with several different Exceptions when using SSL? I'm trying to send a mail message using System.Net.Mail.SmtpClient with SSL enabled. While changing no external factors (i.e. hit F5, then hit F5 Again - or even in a loop) it works some times, but most of the times it fails.
Example code:
public void SendMail()
        {
            using (var client = new SmtpClient())
            {
                MailMessage mailMessage = new MailMessage();
                client.EnableSsl = true;
                client.Host = "smtp.example.com";
                client.Timeout = 10000;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                mailMessage.From = new MailAddress("from@example.com");
                mailMessage.To.Add(new MailAddress("to@example.com"));
                mailMessage.Subject = "Test";
                mailMessage.Body = "Message " + DateTime.Now.ToString();
                try
                {
                    client.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    // This being a Pokemon block is besides the point
                }
            }
        }

In my catch block I just get a timeout, but if I set up a trace for System.Net and System.Net.Sockets I can see a number of different exceptions:

*

*Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall

*Unable to read data from the transport connection: An established connection was aborted by the software in your host machine

*Cannot access a disposed object

*Reading is not supported on this stream

*Writing is not supported on this stream

All of which happen post EHLO, STARTTLS and authentication. The client and the server are chatting along in their cryptographic ways when the exceptions are thrown.
System.Net.Mail.SmtpClient.Send() is the the only frame all call stacks have in common.
Of course I've tried changing the code in a number of ways, such as setting client.UseDefaultCredentials, using client.SendAsync() and whatnot. But I suspect it's something entirely different knocking the connection over at different times - a configuration error on one of the machines involved perhaps?
So I've checked the Event Logs for signs of something messing with the connection, but I haven't found anything.
Any suggestions as to what I should be looking for here?

A: Sometimes a timeout is just a timeout ...
Digging further into this issue I used Wireshark to see what was going on at the network level.
When the failures happened, the client machine invariably sent a TCP [RST, ACK] packet around 10 seconds after EHLO. A timespan conspicuously close to my timeout value. When I doubled the timeout value the mails came through without failure every single time.
Of course if we were to spend more than 10 seconds sending each mail, we'd soon be queuing up mails for hours in our production system, so I needed to find out why it took so long.
One detail caught my attention:
The client was spending upwards of four seconds between two packets. And it was generally spending hundreds of milliseconds between packets whereas the server would respond within tens.
The next step was to build the code without debug symbols and measure again without a debugger attached. The time spent per e-mail sent immediately went sub-second. Now it's no news to me that code runs slower with a debugger attached, but seeing it run that much slower was a surprise.
So the lessons for me to learn were: Try not to overanalyze, and when timing is involved kill the debugger once in a while.

A: This should be a comment (I don't have reputation to make comments), but it could be a firewall issue, given you're getting an "Unable to read data from the transport connection: An established connection was aborted by the software in your host machine" error (basically, firewall or anti-virus cancelled your attempt to send a mail).
The error "Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall" happens when a stream is closed - see this question - and the other errors you've listed seem like they're related to trying to access a stream when it's closed, too.
All these error point to a common cause, a connection cancelled somewhere between you and the server and most likely on your machine/ network, and you get different errors depending at what point the effect propagates through to your application.
Another thing is, if you use
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
then you have to enable ssl afterwards, not before, otherwise it's cleared.

A: I suppose you have missed to set Credentials property of your host. However the another reason for exceptions may be wrong host name and port.Try something like :
    public void SendMail()
    {
        try
        {
            var fromAddress = new MailAddress("from@example.com", "Some text");
            var toAddress = new MailAddress("to@example.com");
            const string fromPassword = "from account password";

            var smtp = new SmtpClient
            {
                Host = "smtp.example.com",
                Port = "your host port", //for gmail is 587
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = "Test",
                Body = "Message " + DateTime.Now.ToString()
            })
            {
                smtp.Send(message);
            }
        }
        catch (Exception ex)
        {
            //do something
        }
   }

It is tested with gmail host which is smtp.gmail.com and it works correctly


text:
Q: comes to think of it? Which of the expressions, "come to think of it" or "comes to think of it", grammatically correct? Or are they grammatical at all?
If it is a short form of,

When one comes to think of it, I would rather have a cat.

It should be

Comes to think of it, I would rather have a cat.

But it seems that it is more often used as

Come to think of it, I would rather have a cat.

Which one is correct?
Grammatically, it neither seems to be a normal sentence. Are there more expressions with similar structure (verb phrase that is not an imperative).

A: The expression come to think of it actually functions as a phrase

come to think of it
on reflection (said when an idea or point occurs to one while one is speaking):
come to think of it, that was very daring of you

and therefore "Come to think of it, I would rather have a cat." is the correct choice of sentence.


text:
Q: Polymer Custom Build Crisper Babel Im using the example of the gulpfile.js that is provided in the polymer-init-custom-build project.
Im trying to optimize my code using Vulcanize Crisper Babel (https://www.polymer-project.org/1.0/docs/tools/optimize-for-production). I add the following code to my gulpfile.js in order to make this and i have the following error:
The following tasks did not complete: default, output
Did you forget to signal async completion?
function source() {
 return project.splitSource()
// Add your own build tasks here!
.pipe(gulpif('src/*.*',crisper()))
.pipe(gulpif('src/*.js',babel()))
.pipe(gulpif('src/*.html', strip()))
.pipe(gulpif('**/*.{png,gif,jpg,svg}', images.minify()))
.pipe(gulpif('src/*.html', minifyInline()))
.pipe(gulpif('src/*.html', htmlmin({collapseWhitespace: true})))
.pipe(project.rejoin()); // Call rejoin when you're finished
}

Is there any way to implement this?

A: Removing the vulcanize and crisper it works because both of those are handled by the library.
Here is my final code that it works and make vulcanize crisper and babel:
 * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.

'use strict';

const path = require('path');
const gulp = require('gulp');
const gulpif = require('gulp-if');

// Got problems? Try logging 'em
// const logging = require('plylog');
// logging.setVerbose();

// !!! IMPORTANT !!! //
// Keep the global.config above any of the gulp-tasks that depend on it
global.config = {
  polymerJsonPath: path.join(process.cwd(), 'polymer.json'),
  build: {
    rootDirectory: 'build',
    bundledDirectory: 'bundled',
    unbundledDirectory: 'unbundled',
    // Accepts either 'bundled', 'unbundled', or 'both'
    // A bundled version will be vulcanized and sharded. An unbundled version
    // will not have its files combined (this is for projects using HTTP/2
    // server push). Using the 'both' option will create two output projects,
    // one for bundled and one for unbundled
    bundleType: 'both'
  },
  // Path to your service worker, relative to the build root directory
  serviceWorkerPath: 'service-worker.js',
  // Service Worker precache options based on
  // https://github.com/GoogleChrome/sw-precache#options-parameter
  swPrecacheConfig: {
    navigateFallback: '/index.html'
  }
};

const clean = require('./gulp-tasks/clean.js');
const images = require('./gulp-tasks/images.js');
const uglify =  require('gulp-uglify');
const htmlmin = require('gulp-htmlmin');
const project = require('./gulp-tasks/project.js');
var minifyInline = require('gulp-minify-inline');
var strip = require('gulp-strip-comments');
const babel = require('gulp-babel');
var crisper = require('gulp-crisper');

// The source task will split all of your source files into one
// big ReadableStream. Source files are those in src/** as well as anything
// added to the sourceGlobs property of polymer.json.
// Because most HTML Imports contain inline CSS and JS, those inline resources
// will be split out into temporary files. You can use gulpif to filter files
// out of the stream and run them through specific tasks. An example is provided
// which filters all images and runs them through imagemin
function source() {
  return project.splitSource()
    .pipe(gulpif('**/*.js', uglify()))
    .pipe(gulpif('src/**/*.js',babel({
            presets: ['es2015']
        })))
    .pipe(gulpif('src/**/*.html', strip()))
    .pipe(gulpif('**/*.{png,gif,jpg,svg}', images.minify()))
    .pipe(gulpif('src/**/*.html', minifyInline()))
    .pipe(gulpif('src/**/*.html', htmlmin({collapseWhitespace: true})))
    .pipe(project.rejoin());
// Call rejoin when you're finished
}

// The dependencies task will split all of your bower_components files into one
// big ReadableStream
// You probably don't need to do anything to your dependencies but it's here in
// case you need it :)
function dependencies() {
  return project.splitDependencies()
    .pipe(gulpif('**/*.js', uglify()))
    .pipe(gulpif('**/*.html', strip()))
    .pipe(gulpif('**/*.{png,gif,jpg,svg}', images.minify()))
    .pipe(gulpif('**/*.html', minifyInline()))
    .pipe(gulpif('**/*.html', htmlmin({collapseWhitespace: true})))
    .pipe(project.rejoin());
}

// Clean the build directory, split all source and dependency files into streams
// and process them, and output bundled and unbundled versions of the project
// with their own service workers

gulp.task('default', gulp.series([
  clean.build,
  project.merge(source, dependencies),
  project.serviceWorker
]));


text:
Q: Is there a straightedge and compass construction of incommensurables in the hyperbolic plane? In other words, given a segment in the hyperbolic plane is there a straightedge and compass construction of a segment incommensurable with it? In the Euclidean plane one can take the diagonal of the square built on the segment, as Pythagoreans discovered. However, equivalence of this incommensurability and irrationality of $\sqrt{2}$ relies on the Euclidean Pythagorean theorem. Pythagoreans originally believed that any two segments have a common measure, how hard would it have been for them to discover their mistake if we happened to live in a hyperbolic space?
The "straightedge" of course has to be hyperbolic. More precisely, a construction can use all Hilbert's axioms of the hyperbolic plane (including the axiom of Archimedes) except the Cantor's axiom of continuity. Equivalently, the question asks if there is a pair of incommensurable segments in every subset of the hyperbolic plane closed under straightedge and compass constructions, but not necessarily metrically complete.
This may not be as easy as it looks. There are no squares in the hyperbolic plane, and the hypotenuse of an equilateral right triangle can be commensurable with its leg. In fact, it follows from the hyperbolic Pythagorean theorem that any number in
$(\sqrt{2},2)$ can be the hypotenuse/leg ratio depending on the size of the triangle. If the ratio is rational for the given segment the Pythagorean construction won't work. One could try doubling/halving the segment multiple times and then taking hypotenuses on various concatenations, but it is conceivable that all of them remain commensurable since there do exist non-rational analytic functions that map rationals into rationals. Perhaps there is a construction more taylored to the hyperbolic plane. But standard constructions of hyperbolic parallels, and therefore of ideal triangles, do use the axiom of continuity.

A: Yes. the fundamental theorem is that the constructible angles in the non-Euclidean plane are exactly the constructible angle in the Euclidean plane. Lengths come from the two laws of cosines and the law of sines. In particular, length 1 is not constructible. As i recall, positive length $x$ is constructible if and only if $\sinh x$ is constructible in the Euclidean plane.
See my 1995 Intelligencer article at http://zakuski.utsa.edu/~jagy/bib.html
Let's see, in the fourth edition of his book, Marvin Jay Greenberg included Robin Hartshorne's proof of this, very different sort of language.
EDIT: it seems part of the question was constructible lengths with irrational ratio. $\log 3$ and $\log 2$ should work.


text:
Q: Where is the correct place to put vendor files in Cakephp 2.X? I've taken over an old CakePHP 2.X website and have no prior experience with CakePHP so please forgive me if this is a stupid question.
I was looking at making some changes to some vendor files and noticed that we appear to have multiple copies of various files (which are, for the most part, identical) in 2 different places:

*

*app/webroot/api/vendor/API/lib/

*vendors/API/lib/

Additionally I noticed there are several other vendor directories in various other places.
I am using App::import('Vendor', 'example', array('file' => 'API/lib/example.php')); to load the scripts in question.
Could someone please explain to me what the best practices are regarding file structure relating to vendor files? Additionally, am I safe to delete the duplicate copy of all the files? How does CakePHP know which copy to load?
Edit:
I have come to the conclusion that the files are being loaded from vendors/API/lib/ rather than app/webroot/api/vendor/API/lib/, is it possible that the files in the latter location are redundant? I cannot seem to find any references to them.

A: Well as Sudhir has commented you, there is a folder in your app project which is called Vendor. I would recommend you to put  it there.
app > Vendor
For example, I have created a folder called Csv for generating my own csv files through a Shell which is launching them. It is located inside app > Vendor > Csv
For importing this to my projects, I did the next for being able to use it:
     <?php

      include('GenericShell.php');
      require_once(ROOT . DS . 'app' . DS . 'Vendor' . DS . 'Csv' . DS .
      'CsvGenerator.php');

     class CsvPatientsShell extends GenericShell {

That's one only example with PHP.
One other one would be, if in this case you have a Component which is called component.php and you want to import it to a Controller which you use frequently inside your project :
Component would be located into
              Controller > Component > Namecomponent.php
The next thing you would have to do would be to do the import likewise inside your controller:
Let's say your controller's name is NameController.php and is located inside the Controller folder.
Controller > NameController.php
  public function main_function() {

    App::import('Component', 'Namecomponent');
    $NameComponent = new NameComponent();

    $this->layout = null;
    $this->autoLayout = false;
    die();
}

That would be a more correct way to do it with CakePhp but both mentioned are legit I'd say.
I hope that will help you somehow.


text:
Q: ios how to access the delegatee Say that self is the object myObject and I do something like [self setDelegate:theDelegate]
From inside theDelegate how can I access myObject ?

A: You can't. Delegate doesn't need to know about objects it's delegating. Most of delegate methods have a parameter that holds a pointer to instance which called the delegate, in case delegate needs to interact with the delegated object upon receiving a message from it. That's all you should ever do.
Example - change a background color of UITextField instance when it's done with editing:
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    // textField is a pointer to an instance that called us (the delegate)
    textField.backgroundColor = [UIColor redColor];
}


text:
Q: PhpUnit mock included class method I have two classes, ClassA, ClassB. In ClassA I have Method which call method from ClassB.
For Example:
function functionInClassB($state)
{
  if ($state) {
    return true;
  } else {
    return false;
  }
}

function functionInClassA ()
{
  if (functionInClassB(1)) {
    return "Anything";
  }
}

Now, I want test functionInClassB with PhpUnit and I dont want functionInClassB ran. I want return value which I want.
Sorry for my English, please help!!!

A: Old question, but I think you're referring to stubbing / mocking.
How easy /sensible it is depends. If you want to call functionInClassB statically then you're out of luck; static stuff doesn't work well with testing. But if you're calling the method on an instance then the following should work:
class A {
  protected $instanceOfB;
  public function functionInClassA(B $injectedInstanceOfB) {
    if ($injectedInstanceOfB->functionInClassB(1)) return 'anything';
  }
}

class B {
  public function functionInClassB($state) {
    if ($state) {
      return true;
    } else {
      return false;
    }
  }
}

class yourPHPUnitTest extends \PHPUnit\Framework\TestCase {
  public function testA() {
    $stubOfB = $this->createStub(\B::class);
    // Optionally...
    $stubOfB->method('functionInClassB')->willReturn('something');

    // Thing you want to test
    $a = new A();
    $result = $a->functionInClassA($stubOfB);
    $this->assertEqual('something', $result);
  }
}


text:
Q: Logging out an specific user in ASP.NET MVC How can I logout a specific user from my ASP.NET MVC 4 application? I prefer to perform this with the User.Id property.

A: Well, your problem, based on your comments, is about changing/updating/adding a person's role, but you wish to reflect this by logging him out.
Because of that addition/change, the new role is not reflected into user's cookie, only in the database. That is the reason he needs to be log out and login again in order this modification to take place.
Essentially, if you are using cookie authentication, what about trying this in your Startup.Auth.cs:
app.UseCookieAuthentication(new CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(1),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

Using the OnValidateIdentity will validate user's request every validateInterval minutes, so in the code above the cookie will be updated every 1 minute. If you provide a TimeSpan.FromMinutes(0) will mean that the cookie will be updated in each user's request.
Please check also the following posts and answers on StackOverflow in order to solve this particular issue.

*

*MVC 5 AddToRole requires logout before it works?

*ASP.NET Identity, add another user to role instantly (they don't have to log out and in again)

*What is ASP.NET Identity's IUserSecurityStampStore<TUser> interface?
Hope this will help.


text:
Q: Java socket/JavaFX - sending mssgs makes clients stop working I am trying to do checkers using java sockets. However, when I run a client, it gets stuck in a loop and stops responding.
So far my app has methods to draw a board, move checkers and create connection between a server and clients.
The connection is created correctly.
The problem is with play() which is responsible for handle server messages.
Pls help me to modify play() to have it working.

Client App

public class CheckersApp extends Application {

public static final int TILE_SIZE = 100;
public static final int WIDTH = 8;
public static final int HEIGHT = 8;

private Tile[][] board = new Tile[WIDTH][HEIGHT];

private Group tileGroup = new Group();
private Group pieceGroup = new Group();
private Label text = new Label();

private static int PORT = 8901;
private Socket socket;
private BufferedReader in;
private PrintWriter out;

// method to draw a board with checkers

private Parent createContent() {
        ...
}

// method to check if moving checkers is possbile
private MoveResult tryMove(Piece piece, int newX, int newY) {
      ...
}

@Override
public void start(Stage primaryStage) throws Exception {
    Scene scene = new Scene(createContent());
    primaryStage.setTitle("CheckersApp");
    primaryStage.setScene(scene);
    primaryStage.show();

    // Setup networking
    socket = new Socket("LAP00132", PORT);
    in = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);

    play();
}

// method to move checkers
private Piece makePiece(PieceType type, int x, int y) {
  ...
}

// method to get responses from Server
public void play() throws Exception {
    String response;
    try {
        response = in.readLine();
        if (response.startsWith("WELCOME")) {
           // char mark = response.charAt(8);
        }
        while (true) {
            response = in.readLine();
            if (response.startsWith("VALID_MOVE")) {
                text.setText("Valid move, please wait");

            } else if (response.startsWith("OPPONENT_MOVED")) {

                text.setText("Opponent moved, your turn");
            } else if (response.startsWith("VICTORY")) {
                text.setText("You win");
                break;
            } else if (response.startsWith("DEFEAT")) {
                text.setText("You lose");
                break;
            } else if (response.startsWith("TIE")) {
                text.setText("You tied");
                break;
            } else if (response.startsWith("MESSAGE")) {
                text.setText(response.substring(8));
            }
        }
        out.println("QUIT");
    }
    finally {
        socket.close();
    }
}

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

Server App

 public class Server {

/**
 * Runs the application. Pairs up clients that connect.
 */
public static void main(String[] args) throws Exception {
    ServerSocket listener = new ServerSocket(8901);
    System.out.println("Server is Running");
    try {
        while (true) {
            Game game = new Game();
            Game.Player playerX = game.new Player(listener.accept(), 'X');
            System.out.println("Połączony X");
            Game.Player playerO = game.new Player(listener.accept(), 'O');
            System.out.println("Połączony O");
            playerX.setOpponent(playerO);
            playerO.setOpponent(playerX);
            game.currentPlayer = playerX;
            playerX.start();
            playerO.start();
        }
    } finally {
        listener.close();}}}

class Game {

public static final int WIDTH = 8;
public static final int HEIGHT = 8;
//private Tile[][] board = new Tile[WIDTH][HEIGHT];

Player currentPlayer;

/**
 * Called by the player threads when a player tries to make a
 * move.  This method checks to see if the move is legal: that
 * is, the player requesting the move must be the current player
 */
public synchronized boolean legalMove(Player player) {
    if (player == currentPlayer) {
        currentPlayer = currentPlayer.opponent;
        currentPlayer.otherPlayerMoved();
        return true;
    }
    return false;
}

class Player extends Thread {
    char mark;
    Player opponent;
    Socket socket;
    BufferedReader input;
    PrintWriter output;

    /**
     * Constructs a handler thread for a given socket and mark
     * initializes the stream fields, displays the first two
     * welcoming messages.
     */
    public Player(Socket socket, char mark) {
        this.socket = socket;
        this.mark = mark;
        try {
            input = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
            output = new PrintWriter(socket.getOutputStream(), true);
            output.println("WELCOME " + mark);
            System.out.println("Welcome ");
            output.println("MESSAGE Waiting for opponent to connect");
        } catch (IOException e) {
            System.out.println("Player died: " + e);
        }
    }

    /**
     * Accepts notification of who the opponent is.
     */
    public void setOpponent(Player opponent) {
        this.opponent = opponent;
    }

    /**
     * Handles the otherPlayerMoved message.
     */
    public void otherPlayerMoved() {
        output.println("OPPONENT_MOVED ");
        System.out.println("OPPONENT_MOVED");
    }

    /**
     * The run method of this thread.
     */
    public void run() {
        try {
            // The thread is only started after everyone connects.
            output.println("MESSAGE All players connected");

            // Tell the first player that it is her turn.
            if (mark == 'X') {
                output.println("MESSAGE Your move");
            }

            // Repeatedly get commands from the client and process them.
            while (true) {
                String command = input.readLine();
                if (command.startsWith("MOVE")) {
                    if (legalMove(this)) {
                        output.println("VALID_MOVE");
                        System.out.println("VALID MOVE");
                    } else {
                        output.println("MESSAGE ?");
                    }
                } else if (command.startsWith("QUIT")) {
                    return;
                }
            }
        } catch (IOException e) {
            System.out.println("Player died: " + e);
        } finally {
            try {socket.close();} catch (IOException e) {}
        }
    }
}}

A: Your while(true) loop just waits for a line. It blocks the ability to perform any actions on the UI.
Spawn a separate thread to handle server communications. Obviously you need to be aware of the dangers of multi-threading and multi-thread access of model and UI data.


text:
Q: Create SQL user-defined function in ColdFusion with MS SQL Server I'm doing queries in which I want to extract the left-most n characters from a string that has been stripped of all leading and following spaces. An example is:
Select SUBSTRING(LTRIM(RTRIM(somefield)), 0, @n) AS mydata
FROM sometable

It's the only way I can figure to do it on a SQL Server.
I've never written a UDF before, but I think if I was just working on a SQL Server, I could create a user-defined function such as:
CREATE FUNCTION udfLeftTrimmed
(
    @inputString nvarchar(50),
    @n int
)
RETURNS nvarchar(@n)
AS
BEGIN
    RETURN SUBSTRING(LTRIM(RTRIM(@inputString)), 0, @n);
END

I could then do something like:
Select udfLeftTrimmed(somefield,6) AS mydata
FROM sometable

which is at least a little easier to read and understand.
The question is, how do I create the UDF in ColdFusion? All my searches for SQL user-defined function in ColdFusion just gave me how to create ColdFusion functions.

A: Since there is nothing special or "dynamic" about your UDF you really don't need to create it in CF.  You should just create it using MSSQL Manager. UDFs in SQL are like stored procedures. Once created they are a part of the DB/Schema.  so create once, use as many times as you like (as @leigh has mentioned).
Keep in mind that using a SQL udf in SQL usually requires the user prepend as in:
<cfquery...>
Select dbo.udfLeftTrimmed(somefield,6) AS mydata
FROM sometable
</cfquery>

Note the "dbo.udf..."  that dbo is important and may be why your subsequent try is failing - besides getting a duplicate UDF error by now. :)
NOTE:
To follow up on your comments and Leighs, you can create your UDF in a DB accessible to your user then access it as dbo.dbname.function ... as inthe following code:
<cfquery...>
 Select dbo.myspecialDatabase.udfLeftTrimmed(somefield,6) AS mydata
 FROM sometable
</cfquery>

Then you need only create it one time.


text:
Q: php post input validation how can I validate on test.php to echo all of the entered text for fname value to be echo as text and only text whether its html,js or php
<html>
<body>
<form action="test.php" method="POST">
Enter Your name : <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>

A: this is the key
htmlspecialchars()

A: htmlspecialchars() or htmlentities() will achieve what you need.
An example:
if (isset($_POST['txtExample'])) {
    echo(htmlentities($_POST['txtExample']), ENT_QUOTES));
}

Good luck.


text:
Q: Why do I receive null object from laravel API? In reactjs using axios when i send a get request to laravel api i receive a null object but i receive data in Insomnia api tester.
Here is my react js code:
class EditStudent extends Component {

state = {
    name: '',
    course: '',
    email: '',
    phone: ''
}

handleInput = (e) => {
    this.setState({
        [e.target.name]: e.target.value
    });

}

async componentDidMount(){
    const std_id = this.props.match.id;
    const result = await axios.get(`http://localhost:8000/api/edit-student/${std_id}`);
    console.log(result); //the answer I receive comes null

}

My api controller:
public function edit($id){

    $student = Student::find($id);
    $student = $student;
    return response()->json([
        "status" => 200,
        "student" => $student,
    ]);
}

I have also installed fruitcake for laravel CORS issue.


text:
Q: How do I declare a scala case class to be an instance of Scalaz's Semigroup? I have a type, defined as follows:
import scalaz._, Scalaz._
case class MyInt(i : Int)

I want to make an instance of Semigroup. I tried this:
object MyInt {
  implicit def myIntSemigroup: Semigroup[MyInt] = new Semigroup[MyInt] {
    def append(a: MyInt, b: MyInt) : MyInt = MyInt(a.i + b.i)
  }
}

When I run sbt console, I get this error:
[info] Set current project to hello (in build file:/home/mp/code/scala/examples/semigroup/)
[info] Compiling 1 Scala source to /home/mp/code/scala/examples/semigroup/target/scala-2.10/classes...
[error] /home/mp/code/scala/examples/semigroup/src/main/scala/Main.scala:6: object creation impossible, since method append in trait Semigroup of type (f1: MyInt, f2: => MyInt)MyInt is not defined
[error]   implicit def myIntSemigroup: Semigroup[MyInt] = new Semigroup[MyInt] {
[error]                                                       ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 5 s, completed 25-Jun-2015 08:15:37

How do I make MyInt a Semigroup so I can use |+| on it?
For completeness, here is my build.sbt file:
name := "hello"
version := "1.0"
scalaVersion := "2.10.5"
libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.1.3"

A: If you look carefully for the signature of the Scalaz semigroup, the second parameter is defined as by name while in your implementation you are  having a different signature. Change your second parameter to b: => MyInt and it should compile


text:
Q: Read a binary file using Numpy fromfile and a given offset I have a binary file which contains records of position of a plane.
Each record look like:
0x00: Time, float32
0x04: X, float32 // X axis position
0x08: Y, float32 // Y axis position
0x0C: Elevation, float32
0x10: float32*4 = Quaternion (x,y,z axis and w scalar)
0x20: Distance, float32 (unused)

So each record is 32 bytes long.
I would like to get a Numpy array.
At offset 1859 there is an unsigned int 32 (4 bytes) which indicates the number of elements of the array. 12019 in my case.
I don't care (for now) header data (before offset 1859)
Array only start at offset 1863 (=1859+4).
I defined my own Numpy dtype like
dtype = np.dtype([
    ("time", np.float32),
    ("PosX", np.float32),
    ("PosY", np.float32),
    ("Alt", np.float32),
    ("Qx", np.float32),
    ("Qy", np.float32),
    ("Qz", np.float32),
    ("Qw", np.float32),
    ("dist", np.float32),
])

And I'm reading file using fromfile:
a_bytes = np.fromfile(filename, dtype=dtype)

But I don't see any parameter to provide to fromfile to pass offset.

A: I faced a similar problem, but none of the answers above satisfied me.
I needed to implement something like virtual table with a very big number of binary records that potentially occupied more memory than I can afford in one numpy array. So my question was how to read and write a small set of integers from/to a binary file - a subset of a file into a subset of numpy array.
This is a solution that worked for me:
import numpy as np
recordLen = 10 # number of int64's per record
recordSize = recordLen * 8 # size of a record in bytes
memArray = np.zeros(recordLen, dtype=np.int64) # a buffer for 1 record

# Create a binary file and open it for write+read
with open('BinaryFile.dat', 'w+b') as file:
    # Writing the array into the file as record recordNo:
    recordNo = 200 # the index of a target record in the file
    file.seek(recordSize * recordNo)
    bytes = memArray.tobytes()
    file.write(bytes)

    # Reading a record recordNo from file into the memArray
    file.seek(recordSize * recordNo)
    bytes = file.read(recordSize)
    memArray = np.frombuffer(bytes, dtype=np.int64).copy()
    # Note copy() added to make the memArray mutable

A: You can open the file with a standard python file open, then seek to skip the header, then pass in the file object to fromfile. Something like this:
import numpy as np
import os

dtype = np.dtype([
    ("time", np.float32),
    ("PosX", np.float32),
    ("PosY", np.float32),
    ("Alt", np.float32),
    ("Qx", np.float32),
    ("Qy", np.float32),
    ("Qz", np.float32),
    ("Qw", np.float32),
    ("dist", np.float32),
])

f = open("myfile", "rb")
f.seek(1863, os.SEEK_SET)

data = np.fromfile(f, dtype=dtype)
print x

A: I suggest using numpy frombuffer:
with open(file_path, 'rb') as file_obj:
    file_obj.seek(seek_to_position)
    data_ro = np.frombuffer(file_obj.read(total_num_bytes), dtype=your_dtype_here)
    data_rw = data_ro.copy() #without copy(), the result is read-only


text:
Q: SQL Server 2005 export specific data from the old database to the new database I have two databases DB_OLD and DB_NEW, both on SQL Server 2005, and I need to import data from DB_OLD to DB_NEW.
DB_NEW has the same tables from DB_OLD plus some new columns (but this won't be a problem since the columns accept NULL values).
There's a catch: I only have to import some data, not the entire DB_OLD.
In order to simply export the data from DB_OLD i tried to use SQL Server Import and Export Wizard in order to write my own select queries. The problem is that i don't know how to set multiple sources so i can import each select into the right table from DB_NEW.
I could create a view for each table and selecting there the data that needs to be transferred but I would like not to do this.
So, my question is: how can I use multiple sources without creating views? or is out there a tool that would better suit my needs?
Thanks experts.

A: I managed to solve it out just by using the sp_addlinkedserver and use custom select and insert queries


text:
Q: How to debug "No File System for scheme: hdfs" exception in Java? Everything is correct in my code and pom.xml.

java. io. IO Exception: No File System for scheme: hdfs
  at org. apache. hadoop. fs. FileSystem. getFileSystemClass(FileSystem.java:2579)
  at org.apache.hadoop.fs.FileSystem.createFileSystem (FileSystem.java:2586)

Code:
public static void main(String[] args) throws Exception {

    System.out.println("start");

    OutputStream outputStream = null;
    try {

        String c11 = "c11";
        String c12 = "c12";
        String c13 = "c13";

        String c21 = "c21";
        String c22 = "c22";
        String c23 = "c22";

        Configuration configuration = new Configuration();
        FileSystem hdfs = FileSystem.get(new URI("hdfs://sandbox.hortonworks.com:8020"), configuration);
        outputStream = hdfs.create(
                new Path("hdfs://sandbox.hortonworks.com:8020/user/hue/oozie/workspaces/my2/windowsCompleted.txt"),
                new Progressable() {
                    @Override
                    public void progress() {
                    }
                });
        System.out.println("HELLO");
        byte[] byt = null;
        String input1 = c11 + "|" + c12 + "|" + c13 + "\n";
        String input2 = c21 + "|" + c22 + "|" + c23;
        byt = input1.toString().getBytes();
        outputStream.write(byt);

        byt = input2.toString().getBytes();
        outputStream.write(byt);

        outputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != outputStream)
            outputStream.close();
    }
    System.out.println("END");

}

POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BBN</groupId>
<artifactId>BBN</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BBN</name>
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.2-1003-jdbc4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hive</groupId>
        <artifactId>hive-jdbc</artifactId>
        <version>0.14.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-client</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.parquet</groupId>
        <artifactId>parquet-hadoop</artifactId>
        <version>1.7.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>0.20.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.parquet</groupId>
        <artifactId>parquet-avro</artifactId>
        <version>1.7.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.parquet</groupId>
        <artifactId>parquet-column</artifactId>
        <version>1.7.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.parquet</groupId>
        <artifactId>parquet-common</artifactId>
        <version>1.7.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.parquet</groupId>
        <artifactId>parquet-format</artifactId>
        <version>2.3.0-incubating</version>
    </dependency>
    <dependency>
        <groupId>org.apache.parquet</groupId>
        <artifactId>parquet-generator</artifactId>
        <version>1.7.0</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-bundle</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-core</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <!--<version>1.8.0_101</version>-->
        <version>1.7.0_79</version>
        <scope>system</scope>
        <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
    </dependency>
    <!-- Added log4j for logging -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-hdfs -->
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-hdfs</artifactId>
        <version>2.3.0</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.bbn.main.WindowsLoadData</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </plugin>
    </plugins>
</build>

</project>


text:
Q: Cypress interface is not the same between open and run command When I run cypress open here is the interface I get:

But if I run cypress run --browser chrome --headed --no-exit --spec cypress/e2e/test.cy.js the interface is not the same, I lose the button before the url (circled in red) and the url is not clickable.

Any idea how to get the same interface when I use cypress run ?


text:
Q: Store google maps lat and lng to mysql I have the following javascript.
    <script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script src=geo.js></script>
<script>
      function onPositionUpdate(position)
        {
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            document.write("Current position: " + lat + " " + lng);

        }

          </script>

I want to upload the results to my database.
Column layout
ID   |   Lat   |   LNG   |   URL
How can i accomplish this?

A: you will need to use server side language (e.g. PHP ) and send this data with ajax request


text:
Q: Progress bar on file upload on Phonegap with Framework7 I am trying to upload an image to a server using phonegap/cordova and Framework7. I am able to upload the image without any issues, but how can I display a progress bar with the upload status?
My HTML:

Javascript/JQuery
function uploadPhoto(imageURI) {
 var options = new FileUploadOptions();
 options.fileKey = "file";
 options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
 options.mimeType = "image/jpeg";
 console.log(options.fileName);
 var params = new Object();
 params.value1 = "test";
 params.value2 = "param";
 options.params = params;
 options.chunkedMode = false;

var ft = new FileTransfer();
 ft.upload(imageURI, "http://www.my-server.com/upload.php", function(result){
 console.log(JSON.stringify(result));
 }, function(error){
 console.log(JSON.stringify(error));
 }, options);

 // I have tried this to show progress but it doesn't work.
     $("#progressbar").show();
    ft.onprogress = function(progressEvent) {

    perc = Math.floor((progressEvent.loaded / progressEvent.total) * 100);

    $("#progressbar").progressbar({value:perc});

    }
 }

A: From the framework7 docs :
var progressbar = $$('#progressbar');
myApp.setProgressbar(progressbar, prec);

For other options refer on Progressbar framework7


text:
Q: What HD/SSD performance benchmarks are relevant to SQL Server? I'm looking to buy an SSD for a SQL Server computer, what benchmarks should I be comparing? High/low queue depth? Random/sequential transfer rates? IOPS?

A: IOPS pretty much.
Queue depth is irrelevant - basiaclly some higher end systems work better with more stuff queued. This wont give you any sensible information without context.
Transfer rates depend on IOPS - someone has to read / write the stuff first.
At the end, random IO, always runs down to IOPS. IOPS directy transfer to transfer rates when needed. Note that SQL Server ALWAYS does 64k IOs or multiple of that for enterprise. So, 4kb etc. is not relevant. From that you can pull all other information. Response time too slow, queues up - not enough IOPS available.

A: The benchmarks you want are IO latency for the following workloads:

*

*Random reads

*Random writes

You might also be interested in the throughput (MB/s) of these workloads:

*

*Sequential reads

*Sequential writes

For all the writes, bear in mind that caching to volatile memory before IO hits the disk can make MB/s seem higher than it really is. SSDs are as good at random IO as they are at sequential IO.

A: There is a good article on TechNet which is no longer being maintained, but which non-the-less give you an understanding of how IOPS and Disk Saturation can affect SQL Server Disk IO performance.
SQL Server Best Practices Article (TechNet)

Summary: The I/O system is important to the performance of SQL Server. When configuring a new server for SQL Server or when adding or modifying the disk configuration of an existing system, it is good practice to determine the capacity of the I/O subsystem prior to deploying SQL Server. This white paper discusses validating and determining the capacity of an I/O subsystem. A number of tools are available for performing this type of testing. This white paper focuses on the SQLIO.exe tool, but also compares all available tools. It also covers basic I/O configuration best practices for SQL Server 2005.

The article goes on to explain that SQL Server will read in multiples of 64 kb which corresponds to an Extent (which itself is 8 x 8pages ; page = 8 kb) Understanding Pages and Extents
SQL Server will read 64 kb of data (that's why you should format your disks with 64kb block size) and depending on the nature of the query in multiples of that: 64 kb, 128 kb, 256 kb, 512 kb and even 1024 kb (Enterprise Edition).
You would want to consider running a tool to test the various IO patterns (read/write; random/sequential; 8 kb - 1024 kb) depending on your SQL Server's edition and then comparing the results of an HDD with an SSD.
There is an old recommendation, that write latency for Transaction Log files should be between 1-5 ms (recommended 1 ms) and that read latency for Data files should be between 5-20 ms (recommended 10 ms).

Measure of disk latency. Lower values are better but this can vary and is dependent on the size and nature of the I/Os being issued. Numbers also vary across different storage configurations (cache size/utilization can impact this greatly).
On well-tuned I/O subsystems, ideal values would be:
•1–5 ms for Log (ideally 1 ms on arrays with cache)
  •4–20 ms for Data on OLTP systems (ideally 10 ms or less)
  •30 ms or less on DSS (decision support system) type. Latencies here can vary significantly depending on the number of simultaneous queries being issued against the system. Sustained values of more than this when the total throughput is less than expected should be investigated.
Consider these in combination with what is normal for your particular system.
Make sure to monitor disk latencies for trend analysis. The number of I/Os and latency specific to SQL Server data files can be found by using the sys.dm_io_virtual_file_stats dynamic management view in SQL Server 2005.

The article lists various counters to monitor which will provide you with a baseline, from which you can then determine the performance gains if you changes your disks from HDD to SSD.
You need a combination of:

*

*Disk Reads/sec

*Disk Writes/sec

*Average Disk/sec Read

*Average Disk/sec Write

*Average Disk Bytes/Read

*Average Disk Bytes/Write

*Disk Read Bytes/sec

*Disk Write Bytes/sec

Plan to monitor these values on your old HDD system and then compare them to the values on your SSD system and compare the values.

A: The short answer is "It Depends"
Unfortunately without knowing your usage patterns it is almost impossible to suggest an "ideal" solution.
Some things to keep in mind

*

*Separate your data, logs and O/S. You can put your data and O/S on a spinning disk and put only the logs on your SSD, this will get you a boost at a lower cost. You should really do this anyway, even if you are using spinning disks, separate all the portions out onto their own volumes, RAID 10 each if you can afford it.

*You may be better served by adding RAM to your solution, if you can load your entire database into RAM then it's so much faster than an SSD or HDD could ever be. You can accomplish this a few different ways.

*If you do go down the route of SSD throughout, make sure your backups are good. Best do this anyway :)


text:
Q: LKMG chardev.c question about register_chrdev function In register_chrdev function we have to give the device name. Even though we create a device with another name with same major number it works correctly. So what is the significance of giving name in that function.
I am a beginner to this :)

A: As per the man page for register_chrdev:
The name parameter is a short name for  the  device
and  is  displayed  in the The /proc/devices list. It also
must exactly match the name  passed  to  unregister_chrdev
function when releasing the functions.

So, the name isn't really used by the kernel at all except as a way for you to later identify the registration so you can undo it, and to have something sensible to call the driver in the /proc devices list.
The reason why having two seperate register_chrdev's with different names and the same major works is that modern Linux kernels allow for multiple drivers to register for the same major number, and basically share it. Presumably both drivers would get all calls for that major and have to decide based on minor number whether to take action or not. I'm not really sure of this, as all drivers I've ever worked on and most drives over all follow a 'one driver per major number' idiom
One last thing, rather than hardcoding a major number, its possible to just pass zero to register_chrdev and have the kernel pick a free major number for you and return it to you. This way you don't have to worry about stepping on other drivers' toes, but you do then need to have your userspace code check /proc/devices in order to mknod the /dev entry correctly.


text:
Q: How to link an APM agent like NewRelic to a Spring Boot application with bootBuildImage? I have a gradle based Spring Boot 3 application. I use the bootBuildImage gradle task in circleci to build a docker image of this application.
Now, I want to add NewRelic to this application. I know I can do it by writing my own Dockerfile but I want to do it by configuring the bootBuildImage gradle task.
I saw that I can add buildPacks like this:
tasks.named("bootBuildImage") {
    buildpacks = [...]
}

And it appears that NewRelic has a buildpack here.
How can I generate the docker image with NewRelic integration?
Bonus: I need to inject environment variable as NEW_RELIC_ENABLE_AGENT=true|false. How can I do it?

A: You're on the right track. You want to use the New Relic Buildpack that you found.
High-level instructions for that buildpack can be found here. It essentially works by taking in bindings (the secret config data) and the buildpack securely maps those values to the standard New Relic agent configuration properties (through env variables).
An example of an APM tool configured through bindings can be found here. The specific example is using a different APM tool, but the same steps will work with any APM tool configured through bindings, like New Relic.
For your app:

*

*Create a bindings directory. The root of your project is a reasonable place, but the path doesn't ultimately matter. Don't check in binding files that contain secret data :)

*In the folder, create a subfolder called new-relic. Again, the name doesn't really matter.

*In the folder from the previous step, create a file called type. The name does matter. In that file, write NewRelic and that's it. Save the file. This is how the buildpack identifies the bindings.

*In the same folder, you can now add additional files to configure New Relic. The name of the file is the key and the contents of the file are the value. When your app runs, the buildpack will read the bindings and translate these to New Relic configuration settings in the form NEW_RELIC_<KEY>=<VALUE>. Thus if you read the New Relic docs and see a property called foo, you could make a file called foo set the value to bar and at runtime, you'll end up with an env variable NEW_RELIC_foo=bar being set. The New Relic agent reads environment variables for it's configuration, although sometimes it's not the first way that's mentioned in their docs.

*Next you need to configure your build.gradle file. These changes will tell bootBuildImage to add the New Relic buildpack and to pass through your bindings.

*

*In the tasks.named("bootBuildImage") block, add buildpacks = ["urn:cnb:builder:paketo-buildpacks/java", "gcr.io/paketo-buildpacks/new-relic"]. This will run the standard Java buildpack and then append New Relic onto the end of that list. Example.

*Add a bindings list. In the same tasks.named("bootBuildImage") block add bindings = ["path/to/local/bindings/new-relic:/platform/bindings/new-relic"]. This will mount path/to/local/bindings/new-relic on your host to /platform/bindings/new-relic in the container, which is where the buildpack expects bindings to live. You will need to change the first path to point to the local bindings you created above (you can probably use a Gradle variable to the project to reference them, but I don't know if off the top of my head). Don't change the path on the container side, that needs to be exactly what I put above.

*Run your build. ./gradlew bootBuildImage. In the output, you should see the New Relic buildpack pass detection (it passes if it finds the type file with NewRelic as the contents) and it should also run and contribute the New Relic agent as is described in the buildpack README.md.

*After a successful build, you'll have the image. The key to remember is that bindings are not added to the image. This is intentional for security reasons. You don't want secret binding info to be included in the image, as that will leak your secrets.
This means that you must also pass the bindings through to your container runtime when you run the image. If you're using Docker, you can docker run --volume path/to/local/bindings/new-relic:/platform/bindings/new-relic ... and use the same paths as build time. If you're deploying to Kubernets, you'll need to set up Secrets in K8s and mount those secrets as files within the container under the same path as before /platform/bindings/new-relic. So you need to make a type file, /platform/bindings/new-relic/type, and files for each key/value parameter you want to set.
At some point in the future, we're working to have all of the APM buildpacks included in the main Java buildpack by default. This would eliminate the first config change in step #5.
Because managing bindings can be kind of a pain, I also have a project called binding-tool that can help with steps 1-3. It allows you to easily create the binding files, like bt add -t NewRelic -p key1=val1 -p key2=val2. It's not doing anything magic, just creates the files for you, but I find it handy. In the future, I want it to generate the Kubernetes YAML as well.


text:
Q: Import data with Sqoop, timestamp datatype Is it possible to import data via Sqoop to a Hive table, stored as Parquet, and previously created with decimal and timestamp datatypes?

A: Yes, you can import via to Sqoop to Hive table stored as Parquet.
Sqoop has added Parquet Support
sqoop import \
--connect jdbc:mysql://the_mysql_server/the_mysql_database \
--username the_mysql_user --password the_mysql_password \
--table sourcetablename\
--hive-import –hive-table destinationtablename\
--as-parquetfile -m 1

If you want to change datatype to hive datatype while importing data from RDBMS
e.g
use this parameter --map-column-hive col1=hivedatatype,col2=hivedatatype
sqoop import \
...
...
--map-column-hive id=STRING,price=DECIMAL


text:
Q: Matching values from columns from two files, need to speed things up dramatically Here's the script:
    #!/bin/bash
    LC_ALL=C
    while read line
    do
    gi=$(echo $line | awk '{print $2}')
    kegg=$(echo $line | awk '{print $1}')
    hitline=$(fgrep "$gi" blastoutput.tsv)
    if [ -n "$hitline" ]
    then
    echo "$hitline\t$kegg"
    fi
    done <genes_ncbi-gi.list.mod

genes_ncbi-gi.list.mod has 11,461,266 lines and looks like:
    hsa:1   21071030
    hsa:10  116295260
    hsa:100 47078295
    ...

I'm feeding the script a modified tabular blast output which looks like:
    consensus0_0_1_1142_+   gi  374264077   ref ZP_09622622.1       87.86   379 46  0   1   379 26  404 0.0  721
    consensus0_0_1_1142_+   gi  388456578   ref ZP_10138873.1       86.28   379 52  0   1   379 26  404 0.0  704
    consensus0_0_1_1142_+   gi  148358975   ref YP_001250182.1      87.34   379 48  0   1   379 26  404 0.0  703
    ...

The script works. However, it's incredibly slow and it's not going to get the job done as such.
Now, I found this thread incredibly helpful.
I came as far as:
    awk 'NR==FNR{a[$2];next}$3 in a{print $0}' genes_ncbi-gi.list.mod blastoutput.tsv

And it works and is very fast. My remaining problem is that I can't figure out how to make awk print the first column of the first file to the end of the lines of the second file that match from their third column with the array. I'm sorry I had to make a new thread about this. I don't have good enough reputation to "comment" this in the linked thread, nor do I have the reputation to ask this in the chats. Thanks.
So again: I want to print the lines from the blastoutput.tsv file that have a matching gi in the genes_ncbi-gi.list.mod file. Additionally, I want to print the first column of the genes_ncbi-gi.list.mod at the end of the matching blastoutput.tsv lines.

A: unforfunately, join's output specifiers are very rudimentary, so you have to specify every field.
join -1 2 -2 3 -o 2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,2.10,2.11,2.12,2.13,2.14,2.15,1.1 <(sort -bk2,2 genes_ncbi-gi.list.mod) <(sort -bk3,3 blastoutput.tsv)

I assume your shell is bash/ksh/zsh


text:
Q: Using reflection to verify all instances of a trait have a unique field Consider the following code. Animals should have a unique ID. I want to dynamically verify (in a test) that all concrete subtypes of Animal have unique IDs. I want my test to fail if, for example, Cat and Fish both try to pass in uniqueId = 2.
sealed trait Animal {
  val uniqueId: Int
}

abstract class Mammal(val uniqueId: Int) extends Animal

abstract class Fish(val uniqueId: Int) extends Animal

case class Dog(age: Int, name: String) extends Mammal(1)

case class Cat(favouriteFood: String) extends Mammal(2)

case class Salmon(isCute: Boolean) extends Fish(3)

I'm using reflections to get the classes.
    import org.reflections.Reflections
    val reflections                 = new Reflections("package.blah")
    val allSubtypes: Seq[Class[_ <: Animal]] = reflections.getSubTypesOf(classOf[Animal]).asScala.toList
    val concreteSubtypes: Seq[Class[_ <: Animal]] = allSubtypes.filter(c => !Modifier.isAbstract(c.getModifiers))

I'm starting to suspect it might not be possible but would love to be wrong! I have the classes but no way to instantiate instances of them because all the constructors differ and I'm not sure if I can access the uniqueId from just the class.

A: As Tomer Shetah's comment says, this doesn't seem to be possible as stated. But it may work if you can split Animal and AnimalCompanion, and make the id actually unique per AnimalCompanion:
abstract class AnimalCompanion(val uniqueId: Int)

sealed trait Animal {
  def companion: AnimalCompanion
  def uniqueId = companion.uniqueId
}

abstract class Mammal(val companion: AnimalCompanion) extends Animal

abstract class Fish(val companion: AnimalCompanion) extends Animal

case class Dog(age: Int, name: String) extends Mammal(Dog)

object Dog extends AnimalCompanion(1)

case class Cat(favouriteFood: String) extends Mammal(Cat)

object Cat extends AnimalCompanion(2)

case class Salmon(isCute: Boolean) extends Fish(Salmon)

object Salmon extends AnimalCompanion(3)

Then you find all subtypes of AnimalCompanion in the same way, and because they are all objects they'll have the MODULE$ field holding the instance and that instance will have the uniqueId field and getter method.
Without testing, something like this should work:
val allCompanionClasses = reflections.getSubTypesOf(classOf[AnimalCompanion]).asScala
val allCompanionInstances = allCompanionClasses.map(_.getField("MODULE$").get(null))
val allUniqueIds = allCompanionInstances.map(x => x.getClass().getMethod("uniqueId").invoke(x))

and then it remains to check they are actually unique e.g. by
allUniqueIds.toSet.size == allUniqueIds.size

Without changing the structure, I'd consider a different approach: provide the instances yourself, just verify they include all classes.
val instances = Set(Dog(0, ""), Cat(""), Salmon(true))

// allSubtypes defined in the question
assert(allSubtypes.toSet == instances.map(_.getClass))
// same logic as above but we already have a Set
assert(instances.map(_.uniqueId).size == instances.size)


text:
Q: How do i create a conditional query in mongoose In laravel we create a conditional query and can implement later.
use App\Http\Models\User

$user = new User;
$query = $user->find("foo");
$result = $query->getPostByUser();

In Mongoose, i tried this way, but query reuturn a executed result.
import User from "../Models/User.js";

const query = await Post.find(
    {
        foo: "bar"
    }
);
const Post = await query.limit(5);

How can i create a conditonal query in mongoose like in laravel.

A: all mongoose model's methods will return query and then you need to execute your query with either await or .exec() so try this:

    const query = Post.find({foo: "bar"});
    const post = await query.limit(5);


text:
Q: How to obtain the consecutive numbers between two numbers in rows in excel I need your help on this issue whether the solution is from excel formula, power query or macros.
I have a list of products which have a start and ending serials numbers and I would like to have automatically the list of serial numbers by rows in excel for each product based on their respective start and ending numbers.
Thanks a lot in advance.

A: You can obtain your desired output using Power Query,
• Select any cell in your original table,
• Data --> Get & Transform Data --> From Table/Range or From within sheet,
• When the PQ Editor opens, navigate to Home --> Advanced Editor,
• Make note of the Table Name in Line 2 of the code,
• Replace the existing code with the M-Code below,
• Change the table name in line 2 of the pasted code to your "real" table name
M Code
let
    Source = Excel.CurrentWorkbook(){[Name="Table11"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Item", type text}, {"Start Serial", Int64.Type}, {"End Serial", Int64.Type}}),
    #"Added Custom" = Table.AddColumn(#"Changed Type", "Custom", each {[Start Serial]..[End Serial]}),
    #"Expanded Custom" = Table.ExpandListColumn(#"Added Custom", "Custom"),
    #"Removed Columns" = Table.RemoveColumns(#"Expanded Custom",{"Start Serial", "End Serial"})
in
    #"Removed Columns"

A: If the leftmost table was loaded into powerquery (data ... from table range,  [x] column headers) add column ... custom column ... with formula
= {[Start Serial] ... [End Serial]}

then use arrows atop the column to expand into rows. File close and load


text:
Q: SOAP client in Delphi "The handle is in the wrong state for the requested operation" I have built the worlds dumbest and most simple SOAP server, in about 3 clicks, in visual studio. The exact steps in visual studio 2010: First create a new project as a web application, Then add a new item of type web service. (See accepted answer here for picture.) That soap server service Service1 has a simple method GetData:
A snippet from clientService1.pas, created using WSDL importer...
  IService1 = interface(IInvokable)
  ['{967498E8-4F67-AAA5-A38F-F74D8C7E346A}']
    function  GetData(const value: Integer): string; stdcall;
    function  GetDataUsingDataContract(const composite: CompositeType2): CompositeType2; stdcall;
  end;

When I try to run this method, like this:
procedure TForm3.Button1Click(Sender: TObject);
var
 rio : THTTPRIO;
 sv:IService1;
 addr : string;
 data : string;
begin
    //addr := '....'; // url from visual studio 2010 live debug instance.
    rio := THTTPRIO.Create(nil);
    sv := GetIService1( true, addr, rio );
    try
        data := sv.GetData(  0);

        Button1.Caption := data;

    finally
        sv := nil;

        rio.Free;
    end;
 end;

The error I get is this:
ESOAPHTTPException:
 The handle is in the wrong state for the requested operation -
 URL:http://localhost:8732/Design_Time_Addresses/WcfServiceLibrary1/Service1/ -
 SOAPAction:http://tempuri.org/IService1/GetData'.

The URL works fine when I paste the url above into a web browser, so the usual answer that the SOAP code in Delphi has the tendency to not notice an HTTP failure, does not seem likely. Rather it seems that I am either (a) experiencing breakage in WinInet (known to happen in some versions of windows), or (b) doing something wrong?
It seems to me that anybody who has visual studio and delphi both installed, should be able to try to get the dummy starter Soap server in Visual Studio talking to the soap client in Delphi, without any effort at all. But I can not figure out the simplest things.

A: At one time there was a discussion about the error in a conversation now long since deleted from Embarcadero forums, by Bruneau Babet, an embarcadero staffer.
Bruno said:

Hello,
I've posted a patched version of SOAPHTTPTrans.pas that contains a fix
  for  this issue here:
[forum link redacted, it didn't work anymore anyways, the post is gone]
You may still override the event as described in the C++Builder
  section  referred; or, much simpler, at least for Delphi users, simply
  add the  updated SOAPHTTPTrans.pas to your app's project. Let us know
  if that does  not work for you.
Cheers,
Bruneau

You can get the repair and the notes about it in its original forum formatting from the following pastebin link  and on bitbucket so you don't have to extract the file from the surrounding text.
Warren Update 2016: I have been informed by someone who tried to use the fix on Delphi XE that this fix does NOT work for them in Delphi XE.  Any further updates to the code in bitbucket that resolve the remaining bugs would be appreciated.

A: I ran into the The handle is in the wrong state for the requested operation issue in November 2018 using Delphi Tokyo 10.2.3, then looked at the code patch in the pastebin link under Arjen's answer.
That code is very old and the test code no longer works (SOAP service unavailable). Also, it is unclear from Bruneau's code what he patched exactly.
Comparing that source and the one from my Delphi version it seems that these are the (two) required modifications in the HandleWinInetError procedure ('PATCH HERE'):
function THTTPReqResp.HandleWinInetError(LastError: DWord;
                                         Request: HINTERNET;
                                         RaiseError: Boolean): DWord;

  function CallInternetErrorDlg: DWord;
  var
    P: Pointer;
  begin
    Result := InternetErrorDlg(GetDesktopWindow(), Request, LastError,
                               FLAGS_ERROR_UI_FILTER_FOR_ERRORS or
                               FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS or
                               FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, P);

    { After selecting client certificate send request again,
      Note: InternetErrorDlg always returns ERROR_SUCCESS when called with
            ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED }
    if LastError = ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED then
      Result := ERROR_INTERNET_FORCE_RETRY;
  end;

const
  { Missing from our WinInet currently }
  INTERNET_OPTION_CLIENT_CERT_CONTEXT = 84;

var
  Flags, FlagsLen, DWCert, DWCertLen: DWord;
  ClientCertInfo: IClientCertInfo;
  CertSerialNum: string;
{$IFDEF CLIENT_CERTIFICATE_SUPPORT}
  hStore: HCERTSTORE;
  CertContext: PCERT_CONTEXT;
{$ENDIF}
begin
  { Dispatch to custom handler, if there's one }
  if Assigned(FOnWinInetError) then
    Result := FOnWinInetError(LastError, Request)
  else
  begin
    Result := ERROR_INTERNET_FORCE_RETRY;
    { Handle INVALID_CA discreetly }
    if (LastError = ERROR_INTERNET_INVALID_CA) and (soIgnoreInvalidCerts in InvokeOptions) then
    begin
      FlagsLen := SizeOf(Flags);
      InternetQueryOption(Request, INTERNET_OPTION_SECURITY_FLAGS, Pointer(@Flags), FlagsLen);
      Flags := Flags or SECURITY_FLAG_IGNORE_UNKNOWN_CA;
      InternetSetOption(Request, INTERNET_OPTION_SECURITY_FLAGS, Pointer(@Flags), FlagsLen);
    end
    else if (LastError = ERROR_INTERNET_SEC_CERT_REV_FAILED) and (soIgnoreInvalidCerts in InvokeOptions) then
    begin
      FlagsLen := SizeOf(Flags);
      InternetQueryOption(Request, INTERNET_OPTION_SECURITY_FLAGS, Pointer(@Flags), FlagsLen);
      Flags := Flags or SECURITY_FLAG_IGNORE_REVOCATION;
      InternetSetOption(Request, INTERNET_OPTION_SECURITY_FLAGS, Pointer(@Flags), FlagsLen);
    end
{$IFDEF CLIENT_CERTIFICATE_SUPPORT}
    else if (LastError = ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED) and
             Supports(Self, IClientCertInfo, ClientCertInfo) and
             (ClientCertInfo.GetCertSerialNumber <> '') then
    begin
      CertSerialNum := ClientCertInfo.GetCertSerialNumber();
      hStore := ClientCertInfo.GetCertStore();
      if hStore = nil then
      begin
        hStore := CertOpenSystemStore(0, PChar('MY'));
        ClientCertInfo.SetCertStore(hStore);
      end;
      CertContext := FindCertWithSerialNumber(hStore, CertSerialNum);
      if CertContext <> nil then
      begin
        ClientCertInfo.SetCertContext(CertContext);
        InternetSetOption(Request, INTERNET_OPTION_CLIENT_CERT_CONTEXT,
                          CertContext, SizeOf(CERT_CONTEXT));
      end
      else
      begin
        if RaiseError then RaiseCheck(LastError);  // PATCH HERE
        Result := CallInternetErrorDlg;
      end;
    end
{$ENDIF}
    else if (LastError = ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED) and (soPickFirstClientCertificate in InvokeOptions) then
    begin
      { This instructs WinInet to pick the first (a random?) client cerficate }
      DWCertLen := SizeOf(DWCert);
      DWCert := 0;
      InternetSetOption(Request, INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT,
                        Pointer(@DWCert), DWCertLen);
    end
    else
    begin
      if RaiseError then RaiseCheck(LastError);  // PATCH HERE
      Result := CallInternetErrorDlg;
    end;
  end;
end;

Note that the RaiseError procedure parameter was not even used before this patch ;-)
Here is some test code using the SOAP service from NOAA's National Digital Forecast Database (NDFD) SOAP Web Service:
Uses SOAP.SOAPHTTPTrans;

const Request2 =
'<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ndf="http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl">' +
'   <soapenv:Header/>' +
'   <soapenv:Body>' +
'      <ndf:NDFDgenByDay soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'         <latitude xsi:type="xsd:decimal">38.9936</latitude>' +
'         <longitude xsi:type="xsd:decimal">-77.0224</longitude>' +
'         <startDate xsi:type="xsd:date">%tomorrow%</startDate>' +
'         <numDays xsi:type="xsd:integer">5</numDays>' +
'         <Unit xsi:type="dwml:unitType" xmlns:dwml="http://graphical.weather.gov/xml/DWMLgen/schema/DWML.xsd">e</Unit>' +
'         <format xsi:type="dwml:formatType" xmlns:dwml="http://graphical.weather.gov/xml/DWMLgen/schema/DWML.xsd">12 hourly</format>' +
'      </ndf:NDFDgenByDay>' +
'   </soapenv:Body>' +
'</soapenv:Envelope>';

const URL2= 'https://graphical.weather.gov:443/xml/SOAP_server/ndfdXMLserver.php';

procedure TFrmHandleWinINetError.Button1Click(Sender: TObject);
var
  RR: THTTPReqResp;
  Response: TMemoryStream;
  U8: UTF8String;
begin
  RR := THTTPReqResp.Create(nil);
  try
    try
      RR.URL := URL2;
      RR.UseUTF8InHeader := True;
      RR.SoapAction := 'NDFDgenByDay';
      Response := TMemoryStream.Create;
      RR.Execute(Request2, Response);
      SetLength(U8, Response.Size);
      Response.Position := 0;
      Response.Read(U8[1], Length(U8));
      ShowMessage(String(U8));
      except
        on E:Exception do ShowMessage('ERROR CAUGHT: ' + e.message);
      end;
    finally
      Response.Free;
      RR.Free;
    end;
  end;
end;

Without the patch errors in the tail end of the URL are caught, but errors in the domain name just trigger an empty error message.
With the patch those are also caught.
I have a reported the issue in the RAD Studio Quality Portal under number RSP-21862
Use at your own risk and please report any additional findings.

Addition: The issue was fixed in Dec 2018 in Delphi 10.3 Rio and the Quality Portal issue was closed with the following remark:

In RAD Studio 10.3 the implementation of THTTPReqResp was changed and replaced with THTTPClient. So, this issue no longer applies.

I have not verified this.


text:
Q: Matlab Workspace: how to best handle multiple activities and save I am new to Matlab and working through voice emotion recognition and have created folders for each emotion (7).
I am now working through FFT filtering and neural network training for each emotion.
Is it best to create a new Workspace for each emotion then save the Workspace to emotions folder?
There is the potential for variables clashes if I use the one Workspace,
or can anyone suggest a tidy way to work for ease of recall etc.


text:
Q: Rails: resource management via tabs/ajax Traditionally, a resource's index displays all of its objects, which you click to be taken to their respective show (or edit, delete, etc) methods.  Instead, our interface is more iPad-like (or Lion's new Mail app), in the sense that the index displays all of its objects as tabs on the left, with a large content area on the right.  Clicking an object fills the right content area with that object's show partial.
It seems to me that this will just require changing the show (and edit, etc) link_to's to :remote => true which will invoke show.js.erb which replaces the right-hand content with the new show partial.
// show.js.erb
$('#right').html(' <%= render :partial => "show" %> ');

Assuming that is the best way (?), it means a ***.js.erb file is needed for nearly every controller action of every resource that we want to have this behavior.  Anyway to DRY that up?

A: $("#right").html("<%= escape_javascript(render("show")) %>");
I recommend this Right way on rails-3.