text:
Q: When and when-not to install into the GAC? When should you install into the GAC and when should you not? (I am referring, really, to installing on a client's machine when they have purchased our product(s)).

*

*I have an assembly that is only going to be used with my one application (GAC or no-GAC)?

*I have an assembly that all my applications share (GAC or no-GAC)?

*All my applications may use different versions of  my assembly (GAC or no-GAC)?
These are three scenarios... but I am sure there are more. I'm not necessarily looking an answer to only these three questions.
Similar question: What are the advantages and disadvantages of using the GAC?

A: If you are installing asp.net web applications and you are the owner and have complete control over the machine, then in some cases it could make sense putting your assemblies, which you plan to share across sites/web instances in the global assembly cache.
You could dramatically improve the initial loading time and memory usage of the application on servers which have many multiple instances of the same ASP.NET applications if you put the assemblies in the GAC. At least I saw this on our servers with dozens of installations.

A: If you're shipping a reusable library consisting of multiple assemblies, but only few of them form a facade, you can consider installing the assemblies into GAC, if the package is installed to developer's PCs.
Imagine, you ship 6 assemblies, and only one of these 6 assemblies contains a facade - i.e. other 5 are used only by the facade itself. You ship:

*

*MyProduct.Facade.dll - that's the only component intended to be used by developers

*MyProduct.Core.dll - used by MyProduct.Facade.dll, but not intended to be used by developers

*MyProduct.Component1.dll - the same

*MyProduct.Component2.dll - the same

*ThirdParty.Lib1.dll - third-party library used by MyProduct.Component1.dll

*ThirdParty.Lib2.dll - the same

*etc.

Developers using your project would like to reference just MyProduct.Facade.dll in their own projects. But when their project runs, it must be able to load all the assemblies it references - recursively. How this can be achieved? In general, they must be available either in Bin folder, on in GAC:

*

*You may ask the developers to locate your installation folder and add references to all N assemblies you put there. This will ensure they'll be copied into Bin folder to be available in runtime.

*You may install VS.NET project template already containing these 6 references. A bit complex, since you should inject the actual path to your assemblies into this template before its installation. This can be done only by installer, since this path depends on installation path.

*You may ask developers to create a special post-build step in .csproj / .vbproj file copying the necessary dependencies to Bin folder. The same disadvantages.

*Finally, you may install all your assemblies into GAC. In this case developers must add the reference just to MyProduct.Facade.dll from their project. Everything else will be available in runtime anyway.

Note: last option doesn't make you to do the same while shipping the project to production PCs. You can either ship all the assemblies within Bin folder, or install them into GAC - all depends all your wish.
So the solution described shows the advantage of putting third-party assemblies into GAC during the development. It doesn't related to production.
As you may find, installation into GAC is mainly intended to solve the problem of location of required assemblies (dependencies). If an assembly is installed into GAC, you may consider it exists "nearby" any application. It's like adding path to .exe to your PATH variable, but in "managed way".  - of course, this is rather simplified description ;)

A: General MS guidelines

*

*no

*no

*no

GAC is really a repository for Microsoft common .NET libraries. Yes, they let developers use it too, but as a rule of thumb, if you don't need GAC, don't use it. keep things simple and local if it doesn't hurt.

*

*I would consider GAC only for performance reasons, for example if you have some huge assemblies, try to place them into GAC and NGEN them. It should significantly increase performance. Microsoft does it for all standard .NET framework assemblies during installation (now you know why that installation takes so long). Paint.NET does it as well (to improve startup time of their app). However most of us don't work on huge frameworks or photoshop competitors, so most of the time, performance gains from having assembly in GAC are minimal. Not worth giving up simple x-copy deployment.

*Some developers might use GAC to make sure that users with insufficient privileges can't delete or modify their assemblies.

*For others it might be for versioning reasons but here you should really reconsider. I'm not going to repeat what has been already said, you can read here why.
And don't forget that once you want to deploy into GAC, your installer will need administrator privileges, you can pretty much forget click-once deployment, etc...

A: Here's the link from Chris Sells called "Avoid the GAC"
https://sellsbrothers.com/12503
The explanation is pretty long, but in short, the two cases he identifies are

*

*Fixing critical bugs without touching the affected apps (and without breaking anything!)

*Sharing types at run-time between assemblies deployed separately
Note: There is a very long discussion thread at the end of Chris's the post, very nice list of comments.

A: Useful cases for GAC:

*

*COM-callable code - i.e. you want some non-.NET code to be able to access you without messing with dlls etc

*Serviced Components (COM+)

*If you are writing code that is so common it is actually meaningful to use GAC - primarily .NET framework components etc

*If you want to use NGEN to pre-JIT the code

Other than that, I tend to avoid the GAC like the plague. It is far easier to just deploy the necessary dlls with your app via robocopy etc; this gives isolation and easy deployment.

A: first if you are installing this on a client machine you will need to add a custom action to install the app in the GAC and another one when removing.
on case A definitely not GAC
on case B if your library will be constantly changing you will need to add every version of the assembly into the gac everytime and update to that assembly occurs
on case C side by side execution allows you to run different assembly versions and you dont need to add anything to differentiate the versions.
Used only if you really need to

A: It only makes sense to install into the GAC if lots and lots of web applications on the same server will be sharing exactly the same libraries. For example, on a Sharepoint server there can be hundreds of web sites that all need to share the same web part, so in this case it makes sense to deploy the compiled web part to the GAC.


text:
Q: Check if all values are positive in a moving window I have a data frame contains a column with some values.
Let be 2 a window length, I need a new column which is 1 if all elements in a rolling window are positive, 0 otherwise.
Namely:
┌─────┬─────────────┐
│ col ┆ is_positive │
│ --- ┆ ---         │
│ i64 ┆ i64         │
╞═════╪═════════════╡
│ 1   ┆ null        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
└─────┴─────────────┘

Any advice?
Thanks

A: One easy approach is to test the value of a rolling_min.
(
    df
    .with_column(
        (pl.col('col').rolling_min(window_size=2) > 0).alias('is_positive')
    )
)

shape: (8, 2)
┌─────┬─────────────┐
│ col ┆ is_positive │
│ --- ┆ ---         │
│ i64 ┆ bool        │
╞═════╪═════════════╡
│ 1   ┆ null        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ true        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ false       │
└─────┴─────────────┘

Edit
I just noticed that you specifically stated that you need 1's and 0's.  We can simply add a cast to accomplish that.
(
    df
    .with_column(
        (pl.col('col').rolling_min(window_size=2) > 0).cast(pl.Int64).alias('is_positive')
    )
)

shape: (8, 2)
┌─────┬─────────────┐
│ col ┆ is_positive │
│ --- ┆ ---         │
│ i64 ┆ i64         │
╞═════╪═════════════╡
│ 1   ┆ null        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
└─────┴─────────────┘

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can i remove this weird mark in html ? in this piece of html,

when it's displayed in the browser, there's a small mark next to the first image. Why does it appear and how can i remove it?
Here's an image to show it :

A: Just try setting the text-decoration: none for the two links above.
The problem you are facing is that the links are underlined by default, and there might be a line-break after the image that is causing a white-space characters, and the default text-decoration: underline; is showing an underline under that white-space character.

A: Remove the white-space between  and  like this:

A: I don't know the reason as I too have been struggling with this for a long time (something to do with white-space). However, what I have found is that if you set the display to inline-block, this problem goes away.
a { display: inline-block; }
See this fiddle: http://jsfiddle.net/mznMY/

A: You are using an a anchor which contains underline symbol
Put text-decoration: none to your a.


text:
Q: Add a settings page for bitbucket add-on I have created an add-on for Atlassian Bitbucket Server. I would like the add-on to be enabled or disabled at the repository level.
So I was able to add a web-item at the ADD-ONs section of Settings page of a repository. Now, how do I add my enable/disable radio buttons or a toggle button on the right side screen?
Right now, clicking on web-item takes me to a servlet and renders a velocity template on a different page. But for other add-ons I have noticed that, the settings page is rendered on the same page unlike my case.
How to achieve that?

A: I have figured this out myself. My assumption that, the settings page is rendered on the same page is not true. The settings page is appeared as a new page but that just looks like the previous page.
To make the new page look consistent, use page decorators in the velocity template or in my case, I have used a soy template.
Check this repository to understand how to add various page decorators for the soy templates. : https://bitbucket.org/atlassian/bitbucket-example-plugin
Thanks,
Kaushik


text:
Q: Uncaught Syntax Error with Javascript and Php Strings I have a php webpage that displays a calendar with specific dates displayed on it.
The dates are stored in a MySql database.
At the beginning of the webpage, I do the following:
<?php
//Load in database

$query = "SELECT ID, Full_Name, Arrival_Date, Departure_Date FROM bookings ORDER BY Arrival_Date";

if ($result = $dbc->query($query))       //Retrieve all the booking details
{
    $numrows = $result-> num_rows;

    $id_array;
    $name_array;
    $arrival_array;
    $departure_array;

    for ($count = 0; $count < $numrows; $count++)
    {
        $row = $result->fetch_assoc();

        $id_array[$count] = $row['ID'];
        $name_array[$count] = $row['Full_Name'];
        $arrival_array[$count] = $row['Arrival_Date'];
        $departure_array[$count] = strval($row['Departure_Date']);
    }
}
else
{
    //Error
}
?>

ID is a number
Full_Name is a string
Arrival_Date and Departure_Date are dates (YYYY-MM-DD)
The calendar is a javascript object therefore I need to get the booking information into my javascript function to be able to use it.
This is how I am trying to do that:
<script type="text/javascript">
    var array_ID = [<?php echo implode(",",$id_array); ?>];
    var array_name = [<?php echo implode(",",$name_array); ?>];
    var array_arrival = [<?php echo implode(",",$arrival_array); ?>];
    var array_departure = [<?php echo implode(",",$departure_array); ?>];

    var booking_numbers = <?php echo $numrows; ?>;
</script>

However, I am getting an error 'Uncaught SyntaxError: Unexpected Identifier' on the line:
var array_name = [<?php echo implode(",",$name_array); ?>];

I suspect this is because some of the names have spaces in as the array is coming up as
var array_name = [Pippa,Pippa Smith,Pippa Smith];

When the php values are put in.
So here's my question. How can I tell javascript to treat those inputs as a string.
And I'm aware this might be a terrible way of combining javascript and php, so if anyone has any better suggestions, I'll happily take them!

A: 1) one way around is using implode in php and spliting it in javasciript using split..
best way though is to use echo json_encode($id_array) in php  so that it converts the array into javascript object

A: You have to mark string literals for javascript by putting them between quotes.
var array_name = ["Pippa","Pippa Smith","Pippa Smith"];

Use json_encode() to get a valid javascript object literal from your php value(s).

on a side-note: why do you change the structure of the data from
[1] x y z
[2] X Y Z

to
 [1]  [2]
  x    X
  y    Y
  z    Z

i.e. why do you have those separate variables array_ID, array_name, array_arrival, array_departure instead of one array holding all the information?


text:
Q: C++ how to implment a stoppable future function call? I want to execute a function after a timeout period, something like:
sleep(1000);
doWork();

But before the timeout is reached, I can stop the execution in this thread or other thread, like:
if(someCondition)
{
    stop the doWork() it is not started.
}

Is there any existing std/boost class to do this kind of task?

A: You may use a combination of a variable indicating whether the work needs to be done combined with a timed condition variable: you'd wait for the sleep time and if the wait terminates you'd check if the work should be aborted, more sleeping is needed (condition variables can always stop waiting spuriously), or the work can be started:
bool                    do_work(true);
std::mutex              mutex;
std::condition_variable condition;

std::chrono::time_point<std::chrono::steady_clock> abs_time(
     std::chrono::steady_clock::now() + std::chrono::milliseconds(1000));
std::unique_lock<std::mutex> kerberos;
if (condition.wait_until(kerberos, abs_time, [&]{ return do_work; })) {
    // do the work
}

The other thread cancelling the work would acquire a lock for the mutex, set do_work to false, and notify_one() the condition variable.

A: a mutex will do - thread 1 waits for the mutex, or timeout. If the 2nd thread resets the mutex the 1st thread will stop blocking before the timeout is up.
On Windows you'd typically use an Event to do this, but boost has condition variables that seem to do the same thing - communicate a waitable event to another thread.

A: That is a neat question, but I think the best solution depends on your application's needs and constraints. For example, can you use a busy wait sleep function that polls the condition, or do you need something that does not use as much of the CPU?
Here is a first stab at a solution that may work for you:
#define SLEEP_RESOLUTION 1000 // A value in microseconds

void do_work_with_delay(int delay_time) { // Specify the delay in ms

    bool condition_reached = sleep_and_check(delay_time);

    if (condition_reached) {
        return;
    }

    do_work();
}

bool sleep_and_check(int delay_time) {
    int accumulated_delay = 0;

    while (accumulated_delay < delay_time*1000) { // Loop until we have waited
                                             // the whole delay_time
        if (someCondition) // Check the condition, return true if it has been met
            return true;

        usleep(SLEEP_RESOLUTION); // Condition not met, sleep and check again next time
        accumulated_delay += SLEEP_RESOLUTION;
    }
    return false; // Return false to show the whole time
                  // went by without meeting the condition
}


text:
Q: Are functions of moderate growth a bornological space? I was thinking a bit about distribution theory the last weeks and stumbled across the following question:
There are two natural locally convex topologies on the space of smooth functions of moderate growth $\mathcal{O}_M(\mathbb{R}^n) := \{f\in C^\infty(\mathbb{R}^n) \mid \forall\alpha: \partial^\alpha f \,\text{is bounded by a polynomial}\}$.
One is generated by the seminorms $f\mapsto\|\phi \cdot \partial^\alpha f\|_{L^\infty}$ for all $\phi\in\mathcal{S}(\mathbb{R}^n)$ and all multiindices $\alpha$. Let's call that one $\tau_S$.
The other one is the colimit of the subspaces $\mathcal{O}_M^N := \{f \mid \forall\alpha: \partial^\alpha f(x) \in O(x^{N(\alpha)})\}$ where $N$ ranges over all functions $\mathbb{N}^n\to\mathbb{N}, \alpha\mapsto N(\alpha)$ (with the pointwise partial ordering this becomes a filtered colimit). Here $\mathcal{O}_M^N$ is endowed with the seminorms $f\mapsto \|\frac{\partial^\alpha f(x)}{1+\|x\|^{N(\alpha)}}\|_{L^\infty}$ for all multiindices $\alpha$. Let call this topology on $\mathcal{O}_M$ by the name of $\tau_G$.
My question is:

Are these topologies equal?

It is easy to see that $id: (\mathcal{O}_M,\tau_G)\to(\mathcal{O}_M,\tau_S)$ is continuous and I can show that the inverse map is bounded, that is: it maps bounded sets to bounded sets.
Because $\tau_G$ is the colimit of metric topologies, it is bornological. This means that $\tau_G$ is the "bornologification" of $\tau_S$. Therefore it is equivalent to ask:

Is $(\mathcal{O}_M,\tau_S)$ a bornological space?

A: Yes, $\mathscr O_M$ is bornological. Grothendieck calls this "not trivial" and proves it in his thesis via a tensor product representation and quite general results about tensor products. Together with Julian Larcher, I recently gave an alternative proof which is still in the refereeing process. If you are interested I can send you the preprint by email.

The preprint is now in the arXiv.


text:
Q: RabbitMQ Persistence with Azure Fileshare RabbitMQ cannot start when using azure fileShare as storage of rabbit volume. It is throwing error
Cookie file /var/lib/rabbitmq/.erlang.cookie must be accessible by owner only
I cannot do chmod 400 /var/lib/rabbitmq/.erlang.cookie since the pods is crashing before start.
Anyone having a similar issue?
Below is my manifest file.
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-azure-file-static-mi
  labels:
    app.kubernetes.io/name: csi-test
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteMany
  csi:
    driver: file.csi.azure.com
    readOnly: false
    volumeHandle: csi-test-109222
    volumeAttributes:
      resourceGroup: RG
      storageAccount: test
      shareName: bob3
  mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=1000
  - gid=1000
  - mfsymlinks
  - nobrl
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-azure-file-static-mi
  labels:
    app.kubernetes.io/name: csi-test
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: ""
  volumeName: pv-azure-file-static-mi
  resources:
    requests:
      storage: 1Gi
---
apiVersion: v1
kind: Service
metadata:
  name: rabbit
  labels:
    app: rabbit
    name: rabbit
spec:
  type: NodePort
  ports:
    - port: 15672
      targetPort: 15672
  selector:
    app: rabbit
    name: rabbit

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbit
  labels:
    app: rabbit
    name: rabbit
spec:
  replicas: 1
  selector:
    matchLabels:
      app: rabbit
      name: rabbit
  template:
    metadata:
      labels:
        app: rabbit
        name: rabbit
    spec:
      hostname: rabbit
      containers:
      - name: rabbit
        image: rabbitmq:3.8.0-management
        imagePullPolicy: Always
        ports:
          - name: http
            containerPort: 15672
            protocol: TCP
          - name: amqp
            containerPort: 5672
            protocol: TCP
        resources:
          limits:
            cpu: 1
            memory: 1024Mi
          requests:
            cpu: 200m
            memory: 512Mi
        volumeMounts:
        - name: volume
          mountPath: "/var/lib/rabbitmq"
      volumes:
        - name: volume
          persistentVolumeClaim:
            claimName: pvc-azure-file-static-mi

Logs

Cookie file /var/lib/rabbitmq/.erlang.cookie must be accessible by
owner only 2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
supervisor: {local,net_sup} 2022-03-10 06:55:02.847364+00:00 [erro]
<0.143.0>     errorContext: start_error 2022-03-10
06:55:02.847364+00:00 [erro] <0.143.0>     reason: {"Cookie file
/var/lib/rabbitmq/.erlang.cookie must be accessible by owner only",
2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
[{auth,init_no_setcookie,0,[{file,"auth.erl"},{line,293}]}, 2022-03-10
06:55:02.847364+00:00 [erro] <0.143.0>
{auth,init,1,[{file,"auth.erl"},{line,144}]}, 2022-03-10
06:55:02.847364+00:00 [erro] <0.143.0>
{gen_server,init_it,2,[{file,"gen_server.erl"},{line,423}]},
2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
{gen_server,init_it,6,[{file,"gen_server.erl"},{line,390}]},
2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
{proc_lib,init_p_do_apply,3, 2022-03-10 06:55:02.847364+00:00 [erro]
<0.143.0>
[{file,"proc_lib.erl"},{line,226}]}]} 2022-03-10 06:55:02.847364+00:00
[erro] <0.143.0>     offender: [{pid,undefined}, 2022-03-10
06:55:02.847364+00:00 [erro] <0.143.0>                {id,auth},
2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
{mfargs,{auth,start_link,[]}}, 2022-03-10 06:55:02.847364+00:00 [erro]
<0.143.0>                {restart_type,permanent}, 2022-03-10
06:55:02.847364+00:00 [erro] <0.143.0>
{significant,false}, 2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
{shutdown,2000}, 2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
{child_type,worker}] 2022-03-10 06:55:02.847364+00:00 [erro] <0.143.0>
2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>   crasher:
2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>     initial call:
auth:init/1 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>     pid:
<0.145.0> 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
registered_name: [] 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
exception error: "Cookie file /var/lib/rabbitmq/.erlang.cookie must be
accessible by owner only" 2022-03-10 06:55:02.847486+00:00 [erro]
<0.145.0>       in function  auth:init_no_setcookie/0 (auth.erl, line
293) 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>       in call
from auth:init/1 (auth.erl, line 144) 2022-03-10 06:55:02.847486+00:00
[erro] <0.145.0>       in call from gen_server:init_it/2
(gen_server.erl, line 423) 2022-03-10 06:55:02.847486+00:00 [erro]
<0.145.0>       in call from gen_server:init_it/6 (gen_server.erl,
line 390) 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
ancestors: [net_sup,kernel_sup,<0.47.0>] 2022-03-10
06:55:02.847486+00:00 [erro] <0.145.0>     message_queue_len: 0
2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>     messages: []
2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>     links:
[<0.143.0>] 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
dictionary: [] 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
trap_exit: true 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
status: running 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
heap_size: 610 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
stack_size: 29 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
reductions: 2022 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
neighbours: 2022-03-10 06:55:02.847486+00:00 [erro] <0.145.0>
2022-03-10 06:55:02.855931+00:00 [erro] <0.130.0> 2022-03-10
06:55:02.855931+00:00 [erro] <0.130.0> BOOT FAILED 2022-03-10
06:55:02.855931+00:00 [erro] <0.130.0> =========== 2022-03-10
06:55:02.855931+00:00 [erro] <0.130.0> Exception during startup:
2022-03-10 06:55:02.855931+00:00 [erro] <0.130.0>

A: Switching to rabbitMQ version v3.9.9 from v3.8.0 and mounting /var/lib/rabbitmq/mnesia instead of /var/lib/rabbitmq solves the issue for me in mounting rabbitmq volume to fileshare in Azure.


text:
Q: Replacement of a MOSFET alternative This is the MOSFET part that I'm using in the current design - LP0701
Can the NVJS4151P be the right alternative for the LP0701? I am not sure as some parameters do not match.
My requirements :

*

*500 mA (continuous current)

*3.3V or 2.5V (source – input voltage)

*1.2V (drain – output voltage)

*VGS in the range of:

*(–1.2V to –1.5V) @ 500 mA for 3.3V source voltage

*(–1.0V to –1.1V) @ 500 mA for 2.5V source voltage
Would the new part suit?


text:
Q: create client side file using java i am trying to create a project which create a file in client side . i ave done the coding to create a file .but it obviously will be created in server side.. can any one help to do this. below is the code i have done..
    File file = new File("d:/file.txt");
        try {

            String content = "This is the content to write into file";
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }

I have also tried to create a file using filesysapi, which is done using HTML and javascript. but i got "Error: SECURITY_ERR"

A: using socket programming, 1st create a communication between server and client machines.
  Socket kkSocket = new Socket(hostName, portNumber)
then use  File file = new File("hostname@d:/file.txt");
if your host file does not contain hostname IP address maping, then instead of giving hostname, use IP address.

A: Despite what everyone is saying, you can create a client-side file via javascript. It's a sandboxed portion of the File System, done via HTML5's FileSystem API.
HOWEVER, my guess is your SECURITY_ERR is probably because you are opening an html page with the target javascript via File://PATH_TO_HTML_PAGE in your browser. The File-System API Will not work unless your grabbing the html/javascript/css from a server (like locahost:8080/test.html - Netbeans has some options to run a glassfish/server instance pretty painlessly locally on your machine if you have no experience with servers.).
Update 1-31-2014
Found this in an article on the File-System API, which confirmed the above paragraph for me:

You may need the --allow-file-access-from-files flag if you're debugging your app from file://. Not using these flags will result in a SECURITY_ERR or QUOTA_EXCEEDED_ERR FileError.

end update
That said, in the previous comment on a different question you asked and I answered, you were using TEMPORARY Storage. I use PERSISTENT because it is more reliable, and the browser displays a message asking for permission to store the data locally on the target machine. Here is how I have been making files locally on client machines for persistent data storage for the past couple years. This to the best of my knowledge only works with a handful of browser's, I use Google Chrome - the following defeinitely works in Google Chrome.
The following is javascript and needs to be within either an external script or script tags.
//this is a callback function that gets passed to your request for the file-System.
var onInitFs = function(fileSys){
    //fileSystem is a global variable
    fileSystem = fileSys;
    //once you have access to the fileSystem api, then you can create a file locally
    makeAFile();
    makeAndWriteContent();
};
var errorHandler = function(e){console.log('Error', e);};

//request 1 GB memory in a quota request
//note the internal callback `function(grantedBytes){...}` which makes the actual
//request for the Filesystem, on success `onInitFs` is called.
///on error the `errorHandler` is called
navigator.webkitPersistentStorage.requestQuota(1024*1024*1024*1, function(grantedBytes) {
    window.webkitRequestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
}, errorHandler);

//this method will only work once the fileSystem variable has been initialized
function makeAFile(){
    var callbackFunctionOnSuccess = function(){console.log("created new file")}
    fileSystem.root.getFile("test.txt", {
        create: true
    }, callbackFunctionOnSuccess, function(error){console.log(error);});
}

function makeAndWriteContent(){
    //this is going to be passed as a callback function, to be executed after
    //contents are written to the test2.txt file.
    var readFile = function(){
       fileSystem.root.getFile("test2.txt", {create: false}, function(fileEntry) {
           fileEntry.file(function(file) {
              var reader = new FileReader();
              reader.onloadend = function(e) {
                console.log(this.result);
              };
              reader.readAsText(file);
           }, function(error){console.log(error);});
         }, function(error){console.log(error);});
    }

    fileSystem.root.getFile("test2.txt", {
        create: true
    }, function(fileEntry) {
        fileEntry.createWriter(function(writer) {
            writer.onwriteend = function(e) {
                writer.onwriteend = function(e){
                    //now, we will read back what we wrote.
                    readFile();
                }
                writer.onerror = function(e3){console.log(e3);
                }
                var blob = new Blob(["Hello World"]);
                writer.write(blob);
            };
            writer.onerror = function(e3) {console.log(e3);};
            //make sure our target file is empty before writing to it.
            writer.truncate(0);
        }, errorHandler);
    }, errorHandler);
}

One thing to keep in mind is that the File-System API is asynchronous so you have to get use to using callback functions. If you try to access the File-System API before it's instantiated, or if you try to access files before they are ready, you will also get errors. Callback functions are essential.

A: You can not create file on client side because browser does not allow doing that.


text:
Q: Run Github actions in monorepo I have a project which contains 2 folder: backend  and frontend. In each folder i added the corresponded project, each project has its own package.json. Also in each folder/project  i have .github with sett workflow/file.yml where is sett github actions for backend and also for frontendEX: 1. frontend/.github/workflows/file.yml and 2. backend/.github/workflows/file.yml.backend folder is the root and frontend is located inside it.  Now if i push my changes being in backend folder i trigger only BE github actions, but i also need to run the frontend actions.  Question: Does somebody face this kind of issue and how to  run both github actions?

A: You can run many workflows at same time, as you want.

*

*You must have a .github/workflows folder, where your actions will be;

*Each file must have a on clause

*Use cd backend and cd frontend to access file on subdirectories during the action

*You can add some pwd && ls to check if you are on right directory

It's enough to run more than on action, for the back and the front.


text:
Q: Flask redirects to wrong view when redirecting to index I keep running into this strange issue that I can't seem to figure out a solution for. I cannot copy and show all of my code in it's entirety here, but I will try to outline the general structure of my flask app to present my issue.
(Let's ignore all of the content in the /static folder and my helper modules)
I have 3 main views, let's call them viewA, viewB, and index:
viewA.html
viewB.html
index.html

viewA and viewB both display two forms, but with different content (i.e. viewA displays form1 & form2, and viewB also displays form1 & form2).
A simplified version of my script code is as follows:
#imports
from flask import Flask, render_template, session, redirect, url_for, request
from flask_wtf import FlaskForm
#etc. etc.

app = Flask(__name__)
app.config['SECRET_KEY'] = 'blah blah blah'

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)

class FormOne(FlaskForm):
    sample_field = StringField('Sample Field:')

class FormTwo(FlaskForm):
    other_field = StringField('Other Field:', validators=[Required()])
    submit = SubmitField('Submit')

class UploadToA(FlaskForm):
    content= StringField('Content to send to view A:', validators=[Required()])
    submit = SubmitField('Submit')

class UploadToB(FlaskForm):
    content= StringField('Content to send to view A:', validators=[Required()])
    submit = SubmitField('Submit')

@app.route('/ViewA', methods=['GET', 'POST'])
def view_a():
    """
    A lot of data manipulation
    """

    form1 = FormOne()
    form2 = FormTwo()

    if request.method == 'GET':
        """
        populate forms with content
        """

    if request.method == 'POST':
        if form2.validate_on_submit();
            """
            clear session variables
            """
            return redirect(url_for('index'), code=302)
    return render_template('viewA.html', form1=form1, form2=form2)

@app.route('/ViewB', methods=['GET', 'POST'])
def view_b():
    """
    A lot of data manipulation
    """

    form1 = FormOne()
    form2 = FormTwo()

    if request.method == 'GET':
        """
        populate forms with content
        """
    if request.method == 'POST':
        if form2.validate_on_submit();
            """
            clear session variables
            """

            return redirect(url_for('index'), code=302)
    return render_template('viewB.html', form1=form1, form2=form2)

@app.route('/', methods=['GET', 'POST'])
def index():
    """
    Some data manipulation
    """

    formA = UploadToA()
    formB = UploadToB()

    if formA.validate_on_submit()':
        """
        pull content from form A
        create some session variables
        """

        return redirect(url_for('view_a'))
    if formB.validate_on_submit()':
        """
        pull content from form B
        create some session variables
        """

        return redirect(url_for('view_b'))
    return render_template('index.html', formA=formA, formB=formB)

if __name__ == '__main__':
    manager.run()

Now the issue at hand I am having here is that for some strange reason when I'm in 'viewA.html' and I submit my form, I SHOULD be redirected back to 'index.html' but for some strange reason it redirects me to 'viewB.html'. Furthermore, the opposite also holds true: when i'm in 'viewB.html' and I submit my form, I SHOULD also be redirected back to 'index.html' but it redirects me to 'viewA.html'. Yet, if I am in either viewA or viewB, I have no issues of going back to the index view if I manually enter the url into my browser.
Any ideas as to why I might be running into this issue?
Thanks in advance :)

A: I have finally figured out the source of my problem. It turns out that in my 'viewA.html' template file, I had the following in my < form > tag:
<form class="form form-horizontal" method="post" role="form" action="{{url_for('index')}}">

And the problem all lies in that last part:
action="{{url_for('index')}}"

As a result, everytime I would submit form2 in viewA.html it would create a post request for my index page rather than a post request for the viewA.html page (which caused a redirect to the wrong view). Thus, by simply removing the action attribute (action="{{url_for('index')}}"), I was able to solve my problem!

A: Since the full code isn't here, I can't confirm this for sure, but what I think is happening is this:

*

*You open form A

*You submit form A

*It sends a redirect to /index

*It sends a redirect to /FormB

if formB.validate_on_submit():
    return redirect(url_for('view_b'))

This is probably sending a redirect to View B. Try changing that last line to something like return something_else and seeing if it sends that after submitting form A.


text:
Q: What causes the uncertainty in the threshold voltage of a CMOS switch? CMOS switches such as the DG419 have a threshold voltage - i.e. the voltage at which the output state is flipped - which is dependent upon the logic level and the positive supply rail. However, the exact threshold voltage at which the state will flip is undefined. For the DG419, the threshold occurs within a region spanning many volts, particularly for lower supply voltages:

What causes this uncertain region in switching? I guess it's not the material itself, but rather something else such as stray capacitance or source impedance.

A: It's a CMOS input, so there are two transistors 'fighting' each other at the input threshold.
Variations in the semiconductor manufacturing process will result in different behaviors for one vs. the other, so the point where they switch will vary. That variation is accentuated at relatively low supply voltages where the transistors are barely working at all (what is 'relatively low' will be different for a high voltage analog switch like the DGxx series vs. a chip designed for 3.3V Vdd).
Chances are that under fixed and benign conditions (temperature and supply voltage) the threshold will stay pretty much fixed for any given sample of chip.


text:
Q: Splitting & Moving cell in Pandas I have a slight problem with my pandas DataFrame.
As the image shows, the first row has released_date as "Released 2006" while all other values for the same column have the format "Released MMM DD".
I would like to split the first cell under released_date to "Released" and "2006", copy "2006" to year column and subsequently move everything by one column. Any ideas?
Current Format:
...|**released_date**| **year** | **genre**  | ...
...| Released   2006 | Arcade   |    Comic   |...

Desired output format:
...|**released_date**| **year** | **genre**  | ...
...|    Released     |     2006 |     Arcade |...

Thanks in advance!!

Here's the code to read the file in:
import pandas as pd
df = pd.read_csv("IndieGameCSV/page_1.csv", \
    names=["Windows","Mac","Linux","engine","release_date","year","genre1",\
           "theme","players","score_final","rating", "link" ], index_col=False)

and here is the data as seen in the image:
True, False, True,Custom Built,Released 2006,Arcade,Comic,Single Player,                     10,1 v, http://indiedb.com/games/tux-climber,
True, True, True,Custom Built,Released Oct 20, 2014,Role Playing,Fantasy,MMO,                     7.3,45 , http://indiedb.com/games/pokemon-planet,
True, True, True,Ren'py,Released May 16, 2015,Turn Based Strategy,Noire,Single Player,                     9,1 v, http://indiedb.com/games/black-closet,
True, True, False,ShiVa3D,Released Jan 2, 2015,First Person Shooter,Sci-Fi,Single Player,                     7.8,4 v, http://indiedb.com/games/kumoon,

A: You can use the str.extract method to extract the year:
In [11]: df["release_date"].str.extract("(\d{4})")
Out[11]:
0    2006
1    2014
2    2015
3    2015
Name: "release_date", dtype: object

If you wanted to split the DataFrame you can also look .str.match, to check whether a column matches a regex:
In [12]: df["release_date"].str.match("Released \d{4}")
Out[12]:
0     True
1    False
2    False
3    False
Name: "release_date", dtype: bool

and index the df with this and ~this.


text:
Q: repeating animation using java.swingTimer I am writing the code of Game bean machine (Galton box) using animated graphics.
I am using swing.Timer to make the red ball move, by letting the Timer object take an ActionListener.
Here is the output:
The red ball here is moving randomly :
http://imgur.com/J9Xq0t5&HIv1udp
And here it reaches the bottom:
http://imgur.com/J9Xq0t5&HIv1udp#1
The problem is that I want to make several balls moving not only 1 but I actually cannot, I tried to put the Timer object in a loop but it only speeded up the ball motion.
Here is the code I wrote:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Scanner;
import javax.swing.*;

public class GameBean extends JFrame{
private int nSlots;
private int balls;

public GameBean (int nSlots, int balls){
    this.balls=balls;
    this.nSlots=nSlots;
    Timer timer=new Timer(500,new RandomListener());

    timer.start();

    JPanel panel = new JPanel();

    this.add(canvas);
}

Ball canvas = new Ball();

 public static void main(String[] args) {

    Scanner input=new Scanner(System.in);

    System.out.println("Please enter number of slots: ");
    int nSlots=input.nextInt();

    JFrame frame = new GameBean (nSlots, 5);

    frame.setTitle("Bean Game Machine");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setSize(300, 500);
    frame.setVisible(true);

   }
 class RandomListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
         canvas.moveRandom();
    }
}

class Ball extends JPanel{
    Random rand=new Random();
    private int n;
    private int raduis = 10;
    private int moveRaduis=12;
    private int L = 0;
    private int R = 0;
    private int D = 0;

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.RED);

        g.fillOval(getWidth()/2 -raduis/2  + R + L, 0 + D , moveRaduis, moveRaduis);

        repaint();
        int  i=0;
        int width=(getWidth()/8);
        int space=(getWidth()-nSlots*30)/2;
        g.setColor(Color.BLACK);
        for(i=0;i<=nSlots;i++){
            g.drawLine(space+(30*i),getHeight()-balls*(raduis) ,space+(30*i) ,getHeight() );
            if(i!=0 && i!=nSlots)
                g.fillOval(space+(30*i)-5, getHeight()-balls*(raduis)-5, 10, 10);
            if(i==0){
                g.drawLine(space,getHeight()-balls*(raduis) , space+((nSlots)*15)-(raduis/2)-15 , getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2);
                g.drawLine(space+((nSlots)*15)-(raduis/2)-15 , getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2 , space+((nSlots)*15)-(raduis/2)-15 , getHeight()/2-nSlots*nSlots);//vertical line

            }
            if(i==nSlots){
                g.drawLine(space+(30*i), getHeight()-balls*(raduis), space+((nSlots)*15)+(raduis/2)+15, getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2);
                g.drawLine(space+((nSlots)*15)+(raduis/2)+15 , getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2 , space+((nSlots)*15)+(raduis/2)+15 , getHeight()/2-nSlots*nSlots);//vertical line

            }

        }

        int o=1;
        for(i=1;i<=nSlots-2;i++){
            int k=2;
            for(int j=i;j<=nSlots-2;j++){
                g.fillOval(space+((i+k)*15)-raduis/2, getHeight()-(balls*raduis)-(30*o)-raduis/2, raduis, raduis);
                k=k+2;
             }o++;
        }

      }

    public void moveRandom(){

        n=1+rand.nextInt(100);
        if(n<=51){
            D+=15;

            if(D<=(getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2))//if(D<=14*15)
                L=0;
            else if(D>getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2 && D<getHeight()-balls*(raduis))
            {
                D+=15;
                L-=15;

            }
            else if(D>=getHeight()-balls*(raduis))
            {
                if(D==31*15)D-=15;
                D=D;

            }

        }
        else if (n>=51 && n<=100){
            D+=15;
            if(D<=getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2)
                R=0;
            else if(D>getHeight()-15-(balls*raduis)-(30*(nSlots-2))-raduis/2 && D<getHeight()-balls*(raduis))
                {
                D+=15;
                R+=15;
            }
            else if(D>=getHeight()-balls*(raduis)){

                if(D==31*15)D-=15;
                D=D;

            }

        }

    }
    }

    }

Any HELP please !
Thanks all..

A: Here's a suggestion.
Don't make each ball extends JPanel. Just make it a class for holding/manipulating/drawing the state.
Ball.java (notice Java naming convention)
public class Ball {
    int x, y; // and whatever other state you need

    public Ball(int x, int y {}  // or however you want to construct the ball

    public void draw(Graphics g) {
        // draw ball here
    }
    public void move() {
        // do calculations to move here
    }
}

Then just have one BallPanel class that extends JPanel and do the painting there. Just hold a List<Ball> in the class and you can call each Ball's draw() method in the paintComponent and each Ball's move() method in the Timer. You could even dynamically add balls to be animated by just adding a new Ball to the list. Something like
public class BallPanel extends JPanel {
    private List<Ball> balls;  // create the list

    public BallPanel() {
        Timer timer = new Timer(40, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                for (Ball ball: balls) {
                    ball.move();
                }
                repaint();
            }
        });
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Ball ball : balls) {
            ball.draw(g);
        }
    }
}

This way you don't have to worry above separate timers and layering panels.
See a bunch of complete example, using this technique, here and here and here and here and here and here.


text:
Q: Перехват трафика провайдером (несколько нехороших слов) МТС/Vodafone Украина перехватывает 404 ошибки и делает редирект на свою рекламу, подсовывая мне зачем-то на ПК файлы для Андроида.
В результате я не могу нормально отладить сайт.
Думал, подниму VPN и решу проблему, но и после этого идет редирект. Но вроде только с IP моего сервера. В чем причина и как от этого избавится?


text:
Q: How do I create a unique object? I want
class MyClass(object):
    _my_unique = ????      # if this were lisp, I would have written (cons nil nil) here

    def myFunc (self, arg):
        assert arg != _my_unique    # this must never fail
        ...

What do use instead of ??? to ensure that the assert never fails?
(With Lisp, I could create _my_unique with (cons nil nil) and used eq in assert).
PS. Use case: I will put _my_unique in a dict, so I want it to be equal to itself, but I do not want it to be equal (in the dict collision sense) to anything passed in from the outside.

A: You can use object(), but this won't make the assert "never fail".  It will still fail if you call myFunc and pass MyClass.my_unique as the object.  Also, if you want to test whether it's the same object, use arg is not my_unique rather than !=.

A: You can use object().

Return a new featureless object. object is a base for all new style
  classes. It has the methods that are common to all instances of new
  style classes.

A: If what you're asking is "how do I make _my_unique unique for each instance of MyClass", you could simply create a new, empty object in the constructor.
For example:
>>> class MyClass(object):
...     def __init__(self):
...         self._my_unique = object()
...
>>> foo=MyClass()
>>> bar=MyClass()
>>> foo._my_unique
<object object at 0x100ce70c0>
>>> bar._my_unique
<object object at 0x100ce7090>

If you want to hide _my_unique, give it two underscores. This way, nobody can accidentally get at the value. It's not impossible, but they would need to work a little harder to get at the value. This is called name mangling, and you can read more about it here: http://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references
>>> class MyClass(object):
...     def __init__(self):
...         self.__my_unique = object()
...
>>> foo=MyClass()
>>> foo.__my_unique
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute '__my_unique'

A: This is a mildly confusing question, as it seems to mix a bunch of concepts without purpose. For one thing, most any object in Python is unique, but there may be multiple ways to reach them. The operator to check identities is not != (inequality) but is not. Unlike Java, Python does not require you to put things in a class, and does not implicitly look in self (which they know as implicit this). cons from Lisp is used to construct pairs which frequently form singly linked lists, a structure that's unusual in Python because we use dynamic reference arrays known as lists. Lists are mutable, and thus constructing one using list() or [] will produce a unique object.
So, while it is rather pointless, one way to write a function producing functions that perform the useless assert might be:
def createfunc():
  mylist=[]
  def subfunc(x):
    assert x is not mylist
  return subfunc

Each call to createfunc() returns a new function with its own mylist. However, the object being unique doesn't make it impossible to reach:
f=createfunc()
f(f.func_closure[0].cell_contents)   # raises AssertionError

Regarding the PS, to be relevant to dict collissions, your object must also be hashable, which makes object() a better choice than list() for the unique object.


text:
Q: Euclidean distance using intrinsic instruction For a research project, I need to compute a lot of Euclidean distances, where certain dimensions must be selected and others discarded. In the current state of the program, the array of selected dimensions has 100-ish elements, and I compute around 2-3 million distances. My current piece of code is as follow :
float compute_distance(const float* p1, const float* p2) const
{
    __m256 euclidean = _mm256_setzero_ps();

    const uint16_t n = nbr_dimensions;
    const uint16_t aligend_n = n - n % 16;
    const float* local_selected = selected_dimensions;

    for (uint16_t i = 0; i < aligend_n; i += 16)
    {
        const __m256 r1 = _mm256_sub_ps(_mm256_load_ps(&p1[i]), _mm256_load_ps(&p2[i]));
        euclidean = _mm256_fmadd_ps(_mm256_mul_ps(r1, r1), _mm256_load_ps(&local_selected[i]), euclidean);
        const __m256 r2 = _mm256_sub_ps(_mm256_load_ps(&p1[i + 8]), _mm256_load_ps(&p2[i + 8]));
        euclidean = _mm256_fmadd_ps(_mm256_mul_ps(r2, r2), _mm256_load_ps(&local_selected[i + 8]), euclidean);
    }
    float distance = hsum256_ps_avx(euclidean);

    for (uint16_t i = aligend_n; i < n; ++i)
    {
        const float num = p1[i] - p2[i];
        distance += num * num * local_selected[i];
    }

    return distance;
}

The selected dimensions are pre-determined. I could thus pre-compute an array of  __m256 to pass to a _mm256_blendv_ps instead of multiplying by 0 or 1 in the line euclidean = _mm256_fmadd_ps(_mm256_mul_ps(r1, r1), _mm256_load_ps(&local_selected[i]), euclidean);. But I'm rather a novice in intrinsic instructions, and I have not yet found a working solution.
I was wondering if you guys could have some advice, or even code suggestions,  to improve the running speed of this function. As a side note, I do not have access to AVX-512 instructions.

Update:
Using the first above-mentioned solution, it comes:
float compute_distance(const float* p1, const float* p2) const
{
    const size_t n = nbr_dimensions;
    const size_t aligend_n = n - n % 16;
    const unsigned int* local_selected = selected_dimensions;
    const __m256* local_masks = masks;

    __m256 euc1 = _mm256_setzero_ps(), euc2 = _mm256_setzero_ps(),
        euc3 = _mm256_setzero_ps(), euc4 = _mm256_setzero_ps();

    const size_t n_max = aligend_n/8;
    for (size_t i = 0; i < n_max; i += 4)
    {
        const __m256 r1 = _mm256_sub_ps(_mm256_load_ps(&p1[i * 8 + 0]), _mm256_load_ps(&p2[i * 8 + 0]));
        const __m256 r1_1 = _mm256_and_ps(r1, local_masks[i + 0]);
        euc1 = _mm256_fmadd_ps(r1_1, r1_1, euc1);

        const __m256 r2 = _mm256_sub_ps(_mm256_load_ps(&p1[i * 8 + 8]), _mm256_load_ps(&p2[i * 8 + 8]));
        const __m256 r2_1 = _mm256_and_ps(r2, local_masks[i + 1]);
        euc2 = _mm256_fmadd_ps(r2_1, r2_1, euc2);

        const __m256 r3 = _mm256_sub_ps(_mm256_load_ps(&p1[i * 8 + 16]), _mm256_load_ps(&p2[i * 8 + 16]));
        const __m256 r3_1 = _mm256_and_ps(r3, local_masks[i + 2]);
        euc3 = _mm256_fmadd_ps(r3_1, r3_1, euc3);

        const __m256 r4 = _mm256_sub_ps(_mm256_load_ps(&p1[i * 8 + 24]), _mm256_load_ps(&p2[i * 8 + 24]));
        const __m256 r4_1 = _mm256_and_ps(r4, local_masks[i + 3]);
        euc4 = _mm256_fmadd_ps(r4_1, r4_1, euc4);
    }

    float distance = hsum256_ps_avx(_mm256_add_ps(_mm256_add_ps(euc1, euc2), _mm256_add_ps(euc3, euc4)));

    for (size_t i = aligend_n; i < n; ++i)
    {
        const float num = p1[i] - p2[i];
        distance += num * num * local_selected[i];
    }

    return distance;
}

A: Basic advice:
Don't use uint16_t for your loop counter unless you really want to force the compiler to truncate to 16 bits every time.  Use at least unsigned, or you sometimes get better asm from using uintptr_t (or more conventionally, size_t).  Zero-extension from 32-bit to pointer width happens for free on x86-64 just from using 32-bit operand-size asm instructions, but sometimes compilers still don't do great.
Use five or more separate accumulators instead of one euclidean, so multiple sub / FMA instructions can be in flight without bottlenecking on the latency of a loop-carried dependency chain that does FMAs into one accumulator.
FMA has a latency of 5 cycles but a throughput of one per 0.5 cycles on Intel Haswell.  See also latency vs throughput in intel intrinsics, and also my answer on Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? for a more-advanced version.

Avoid passing args through global variables.  Apparently your n is a compile-time constant (which is good), but selected_dimensions isn't, is it?  If it is, then you're only using one set of masks in your whole program, so nevermind the stuff below about compressing masks.
Using global variables can defeat compiler optimization when it inlines your function into a caller which sets a global before calling it.  (Usually only if there's a non-inline function call between setting the global and using it, but that's not uncommon.)

update: your arrays are small, only ~100 elements, so unrolling by only 2 is maybe good, to reduce startup / cleanup overhead.  Out-of-order execution can hide the FMA latency over this short number of iterations, especially if the final result of this function call isn't needed to decide the input parameters to the next call.
Total function-call overhead is important, not just how efficient the vectorization is for large arrays.
As discussed in comments, peeling the first iteration of the loop lets you avoid the first FMA by initializing euc1 = stuff(p1[0], p2[0]); instead of _mm256_setzero_ps().
Padding your arrays out to a full vector (or even a full unrolled loop-body of 2 vectors) with zeros lets you avoid the scalar cleanup loop entirely, and make the whole function very compact.
If you couldn't just pad, you could still avoid a scalar cleanup by loading an unaligned vector that goes right up to the end of the inputs, and mask that to avoid double-counting.  (See this Q&A for a way to generate a mask based on a misalignment count).  In other kinds of problems where you're writing an output array, it's fine to redo overlapping elements.
You don't show your hsum256_ps_avx code, but that's a decent fraction of the total latency and maybe throughput of your function.  Make sure you optimize it for throughput: e.g. avoid haddps / _mm_hadd_ps.  See my answer on Fastest way to do horizontal float vector sum on x86.

Your specific case:

I could thus pre-compute an array of  __m256 to pass to a _mm256_blendv_ps instead of multiplying by 0 or 1 in the FMA.

Yes, that would be better, especially if it lets you fold something else into an FMAdd / FMSub. But even better than that, use a boolean _mm256_and_ps with all-zero or all-ones.  That leaves a value unchanged (1 & x == x) or zeroed (0 & x == 0, and the binary representation of float 0.0 is all-zeros.)
If your masks aren't missing in cache, then store them fully unpacked so they can just be loaded.
If you're using different masks with the same p1 and p2, you could pre-compute p1-p2 squared, and then just do a masked add_ps reduction over that.  (But note that FMA has better throughput than ADD on Intel pre-Skylake.  Haswell/Broadwell have 2 FMA units, but run ADDPS on a dedicated unit with lower latency (3c vs. 5c).  There's only one vector-FP add unit.  Skylake just runs everything on the FMA units with 4 cycle latency.)  Anyway, this means it can actually be a throughput win to use FMA as 1.0 * x + y.  But you're probably fine, because you still need to load the mask and the square(p1-p2) separately, so that's 2 loads per FP add, so one per cycle keeps up with load throughput.  Unless you (or the compiler) peel a few iterations at the front and keep the float data for those iterations in registers across multiple different local_selected masks.

update: I wrote this assuming that the array size was 2-3 million, rather than ~100.  Profile for L1D cache misses to decide if spending more CPU instructions to reduce cache footprint is worth it.  If you always use the same mask for all 3 million calls, it's probably not worth it to compress.
You could compact your masks down to 8 bits per element and load them with pmovsx (_mm256_cvtepi8_epi32) (sign-extending an all-ones value produces a wider all-ones, because that's how 2's complement -1 works).  Unfortunately using it as a load is annoying; compilers sometimes fail to optimize _mm256_cvtepi8_epi32(_mm_cvtsi64x_si128(foo)) into vpmovsxbd ymm0, [mem], and instead actually use a separate vmovq instruction.
const uint64_t *local_selected = something;  // packed to 1B per element

__m256 euc1 = _mm256_setzero_ps(), euc2 = _mm256_setzero_ps(),
euc3 =  _mm256_setzero_ps(), euc4 =  _mm256_setzero_ps();

for (i = 0 ; i < n ; i += 8*4) {  // 8 floats * an unroll of 4

    __m256 mask = _mm256_castsi256_ps( _mm256_cvtepi8_epi32(_mm_cvtsi64x_si128(local_selected[i*1 + 0])) );
    // __m256 mask = _mm256_load_ps(local_selected[i*8 + 0]); //  without packing

    const __m256 r1 = _mm256_sub_ps(_mm256_load_ps(&p1[i*8 + 0]), _mm256_load_ps(&p2[i*8 + 0]));
    r1 = _mm256_and_ps(r1, mask);             // zero r1 or leave it untouched.
    euc1 = _mm256_fmadd_ps(r1, r1, euc1);    // euc1 += r1*r1
    // ... same for r2 with local_selected[i + 1]
    // and p1/p2[i*8 + 8]
    // euc2 += (r2*r2) & mask2

    // and again for euc3 (local_selected[i + 2], p1/p2[i*8 + 16]
    // and again for euc3 (local_selected[i + 3], p1/p2[i*8 + 24]
}
euclidean = hsum (euc1+euc2+euc3+euc4);

I guess you bottleneck slightly on load throughput without the pmovsx, since you have three loads for three vector ALU operations.  (And with micro-fusion, it's only 4 total fused-domain uops on an Intel CPU, so it's not bottlenecked on the front-end).  And the three ALU uops can run on different ports (vandps is 1 uop for port 5 on Intel pre-Skylake.  On SKL it can run on any port).
Adding in a shuffle (the pmovsx) potentially bottlenecks on port5 (on Haswell/Broadwell).  You might want to do use vpand for the masking so it can run on any port, if you're tuning for HSW/BDW, even if they have extra bypass latency between an integer AND and FP math instructions.  With enough accumulators, you're not latency-bound.  (Skylake has extra bypass latency for VANDPS depending on which port it happens to run on).
blendv is slower than AND: always at least 2 uops.

Compressing the mask even more for large arrays
If your arrays are larger than L2 cache, and your mask array has as many elements as your float arrays, you will most likely bottleneck on load bandwidth (at least once you unroll with multiple vector accumulators).  This means that spending more instructions unpacking the mask data is worth it to reduce that part of the bandwidth requirement.
I think the ideal format for your mask data is with 32 vectors of masks interleaved, which makes it very cheap to "unpack" on the fly.  Use a shift to bring the right mask into the high bit of each 32-bit element, and use it with vblendvps to conditionally zero elements by blending with zero.  (Or with an arithmetic right shift + boolean AND)
__m256i masks = _mm256_load_si256(...);

                          // this actually needs a cast to __m256, omitted for readability
r0 = _mm256_blendv_ps(_mm256_setzero_ps(), r0, masks);
...

__m256i mask1 = _mm256_slli_epi32(masks, 1);
r1 = _mm256_blendv_ps(_mm256_setzero_ps(), r1, mask1);
...

__m256i mask2 = _mm256_slli_epi32(masks, 2);
r2 = _mm256_blendv_ps(_mm256_setzero_ps(), r2, mask2);
...

// fully unrolling is overkill; you can set up for a loop back to r0 with
masks = _mm256_slli_epi32(masks, 4);

You could also do masks = _mm256_slli_epi32(masks, 1); at every step, which might be better because it uses 1 register less.  But it might be more sensitive to resource conflicts causing latency on the mask dep chain, since every mask depends on the previous one.
Intel Haswell runs both vblendvps uops on port5 only, so you could consider using _mm256_srai_epi32 + _mm256_and_ps.  But Skylake can run the 2 uops on any of p015, so blend is good there (although it does tie up a vector register holding the all-zero vector).

Generate masks in that interleaved format with a packed-compare, then _mm256_srli_epi32(cmp_result, 31) and OR that into the vector you're building up.  Then left-shift it by 1.  Repeat 32 times.

You can still use this format if you have fewer than 32 whole vectors of data in your arrays.  The lower bits will just go unused.  Or you could have the masks for 2 or more selected_dimensions per vector.  e.g. the top 16 bits of each element are for one selected_dimensions, and the bottom 16 bits are for another.  You could do something like
__m256i masks =  _mm256_load_si256(dimensions[selector/2]);
masks = _mm256_sll_epi32(masks, 16 * (selector % 2));

// or maybe
if (selector % 2) {
    masks = _mm256_slli_epi32(masks, 16);
}

AVX512:
AVX512 can use a bitmap mask directly, so it's somewhat more efficient.  Just use const __mmask16 *local_selected = whatever; to declare an array of 16-bit masks (for use with 512b vectors of 16 floats), and use r0 = _mm512_maskz_sub_ps(p1,p2, local_selected[i]); to zero-mask the subtraction.
If you actually bottleneck on load-port uop throughput (2 loads per clock), you might try loading 64 bits of mask data at once, and using a mask-shift to get a different low-16 of it.  This probably won't be a problem unless your data is hot in L1D cache, though.
It's very easy to generate the mask data in the first place with a compare-into-mask, with no interleaving required.

Ideally you could cache-block the code that calls this so you could reuse data while it was hot in cache.  e.g. get all the combinations you want from the first 64kiB of p1 and p2, then move on to later elements and do them while they're hot in cache.


text:
Q: My microphone is not working in Mac book pro 17 after ubuntu 16.04 My microphone is not working in Mac bookpro 17(2010) after ubuntu 15.10 to 16.04.
Sound settings Input shows microphone build-in Audio. but no input level signal.
BTW, my Mac bookpro 13(2009)'s build-in microphone is working in Ubuntu 16.04.
How to fix it? please help me.

A: With my old macbook 2,1 (Libreboot + Elementary OS Loki (based on Ubuntu 16.04)) the solution to getting the microphone working was installing pavucontrol and on the Input Devices tab choosing Microphone (unplugged) instead of Line In (plugged in). In fact I have nothing plugged in or unplugged.

A: I have a MacBook Pro Core i5 2.5 13" Retina 2012 and was in the same position, sound worked fine but no microphone.
Adding the following line to the bottom of /etc/modprobe.d/alsa-base.conf worked for me:
options snd-hda-intel model=mbp101

as per Microphone not working on Ubuntu 14.04 on MacBookPro10,2
I think I had done this in the past but a clean install of Xenial had removed the line, perhaps the same happened when you upgraded?

A: The downvoted answer from above works on a 2009 MacBook Pro, with Ubuntu 20.04.  Conversely, only the microphone would be detected, not the line input.
"Adding the following line to the bottom of /etc/modprobe.d/alsa-base.conf worked for me:
options snd-hda-intel model=mbp101"
Thank you @nicja


text:
Q: How can I install PEAR::Mail for TYPO3 without pear or phar? In order to use the TYPO3 extension 'Direct Mail' with an external SMTP server, I need to install PEAR::Mail (http://pear.php.net/package/Mail/download/1.2.0).
At least, that is what the text in the Direct Mail configuration tells me:

Enable Sending through SMTP [SmtpEnabled]
      Send all emails not through sendmail but through an external SMTP
  account (requires PEAR::Mail to be installed on the system)

I have neither pear nor phar available.
How do I install the package after downloading it manually?

A: The correct way
You need to do everything the PEAR installer does - but manually.
That is, read the package.xml file, note which files need to be extracted to which places (don't forget the baseinstalldir) and then extract the files.
After that you need to resolve all dependencies and install the dependent packages in the correct version as noted in the package.xml file.
Also do not forget to execute the replacement tasks as noted in the package.xml file.
The fast way
Extract the tgz, delete package.xml and adjust your include path.
Then run fast and NEVER EVER ASK FOR HELP BECAUSE IT DOES NOT WORK.


text:
Q: Javascript not working in Ruby on Rails Deployment mode I cannot get any javascript to run when my Ruby on Rails project is in deployment mode.  I have a js at vendor/assets/javascript/theme/index-slider.js.  It has an alert in this file to test that the javascript is working:
alert('TestTestTest');

When I run the project in the development mode, all the javascript runs properly.  Additionally, if I add <script>alert("Testme");</script> to my index.html.erb file, that javascript runs in production mode.
I have been running rake assets:precompile and RAILS_ENV=production rake assets:precompile when making changes as well as restarting the server
How can I get Javascript to run in Production mode? (Also I am rather new to Ruby on Rails so I am not sure which files/information I should include to be helpful.)  Thanks.
application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require bootstrap/bootstrap
//= require theme/bootstrap.min
//= require theme/flexslider
//= require theme/index-slider
//= require theme/jquery.countdown.min
//= require theme/jquery.isotope.min
//= require theme/theme
//= require_tree .

A: I've found that the issue lies in the application.js file.  I've added bootstrap into my project by hand as well as a boostrap theme.  I've found that for whatever reason, the //= require bootstrap/bootstrap line should not be included above the theme I have chosen.

A: You need to compile assets for your production as well
rake assets:precompile RAILS_ENV=production


text:
Q: Wrong scope for my nested classes? At work I monitor a very large list of servers and websites associated with the application running on the servers. Generally each application has a cluster of servers behind it and roughly 6-10 different web-pages. So what I did was I created a Servers class that will take in a server's name(s) and control the urls that are associated with it. Now here's the part I'm struggling with. Each url is going to have two values associated with it: the physical url and the status of the url (online/offline). I came up with two ways of handling this: either I create a 2D array (or list) OR create a url subclass. The subclass method seemed like it would be better since I thought accessing all the methods of the subclass would be easy... Well right now I can't call them at all outside of the Servers class. This makes me think I have an issue with the scope of the classes/methods. Here's my Servers.cs code... What am I doing wrong?
public class Server
{
    public List<string> serverNames = new List<string>();
    public List<object> urlList = new List<object>();
    public string[][] urlArr = new string[1][];

    public Server()
    {

    }

    public Server(string nm)
    {
        serverNames.Add(nm);
    }

    public void setName(string newName)
    {
        serverNames.Add(newName);
    }

    public void addUrl(string newUrl)
    {
        Server.Url url = new Server.Url(newUrl);
        urlList.Add(url);
        url.SetStatus(false);
    }

    protected class Url
    {
        public string url;
        public bool status;

        public Url()
        {
        }

        public Url(string URL)
        {
            url = URL;
        }

        public void SetStatus(bool stat)
        {
            status = stat;
        }

        public bool ReturnStatus()
        {
            return status;
        }
    }
}

Here is how I'm trying to call the Url class method ReturnStatus to see the status of that url. The problem is that the ReturnStatus method isn't available...
private void button2_Click(object sender, EventArgs e)
{
    int length = serversList[0].urlList.Count;

    for (int i = 0; i <= length - 1; i++)
    {
        listBox1.Items.Add(serversList[0].urlList[i].ToString()+                             serversList[0].urlList[i].ReturnStatus());
    }
}

A:
Creating a Url class is definitely the right move here. It allows you flexibility and growth potential for if you end up needing to store more information in it (perhaps LastGoodStatusTime or some other reporting data). However, it looks like you probably don't want it to be an inner class. Just make it its own class, then everyone can have access to it.
Additionally, as one of the comments mentioned, the Status in the Url class would be better made as a property.
public class Server
{
    public List<string> serverNames = new List<string>();
    public List<object> urlList = new List<object>();
    public string[][] urlArr = new string[1][];

    public Server()
    {

    }

    public Server(string nm)
    {
        serverNames.Add(nm);
    }

    public void setName(string newName)
    {
        serverNames.Add(newName);
    }

    public void addUrl(string newUrl)
    {
        Server.Url url = new Server.Url(newUrl);
        urlList.Add(url);
        url.SetStatus(false);
    }
}

public class Url
{
    public string url;
    public bool Status { get; set; }

    public Url()
    {
    }

    public Url(string URL)
    {
        url = URL;
    }
}

Note that if you strongly desire to go the route of keeping Url an inner class, you'll need to:

*

*Make it public

*Refer to Url in external classes as Server.Url, as in var myUrl = new Server.Url("http://stackoverflow.com/");


text:
Q: Reference multiple keys from one table New to relational DBMS here. I have created table Users and table Sports.
Users Table
CREATE TABLE IF NOT EXISTS schema1.users
(
    user_id serial NOT NULL,
    user_name text NOT NULL,
    user_location text NOT NULL,
    sport_id integer,
    CONSTRAINT users_pkey PRIMARY KEY (user_id)
    CONSTRAINT sports_pkey FOREIGN KEY (sport_id)
        REFERENCES schema1.sports (sport_id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
);

Sports Table
CREATE TABLE IF NOT EXISTS schema1.sports
(
    sport_id serial NOT NULL,
    sport_name text,
    sport_category text,
    CONSTRAINT sports_pkey PRIMARY KEY (sport_id)
);

A person may be interested in more than one sports.
For example, user A may be interested in basketball and baseball.
How this should be handled in order to be able to relate one user to multiple ids from the second table?


text:
Q: Rails 3 observers and current_user There is few similar questions on Stackoverflow about getting of current_user form Rails 3 observers, but basic ideas the same:
1) passing of current_user via
attr_accessor :current_user

in the model we need to observe.
But this unacceptable for me, as, i need to observer 10 models (create, update, delete actions), and i don't want to pass this on each action, for each controller.
2) Storing current user in Thread. Completely unacceptable.
So what is the best practice? And, let's say, i want to get not only current_user in my observer, but also, IP address?
Any ideas?

A: After investigating for more, i found it's totally useless to use Rails native observers in a such a tasks. Because, if you need to pass something from controllers, in my case it was current_user, this totally ruins observer's beauty.
So my answer to my own question is: still stuck with something like acts_as_audited

A: My suggestion would be to add a last_modification_by field to your model. In your observer you could then use that to figure out who made the change and who gets the notification.
Then have your view/controller code put the current user in that field.
This seems to me to be the safest approach. I'd worry about the observer using the current user - it feels to me that the current user should be divorced from the quasi background-processing that the observer is doing. (Which is why stashing the current user in a Thread - which I've used in the past with great success - feels wrong here also).
This approach (having a last_modified_by also lets you make modifications to records in batch - perhaps sending email to the owner of the record that, "The system has updated your record because (some daily processing routine happened). last_modified_by some created user which represents the system (or admin user).


text:
Q: Generalized term for correspondence chess I'm looking for a term to describe a game where neither player is present at the same time. Chess-by-mail is a good example of this, but the opponents may be separated by time instead of by distance. Another example is my aunt, who used to play Scrabble with her friend by phone. Each had a separate Scrabble board, and she would get a phone call once or twice a day from her friend to let her know what move her friend had made. "Correspondence gaming" is not an uncommon term, but what I'm trying to describe doesn't always involve correspondence. For example, you could have a game set up in the break room at work, where each player just takes turns as they are able, rather than all sitting down and playing at the same time.
Example Sentences:
*

*This Catan tournament will include a _______ game.

*He never met his opponent in the ________ game of Uno.

Summary: What is the term for a game where the opponents are separated by time?

A: The word in use for the situation you describe is 'asynchronous':

asynchronous, adj.
1. Not synchronous; not existing or occurring at the same time, not coinciding in time.

In your examples, the use would be verbatim:

*

*This Catan tournament will include an asynchronous game.

*He never met his opponent in the asynchronous game of Uno.

Although the term 'asynchronous game' (or 'asynchronous gaming') is a comparatively recent coinage applied primarily to contemporary gaming conditions, it serves your purposes, and the purposes of others with the same descriptive needs, admirably. As Christian Dolan put it in a 2012 Vice article titled "Asynchronous Gaming Is Sexier Than it Sounds":

Asynchronous gaming has been around ever since Oxford dons first took a break from running Asian spy rings and having affairs with Vladimir Nabokov, and decided to play postal chess with each other instead. It's as old, probably, as the Penny Black. Modern asynchronous gaming really got its mainstream start with Facebook, however, and its first star was Scrabulous.

More specific terms such as 'play-by-mail game' (often abbreviated PBM) or 'play-by-post game', along with 'correspondence game' have long been in use to describe chess and, since the 1960s, a board game called Diplomacy. The latter was, more recently, played via email.
Before being marginalized by computer-assisted gaming, a variety of play-by-mail games were popular:

In the 1980s, play-by-mail games reached their peak of popularity with the advent of Gaming Universal, Paper Mayhem and Flagship magazine, the first professional magazines devoted to play-by-mail games. (An earlier fanzine, Nuts & Bolts of PBM, was the first publication to exclusively cover the hobby.) Bob McLain, the publisher and editor of Gaming Universal, further popularized the hobby by writing articles that appeared in many of the leading mainstream gaming magazines of the time.

(Wikipedia, "Play-by-mail game")


text:
Q: YA sci fi novel a group of kids find out they're alien royalty. One of the girls has blue skin and can read minds I've been looking for this book for years! It's about a group of kids, and someone gathers them all up. They find out they have powers, and are alien princes and princesses.  They each have a different power.  One of them is a girl with blue skin, and she can read minds and she thinks she's ugly.  At one point in time, they have to all go inside one of the girls' mind and find her because something traumatic happened so she was hiding in her own mind. And I think she tries to drown them maybe? I just remember it being really dark and dangerous inside. I don't remember any physical characteristics of the book. I read it probably in the early to mid 2000's. I think it was just in the YA section at my local library.
I've googled for hours trying to find it, I'm hoping a human can maybe help now!


text:
Q: Multiple Logs messages in Test I have a script like below:
[CCO-XXXXX_4]
         [Tags]    TEST_CCO-XXXXX
         Run Keyword And Continue On Failure        Run Test      General                test.out         testProfile          mode.out
         Run Keyword And Continue On Failure        Run Test      General                test.out         testProfile          mode.out

The Idea is to run 2 test cases with different arguments:
Run Test
    [Documentation]    Run the suite
    [Arguments]       ${type}     ${profile}     ${file}    ${test}
    When suite config is updated
    Then publish test status

Then publish test status
    Set Test Message     ${LogStr}

Stop Test
    [Documentation]    Stop Execution of suite
    [Arguments]       ${FIALUREMSG}
    Log To Console    ${FIALUREMSG}
    Fail        ${FIALUREMSG}

The issue is in the report - when the test fails for both the runs then there are 2 separate individual messages in report messages: "This is stop called"
But when it passes only one message log is available - since there are two runs for the above two test cases is it not possible that the for each individual test there can be test related message : [ex "Hello this an example" should be logged twice?]

A: Your problem is that Set Test Message overrides the earlier content in every iterations. To fix the problem you should use the append parameter of this keyword. For example:
Set Test Message    is continued.   append=yes

Relevant part from the documentation:

If the optional append argument is given a true value (see Boolean arguments), the given message is added after the possible earlier message by joining the messages with a space.


text:
Q: Are .NET string operations case sensitive? Are .NET string functions like IndexOf("blah") case sensitive?
From what I remember they aren't, but for some reason I am seeing bugs in my app where the text in the query string is in camel case (like UserID) and I'm testing for IndexOf("userid").

A: Yes, string functions are case sensitive by default. They typically have an overload that lets you indicate the kind of string comparison you want. This is also true for IndexOf. To get the index of your string, in a case-insensitive way, you can do:
string blaBlah = "blaBlah";
int idx = blaBlah.IndexOf("blah", StringComparison.OrdinalIgnoreCase);

A: One thing I'd like to add to the existing answers (since you were originally asking about ASP.NET):
Some name/value collections, such as the Request.QueryString and probably also Request.Form are not case-sensitive. For example if I navigate to an ASPX page using the following URL
http://server/mypage.aspx?user=admin

then both of the following lines will return "admin":
var user1 = Request.QueryString["user"];
var user2 = Request.QueryString["USER"];

A: .NET string comparisons are indeed case sensitive.  You could use things like ToUpper() to normalize things before comparing them.

A: As default they are case sensitive but most of them (if not all) including IndexOf has an overload that takes a StringComparison argument. E.g. if you pass
StringComparison.InvariantCultureIgnoreCase

as the StringComparison argument to IndexOf it will (as the name implies) ignore case differences


text:
Q: Geometry and land The word "geometry" in Greek means "measurement of Earth/land". This may imply that geometry was originally invented in order to solve problems related to land. Are there historical accounts of concrete problems related to land, either from ancient Greece or elsewhere, whose solution required the development of geometric concepts or theorems?

A: The standard reference for geometry as land measuring is Herodotus in The Histories, written c. 440 BC. He describes how the Egyptians had to measure the land after each flooding of the Nile:
This king also (they said) divided the country among all the Egyptians by giving each an equal parcel of land, and made this his source of revenue, assessing the payment of a yearly tax. And any man who was robbed by the river of part of his land could come to Sesostris and declare what had happened; then the king would send men to look into it and calculate the part by which the land was diminished, so that thereafter it should pay in proportion to the tax originally imposed. From this, in my opinion, the Greeks learned the art of measuring land.
For another reference, the Roman poet Virgil wrote c. 20 BC about how Carthage was founded by Queen Dido and her followers, perhaps around 800 BC or so:
They came to this place, and bought land, where you now see
the vast walls, and resurgent stronghold, of new Carthage,
as much as they could enclose with the strips of hide
from a single bull, and from that they called it Byrsa.
From this is derived the isoperimetrical Dido's Problem, which is to enclose as much land as possible by a curve of fixed length, where the land is bounded by the sea (or a straight line) on one side.


text:
Q: How to communicate between HTML/Javascript and C++ in Qt WebChannel in platform independent way? For desktops (Windows, Mac, Ubuntu), there is a QWebEngineView and for mobiles (Android, iOS), there is a native QWebView.
Unfortunately, mobiles don't support QWebEngineView.
For example, as discussed in below post:
How to use Qt WebEngine and QWebChannel?
The setWebChannel() is available in QWebEnginePage which is accessible only in QWebEngineView. However, QWebPage doesn't have such method which is accessible in QWebView.
Now, there is another platform independent way, which works on all the platforms, as discussed in Integrating Web Content.
But the example uses QWebChannelAbstractTransport, which can be used only with JSON. Now JSON, due to its over-descriptive nature, could be quite expensive, if the C++ module is sitting somewhere in server and HTML is local; i.e. real client-server communication over internet.
It would have been better, had they use protobuf.
Is there any optimised and platform agnostic way of calling HTML/Javascript from C++ in Qt?
[Note: BTW, current Qt way of calling C++ from Javascript is quite handy using channel.objects and I would like to retain that way.]

A: With QWebChannel to communicate between C++ and HTML/JS, Qt currently, uses JSON to transport event invocation/data (see QWebChannelAbstractTransport & QWebChannel.js). Over the internet, JSON when compared to Google Protobuf, may be having a overhead of sending field names but this should be negligible compared to 'No data (strings/text) optimization" in either protocols.
Is there any optimised and platform agnostic way of calling HTML/Javascript from C++ in Qt?
The optimized way would be for Qt to provide string/bytes (instead of QJsonObject) in QWebChannelAbstractTransport and JS (both the connection ends) so that we can use custom protocols for transport.
A work around/alternate solution (may not be the optimized way) would be to use the current abstraction to transport using Protobuf/custom protocol like here:
Refer to Qt WebChannel Examples
    In websockettransport.cpp (shared folder in examples)
        C++

        void WebSocketTransport::sendMessage(const QJsonObject &message)
        // Convert message from QJsonObject to Protobuf/custom protocol and
        // use m_socket->sendTextMessage or sendBinaryMessage as required

        void WebSocketTransport::textMessageReceived(const QString &messageData)
        //with QWebSocket::binary[ or text]MessageReceived slot,
        //convert the message from client (in Protobuf/custom protocol) to
        //JSON and still
        emit messageReceived(message.object(), this);

JS:
Similarly, since the QWebChannel.js uses socket, need to set the socket to binary or text as required and convert the ProtoBuf/custom protocol message to json as needed by Qt
Simple illustration on using Protobuf (needs all messages to be predefined)/custom protocol in QWebchannel:
C++ -> WebSocketTransport (JSON to Protobuf/custom protocol) -> transmit -> websocket JS (Protobuf/custom protocol to JSON) -> (QWebChannel.js)
JS -> (QWebChannel.js) -> websocket JS (JSON to Protobuf/custom protocol) -> transmit -> WebSocketTransport (Protobuf/custom protocol to JSON) -> C++
Note: JS works on objects (from JSON or any protocol) and may not need conversion as said above; but this needs to be determined.


text:
Q: What is the need to repeat property creating? According to the books and websites I have checked when I create a class i want to make sure that the properties are not directly accessible. As such make them Private and then make getters and setters.
As such I have the following for a Card class
    private Suits _suit;
    public Suits Suit { get; set; }
    private Values _value;
    public Values Value { get; set; }

    public Suits Suit { get; set; }
    public Values Value { get; set; }

After I completed the class and did test on it, it states that Suit has 2 references and that _suit is unused. It is the same with Value, it is marked with 8 references and _value is unused. I deleted the two private statements (Creating the second block of code) and the program that I was working on did not change. What is the point of creating a private and then a public if one does not get used. Am I missing something?

A: Your auto-implemented properties don't reference your fields at all. They have their own auto-generated backing fields that are separate from your fields. This is why deleting your fields has no effect on your properties.
Auto-implemented properties are only encapsulated insofar that you access the properties directly, and not their auto-generated fields. So generally speaking, you're still allowing them to be accessed directly, kind of. What you want to accomplish with properties really depends on how you want your data to be able to be accessed. If you want them to be read-only by callers but writable within the class, give them private setters:
public Suits Suit { get; private set; }
public Values Value { get; private set; }

If you don't want them to be writable after each time the class is initialized, leave the setters out entirely:
public Suits Suit { get; }
public Values Value { get; }

(Also, since these appear to be enum properties, having no setter makes them effectively immutable.)

A: The syntax you have for the public ones is that of auto-implemented properties. As commented above, the compiler will automatically turn such properties into get- and set- methods that access a private backing field.
This syntax wasn't available in the original language spec, so there are texts that will describe the use of backing fields as necessary. However, your original source needs to be a little different to actually use them:
private Values _value;
public Values Value
{
    get { return _value; }
    set { _value = value; }
}

This is functionally identical to what you get with the { get; set; } syntax; your code in the first example is being compiled into two auto properties with hidden backing fields, plus two fields you've explicitly declared which the compiler correctly identifies as unused.
There is however a scenario where you will have to use this longhand form: when you want your getter/setter methods to perform additional validation or processing before seting/returning the internal field value; automatic properties don't allow you to inject the additional code.


text:
Q: How to create a custom analyzer in Pylucene 8.6.1? I have looked at this, this and this but I'm not sure why they don't work for me.
I would normally use an analyzer like below.
import lucene
from org.apache.lucene.analysis.core import WhitespaceAnalyzer
from org.apache.lucene.index import IndexWriterConfig, IndexWriter
from org.apache.lucene.store import SimpleFSDirectory
from java.nio.file import Paths
from org.apache.lucene.document import Document, Field, TextField

index_path = "./index"

lucene.initVM()

analyzer =  WhitespaceAnalyzer()
config = IndexWriterConfig(analyzer)
store = SimpleFSDirectory(Paths.get(index_path))
writer = IndexWriter(store, config)

doc = Document()
doc.add(Field("title", "The quick brown fox.",  TextField.TYPE_STORED))
writer.addDocument(doc)

writer.close()
store.close()

Instead of the WhitespaceAnalyzer() I would like to use MyAnalyzer() which should have LowerCaseFilter and WhitespaceTokenizer.
from org.apache.lucene.analysis.core import LowerCaseFilter, WhitespaceTokenizer
from org.apache.pylucene.analysis import PythonAnalyzer

class MyAnalyzer(PythonAnalyzer):
    def __init__(self):
        PythonAnalyzer.__init__(self)

    def createComponents(self, fieldName):
        # What do I write here?

Can you please help me write and use MyAnalyzer()?

A: I found here and here that the below works.
from org.apache.lucene.analysis.core import LowerCaseFilter, WhitespaceTokenizer
from org.apache.pylucene.analysis import PythonAnalyzer
from org.apache.lucene.analysis import Analyzer

class MyAnalyzer(PythonAnalyzer):
    def __init__(self):
        PythonAnalyzer.__init__(self)

    def createComponents(self, fieldName):
        source = WhitespaceTokenizer()
        result = LowerCaseFilter(source)
        return Analyzer.TokenStreamComponents(source, result)

It would be great if someone can point me in the right direction to be able to find these answer correctly.


text:
Q: Create a PostgreSQL Hyperscale Citus DB from Azure CLI (not ARC) How do I create a hyperscale PostgreSQL DB from the Azure CLI?
Please note, I am not asking about Arc-enabled Kubernetes clusters.
The current documentation is for Portal only.
Is there a way to do this from the Azure CLI?

A: Furkan is here from Microsoft (PostgreSQL Hyperscale Citus team),
We currently do not support the Azure CLI based provisioning. However, we have rest APIs in private preview. You can see the API description here https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresqlhsc/resource-manager


text:
Q: Picking the right Zoom level for different cities in GoogleMaps I have an activity implementing OnMapReadyCallback to display some markers.
Before opening the map i provide a target city which i'd like to look at closer on the map basically by calling :
 LatLng currentCity = new LatLng(cityLat,cityLng)
 CameraUpdate location = CameraUpdateFactory.newLatLngZoom(currentCity,13);
 googleMap.animateCamera(location);

The main problem here is that the zoom level is just an arbitrary number which works fine for some city and bad for others (Too zoomed in, Not enough zoomed in).
What i would like to achieve is to determine the zoom level dynamically depending on the city in the same way Google Maps does.
I know that the bigger the ViewPort of the city is, the smaller the zoom needs to be but i can't find a method to get the ViewPort for a given city and then changing the zoom level accordingly
EDIT : I was thinking about using a Geocoder to get a list of adress using the latitude and longitude of the city using
List<Address> addresses =  mGeocoder.getFromLocation(Lat,Lon,maxLimit);

and then iterating over this list to find out the outermost adresses avaible for that city, in order to build a LatLngBounds to pass at setLatLngBoundsForCameraTarget() method.
The main problem with this approach is that, once again, the "maxLimit" is arbitrary and needs to be quite big for a big city, eventually returning a really big List

A: You can retrieve a view port for the city from the Geocoding API reverse geocoding response.
You should execute HTTP request to retrieve city view port from your activity. Once you receive the response you can construct the LatLngBounds instance and move camera accordingly.
Sample reverse geocoding request that gets city from coordinates is the following
https://maps.googleapis.com/maps/api/geocode/json?latlng=47.376887%2C8.541694&result_type=locality&key=YOUR_API_KEY
I wrote a small example for Map activity that receives lat and lng from the intent, executes the reverse geocoding HTTP request using the Volley library and moves camera to show the city view port.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private float lat;
    private float lng;
    private String name;
    private RequestQueue mRequestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent i = getIntent();
        this.lat = i.getFloatExtra("lat", 0);
        this.lng = i.getFloatExtra("lng", 0);
        this.name = i.getStringExtra("name");

        mRequestQueue = Volley.newRequestQueue(this);

        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng pos = new LatLng(this.lat, this.lng);
        mMap.addMarker(new MarkerOptions().position(pos).title(this.name));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));

        this.fetchReverseGeocodeJson();
    }

    private void fetchReverseGeocodeJson() {
        // Pass second argument as "null" for GET requests
        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
               "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + this.lat + "%2C" + this.lng + "&result_type=locality&key=AIzaSyBrPt88vvoPDDn_imh-RzCXl5Ha2F2LYig",
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String status = response.getString("status");
                            if (status.equals("OK")) {
                                JSONArray results = response.getJSONArray("results");
                                JSONObject item = results.getJSONObject(0);
                                JSONObject geom = item.getJSONObject("geometry");
                                JSONObject bounds = geom.getJSONObject("viewport");
                                JSONObject ne = bounds.getJSONObject("northeast");
                                JSONObject sw = bounds.getJSONObject("southwest");

                                LatLngBounds mapbounds = new LatLngBounds(new LatLng(sw.getDouble("lat"),sw.getDouble("lng")),
                                        new LatLng(ne.getDouble("lat"), ne.getDouble("lng")));

                                mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapbounds, 0));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.e("Error: ", error.getMessage());
                    }
                }
        );

        /* Add your Requests to the RequestQueue to execute */
        mRequestQueue.add(req);
    }
}

You can find a complete sample project at github:
https://github.com/xomena-so/so44735477
Hope this helps!