text:
Q: How to get product data, if the customer has non-signed products, but there are closing products there is a product table that has client_id and status_id fields
how to get a client whose status does not have a product status signed and has a closed product status
products
  id
  client_id
  status_id

A: Essentially, your question suggests aggregation and a having clause for filtering. Assuming that status_id 1 is signed and 2 is closed, that would be:
select client_id
from products
group by client_id
having max(status_id = 1) = 0 and max(status_id = 2) = 1


text:
Q: Unable to install Python3 packages on Debian based OS I am using Kali Linux (based on Debian) and below is the output of the uname -a command
Linux kali 5.3.0-kali2-amd64 #1 SMP Debian 5.3.9-3kali1 (2019-11-20) x86_64 GNU/Linux

I want to install the following python3 packages but apt-get cannot find them:
python3-geoip
python3-whois

Below is the output when I try to install python3-whois package using apt-get command
# sudo apt-get install python3-whois
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python3-whois

I already ran the following commands to update apt-get
sudo apt-get update
sudo apt-get upgrade

The version of Python installed is 3.7.5 and python3 is located in the path: /usr/bin/python3
Update:
Below are the contents of my /etc/apt/sources.list file
#

# deb cdrom:[Debian GNU/Linux 2019.4 _Kali-rolling_ - Official Snapshot amd64 LIVE/INSTALL Binary 20191125-10:47]/ kali-last-snapshot contrib main non-free

#deb cdrom:[Debian GNU/Linux 2019.4 _Kali-rolling_ - Official Snapshot amd64 LIVE/INSTALL Binary 20191125-10:47]/ kali-last-snapshot contrib main non-free

# This system was installed using small removable media
# (e.g. netinst, live or single CD). The matching "deb cdrom"
# entries were disabled at the end of the installation process.
# For information about how to configure apt package sources,
# see the sources.list(5) manual.

deb http://http.kali.org/kali kali-rolling main non-free contrib

I even checked the apt update logs here: /var/log/apt/history.log and there is no information corresponding to the apt-get install commands I ran.
It seems like Kali Linux is not configured with the apt-get repositories by default?
How can I install the above python3 packages?
Thanks.

A: Assuming python's own pip package manager is installed and configured correctly, you may try
pip install python-geoip-python3
pip install python-whois

to install the missing packages. Depending on the installation, the binary may also be called pip3.

A: My thoughts is that Kali is based but is not using the Debian repositories itself, the package exist at https://packages.debian.org/sid/amd64/python3-whois.
So as last chance you can download it manually and install it but a log of apt update is the fest way to check if is using those repositories.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A differential equation of Buckling Rod I tried to solve a differential equation, but unfortunately got stuck at some point.
The problem is to solve the diff. eq. of hard clamped on both ends rod.
And the force compresses the rod at both ends.
the solution(v(x)) is the value of bending I need.
I assuming, that the differential equation of buckling rod is
$$ EI_{x}v''''+Pv''=0$$
where $$P$$ is a force.
and $$EI_x$$ is inflexibility.
Then I find the solution for the diff. eq:
$$v(x) = \frac{(\frac{(c_2 \sin(\sqrt(P) x))}{\sqrt(P)}+\frac{(c_1 \cos(\sqrt(P) x))}{\sqrt(P)})}{\sqrt(P)}+c_4 x+c_3$$
the boundary conditions: $$v(0)=v(l)=0=v'(0)=v'(l)$$ gives the trivial solution for $$c_{1},c_{2},c_{3},c_{4}$$
but I need non-trivial solution.
Could you please help me to find the mistake or explain what's wrong in my equation?

A: First, the solution to your equation is not exactly what you got, but,
$$v(x) = C_1 \cos ax + C_2 \sin ax + C_3x + C_4$$
where $a^2 = \frac{P}{EI_x}$. And then you need to look more carefully at your boundary conditions...
$$v(0) = C_1 + C_4 = 0,\ C_4 = -C_1$$
$$v'(0) = C_2 a + C_3 = 0,\ C_3 = -aC_2$$
$$v(l) = C_1 \cos al + C_2 \sin al + C_3 l + C_4 = C_1(\cos al - 1) +C_2(\sin al -al) = 0$$
$$v'(l) = -C_1 a \sin al + C_2 a \cos al +C_3 = -C_1 a \sin al + C_2 a (\cos al - 1) = 0$$
The last two equations have the trivial solution, but may have a non-trivial solution if the system is degenerate. In this case it equates to the determinant of the coefficient matrix being 0, or:
$$(\cos al -1)^2 + \sin al (\sin al - al)=0$$
Working on this, you can eventually reach that there is a non-trivial solution if
$$\cos al = \frac{4 \pm a^2l^2}{4+a^2l^2}$$.
The simplest of the two solutions comes when $cos al = 1$, then $al = 2\pi n$. For $n=1$, you get a non trivial solution for
$$P = \frac{4 \pi^2 EI}{L^2}$$
which is the critical load for a doubly clamped buckling rod.
The other solution, $\cos al = \frac{4 - a^2l^2}{4+a^2l^2}$ has also inifnitely many solutions, one at $al=0$, the next one around $al \approx 4$, see the graph below where both sides of the equation have been plotted. Since $4 > 2 \pi$, the effective critical load is the other one.


text:
Q: How to specify fieldnames to label using DictReader? I am specifying fieldnames using DictReader, but not all of the columns are useful or even contain data.  How can I specify which columns to label?  Here is my code:
my_tot_reader = csv.DictReader(tot_file, delimiter=';', restkey='Empty Field')
            my_tot_reader.fieldnames = ("Date",
                                        "Pivot ID",
                                        "Empty Field",
                                        "Empty Field",
                                        "Empty Field",
                                        "Empty Field",
                                        "Empty Field",
                                        "Status")

A: You can simply re-use the same key for fields you want to ignore; you'll end up with one such entry in the row dictionary with one of the column values. You do have to provide enough fields to cover all columns up to the last you do want to include.
I'd provide the sequence as a keyword argument, and you could build the tuple through multiplication:
my_tot_reader = csv.DictReader(
    tot_file, delimiter=';', restkey='ignored',
    fieldnames=("Date", "Pivot ID") + ('ignored',) * 5 + ('status',))

I used the field name 'ignored' instead.
Under the hood dict(zip(fields, columns)) is used, which will only produce as many (column, field) combinations as there are matching columns and fields; if fields is shorter than the number of columns the remaining columns are ignored. Duplicate field names result in just one dictionary key surviving:
>>> columns = ('some_date', 'some_id', 'foo', 'bar', 'baz', 'spam', 'eggs', 'some_status', 'qux', 'flub')
>>> fields = ("Date", "Pivot ID") + ('ignored',) * 5 + ('status',)
>>> dict(zip(fields, columns))
{'Date': 'some_date', 'Pivot ID': 'some_id', 'ignored': 'eggs', 'status': 'some_status'}

The extreneous columns are then assigned to the restkey key as a list. Simply not use the 'ignored' key in the resulting rows, or delete it with del row['ignored'] if you want to use the row dictionary elsewhere.


text:
Q: Problems to solve using control instructions in C for practice Need some good problems which students can think of and apply their own logic to solve them using control instructions only. The topics covered until now are basic, not even arrays are done yet. But, I want students to be perfect before proceeding to higher topics.
I tried searching for some example problems, none were as I expected / they were the ones which I already knew.
Some of which I know:

*

*Write a program to find out the value of a^b without using built in functions.

*Write a program to find out Armstrong numbers between a range.

*Write a program to print binary equivalent of a number in reverse order (since arrays are not yet done, just simple logic to print the remainder and divide the number further)

*Count all -ve, +ve and 0 numbers entered by user until user wishes to terminate the program.

*Write a program to display all divisors of a given number.

*Write a program to find if the given number is prime or not.

*Check if the given number is odd or even.

Need more good logically interesting problems which would help students to build their problem solving capability.
Thanks.
PS: Please forgive me if this question is vague or not to the point coz this question has scope for vast answers and I cannot accept a single answer, I guess?

A: Print first 33 terms of Fibonacci-Series

Write factorial of n being input from keyboard on console.

Find hours,minutes,seconds from given seconds.(305 s = 5m + 5s ....)

Calculate dot-product and cross-product of two 2D vectors.

Find the intersecting point of two lines(m=slope, (x0,y0)=a point for each line)

Calculate sin(pi/4) with using series expansion

Print the minimum of values given from keyboard on screen.

Simulate **and** , **or** and **xor** gates.

Find projection of a vector(3D) on another vector.

Find area of a polygon(2D)

Calculate the integral of x-square between x=0 and x=3 using integration by trapezoidal rule

Find roots of: (x-square) plus (two times x) plus (one) equals (zero)

A: *

*Check if number is a palindrome (1234554321)

*Rewrite a function using write() to print a number in the console (similar to printf("%d", ...))

*A function that writes all combinations of 2 digits starting from 12 to 89, not allowing twice the same digit, nor a different order (12, 13, ..., 19, 23, 24... : skipping 21 because it's done with 12)

*A function that write all combinations of n digits (n given as a parameter from 1 to 9) with the same rules (without using arrays)


text:
Q: AngularStrap Popover using trigger focus on img I am using the Popover AngularStrap using the trigger focus on a . The problem is that this trigger just works in a button element, however, the rest of the triggers can be used in a , Is there a way to make it works in a image?

A: Is this what you are looking for?


text:
Q: MVC6 ViewComponents RenderInvoke() vs Invoke() I do not understand the purpose of IViewComponentHelper.RenderInvoke, as it returns void.
The Invoke method will render an html string in my view, which is what am I using always to render an MVC6 ViewComponent.

A: The difference between Invoke and RenderInvoke is their return values and how their result gets to the final output.
With @Component.Invoke(...) you're able to execute a view component and render the value to the page. Or alternatively you can do:
@{
    HtmlString myHtmlString = Component.Invoke(...);
}

This can be useful because you get to inspect the output of the Invoke call prior to it being written to the result stream. In the case of @Component.Invoke(...) the output gets translated into an HtmlString and then lets the page write it to the result stream.
Now for RenderInvoke. Component.RenderInvoke(...) cannot be written with an @ in front of it in the Razor page due to its return value (void). The purpose of this method is: I don't want any intermediary value (HtmlString) just write it directly to the result stream (ViewContext.Writer). Therefore you will always use RenderInvoke in a format similar to this:
@{
    Component.RenderInvoke(...);
}

To sum everything up. Invoke is used for convenience when you want to write @Component.Invoke(...) or is used to inspect the value by saving it to a variable. RenderInvoke does the least amount of work, doesn't create an HtmlString and writes directly to the final output; it's also convenient when you want to render ViewComponents in @functions {...} blocks:
@functions
{
    public void SomeUtility()
    {
        ...
        Component.RenderInvoke(...);
        ...
    }
}

Hopefully this helps!


text:
Q: Fetching swagger-ui returns 404 in a ASP.NET Core 3.1 app in Azure When loading the /swagger/index.html page the browser can't find the swagger-ui resources required when deployed to an App Servicce in Azure, returning 404. It works when running locally. My setup is:
  services.AddSwaggerGen(options =>
  {
      options.SwaggerDoc("v1", new OpenApiInfo
      {
          Title = "Nexus WebApp",
          Version = "v1"
      });
      options.CustomSchemaIds(type => type.ToString());

  });

 var builder = endpoints.CreateApplicationBuilder();

 builder.UseSwagger();

 builder.UseSwaggerUI(options =>
 {
     options.SwaggerEndpoint("/swagger/v1/swagger.json", "Nexus WebApp");
 });

 var pipeline = builder.Build();

 endpoints.Map("/swagger", pipeline)
     .RequireAuthorization(new AuthorizeAttribute());
 endpoints.Map("/swagger/index.html", pipeline)
     .RequireAuthorization(new AuthorizeAttribute());
 endpoints.Map("/swagger/{documentName}/swagger.json", pipeline)
     .RequireAuthorization(new AuthorizeAttribute());

I've tried with a relative path fro the swagger endpoint like so ..\swagger\v1/swagger.json, I've tried specifying a RoutePrefix all to no avail unfortunately. I'm aware similar questions have been asked but unfortunately none seem to help.
Does anyone have any clues?
Update
These are the resources it is returning 404 for:

*

*https://{domain}/swagger/swagger-ui.css

*https://{domain}/swagger/swagger-ui-standalone-preset.js

*https://{domain}/swagger/swagger-ui-bundle.js

A: I suspect, your implementation is wrong. Here is the complete Startup code for setting up Swagger UI in NET Core:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
namespace IDGSwaggerDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion
            (CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Swagger Demo",
                    Description = "Swagger Demo for ValuesController",
                    TermsOfService = "None",
                    Contact = new Contact() { Name = "Joydip Kanjilal",
                    Email = "joydipkanjilal@yahoo.com",
                    Url = "www.google.com"
                }
                });
            });
        }
        public void Configure(IApplicationBuilder app,
       IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
            });
        }
    }
}

Check out this tutorial for more enhanced Swagger implementation.

A: Finally, after struggling with this for hours, I managed to get it to work. Note that I have the special requirement that I have a Web API for which I want controllers to use Bearer token authentication, and at the same time I want the Swagger UI to be protected by OIDC.
I have left out parts in the class that are not relevant for this answer.
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMvc();

// Add authentication to web API
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration);

// Add authentication to web app for Swagger authorization
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration);

builder.Services.AddSwaggerGen();

builder.Services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build();
});

var app = builder.Build();

app.UseAuthentication();

app.UseAuthorization();

app.Use(async (context, next) =>
{
    if (context.Request.Path.StartsWithSegments("/swagger") && context.User.Identity?.IsAuthenticated == false)
    {
        await context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme);
    }
    else
    {
        await next();
    }
});

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
});

app.MapControllers();

app.Run();


text:
Q: shell $@ variable assignment and iteration function f() {
    for arg; do
        echo "$arg"
    done
}

f 'hello world' 'second arg' '3rdarg'

this works fine:
hello world
second arg
3rdarg

but when do I assign $@ to some variable, and then it goes wrong:
function f() {
    local args="$@"
    for arg in "$args"; do
        echo "$arg"
    done
}

output:
hello world second arg 3rdarg

when I unquote the $args, then each argument was split into single word:
hello
world
second
arg
3rdarg

Lastly, I wonder if there's a way to define variable like $@. Any response will be appreciated.

A: You'll need to use an array:
function f() {
    local args=("$@")             # values in parentheses
    for arg in "${args[@]}"; do   # array expansion syntax
        echo "$arg"
    done
}


text:
Q: Spring testing postmapping with params Can anyone tell me how to test this specified method in my controller using Mockito
@RequestMapping(value = "categories", params = {"save"}, method = RequestMethod.POST)
    public String newCategory(@Valid Category category){
        categoriesService.save(category);
        return "redirect:categories";
    }

I'm trying to do this this way, but I'm getting HTTP status code 400 instead of 302 and I don't know how to create correct request to test this mapping
this.mockMvc
                .perform(post("/categories")
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .sessionAttr("category", new Category()))
                .andExpect(status().isFound())
                .andExpect(redirectedUrl("categories"));

EDIT
OK, I have changed my test to this form, and it's working now for me.
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("name", "test");
        params.add("save", "save");
        this.mockMvc
                .perform(post("/manager/categories")
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                        .params(params))
                .andExpect(status().isFound())
                .andExpect(redirectedUrl("categories"));


text:
Q: Segmentation fault when sorting an array of strings when using strcpy in c code Im trying to sort an array of string.If i remove the line
strcpy(a[j-1],a[j]);

terminal doesn't crash.
The array of strings is allocated this way in case that s the problem
array=(char **)malloc(sizeof(char *)*N);

    for(i=0;i<N;i++)
        array[i]=(char *)malloc(sizeof(char)*6);

Sort function
void bubblesort1(char **a,int K)
{
    int i,j;
    char temp[6];

    for(i=1; i<K; i++)
        for(j=(K-1); j>=i; j--)
        {
            if(strcmp(a[j],a[j-1])>0)
            {
                strcpy(temp,a[j-1]);
                strcpy(a[j-1],a[j]);
                strcpy(a[j],temp);

            }

        }

}

Why am i getting the crash?

A: Make sure you allow an extra byte for the null terminator whenever working with character strings.


text:
Q: Problems with texstudio (New computer) I just got a new computer today, its an inspiron 3542, which runs on windows 8.1 and a 64-bit OS. After which i download texstudio to edit some documents, everything works fine until i try to build and compile. When i press compile / build & view nothing updates at all, the document remains the same. But i do notice that on the bottom right there is a message that reads:
Failed to find "C:\Users\ -----\AppData\Local\Temp\texstudio_Zy5708.pdf"; perhaps it has been deleted
I had the same problem on another computer after i downloaded it, which also had a 64 bit OS and ran on windows 8.1
I am pretty new to this latex thing, therefore im not exactly the greatest at understanding it in complex terms. So please try to answer in a way that is understandable if at all possible.
Thank you in advance


text:
Q: Pandas sorting multindex and reset I'm trying to go through a dataframe with 2 index levels.
I previously removed entries from the dataframe, so often the second level is not ascending. But I want it to be.
What's a good way of resetting the second level index to a sorted list?
e.g.
a = [{'A':1, 'B':2, 'C':3, 'D':4}]
b = [{'A':1, 'B':2, 'C':3, 'D':4},
     {'A':1, 'B':2, 'C':3, 'D':5},
     {'A':1, 'B':2, 'C':3, 'D':4}]
c = [{'A':1, 'B':2, 'C':3, 'D':4}]
df = pd.concat({10:pd.DataFrame(a), 20:pd.DataFrame(b), 30:pd.DataFrame(c)})
df.index.names = ['foo', 'bar']

So df would look like this:
         A  B  C  D
foo bar
10  0    1  2  3  4
20  0    1  2  3  4
    1    1  2  3  5
    2    1  2  3  4
30  0    1  2  3  4

Now, if I happen to remove all entries, where column 'D' >=4:
df[df['D']<=4]

we get something like this:
         A  B  C  D
foo bar
10  0    1  2  3  4
20  0    1  2  3  4
    2    1  2  3  4
30  0    1  2  3  4

I now would like to reassign a sorted 'bar' index for every 'foo' index.
It then should look like this:
         A  B  C  D
foo bar
10  0    1  2  3  4
20  0    1  2  3  4
    1    1  2  3  4
30  0    1  2  3  4

This seems easy enough, but I can't figure out a good way to reset the second index level dynamically. Please help.

A: One possible solution with cumcount:
df = df[df['D']<=4]
df.reset_index('bar', drop=True, inplace=True)
df['bar'] = df.groupby(level='foo').cumcount()
df.set_index('bar', inplace=True, append=True)
print (df)
         A  B  C  D
foo bar
10  0    1  2  3  4
20  0    1  2  3  4
    1    1  2  3  4
30  0    1  2  3  4


text:
Q: Substring a middle characters in java I want to substring the value "o to p" in to two string variables like this
o
p

I tried to substring this code but it doesn't seems to work.
String x = rt.substring(rt.indexOf(" to ")+1);

this returns "to p"

A: Try this:
String[] output = "o to p".split(" to ");
String var1 = output[0]; // "o"
String var2 = output[1]; // "p"

A: If you want to do it without split (which is easier, but anyway):
int pos = rt.indexOf(" to ");
String var1 = rt.substring(0, pos);
String var2 = rt.substring(pos + " to ".length());

The point you are missing is that indexOf returns the position of the  start of the search string; if you want what comes after it, you need to increase the index by the length of that search string.

A:        String arr[] = rt.split("to");
        //arr[0] is the 1st part and arr[1] second.


text:
Q: Create a ReadOnly log file with Log4Net AND Separate log in 2 files The first question is:
I'm developing application in c# that creates 2 log files (.txt files): one for errors and another for modifications made by users. This two files are created with log4net. The issue I see is that these files can be edited, and so altered by mistake.
I would like to set these files to readonly, and that log4net still could write to them. Because if I just change the property in the file, the next log won't be written.
Is there a way to do that?
Also, the user of the app can open this logs file from within the app. For that I use the next code:
System.IO.FileInfo finfo = new System.IO.FileInfo("path");
if (finfo.Exists)
{
 //finfo.Attributes = System.IO.FileAttributes.ReadOnly;
 // I don't use the previous line at the moment, because it blocks the followings logs.
 System.Diagnostics.Process.Start("path");
}

And this is the code to create and call the logger:
public static class CLogger
{
   private static readonly ILog logger = LogManager.GetLogger(typeof(CLogger));

   static CLogger()
   {
      XmlConfigurator.Configure(new System.IO.FileInfo("path to .config file"));
   }

   public static void WriteLog(ELogLevel logLevel, String log)
   {
      if (logLevel.Equals(ELogLevel.DEBUG))
      {
         logger.Debug(log);
      }
      else if (logLevel.Equals(ELogLevel.ERROR))
            .
            .
            .
      else if (logLevel.Equals(ELogLevel.WARN))
      {
                logger.Warn(log);
      }
   }
}

Calling to the logger:
CLogger.WriteLog(ELogLevel.ERROR, ex.ToString());

And I have a second question related:
To create this 2 separate log files I use the next lines in the .config file:
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="PATH...\ErrorLog.log" />
      <param name="AppendToFile" value="true" />
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="ERROR"/>
        <param name="LevelMax" value="ERROR"/>
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="" />
        <param name="Footer" value="" />
        <param name="ConversionPattern" value="%d [%t] %-5p %username %m%n" />
      </layout>
      <threshold value="ERROR" />
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="PATH...\TraceLog.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO"/>
        <param name="LevelMax" value="INFO"/>
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="" />
        <param name="Footer" value="" />
        <param name="ConversionPattern" value="%d [%t] %-5p %username %m%n" />
      </layout>
      <threshold value="INFO" />
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header]\r\n" />
        <param name="Footer" value="[Footer]\r\n" />
        <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
      </layout>
      <threshold value="ERROR" />
    </appender>
    <root>
      <level value="ERROR" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
      <level value="INFO" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</configuration>

That works, but am I doing that all right?
I have doubt whether I should use 'LogFileAppender' or 'RollingFileAppender', that's why I used them both.
Thanks in advance.

A: Question 1:
I think that is the wrong way to approach it. If you fear they can modify it by accident, then you have two options:

*

*Make a copy of the log file and display that one.

*Display the log file in a window that you control (i.e. make the text area read-only).

Question 2:
The "normal" FileAppender will always write to the same file, this may not be an issue for your application is stopped once in a while and you can delete the log file when grows too large. For long running applications this is not an option: The rolling RollingFileAppender will create a new file every once a while (defined by certain size or certain time). This way you can delete old logfiles and never run out of disk space.
Maybe you want to check out more on appenders here.


text:
Q: Host key verification failed after changing MAC address I changed my MAC address, I believe using sudo ip link set dev interface address XX:XX:XX:XX:XX:XX, in order to be assigned a new local IP address to fix some network issues I was having. This worked perfectly, and my network issues are fixed. However, I'm now having issues with SSH as a result.
If I git pull origin master from a GitHub remote, I get:
Warning: the RSA host key for 'github.com' differs from the key for the IP address '52.64.108.95'
Offending key for IP in /home/michael/.ssh/known_hosts:105
Matching host key in /home/michael/.ssh/known_hosts:166
Are you sure you want to continue connecting (yes/no)? yes
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So not only does it refuse to connect, but also the RSA host key seems to never match the actual host. Even if I ssh-keygen -f "~/.ssh/known_hosts" -R "github.com" and accept the new host key, this error persists.
However, if I change networks from wired (with the spoofed MAC address) to wireless (with the default address), I no longer get this problem.
Is my SSH key tied to my old MAC address? Or is GitHub itself noticing that I changed my MAC address and refusing to let me connect? How can I resolve this?

A: Check if your private key has a line like Private-MAC: xxxxxxxxxxxxxxxx right at the end.


text:
Q: Hat Matching Problem - which sample points belong to $A_k$ where $k^{th}$ guest goes home with their own hat, $k = 1,2,...,n$? Guests throw their hats into a pile, and when they leave they pick up a random hat. $A_k$ is the event that the $k^{th}$ guest goes home with their own hat, $k=1,2,...,n$.
Describe a sample space first then calculate the probability of $A_k$ occurring by finding which of the sample points belong to $A_k$...I'm not sure how to do this it's kind of confusing. I read up on derangements but am still in the dark.

A: As you point out in your comment above, the sample space is the set consisting of all possible arrangements of hats with guests. The size of this set is therefore $n!$.
For the event $A_k$, the $k^{th}$ hat must be with the $k^{th}$ guest but the remaining $n-1$ hats can be arranged in any order. There are $(n-1)!$ such arrangements so this is the size of set $A_k$.
Since all outcomes in $\Omega$ are equally likely,
$$P(A_k) = \dfrac{|A_k|}{|\Omega |} = \dfrac{(n-1)!}{n!} = \dfrac{1}{n}.$$


text:
Q: How to write Query on Symfony2 How can I write this in my Repository to be able to work with it in my controller ?
SELECT COUNT(id_pnc)
FROM programmevol p
WHERE p.id_pnc IN (
    SELECT id_pnc
    FROM programmevol A
    WHERE p.id_pnc=A.id_pnc
    HAVING COUNT(*)>1
);

A: Try with this:
public function findWhateverYouWant()
{
    $em = $this->getEntityManager();

    $rsm = new ResultSetMappingBuilder($em);

    $sql = sprintf('SELECT COUNT(id_pnc)
                    FROM programmevol p
                    WHERE p.id_pnc IN ( SELECT id_pnc
                                        FROM programmevol A
                                        WHERE p.id_pnc=A.id_pnc
                                        HAVING COUNT(*)>1
                                       )',
                    $rsm->generateSelectClause()
                   );

    $query = $em->createNativeQuery($sql, $rsm);

    return $query->getResult();
}


text:
Q: simple example using resteasy-jaxrs not working I can't get the message "hello" when I visit the page.
package jaxrs.ressources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("greeting")
public class HelloRessource {
    @GET
    @Path("hello")
    @Produces(MediaType.TEXT_PLAIN)
    public String sayhello() {
    return "Hello from JAX-RS";
}}

and this class
package jaxrs.utilities;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class RestActivator  extends Application{

}

The url http://127.0.0.1:8383/JAXRS_Hello_GL-1.0/rest/greeting/hello always  displays "not found"
Is there any solution ?

this is what contains the pom.xml file :
    <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>com.esprit.jaxrs.hello</groupId>
  <artifactId>JAXRS_Hello_GL</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>

  <properties>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>
  <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependencies>

<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.1.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-client</artifactId>
    <version>3.1.4.Final</version>
</dependency>

  </dependencies>

</project>

please tell me if you need other clarification

A: Can you add the initializer:
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-servlet-initializer</artifactId>
    <version>3.1.4.Final</version>
</dependency>

Mr.Paul have the solution in the comments , please check it


text:
Q: How to prove that $\max\{f,g\}$ is Riemann integrable? If f(x) and g(x) are Riemann integrable in [a,b], why $h(x)=\max\{f(x),g(x)\}$ is still
Riemann integrable in [a,b]?
Or maybe it is wrong?

A: Yes, the $Max$ function of two Riemann -integrable functions is Riemann -integrable. This is because the $Max$ of two a.e -continuous bounded functions is also a.e -continuous and bounded.
For $f,g$ continuous, the function $Max${f,g} is continuous. This implies that (since a Riemann-integral must be a.e -continuous) , that $Max${f,g} is a.e -continuous; the points of discontinuity are contained in the union of the points of discontinuity of $f,g$.
Maybe a good (informal) way of seeing that the Max function is continuous for $f,g$ continuous (and then adjust for the fact that they are a.e. continuous) is to draw the graph of two continuous functions $f,g$ and look at the only possible problem points, i.e.,  the points {$x_i$} where the functions go from $f(x_i)<g(x_i)$ to $f(x_i)=g(x_i)$ to $f(x_i)>g(x_i)$; take a neighborhood left of $x_i$ and one right of it. Then do a $\delta - \epsilon$ argument for $g$ at the left of $x_i$, and one for $f$ at the right of $x_i$ to show the $Max$ function is continuous at those points. At every other point, $Max$ will equal either $f$ or $g$ , both of which are continuous. A similar argument works for the boundedness of $Max${f,g}.


text:
Q: Conform a custom type to RandomAccessCollection with only a subscript I usually implement types that behave like arrays, like this one:
struct Dataset: RandomAccessCollection {
    let ids: [Int]
    // Other properties and methods...

    // Boilerplate
    var startIndex: Int { ids.startIndex }
    var endIndex: Int { ids.endIndex }
    func formIndex(after i: inout Int) { i += 1 }
    func formIndex(before i: inout Int) { i -= 1 }

    subscript(index: Int) -> Int {
        // Dummy example, could be more complex and return a different type
        return ids[index]
    }
}

The problem is that I need to write each time lot of boilerplate code for the RandomAccessCollection conformance. I'd like a protocol or a mechanism reduce the boilerplate to just one or two requirements:

*

*An underlying RandomAccessCollection (like the ids property in my example) from which to infer the protocol requirements (startIndex, endIndex, formIndex)

*A subscript that would complete the remaining requirement

This mechanism would resemble the way Dataset inheritance is done in Pytorch currently: only with a __len__ and __getitem__ requirements.
I come up with a draft like this:
protocol ArrayProtocol: RandomAccessCollection where Index == BaseCollection.Index {
    associatedtype BaseCollection: RandomAccessCollection

    var baseCollection: BaseCollection { get set }
    subscript(index: Index) -> Element { get set }
}

// Provide the default implementation of the RandomAccessCollection protocol
extension ArrayProtocol {
    var startIndex: Index { baseCollection.startIndex }
    var endIndex: Index { baseCollection.endIndex }
    func formIndex(after i: inout Index) { baseCollection.index(after: i) }
    func formIndex(before i: inout Index) { baseCollection.index(before: i) }
}

This protocol would be used like that:
struct Dataset: ArrayProtocol {
    let ids: [Int]
    // Other properties and methods...

    // No more boilerplate
    var baseCollection: [Int] { ids }

    subscript(index: Int) -> Int {
        // Dummy example, could be more complex and return a different type
        return ids[index]
    }
}

But I can't find a way to make it working and I feel like the associated type is not a very good design pattern.
Any idea to solve this?
EDIT: the where Index == BaseCollection.Index clause is not necessary, the subscript could have a different Index type than the underlying collection.

A: Associated types are generally used for the generic type (usually the element of the collection). Add the associated type to it typealias BaseCollection = [Int] and remove the subscript requirement for set.
protocol ArrayProtocol: RandomAccessCollection where Index == BaseCollection.Index {
    associatedtype BaseCollection: RandomAccessCollection
    var baseCollection: BaseCollection { get set }
    subscript(index: Index) -> Element { get }
}

extension ArrayProtocol {
    var startIndex: Index { baseCollection.startIndex }
    var endIndex: Index { baseCollection.endIndex }
    func formIndex(after i: inout Index) { baseCollection.index(after: i) }
    func formIndex(before i: inout Index) { baseCollection.index(before: i) }
}

struct Dataset: ArrayProtocol {
    typealias BaseCollection = [Int]
    var baseCollection: BaseCollection = [ ]
    subscript(index: Int) -> Int { baseCollection[index] }
}

Note that if you would like to keep the set requirement subscript(index: Index) -> Element { get set } you would need also to make sure BaseCollection conforms to MutableCollection as well.
subscript(index: Int) -> BaseCollection.Element {
    get { baseCollection[index] }
    set { baseCollection[index] = newValue }
}

A: Mistake in the above answer.
func formIndex(after i: inout Index) { baseCollection.index(after: i) }
func formIndex(before i: inout Index) { baseCollection.index(before: i) }

should be
func formIndex(after i: inout Index) { baseCollection.formIndex(after: &i) }
func formIndex(before i: inout Index) { baseCollection.formIndex(before: &i) }


text:
Q: Установка PyQt5 на Windows 10 Доброго времени суток. Такая проблема: не устанавливается SIP на Windows 10. Выдает такую ошибку:
C:\Windows\system32>pip3 install PyQt5
Collecting PyQt5
Using cached PyQt5-5.9.2-5.9.3-cp35.cp36.cp37-none-win_amd64.whl
Collecting sip<4.20,>=4.19.4 (from PyQt5)
Could not find a version that satisfies the requirement sip<4.20,>=4.19.4
(from PyQt5) (from versions: )
No matching distribution found for sip<4.20,>=4.19.4 (from PyQt5)

Может кто-нибудь знает как решить проблему?


text:
Q: Why can't I assign a variable inside a function in Javascript? Very new to JS here. When I write PHP I have no problem assigning variables inside a function, but inside a JavaScript function it doesn't work. Why?
example:
function hello() {

var animal = 'Dog';
document.write(animal);

}

A: Are you calling the hello() function anywhere? If not, you will not execute the contents of the function and thus, no write will happen.

A: put this snippet inside your function to check if your function is being called
alert('snippet');
If a message box appears, your code should work, but if it does not then the function is not being executed, post some html coding also.


text:
Q: DC Motor PWM Circuit Implementation I'm a little new to this, so bear with me:
I am working on a hobby-related project that involves the operation of two DC motors in parallel, powered by a NiMH battery. (Crappy circuit diagram included)
Part specs:
-Battery- NiMH 4000mAH @ 8.4 V DC
-Microswitch - Rated 15A SPDT to toggle motor operation
-Motors - Rated ~6V operation, 11A stall and 0.9A idle
-Wire 16AWG (if relevant)
Circuit:

Problem:
The battery I have for this project is rated @ 8.4V, whereas the motors are rated for 6 V. I've been looking into finding a way to reduce the voltage to prevent motor damage and remembered PWM from a class I took (I'm an EE undergrad). I figure I could use a PWM circuit to vary the duty cycle in order to prevent motor damage, while conveniently allowing me to alter motor speed with a dial (altering the duty cycle %) without the massive power dissipation a potentiometer would create.
However, I am at a loss as to how to implement such a circuit; the only background on pulse width modulation I have had involve the creation of a basic PWM controller, not on selection and designing one around a circuit.
The circuits I have found online seem like they would work voltage-wise, however when I look at the current ratings they always fall short of the motor stall current. (Example linked)
PWM 1
PWM 2
PWM 3
My question to you is either:
a) How can I make a PWM that is suitable for such a build, or
b) How can I select the right PWM controller to add to the circuit?
Thanks for any insight you can give, please let me know if any more information is needed.
EDIT:
It is worth noting that stall current is transient, as the motors reach max rpm, and thus the idle current, fairly quickly. There is occasional slight load on the motors, however it's not enough to be an issue. My only concern would be the hypothetical PWM motor controller having issues with the initial stall current.

A: In order to properly select a motor for a load and select a controller for the motor, you need to know the rated motor current, the current that the motor can safely draw continuously. The stall current is only tolerable for a very short time. Some larger motors can not tolerate stall current at all. A good controller should limit the current. Larger industrial motors controllers commonly limit overload current to 150% of rated current for one minute and have an instantaneous shut-off at 200% to 250% of rated current. That is probably a reasonable objective for your situation also.
The linked controllers have over-current features to protect the controller, but I did not see anything that would protect the motor. Something like that would be ok for careful operation as a learning experience. Set the speed to zero and connect the motor before connecting power. Turn the speed up slowly and up carefully. That will keep the motor from drawing too much current. Check the current with an ammeter. Operating the motor at 25% of locked rotor current will probably prevent it from getting to hot quickly. With out a specification from the motor manufacturer, you will not be able to determine. How much the current it will tolerate without overheating or what temperature it can withstand.
Two motors are usually not connected to one controller, but it is ok to do that as a learning experience.

A: You would be wiser to use two motors in series and choose a 14V battery such as 4S Li-Ion or equivalent NiMH.  This way the torque is sharing the same current.
But if you expect the motors to see different loads then run in parallel with two 8.4V batteries with conservative changes in speed  to not maintain the stall currents for long during starts uphill with heavy loads.


text:
Q: Error: Cannot find control with name: 'idBed' i'm working on project using angular / spring boot i'm facing this error when trying to add input to my form , all input are working expect this one
front code

       bed
       <select class="form-control"   aria-label="Default select example"
       placeholder=" idBed "
       formControlName="idBed"
        [(ngModel)]="patient.idBed"
        #idBed
       >
         <option value="23">B1</option>
         <option value="23">B2</option>
         <option value="23">B3</option>

       </select>

export class Patient {

    id:number;
    username:string;
    email:string;
    password:string;
    firstname:string;
    lastname:string;
    numcode:string;
    gender:string;
    rome:string;
    idBed:number;
    constructor(){}

}

loginPatient(){

         this._service.loginPatientFormRemote(this.patient).subscribe(
           data =>{

            console.log(data);
            this.patient = new Patient();
            this.isCreated = true;
            this.patientError = new Patient();

A: I had the same error, try many time to change the input, is what exactly i did and know it works, i don't know what is the problem with angular in this case we hade this error
 Error: Cannot find control with name: 'idBed'

which means that the formControllerName doest existe but  it's already existe.

A: I  your .component.ts you need to define an object patient: Patient and maybe instantiate it.
if you are populating it from a service you will need to make a service call like
this.service.getBeds().subscribe(beds =>
this.patientBeds = beds);

and do a *ngFor in your mat-select


text:
Q: WooCommerce webite not displaying properly on any iOS devices I've developed a responsive website with marketplace functionalities in woocommerce and it worked perfectly fine until a couple of days ago.
It works on desktop and android devices except for all iOS devices where it shows a white screen with a fine colorful line at the top. When i try to test it in chrome with iPhone sizes it works fine.
I've spent 3 days searching for a solution but i just can't find anyone with the same problem.
SCREENSHOTS:  iphone and macbook
ALSO this is the website
It doesn't have any errors.
I've uninstalled all the plug-ins i didn't need in case one of those were causing this problem.
I've tried using a health plug-in but it didn't find any problem related to this.

A: It seems that one of my plugins were automatically adding the following CSS to the website:
.site {
overflow-y: -webkit-paged-y;

}
I just changed it to override that

.site {
      overflow-y: visible !important;
  }


text:
Q: A tool in QGIS like region group I am trying to find a tool in QGIS that does the same function as Region group in ArcGIS.
What I am trying to do is to identify uniquely each patch of a raster that has a certain value (e.g "Value" =1) using neighbouring cells.
From the region group docs:

For each cell in the output, the identity of the connected region to which that cell belongs is recorded. A unique number is assigned to each region.

A: To get a similar tool to Region Group, you need to use r.clump in GRASS, which can be accessed from QGIS if you have installed GRASS using OSGeo4W advanced installer.
The tool can be found inQGIS -> Processing Toolbox -> GRASS Commands -> Raster -> r.clump

As a test, I used small portion of land use map with 7 classes, as you can see below:

After running the tool, the land use map was reclassified into 35 groups (35 unique pixel values) with different colors to see the groups clearly, as you can see below:


text:
Q: Get request return error code 405 - method not allowed I've wrote a function for GET request from rest and it says that i have method not allowed - code 405 which is werid and i can not find solution for that.
I am doing GET via current token which was assigned to the user after logged in.
Could someone have a look on the code and tell me what might be wrong ?
func getRequest() -> Void {

    let json: [String: Any] = ["token": SessionMenager.Instance.token]

    let jsonData = try? JSONSerialization.data(withJSONObject: json)

    // create post request
    let url = URL(string: MY_URL)!
    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    // insert json data to the request
    request.httpBody = jsonData
    request.setValue("application/json;charest=utf-8", forHTTPHeaderField: "Content-Type")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }

        if let httpResponse = response as? HTTPURLResponse {
            print("GET : code -  \(httpResponse.statusCode)")
        }

        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        } else{
            print(error.debugDescription)
        }
    }

    task.resume()
}

Thanks in advance!!


text:
Q: Is it better to store class constants in data members or in methods? I recently wrote a class that renders B-spline curves. These curves are defined by a number of control points. Originally, I had intended to use eight control points, so I added a constant to the class, like so:
class Curve
{
   public:
      static const int CONTROL_POINT_COUNT = 8;
};

Now I want to extend this class to allow an arbitrary amount of control points. So I want to change this to:
class Curve
{
   public:
      int getControlPointCount() {return _controlPointCount;}
};

The question is whether it isn't better to store constants in methods to begin with, to facilitate adaptability. In other words, isn't it better to have started thus:
class Curve
{
   public:
      int getControlPointCount() {return 8;}
};

The advantage of this is that I could have just changed one symbol in the method in question, instead of moving around constants etc.
Is this a good practice or a bad one?

A: int getControlPointCount() {return _controlPointCount;}

This is an accessor. Swapping a const static for an accessor is not really a gain as litb has pointed out. What you really need to future-proof is probably a pair of accessor and mutator.
int getControlPointCount() {return _controlPointCount;} // accessor

I'd also throw in a design-const for the accessor and make it:
int getControlPointCount() const {return _controlPointCount;} // accessor

and the corresponding:
void setControlPointCount(int cpc) { _controlPointCount = cpc;} //mutator

Now, the big difference with a static object is that the control-point count is no longer a class-level attribute but an instance level one. This is a design change. Do you want it this way?
Nit: Your class level static count is public and hence does not need an accessor.

A: To better answer your question, one should also know how the controlPointCount variable is set. Is it set outside from your class? In this case, you should also define a setter. Or the Curve class is the sole responsible for setting it? Is it set only on compile time or also on runtime.
Anyway, avoid a magic number even in this form:
int getControlPointCount() {return 8;}

This is better:
int getControlPointCount() {return CONTROL_POINT_COUNT;}

A method has the advantage that you can modify the internal implementation (use a constant value, read from a configuration file, alter the value dynamically), without affecting the external of the class.

A: Typically I favour maintaining as few couplings manually as possible.
The number of control points in the curve is, well, the number of control points in the curve. It's not an independent variable that can be set at will.
So I usually would expose a const standard container reference:
class Curve
{
    private:
        std::vector<Point>& _controlPoints;

    public:
        Curve ( const std::vector<Point>& controlPoints) : _controlPoints(controlPoints)
        {
        }

        const std::vector<Point>& getControlPoints ()
        {
            return _controlPoints;
        }
};

And if you want to know how many control points, then use curve.getControlPoints().size(). I'd suspect that in most of the use cases you'd want the points as well as the count anyway, and by exposing a standard container you can use the standard library's iterator idioms and built-in algorithms, rather getting the count and calling a function like getControlPointWithIndex in a loop.
If there really is nothing else in the curve class, I might even go as far as:
typedef std::vector<Point> Curve;

(often a curve won't render itself, as a renderer class can have details about the rendering pipeline, leaving a curve as purely the geometric artifact)

A: In general, all your data should be private and accessed via getters and setters.  Otherwise you violate encapsulation.  Namely, if you expose the underlying data you lock yourself and your class into a particular representation of that underlying data.
In this specific case I would have done the something like the following I think:
class Curve
{

   protected:

      int getControlPointCount() {return _controlPointCount;}
      int setControlPointCount(int c) { _controlPointCount = c; }

   private:

      static int _controlPointCount = 0;
};

A: class Curve
{
    private:
        int _controlPointCount;

        void setControlPointCount(int cpc_arg)
        {
            _controlPointCount = cpc_arg;
        }

    public:
        curve()
        {
            _controlPointCount = 8;
        }

        int getControlPointCount() const
        {
            return _controlPointCount;
        }
};

I will create a code like this, with set function in private, so that no body can play with control point count, until we move to the next phase of development..where we update start to update the control point count at runtime. at that time, we can move this set method from private to public scope.

A: While understanding the question, I have a number of conceptual problems with the example:

*

*What is the return value for getControlPointCount() when the number of control points is not limited?

*

*Is it MAXINT?

*Is it the current number of control points on the curve (thus breaking the logic that says that this is the largest possible number of points?)

*What happens when you actually attempt to create a curve with MAXINT points? You will run out of memory eventually.

The interface itself seems problematic to me. Like other standard collection classes, the class should have encapsulated its limitation on number of points, and its AddControlPoint() should have returned an error if a limitation on size, memory, or any other violation has occurred.
As for the specific answer, I agree with kgiannakakis: a member function allows more flexibility.

A: I tend to use configuration + constant (default value) for all 'stable' values through the execution of the program. With plain constants for values that cannot change (360 degrees -> 2 pi radians, 60 seconds -> 1 minute) or whose change would break the running code (minimum/maximum values for algorithms that make them unstable).
You are dealing with some different design issues. First you must know whether the number of control points is a class or instance level value. Then whether it is a constant at any of the two levels.
If all curves must share the same number of control points in your application then it is a class level (static) value. If different curves can have different number of control points then it is not a class level value, but rather a instance level one.
In this case, if the number of control points will be constant during the whole life of the curve then it is a instance level constant, if it can change then it is not constant at this level either.
// Assuming that different curves can have different
// number of control points, but that the value cannot
// change dynamically for a curve.
class Curve
{
public:
   explicit Curve( int control_points )
      : control_points_( control_points )
   {}
   // ...
private:
   const int control_points_;
};

namespace constant
{
   const int spline_control_points = 8;
}
class Config
{
public:
   Config();
   void readFile( std::string const & file );

   // returns the configured value for SplineControlPoints or
   // constant::spline_control_points if the option does not
   // appear in config.
   int getSplineControlPoints() const;
};

int main()
{
   Config config;
   config.readFile( "~/.configuration" ); // read config

   Curve c( config.getSplineControlPoints() );
}

A: For integral type I'm usualy using:
class Curve
{
   public:
      enum
      {
          CONTROL_POINT_COUNT = 8
      };
};

If constant doesn't need for any entities except class implementation I declare constants in *.cpp file.
namespace
{
const int CONTROL_POINT_COUNT = 8;
}

A: Constants in general should not be defined inside methods. The example you're choosing has two unique features. First, it's a getter; second, the type being returned is an int. But the point of defining constants is to use them more than once, and to be able to refer to them in a convenient way. Typing "8" as opposed to "controlPointCount" may save you time, and may not seem to incur a maintenance cost, but this won't typically be true if you always define constants inside methods.


text:
Q: Jest: react-router tests returns undefined 'params' I'm trying to test a component with the MemoryRouter as indicated in the React-router docs with initial entries set so I can have params inside the wrapped component.
Component example :
render () {
  console.log(this.props.match.params.item)
}

In the App (works fine) :
<Router>
  <Switch>
    <Route exact path='/' render={() => (
      <Redirect to={`/${guessLocale()}`} />
    )} />
    <Route exact path='/:lang' component={Home} />
    <Route exact path='/:lang/:itemName' component={Vidactic} />
  </Switch>
</Router>

In the test (mount from Enzyme, match is undefined) :
mount(<MemoryRouter initialEntries={['/fr/pamp']}>
  <Vidactic />
</MemoryRouter>)

So I used this workaround but why initialEntries would not work by itself ?
mount(<MemoryRouter initialEntries={['/fr/pamp']}>
  <Vidactic match={{ params: { item: 'pamp' } }} />
</MemoryRouter>)

A: There's no Route in your test, so no matching will take place, and this.props.match will be undefined for Vidactic. Adding the route should make it work:
mount(
  <MemoryRouter initialEntries={['/fr/pamp']}>
    <Route exact path="/:lang/:itemName" component={Vidactic} />
  </MemoryRouter>
);

To avoid duplicating the routes, you might want to put the <Switch>..</Switch> part in a separate component and use that in your tests.


text:
Q: How to text value from a textbox in Coldfusion <cffunction name="TEST" returntype="string" output="false">
    <cfreturn "So your name is #name#?")>
</cffunction>

<cfif (isDefined("form.test"))>
<cfoutput>#test()#</cfoutput>

</cfif>

<cfform>
<cfinput name="names" type="text">
<cfinput name="TEST" type="submit" value="Call test()">
</cfform>

How to get the text from the textbox and set it in a variable?
THANKS!

A: This is how I would re-write this. Please note that I removed cfform and cfinput form example. They are not needed, and will likely cause issues down the road. You should pass in, as arguments, any data your function is going to need.
<cffunction name="test" returntype="string" output="false">
    <cfargument name="name" type="string" required="true" />
    <cfreturn "So, your name is #arguments.name#?" />
</cffunction>

<cfif isDefined("form.name") >
    <cfoutput>#test( htmlEditFormat( form.name ) )#</cfoutput>

</cfif>

<form method="post">
    <input name="name" type="text">
    <input name="TEST" type="submit" value="Call test()">
</form>

A: We just need to pass the correct form field name to fix this issue. In form fieldname <cfinput name="names" type="text"> and the return variable name <cfreturn "So your name is #names#?"> is not same. And unwanted closebracket ")" is there. So, If we correct the code means the issue will be fixed.
<cffunction name="TEST" returntype="string" output="false">
    <cfreturn "So your name is #names#?")>
</cffunction>

<cfif (isDefined("form.test"))>
<cfoutput>#test()#</cfoutput>

</cfif>

<cfform>
<cfinput name="names" type="text">
<cfinput name="TEST" type="submit" value="Call test()">
</cfform>

This fix answer may help you!


text:
Q: HTML rows doesn't show in browser I'm populating HTML tbody with rows through jquery,it doesn't show the new rows in the browser but if I try to see tbody content in chrome console it shows me the html but it doesn't displays that in browser.
Code: Javascript
function initTables() {
MergeObjects_ToArry(statsGroup.obamaFollowers.lang, statsGroup.trumpFollowers.lang, 'lang');
addRowToTable(statsGroup.mergedFollowers['lang'], "tblLanguageGroup");

MergeObjects_ToArry(statsGroup.obamaFollowers.timeZone, statsGroup.trumpFollowers.timeZone, 'timeZone');
addRowToTable(statsGroup.mergedFollowers['timeZone'], "tblTimeZone");

MergeObjects_ToArry(statsGroup.obamaFollowers.age, statsGroup.trumpFollowers.age, 'age');
addRowToTable(statsGroup.mergedFollowers['age'], "tblAgeGroups");
}

function addRowToTable(data, tblId) {
var rowHtml = '';

Object.keys(data).forEach(function (key, index) {
    rowHtml += "
";
    rowHtml += '' + key + '	' + data[key][0] + '	' + data[key][1] + '	';
    rowHtml += "
";
});

$("#" + tblId).find('tbody').append(rowHtml);
}

function MergeObjects_ToArry(obj1, obj2, keyName) {//obama , trump
var obama = jQuery.extend(true, {}, obj1);
var trump = jQuery.extend(true, {}, obj2);

Object.keys(obama).forEach(function (key, index) {
    if (trump[key]) {//if key exists in small
        obama[key] = [obama[key], trump[key]];// Merge values in ARRAY
    }
    else {
        obama[key] = [obama[key], 'N/A']; // key is in only obj1 so add it in mergedObj
    }
});

statsGroup.mergedFollowers[keyName] = obama;
//merge keys in trump not present in obama
}

Code: HTML

@*Account Age Comparision Trump vs Obama*@

                    Account Age Comparision Trump vs Obama

                            Account Age
                            Trump
                            Obama

@*Time Zone Comparision Trump   vs Obama*@

                    Time Zone Comparision Trump vs Obama

                            Time Zone
                            Trump
                            Obama

@*Language Comparision Trump    vs Obama*@

                    Language Comparision Trump vs Obama

In the Browser:

TLDR:
I have the data from api and I have tried to populate the three html table only one gets displayed with new data ,other two have data when I check in console but they don't get displayed.

A: Have you tried to comment the line where you add the chart 'timeZoneChart'? Your api is sending data for timeZone?


text:
Q: How do I make every span in my flexbox the same width while half of the items take a new line when there isn't enough space? I have a flexbox that contains four spans with different lengths. I want those four spans to have the same width. When the width isn't enough to display all four spans I want to display two of the spans in one line and the other two on the next line.

                AliceAliceAlice
                Bob

                Carol
                DaveDave

Unfortunately, this doesn't produce the desired result.


text:
Q: Google sheets API - get sheet details I have looking through the Google Sheets Api documentation to see if I can find how to access a sheet's information (like creation data, last update date, etc) but I can't seem to find anything.
Does anyone know if this is possible and can redirect me to some more documentation?
Thanks
-----EDIT-----
As suggested, I can probably find some information using the google drive api. But this will only give me information about the file, not the individual sheets inside of it, right? Any way to get that level of detail (sheet A was modified at date X, while sheet B was modified at date Y).


text:
Q: Error while building the project- cannot resolve method placeholder() package com.example.shivamgoyal.photografia;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.MyViewHolder> {

    private ArrayList<String> mImagesList;
    private Context mContext;
    private SparseBooleanArray mSparseBooleanArray;

    public ImageAdapter(Context context, ArrayList<String> imageList) {
        mContext = context;
        mSparseBooleanArray = new SparseBooleanArray();
        mImagesList = new ArrayList<String>();
        this.mImagesList = imageList;

    }

    public ArrayList<String> getCheckedItems() {
        ArrayList<String> mTempArry = new ArrayList<String>();

        for(int i=0;i<mImagesList.size();i++) {
            if(mSparseBooleanArray.get(i)) {
                mTempArry.add(mImagesList.get(i));
            }
        }

        return mTempArry;
    }

    public long getItemId(int position) {
        return position;
    }

    CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
        }
    };

    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_multiphoto_item, parent, false);

        return new MyViewHolder(itemView);
    }

    public void onBindViewHolder(MyViewHolder holder, int position) {

        String imageUrl = mImagesList.get(position);

        Glide.with(mContext)
                .load("file://"+imageUrl)
                .apply(RequestOptions.centerCropTransform())
                .placeholder(R.drawable.ic_launcher)
                .error(R.drawable.ic_launcher)
                .into(holder.imageView);

        holder.checkBox.setTag(position);
        holder.checkBox.setChecked(mSparseBooleanArray.get(position));
        holder.checkBox.setOnCheckedChangeListener(mCheckedChangeListener);
    }

    public int getItemCount() {
        return mImagesList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public CheckBox checkBox;
        public ImageView imageView;

        public MyViewHolder(View view) {
            super(view);

            checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
            imageView = (ImageView) view.findViewById(R.id.imageView1);
        }
    }

}

Using android studio 3.0 canary 6 on Windows. When the build process is running there is error- cannot resolve method placeholder() , using glide 3.5.2 but still getting this error. There is error only in placeholder() method, suggest some solutions to get rid from this problem.Imported glide files but it doesn't resolve.

A: Upgrade your GLIDE version .
Placeholder can be added before the loading the media . You should use below version .
compile 'com.github.bumptech.glide:glide:3.7.0'

FYI.

Glide ships with a standard placeholder , which is (for the version
  3.6.1) active by default .


text:
Q: Get domain name from URL - PHP I need to get domain name from URL
domain.com
domain.co.uk
I should get:
.com
.co.uk
I tried with explode function but doesn't display domain ".co.uk"(example)
    <?php
$url = "domain.com";

$host = explode('.', $url);

print $host[1];
?>

A: Yeah, use php function parse_url (http://php.net/parse_url), it will help you.

A: UPDATE based off (currently third answer) -
Remove domain extension
$url = 'php.co.uk';
preg_match('/(.*?)((?:\.co)?.[a-z]{2,4})$/i', $url, $matches);

print_r($matches);

IGNORE FOLLOW - Bad practice, but still explains working of explode.
See when you explode and you use '.', it finds it twice in .co.uk.
So if you where to echo both $host[1] & $host[2] you would get co uk respectively.
So as a partially complete (not sure what your end game is) solution:
Solution:
$url = "domain.co.uk";

$host = explode('.', $url);
$first = true;
foreach($host as $hostExtension){
  if($first){
      $first = !$first;
      continue;
  }
 else{
      echo $hostExtension .'<br>';
  }
}

To be clear though, the other answers explain how you should be parsing the URL. I just merely thought to explain why (answering the question) your code was doing/return what it was and how you would get your intended result.


text:
Q: Posting a model to the controller I asked a question to fill in the model data on the client, into arrays.
Add items to JSON objects
Now my problem is how to post it to the controller.  I have tried this:
 public ActionResult ItemRequest (Model1 model)
 {
    ////
 }

but it never gets there.
I'm trying with an AJAX request to send it:
 function sendRequest() {
    jsonData.items = itemArray;
    $.ajax({
       url: '@Url.Action("ItemRequest")',
       type: 'POST',
       data: JSON.stringify(jsonData),
       ///// and so on
  }

But the action result is never invoked.  I can drop the 'JSON.stringify' and it makes no difference.  Any ideas on how to post this object to the controller?
If I make a psuedo model in JS it works fine, but I don't want to have to make this model, I'd rather use the model passed to the page.
  function itemModel () {
     var self = this;
     this.itemNumber = $("#itemNumberId").val();
     /// etc.
     self.items = [];
  }

  function itemsModel () {
    var self = this;
    this.itemNumber = $("#itemNumberId").val();
     /// etc
  }

then
  var itemCount = 0;
  function addItem() {
    var newItem = new itemModel();
    newItem.items[itemCount] = newItem;
    /// etc
  }

This works fine.
I send the array itemModel the same way with a JSON.stringify directly into the controller method
 public ActionResult ItemRequest(ItemModel model)

A: We are using this to send Data to API controller Methods on our internal test sides:
It's probably not the prettiest solution, but it can be used on any page.
What data should be sent:
$("#btnSend").click(function () {call("controller/method", {ParamName: $("#field").val()}); });

To send the data to a controller:
$(document).ready(function () {
    var call = function (method, requestData, resultHandler) {
        var url = method.substring(0, 1) == "/api/" + method;

        $.ajax({
            url: url,
            dataType: 'json',
            data: JSON.stringify(requestData),
            type: 'POST',
            contentType: 'application/json',
            success: function (data) {
                var isSuccess = data.Status == "success";
                $("#jsonResponse").val(FormatJSON(data));

                if (isSuccess && jQuery.isFunction(resultHandler)) {
                    resultHandler(data);
                }
            }
        });
    };


text:
Q: How do I test iOS upgrade scenarios? I had basic and premium versions of my app installed on one of my test phones. I then updated the firmware to iOS 7.1 Beta 5.
The basic and premium versions have identical binaries (certain features are just switched on or off), but after upgrading, the premium version crashes on launch but not the basic version. I can run the pro version from xcode and see it's crashing because it can't find the model for the persistent store - cocoa error 134130 (though the check to whether  exists at the appropriate location returns true). I can run fresh installs of both versions of the app on the 7.1 simulator with no problems.
I'm not sure whether this is something related to the beta, or if I had a debug version of the premium app on the phone previously and that caused some problem after upgrading.
I'd like to be sure by doing some testing around installing it on 7.0, configuring it various ways, then upgrading to 7.1 and seeing there are any problems. But I'm not sure how to do this. If I run it on the simulator, then switch the simulator to 7.1, it doesn't preserve the apps. It won't let me restore back to a previous version for my test phone; I do have my personal phone running iOS 7 and I could test the upgrade on there, but without the ability to restore I could only run one test.
Any suggestions?

A: Also possible copy you app from one simulator version to another ~/Library/Application Support/iPhone Simulator/7.0/Applications/UUID-UUID-UUID-UUID-UUID to another ~/Library/Application Support/iPhone Simulator/7.1/Applications/UUID-UUID-UUID-UUID-UUID and see what happens.
Simulator should be relaunched to reload available apps.

A: The only way to find the crash is to view the crash logs in Organizer "Xcode -> window -> organizer"


text:
Q: A regex in python for matching multiple lines of certain pattern Hi I am trying to build a multiline regex to group a line followed by lines beginning with at least one white space.  For example
interface Ethernet 1/1

      ip address <>
      mtu <>

ip tcp path-mtu-discovery

router bgp 100

     network 1.1.1.0

How to build a regex that would group "interface ethertnet 1/1" and its subconfig into one group, and "ip tcp path-mtu-discovery" into another group
and the bgp and it's subcommands into another group.  In other words, a line beginning with non-whitespace character should get grouped with, if it is followed by, lines beginning with whitespaces.  Two lines beginning with non-whitespace character should be two different groups.
I tried some of the regex already discussed, but that doesn't help.
Thanks in advance

A: >>> lines = '''interface Ethernet 1/1
...
...       ip address <>
...       mtu <>
...
... ip tcp path-mtu-discovery
...
... router bgp 100
...
...      network 1.1.1.0
... '''
>>> for x in re.findall(r'^\S.*(?:\n(?:[ \t].*|$))*', lines, flags=re.MULTILINE):
...     print(repr(x))
...
'interface Ethernet 1/1\n\n      ip address <>\n      mtu <>\n'
'ip tcp path-mtu-discovery\n'
'router bgp 100\n\n     network 1.1.1.0\n'

*

*^\S.+: matches lines that start with non-space character.

*\n[ \t].*: matches lines start with space character.

*\n$: matches empty line

*\n(?:[ \t].*|$): matches lines start with space or (|), empty line

Using itertools.groupby:
lines = '''interface Ethernet 1/1

      ip address <>
      mtu <>

ip tcp path-mtu-discovery

router bgp 100

     network 1.1.1.0
'''

class LineState:
    def __init__(self):
        self.state = 0
    def __call__(self, line):
        # According to the return value of this
        # method, lines are grouped; lines of same values are
        # grouped together.
        if line and not line[0].isspace():
            # Change state on new config section
            self.state += 1
        return self.state

import itertools
for _, group in itertools.groupby(lines.splitlines(), key=LineState()):
    print(list(group))

prints:
['interface Ethernet 1/1', '', '      ip address <>', '      mtu <>', '']
['ip tcp path-mtu-discovery', '']
['router bgp 100', '', '     network 1.1.1.0']


text:
Q: Send text from Android phone to computer (OSX) I'm having a hard time figuring out how to send data from my Android phone (running 4.3) to my computer. My phone will be outputting some data every couple of seconds, and I would like for my computer to display it. Just displaying it on the terminal would be fine.
I've looked into BlueCove and it is just broken. It is using deprecated calls and it simply doesn't work.
So how do I do this?
I'm just sending ASCII text every couple of seconds.
I've also looked at the bluetooth sample app. However, I don't know how to make the text appear on my computer screen. (Admittedly, the app was meant to work with Android phones.)
Is what I'm asking even possible?
Side note: This doesn't need to be complicated. In fact, I would prefer something down and dirty. I'm just going to be using the output for debugging and testing.


text:
Q: On enter, search for the string in db i have this code:

    Please make your selection:

            <input type="button" value="Insert" onclick="form.html" />

            <input type="button" value="View" onclick="window.location='view-master.php';" />

            <input type="button" value="Edit" onclick="edit.html" />

              <input type="button" value="Search" onclick="showsearchform()" />

then the JS:

when i click on search i get the inoutbox, but what i want to do now is when i type a surname into the box and hit enter i want to connect to the db and search for this surname
I can do the db stuff just not sure of the JS and Jquery

A: html
  <input type="text" name="txt" onkeypress="Search" />

javascript


text:
Q: HTML in new Browser Tab or WIndow In my PHP file, I have a string variable that contains complete HTML code.
$content = '<html>
<head>
  <script>--Some javascript and libraries included--</script>
  <title></title>
</head>
<body>
   <style>--Some Styling--</style>
</body>
</html>';

I get this in a loop and now I want this HTML to open in new tab or window of browser. With every iteration, there would be a new Tab or Window. I don't think it is possible on server side so may be some JavaScript need to be concatenated to it.

A: In loop, I've created the URL to hit the controller and set the parameters with it and then simple use the following statement.
echo '<script type="text/javascript"> window.open("'. $url .'"); </script>';

and In the $url variable, I created the URL and post data in it. That's how, the new tab will open that hits the url and result will be my complete HTML.


text:
Q: Remove Models from Collection Being Filtered I'm filtering a Backbone collection by running it through an _.each() loop and removing items if they don't fit certain criteria.
For some reason, the loop always stops after filtering about half the collection.
I have two theories:

*

*I've noticed that the loop always ends on the item positioned last in the collection. Maybe the items are passed to the loop in a random order, but the loop is referencing the "actual" order of the collection.

*By removing items from the same collection being filtered, I'm messing up the loop and it thinks there are fewer items than there actually are.
Here's a working version: http://jsfiddle.net/aZ9zJ/. Can someone tell me what's going on?
--
By the way, I know about filtering functions like _.filter() and _.where() but prefer to avoid them because they return an array rather than a collection.
I'm open to switching over to a filtering function instead, but would still like to understand why the each/remove technique I'm trying doesn't work.
App.View.Items = Backbone.View.extend({
    tagName: 'p',

    initialize: function() {
        Backbone.on('filter:now', this.filterItems, this);

        this.filtered = new Backbone.Collection;

        this.collection.each(function(item) {
            this.filtered.add(item);
        }, this);

        this.filters = new Backbone.Collection([
            {
                property: 'director',
                criteria: 'Orson Welles'
            }
        ]);

        Backbone.trigger('filter:now');
    },

    filterItems: function() {
        this.filters.each(function(filter) {
            this.filtered.each(function(item) {
                if ( item.get(filter.get('property')) === filter.get('criteria') ) {
                    this.filtered.remove(item);
                }
            }, this);
        }, this);

        console.log(this.filtered);
    }

});

Unfiltered collection:
var itemCollection = new App.Collection.Items([
    {
        title: 'Citizen Kane',
        director: 'Orson Welles'
    },
    {
        title: 'Touch of Evil',
        director: 'Orson Welles'
    },
    {
        title: 'The Third Man',
        director: 'Orson Welles'
    },
    {
        title: 'Jaws',
        director: 'Steven Spielberg'
    },
    {
        title: 'Magnificent Ambersons',
        director: 'Orson Welles'
    }
]);

Instantiate view:
var itemsView = new App.View.Items({ collection: itemCollection });

A:
By the way, I know about filtering functions like _.filter() and
  _.where() but prefer to avoid them because they return an array rather than a collection.

But you should use them none the less.
Messing with the collection being filtered changes its length, so the results may be unpredictable. You should filter your collection and then set the array returned from this operation on your other collection.
this.filtered.set( this.collection.filter(function(item) {
            return item.get(filter.get('property')) === filter.get('criteria');
            }
))

http://jsfiddle.net/aZ9zJ/1/


text:
Q: How to make dynamic list changes in python? Guy am trying to create pages for my tk GUI,so I got this code below that works perfectly,on click of next button it get the first 5 and till end of 100 and vice versa on click of prev button
import tkinter as tk
import math

items = [str(n) for n in range(100)]

page = 0
per_page = 5
n_pages = math.ceil(len(items) / per_page)

def update_list():
    print(page)
    start_index = int(page * per_page)
    end_index = int((page + 1) * per_page)
    items_in_page = items[start_index:end_index]
    view_text = "Page %d/%d: %s" % (page + 1, n_pages, ", ".join(items_in_page))

def change_page(delta):
    global page
    page = min(n_pages - 1, max(0, page + delta))
    update_list()

def prev_btn():
    change_page(-1)

def next_btn():
    change_page(+1)

win = tk.Tk()
win.title("clickers")
tk.Button(win, text="next", command=next_btn).pack()
tk.Button(win, text="prev", command=prev_btn).pack()
show = tk.Entry(win)
show.pack()
update_list()  # to initialize `show`
win.mainloop()

I want to adjust this part of code
items = [str(n) for n in range(100)]

into a list like this,and get it working as just switching them doesn't work
list_ = [1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15], [16,17,18]]

items =[str(n) for n in list_]

so oncick of next button it return first 2(any number choice) list and vice versa for prev,when that's done,please note that this list originally comes from multiple rows of a database that's has been selected,not just some  variable holding a list like I have it,so I need help on how to directly use the loop to get first 2 rows(2 list) from the database,and immediate past 2 rows for prev button


text:
Q: jQuery UI and Splitter Using jQuery UI, how can I use a Splitter kind of feature like the one at
http://methvin.com/splitter/3csplitter.html?
I am asking this as I need 2 things to be implemented on my page;
Portlet (Draggable) :: http://jqueryui.com/sortable/#portlets
and Vertical Splitter :: http://methvin.com/splitter/3csplitter.html
I am not sure how good coding practice it is if I am including 2 separate libraries (even though both are jQuery based);
like http://host.sonspring.com/portlets/ for Portlets
and http://methvin.com/splitter/3csplitter.html for Splitter

A: I used Dmitriy's answer as the base of my implementation. Note that there is nothing stopping that particular implementation from doubling the bounding box when the slider is dragged to the right.
I needed a simple non-moveable splitter for now (with the view to making the panes resizable in the future), and my application is already using jQuery, so I achieved this by changing part of his code as follows:
$(function ()
{
    $(".resizable1").resizable(
    {
        autoHide: false,
        containment: "#wrap",
        ...

I also changed the css cursor style (among other things) to prevent the resizable cursor from being displayed as follows:
.ui-resizable-e {
    cursor: default;
    ...

Thanks Dmitriy!

A: Here is an example on how to create the splitter using jQuery UI:
HTML:

Script:
$(function ()
{
    $(".resizable1").resizable(
    {
        autoHide: true,
        handles: 'e',
        resize: function(e, ui)
        {
            var parent = ui.element.parent();
            var remainingSpace = parent.width() - ui.element.outerWidth(),
                divTwo = ui.element.next(),
                divTwoWidth = (remainingSpace - (divTwo.outerWidth() - divTwo.width()))/parent.width()*100+"%";
                divTwo.width(divTwoWidth);
        },
        stop: function(e, ui)
        {
            var parent = ui.element.parent();
            ui.element.css(
            {
                width: ui.element.width()/parent.width()*100+"%",
            });
        }
    });
});

This is a popular script. I've added little modifications for the fluid layout.
jsFiddle example

A: My first thought was: first you select all the boxes except the last.  Those get a splitter to their right side.
Then, when the splitter is moved, only the two boxes touching the splitter are resized.
This is an example you can copy paste; it works as is.
This can be used for any number of columns; just make sure you also adapt the css.
I added some buttons to expand 1 box; also a reset button.

$(function () {
        // settings
        var minWidth = 15;
        var splitterWidth = 10;  // this sh ould match the css value

        var splitter   =  $('.ui-resizable-e');
        var container =   $('.wrap');
        var boxes =       $('.resizable');

        var subBoxWidth = 0;

        $(".resizable:not(:last)").resizable({
          autoHide: false,
          handles: 'e',
          minWidth: minWidth,

          start: function(event, ui) {
            // We will take/give width from/to the next element; leaving all other divs alone.
            subBoxWidth = ui.element.width() + ui.element.next().width();
            // set maximum width
            ui.element.resizable({
              maxWidth: subBoxWidth - splitterWidth - minWidth
            });
          },

          resize: function(e, ui) {
            var index = $('.wrap').index( ui.element );
            ui.element.next().width(
              subBoxWidth - ui.element.width()
            );
          },

        });
        // collapses all the other boxes to the minimum width; expands the chosen box to what ever width is left
        $('.expand').click(function () {
          var index = $(this).data('index');
          var boxesToCollapse = boxes.length - 1;
          var widthLeft = container.width() - boxesToCollapse * (minWidth + splitterWidth);
          for (var i=0; i<boxes.length; i++) {
            boxes.eq(i).width( i==index ? widthLeft : minWidth);
          }
        });
        $('.reset').click(function () {
          boxes.removeAttr('style');
        });
      });
body {
        padding: 0;
        margin: 0;
      }
      .wrap {
        width: 100%;
        white-space: nowrap;
        background-color: #c0c0c0;
      }
      .resizable {
          width: 25%;
          height: 120px;
          display: inline-block;
          overflow: hidden;
      }
      .ui-resizable-e {
          cursor: e-resize;
          width: 10px;
          top: 0;
          bottom: 0;
          background-color: gray;
          z-index: 10;
      }

 HELLO

 WORLD

 FOO

 BAR

      <input type="button" value="expand 0" data-index="0" class="expand">
      <input type="button" value="expand 1" data-index="1" class="expand">
      <input type="button" value="expand 2" data-index="2" class="expand">
      <input type="button" value="expand 3" data-index="3" class="expand">
      <input type="button" value="reset" class="reset">

A: The Splitter component part of the Shield UI framework allows you to use a mixture of horizontal and vertical splitters.


text:
Q: Scientific formats, subscripts and superscripts in RMarkdown table (docx output) Let's say I have the following rmd:
---
title: "Table won't work"
author: "Exhausted student"
date: "2022/01/28"
output:
  bookdown::word_document2
---

```{r table, echo=F, warning=F, message=F}
library(tidyverse)
a <- tibble(
  constants = c("c", "NA", "h", "e", "H2O"),
  values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
)

knitr::kable(a, digits = 35)
```

which produces this table in Word.
The Problem
I need the scientific format to use superscripts and multiply sign (i.e. 2.998 × 108), and some cells requires subscript (e.g. NA and H2O).
The final table should look like this. How can I do that?
What I've tried/would never try

*

*huxtable package and its markdown() function: I managed to format some contents as H~2~O, then enable markdown across table by huxtable(a) %>% `markdown<-`(TRUE). Which did not recognize the syntax, and apparently would not work in forseeable future according to the author.

*flextable and as_sub(): Produces right format. I pass the lables to flextable::compose(), where the labels were something like as_paragraph(list_values = list("H", as_sub("2"), "O"). The code is obviously too lengthy; plus i have to manipulate cells one-by-one. Technically still doable, but I do have tables with 100+ cells needed formatting.

*Output first, format in Word later: Again, needed manipulation one-by-one. Would be an option if it would work everything out automatically.

*Convincing the school bureaucrats to accept html/pdf/latex as output: this is forever an impossible option.

*Format outside word then export formatted table as image: strictly forbidden in the reports.

Edit: the table works now! Great thanks to Maël's answer, but please check my own findings to see my final result:

A: You can use tildes (~) to put in subscript and carets (^) for superscripts; and use sprintf to get the expected digit format:
---
title: "Table won't work"
author: "Exhausted student"
date: "2022/01/28"
output:
  bookdown::word_document2
---

```{r table, echo=F, warning=F, message=F}
library(tidyverse)

expSup <- function(x, digits=3) {
  sprintf(paste0("%05.", digits, "f x 10^%d^"), x/10^floor(log10(abs(x))), floor(log10(abs(x))))
}

a <- tibble(
  constants = c("c", "N~A~", "h", "e", "H~2~0"),
  values = expSup(c(2.998e8, 6.022e-23, 6.626e-34, -1.602e-19, 18.02))
)

knitr::kable(a)
```

A: An option that probably falls in the no-go zone for this open issue:

*

*Create a html document,

*Insert html tags for subscripts,

*Open the html file (not the viewer),

*ctrl+c, then ctrl+v in your word file.

---
output: html_document
---

```{r table, echo=F, warning=F, message=F}
library(tidyverse)
library(gt)
a <- tibble(
    constants = c("c", "N<sub>A</sub>", "h","e","H<sub>2</sub>O"),
    values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
)
a %>%
  mutate(constants = map(constants, html)) %>%
  gt() %>%
  fmt_scientific(values)

A: The expSup() function in Maël's answer converted the scientific formats into markdown format. For my script, I modified the function a little:
exp_sup <- function(x, digits = 3) {
  sprintf(paste0("%05.", digits, "f $\\times$ 10^%d^"), x / 10^floor(log10(abs(x))), floor(log10(abs(x))))
}

I changed "f x 10^%d^" to "f $\\times$ 10^%d^", so that it displays proper multiply symbol (×).
Using the format in flextable
The format works great in Kable. However, a large portion of my workflow requires flextable to make caption/cross reference/publication style/etc. Unfortunately, although the expSup function automatically formats scientific notations into markdowns, it cannot make markdown syntax work in flextable.
However, ftExtra::colformat_md() can. Hence, by combining the modified exp_sup() function with ftExtra, I was finally able to produce an academic-looking table:

Below is the code for my final output; if you are also trying to produce reproducible academic reports with lots of tables in Word format, hope this helps!
---
title: "The tables work!"
author: "Satisfied Student"
date: "2022/01/28"
output:
  bookdown::word_document2:
    reference_docx: styleRef.docx
---
```{r setup, include = F}
library(easypackages)
packages(
  "tidyverse",
  "flextable", # This works best for my workflow
  "ftExtra", # For markdown formatting work in flextable
  "officer" # You can customize appearance/format/etc. of caption *prefixes*
)

knitr::opts_chunk$set(
  warning = FALSE,
  message = FALSE,
  echo = FALSE,

  # Make the table caption format definable in reference_docx styles
  tab.cap.style = "Table Caption",

  # Make "Table 1:" prefixes not bold
  tab.cap.fp_text = fp_text_lite(bold = FALSE)

  # The tab.cap settings MUST be in a separate chunk from tables
)

# Converts scientific format to markdown
exp_sup <- function(x, digits = 3) {
  sprintf(paste0("%05.", digits, "f $\\times$ 10^%d^"), x / 10^floor(log10(abs(x))), floor(log10(abs(x))))
}
# The $\\times$ makes proper multiply symbols
```

```{r table}
a <- tibble(
  constants = c("c", "N~A~", "h", "e", "H~2~O"),
  values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
)

a %>%
  mutate(values = exp_sup(values)) %>%
  flextable() %>%
  set_caption(
    caption = "(ref:foo)", # Produces formatted caption text
    style = "Table Caption"
  ) %>%
  colformat_md() %>% # Subscript/superscript works in flextable now!
  theme_booktabs() %>% # The 3-part-table used in academics
  align(align = "center", part = "all") %>% #Align everything to center
  set_table_properties(layout = "autofit") # Comfortable width/height every cell
```

(ref:foo) A scientifically formatted `flextable` with ^superscripts^ and ~subscripts~

A: Your code should look like this:
```
{r table, echo=F, warning=F, message=F}
library(tidyverse)
a <- tibble(
  constants = c("c", "NA", "h", "e", "$H_2O$"),
  values = c("$2.998 * {10^{8}}$", "$6.022 * {10^{-23}}$", "$6.626 * {10^{-34}}$", "$-1.602 * {10 ^{-19}}$", "$1.802 * {10^{1}}$")
)

knitr::kable(format = "html", a, digits = 35)
```

Which will give you the output like this:


text:
Q: How can I position a FloatingActionButton spanning two widget in Flutter? I trying to position a FloatingActionButton spanning two widget in flutter.
like this.

However, this is my app screen.

I can't stack the button on the center of two widget.
How can I solve my question :(? This is the sample code of my app. Thanks.
import 'package:flutter/material.dart';
class UserProfileBody extends StatelessWidget {
  const UserProfileBody({
    Key? key,
  }) : super(key: key);

  Widget _buildUserProfilePhoto(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.width,
      ),
      width: MediaQuery.of(context).size.width,
      child: const Image(
        fit: BoxFit.contain,
        image: NetworkImage(defaultUserProfileImage),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _buildUserProfilePhoto(context),
        Stack(
          children: [
            Align(
              alignment: Alignment.topRight,
              child: FloatingActionButton(
                onPressed: () {},
                child: const Icon(Icons.photo_camera),
              ),
            ),
            Column(
              children: [
                ListTile(
                  title: const Text('the title'),
                  subtitle: const Text('the subtitle'),
                  onTap: () {},
                )
              ],
            ),
          ],
        ),
      ],
    );
  }
}

A: You can place image inside stack, in this case UI will be
class UserProfileBody extends StatelessWidget {
  const UserProfileBody({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      final double imageHeight = constraints.maxHeight * .5;
      debugPrint(imageHeight.toString());
      return Column(
        children: [
          Stack(
            clipBehavior: Clip.none,
            children: [
              // image
              Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                    height: imageHeight,
                    color: Colors.green,
                  )
                  // _buildUserProfilePhoto(context),
                  ),
              Positioned(
                top: imageHeight - (64 / 2), //64 is default fab size
                right: 24,
                child: FloatingActionButton(
                  onPressed: () {},
                  child: const Icon(Icons.photo_camera),
                ),
              ),
              // Column(
              //   children: [
              //     ListTile(
              //       title: const Text('the title'),
              //       subtitle: const Text('the subtitle'),
              //       onTap: () {},
              //     )
              //   ],
              // )
            ],
          ),
        ],
      );
    });
  }
}

Play with
Positioned(
  top: imageHeight - (64 / 2), //64 is default fab size
  right: 24,
  child: FloatingActionButton(

Solution 2:
And if you like place image above stack
Positioned(
  top: -(64 / 2),

class UserProfileBody extends StatelessWidget {
  const UserProfileBody({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      final double imageHeight = constraints.maxHeight * .5;
      debugPrint(imageHeight.toString());
      return Column(
        children: [
          Container(
            height: imageHeight,
            color: Colors.green,
          ),
          SizedBox(
            height: constraints.maxHeight - imageHeight,
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                Positioned(
                  top: -(64 / 2), //64 is default fab size
                  right: 24,
                  child: FloatingActionButton(
                    onPressed: () {},
                    child: const Icon(Icons.photo_camera),
                  ),
                ),
                Column(
                  children: [
                    ListTile(
                      title: const Text('the title'),
                      subtitle: const Text('the subtitle'),
                      onTap: () {},
                    )
                  ],
                )
              ],
            ),
          ),
        ],
      );
    });
  }
}

Use clipBehavior: Clip.none, on stack