text:
Q: How to use the t() function in a class component with a constructor? Using i18next with react, I would like to use the t() function in class components, but most of the time, I also need to initialize the state, so I would like to have a constructor as well.
Following the documentation here I get this:
import React from 'react';
import {WithTranslation, withTranslation} from "react-i18next";

interface ExampleProps extends WithTranslation {

}

interface ExampleState {

}

class Example extends React.Component<ExampleProps, ExampleState> {
    render() {
        const t = this.props.t;
        return (

{t('Test')}

        );
    }
}

export default withTranslation()(Example);

This works fine, no problem here. Until I add a constructor:
    constructor(props: ExampleProps, context: any) {
        super(props, context);
    }

withTranslation won't work with this:
TS2345: Argument of type 'typeof Example' is not assignable to parameter of type 'ComponentType<WithTranslationProps>'.   Type 'typeof Example' is not assignable to type 'ComponentClass<WithTranslationProps, any>'.     Types of parameters 'props' and 'props' are incompatible.       Type 'WithTranslationProps' is missing the following properties from type 'WithTranslation<"translation">': t, tReady

If I use interface ExampleProps extends WithTranslationProps {} the type incompatibility disappears, but I can't access the t function, because the WithTranslationProps only has a i18n? nullable type and I can't add anything to the ExampleProps, because I get Property 'newProperty' is missing in type 'WithTranslationProps' but required in type 'ExampleProps'.
const t1 = this.props.i18n?.t; results in TS2722: Cannot invoke an object which is possibly 'undefined' when trying to call t('Test').
const t2 = this.props.t; does not exists.
One solution, If I just initialize the state directly in the class, like:
class Example extends React.Component<ExampleProps, ExampleState> {
    state = {
      // set state here
    }

    render() {

Although I would still like to know if there is a way to use a constructor here.

A: From the React documentation:

If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.

But, wait a minute, what is the context you passed to constructor?
you only need to pass props as the parameter of the constructor.

constructor(props)

A: In react constructor and super methods receive either 0 parameters or 1 (if it's 1, then they should be props), as per documentation
In your render you can just do
render () {
   const { t } = this.props;

   return (

{t('Test')}

        );
}

This deconstruction of the components props makes your code more readable, if you need more variables from props, just add a comma and the name of the variable, and it will be usable inside that function.
Other than that your code seems fine


text:
Q: twitteR lookupUsers for loop I'm relatively new to both R and twitteR and am attempting to write some code that will allow me to export a data frame showing multiple Twitter User Names, the number of friends for each, the number of followers for each, the number of times they are listed in public lists, and the number of time they have been mentioned, hopefully making it look like below:
User | Date | Friends | Followers | Listed | Mentions | StatusCount
The closest reference I could find on SO is this question, which is on "Hold", and when I try running the code listed, it gives the following error:
"Error in fix.by(by.x, x) :
  'by' must specify one or more columns as numbers, names or logical"

Code:
library(RCurl)
library(bitops)
library(digest)
library(ROAuth)
library(rjson)
library(twitteR)
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))

load("twitteR_credentials")
registerTwitterOAuth(twitCred)

clients <- lookupUsers(c('Name','Name1','Name2'), cainfo = "cacert.pem")

for(i in 1:length(clients)) {
   start <- getUser(clients[i])
   friends.object <- start$friendsCount
   followers.object <- start$followersCount
   status.object <- start$statusesCount
   listed.object <- start$listedCount
   mentions.object <- start$mentions
   data <- merge(data.frame(User=start$id, Friends=friends.object),
                 data.frame(User=start$id, Followers=followers.object),
                 data.frame(User=start$id, Statuses=status.object),
                 data.frame(User=start$id, Listed=listed.object)
                 data.frame(User=start$id, Mentions=mentions.object), all=T)
   filename <- paste(clients[i],"Twiter Data.csv", sep=' ')
   setwd("filepath")
   write.csv(data, file=filename)
   remove(data)
}

Any help would be appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding typing changes to of(undefined) in rxJS I have an observable defined like this:
   const orders$ = concat(of(undefined), vm.orders$);     // Observable<any>

I upgraded to Angular 9 (major newer typescript and newer RxJS point release) and the typing of orders$ became Observable<any> instead of <Observable<Orders[]> which is what it was before. So I lost a lot of typing throughout my app.
Yes this example could be rewritten vm.orders$.pipe(startWith(undefined)) but forget about that for a minute ;-)
The change is ultimately because of(undefined) is now Observable<any> instead of Observable<undefined>. So when concatenated together the Orders[] type gets absorbed into any.
The above startWith syntax fixes the typing, as does of<undefined>(undefined) but that's clumsy.
Here's a few examples:
    var concat1 = concat(of(undefined), of(123));               // becomes Observable<any>
    var concat2 = concat(of('cat'), of(123));                   // becomes Observable<string | number>
    var concat3 = concat(of<undefined>(undefined), of(123));    // becomes Observable<number>
    var concat4 = concat(of(123)).pipe(startWith(undefined));   // becomes Observable<number>

One way to 'fix' the loss of typing is by declaring the type of of explicitly, which can be made into a constant like this.
    const UNDEFINED = of<undefined>(undefined);
    var concat5 = concat(UNDEFINED, of(123));                   // becomes Observable<number>

Interestingly there's some upcoming changes in RxJS 7 (which I'm not using) that may be related to this.
So I'm ultimately curious about the following:

*

*what changed the behavior?

*what is the recommended way to handle an undefined observable.?

*if the change is a side effect of a new typescript version then would an UNDEFINED constant in the library make sense (parallel of EMPTY and NEVER)?

*does RxJS 7 address this particular concern?


text:
Q: MATLAB input it not a double error My file is not working and I have no idea why.
When I run y = test(A, x) after I delcare:

A = floor(rand(8,100));
x = floor(rand(100,1));

I get Undefined function 'test' for input arguments of type 'double'.
function [ output_args ] = untitled2( ~ )
    function y = test(A, x)
    %This function computes the pro
    duct of matrix A by
    vector x row-wise
    % define m number of rows here to feed into for loop
    [ma,na] = size(A);
    [mx,nx] = size(x);
    % use if statement to check for proper dimensions
    if(na == mx && nx == 1)
    y = zeros(ma,1);   % initialize y vector for n = 1:ma
    y(n) = A(n,:)*x;
    %end
    else
    disp('Dimensions of matrices do not match')
    y = [];
    end
    end
    end

A: As Ben Voigt correctly told you in comment your problem is that test is defined inside untitled2.
For the code you posted there's no need in doing such thing, so you can solve by just declaring test without the outer untitled2.  So just create a test.m file just use this part of code
function y = test(A, x)
    %This function computes the product of matrix A by vector x row-wise
    % define m number of rows here to feed into for loop
    [ma,na] = size(A);
    [mx,nx] = size(x);
    % use if statement to check for proper dimensions
    if(na == mx && nx == 1)
        y = zeros(ma,1);   % initialize y vector
        for n = 1:ma
            y(n) = A(n,:)*x;
        end
    else
       disp('Dimensions of matrices do not match')
       y = [];
    end
end

And then call the function again


text:
Q: Laravel 5.1 and Redis queue jobs doesn't work i'm using Laravel 5.1, i'm trying to set a queued job to get details which i need to wait (around 2 minutes) till i can get them.
for some reason the queue job doesn't work for me, i saw here some questions about it but non of the answers wasn't helped.
my config/queue.php file looks like this:
'default' => env('QUEUE_DRIVER', 'redis'),

'connections' => [

    'sync' => [
        'driver' => 'sync',
    ],

    'database' => [
        'driver' => 'database',
        'table' => 'jobs',
        'queue' => 'default',
        'expire' => 60,
    ],

    'beanstalkd' => [
        'driver' => 'beanstalkd',
        'host'   => 'localhost',
        'queue'  => 'default',
        'ttr'    => 60,
    ],

    'sqs' => [
        'driver' => 'sqs',
        'key'    => 'your-public-key',
        'secret' => 'your-secret-key',
        'queue'  => 'your-queue-url',
        'region' => 'us-east-1',
    ],

    'iron' => [
        'driver'  => 'iron',
        'host'    => 'mq-aws-us-east-1.iron.io',
        'token'   => 'your-token',
        'project' => 'your-project-id',
        'queue'   => 'your-queue-name',
        'encrypt' => true,
    ],

    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue'  => 'default',
        'expire' => 60,
    ],

the job i trying to queue looks like this:
<?php

namespace LM2\Jobs;

use Illuminate\Support\Facades\Log;
use LM2\Http\Controllers\AnalyticsController;
use LM2\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use LM2\Models\Client;
use LM2\Models\GoogleIntegration;
use LM2\Models\Lead;

class CompleteLeadAnalyticsDetails extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    private $lead;
    private $client;

    public function __construct(Lead $lead, Client $client)
    {
        $this->lead   = $lead;
        $this->client = $client;
    }

    public function handle(AnalyticsController $analyticsController)
    {
        try{
            $integration = GoogleIntegration::where('client_id', $this->client->id)->first();
            $analyticsController->getLeadDetails($integration->view_id,$this->lead->ga_details['uacid'],$this->lead->_id);
        }catch (\Google_Service_Exception $e){
            Log::error("Error!, ". $e->getMessage(). ' On client '.$this->client->name.', '.$this->client->id);
        }

    }
}

and i call it like that:
$complete_analytics_proccess = (new CompleteLeadAnalyticsDetails($lead, $client))->delay(120);
        $this->dispatch($complete_analytics_proccess);

of course i'm using redis server run in the background (i'm using it for real time stuff as well and it's works fine).
i don't get any errors and the error i logged wasn't logged as well.
does anyone have any idea what the problem is? it's looks like i did everything like the official documentation says. appreciate any help, thanks! :)


text:
Q: Is there a way to delete user's own Facebook notifications? I am trying to delete the notifications in my account but not sure if it is possible, I not getting any errors with this code, but the notifications are not deleted.
String path = "/me/notifications/"+id ;
new Request(
    Session.getActiveSession(),
    path,
    null,
    HttpMethod.DELETE,
    new Request.Callback()
    {
        @Override
        public void onCompleted(Response response)
        {
            Log.d("RESPONSE",""+response);
        }
    }
).executeAsync();


text:
Q: Parse Table Generator for Simple Precedence Parsing I have been assigned a compiler project for a mini-Pascal language. The project enforce the use of  'Simple Precedence' as parsing algorithm but allows us to use parse table generator tools for creating the parse table.
Does anyone now such a parse table generator? I have tried searching for one myself but haven't found anything useful yet.
I am writing the program in Java so it would be best if the generator results were in Java, but C/C++ will also be useful. (I am in a bit of a hurry...)
Thanks in advance.


text:
Q: Steam stopped working, reinstalling it didn't help A little while ago my steam stopped working. I have tried uninstalling and reinstalling and that didn't work.
When I try to launch steam the icon just blinks 3 to 4 times and steam never opens.
Ubuntu 16.04 64-bit is the version I'm currently running.
I typed steam in terminal, and this was the dialog that came
Running Steam on ubuntu 16.04 64-bit
STEAM_RUNTIME is enabled automatically
Pins up-to-date!

Seems like it is in working order so I don't know what is wrong
EDIT : So after renaming the 2 directories ~/.steam* and ~/.local/share/Steam Steam comes up with a new error :
Running Steam on ubuntu 16.04 64-bit
STEAM_RUNTIME is enabled automatically
Installing breakpad exception handler for appid(steam)/version(0)
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast


text:
Q: statistics find $(2XI tried to solve the following problem without success:

Let $$f_{X,Y}(x,y) = \begin{cases} k e^{-(x+y)} & \text{for } 0 < x < y < \infty \\ 0 & \text{otherwise} \end{cases}$$
  Find $P(2X < Y)$

k=2
My attempt:
$2x$ is smaller than $y$ for half of $x$ that is for start of $y$ divided by $2$
$$
2 \int_0^{y/2} e^{-(x+y)} \, \mathrm{d} x = 2 \int_0^{y/2} e^{-x} e^{-y} \, \mathrm{d} x
= 2e^{-y} \int_0^{y/2} e^{-x} \, \mathrm{d} x = 2 e^{-y} \left[ e^{-x} \right]_0^{y/2} = 2 e^{-y}\left( e^{-y/2} - 1 \right) \\
= 2e^{-y-y/2} - e^{-y}
$$
The answer sheet's solution:
$$
P(2X \le Y) = \int_0^\infty \int_{2x}^\infty 2 e^{-(x+y)} \, \mathrm{d} y \, \mathrm{d} x
= 2 \int_0^\infty e^{-x} \left( \int_{2x}^\infty e^{-y} \, \mathrm{d} y \right) \, \mathrm{d} x \\
= 2 \int_0^\infty e^{-x}e^{-2x} \, \mathrm{d} x = 2 \int_0^\infty e^{-3x} \, \mathrm{d}x = \frac{2}{3}
$$
Why is what I have done wrong? And why is the answer sheet correct? Especially how does the answer find the limits of integration, and is there any way to check to see if the answer you get is correct given that you know that you must find 2X

A: Right away you should see that your solution is wrong (at least I did). When you want to find the probability of some event that specifies what $X$ and $Y$ must be then you should get a number, not some expression involving $y$. For instance if they asked for the marginal probability meaning $P(X \le 5 \mid Y)$ then indeed the answer would depend on $y$.
The answer sheet is correct because you're attempting to find
$$
P(2X \le Y) = P(\{(x,y) \in \mathbb{R^2} \mid 2x \le y \}) = \int_{\{(x,y) \in \mathbb{R}^2 \mid 2x \le y \}} f_{X,Y}(x,y) \, \mathrm{d} A
$$
In order to think about problems like this it helps to visualize the set over which you're integrating. If we know that $2x \le y$ then we can plot $y = 2x$ and see that the portion of the graph where this is true is above that line. Now how do we integrate over this region? This is a multivariable question, but I'll try to provide as much help as I can.
Note that if we first hold $y$ constant then $0 < x \le \frac{1}{2} y$ and then following we get that $0 < y < \infty$. Using this characterization of our set we see that
$$
\begin{eqnarray}
\int_{\{(x,y) \in \mathbb{R}^2 \mid 2x \le y \}} f_{X,Y}(x,y) \, \mathrm{d} A & = & \int_0^{\infty} \int_0^{y/2} 2e^{-(x+y)} \, \mathrm{d} x \, \mathrm{d} y \\
& = & 2\int_0^\infty e^{-y} \left( e^0 - e^{-y/2} \right) \, \mathrm{d} y \\
& = & 2 \left( \int_0^\infty e^{-y} \, \mathrm{d} y - \int_0^\infty e^{-3/2y} \, \mathrm{d} y \right) \\
& = & 2 \left( 1 - \frac{2}{3} \right) = \frac{2}{3}
\end{eqnarray}
$$
Now of course you can characterize the set as the answer guide did and integrate over $y$ first and $x$ second, as you can see your limits simply change.
I hope this helps!


text:
Q: sklearn.metrics classification_report at the end of each epoch using a generator I feed my train and validation data with the following generator
def sequence_generator(data_type):
    data_type = data_type.decode('ascii')
    sequence_folder = f"{model_attributes['sequences_path']}/{data_type}"
    for numpy_file in random.sample(os.listdir(sequence_folder),len(os.listdir(sequence_folder))):
        if numpy_file.endswith(".npz"):
            with np.load(f"{sequence_folder}/{numpy_file}") as numpy_data:
                sequences = numpy_data['x']
                labels = numpy_data['y']
                class_weight = {0: 1, 1: 2 ,2: 2}
                labels = tf.one_hot(labels, 3)
                sample_weights = np.ones(shape=(len(labels),))
                sample_weights[(labels[:, 1] == 1) | (labels[:, 2] == 1) ] = 2

                for X,y,sample_weight in random.sample(list(zip(sequences,labels,sample_weights)),len(sequences)):
                    yield X,y,sample_weight

train_dataset = tf.data.Dataset.from_generator(generator=sequence_generator,args= ['train'], output_types = (tf.float32, tf.float32))# output_shapes = ((train_shape), (3,)))

train_dataset = train_dataset.cache().batch(BATCH).prefetch(tf.data.AUTOTUNE)

history = model.fit(train_dataset, epochs=EPOCHS, validation_data=validation_dataset, callbacks=[tensorboard,checkpoint,earlystop,lr_callback])

I am trying to return a classification report using
from sklearn.metrics import classification_report

for the validation data at the end of epoch (and maybe training data during the epoch?)
I've tried implementing it like so:
class class_report(tf.keras.callbacks.Callback):
    def __init__(self, val_data, batch_size = 32):
        super().__init__()
        self.validation_data = val_data
        self.batch_size = batch_size

    def on_epoch_end(self, epoch, logs=None):
        y_pred = self.model.predict(self.validation_data)

        report_dictionary = classification_report(self.y_true, y_pred, output_dict = True)

history = model.fit(train_dataset, epochs=EPOCHS, validation_data=validation_dataset,callbacks=[tensorboard,checkpoint,earlystop,lr_callback,class_report(validation_dataset)])

but come into a rabbithole of problems from what I understand is because y_true is within the generator tuple as a prefetch type and/or tensor?
current error:
AttributeError: 'class_report' object has no attribute 'y_true'

How can I properly implement this, even by an alternative method?

Attempts:
I am not very good with imlpementing a class so I've kind of being stabbing in the dark
def on_epoch_end(self, epoch, logs=None):

    print(self.validation_data)

    true_values = self.validation_data[:,1]

    y_pred = self.model.predict(self.validation_data)

........
............
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.]], dtype=float32)>, <tf.Tensor: shape=(64,), dtype=float32, numpy=
array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
       0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
       0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
       0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
       0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],
      dtype=float32)>)
........
............

(0.5s due to class_weights 0.5x1)
  File "Train.py", line 2107, in build_and_train_model
    history = model.fit(train_dataset, epochs=EPOCHS, validation_data=validation_dataset,callbacks=[tensorboard,checkpoint,earlystop,lr_callback,class_report(validation_dataset)])
  File "Location\\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1229, in fit
    callbacks.on_epoch_end(epoch, epoch_logs)
  File "Location\\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\keras\callbacks.py", line 435, in on_epoch_end
    callback.on_epoch_end(epoch, logs)
  File "Train.py", line 254, in on_epoch_end
    true_values = self.validation_data[:,1]
TypeError: 'PrefetchDataset' object is not subscriptable

true_values = list(self.validation_data)[:,1]

File "Train.py", line 254, in on_epoch_end
    true_values = list(self.validation_data)[:,1]
TypeError: list indices must be integers or slices, not tuple

print(self.validation_data[1])

TypeError: 'PrefetchDataset' object does not support indexing


text:
Q: Automatically obtaining market data from MetaTrader 5 using MatLab I'm looking for a way to automatically run a script on MatLab which outputs price data from MetaTrader 5. Can anybody provide me a link to someone who has done this before or the best way to go about doing it?
I've researched online and could not find any useful article to deal with this matter.

A: I've been downloading live Metatrader data, charting it with Matplotlib and developing indicators in Python. There is a user group with links to the code you need to acces the metatrader feed
There's a thread on it here: https://www.mql5.com/en/forum/306742

A: There are several ways to make an interaction between Matlab and Metatrader. The newest way is using Matlab COM services. It can be done either directly or indirectly. The indirect way is possible through the Excel DDE server. I've done it recently using Matlab "actxserver" for the Excel application. The data is first sent from Metatrader to Excel and then read by Matlab through the COM server. Exporting data from MetaTrader to Excel through the DDE server is explained here:
Export data from MT5 to Excel.
Exporting data from Excel to Matlab through COM server is also explained here:
Export data from Excel to Matlab.
These days I'm trying to make a complete direct interaction between MT5 and Matlab. You can contact me for further information if needed.


text:
Q: EF multiple foreign key relationship on same primary key I want to create a many-to-many relationship using EF 6 using a code-first approach. My entities use a composite primary key (to handle multi-tenancy).
Let's take simple and classical example. I have two entities Project and Person which have a many-to-many relationship:
public class Person
{
   [Key, Column(Order = 1),]
   public Int32 Id { get; set; }
   [Key, Column(Order = 2)]
   public int TenantId { get; set; }
   public string Name { get; set; }
}

public class Project
{
   [Key, Column(Order = 1),]
   public Int32 Id { get; set; }
   [Key, Column(Order = 2)]
   public int TenantId { get; set; }
   Public string Name { get; set; }
}

I also have a joining table ProjectPerson like this:
Above I have defined a Project to ProjectPerson relationship. Note that   public class ProjectPerson
    {
       [Key, Column(Order = 1),]
       public Int32 Id { get; set; }
       [Key, Column(Order = 2)]
       [ForeignKey("Project")]
       public int TenantId { get; set; }
   [ForeignKey("Project")]
   public int ProjectId { get; set; }

   public DateTime AddedDate{ get; set; }

   public virtual Project Project { get; set; }
}

TenantId is used as a part of the primary and foreign key.
Up to this point, the model works as expected. But the Person to ProjectPerson relationship is missing.
I have added following two lines to the ProjectPerson class
  [ForeignKey("Person")]
  public int PersonId { get; set; }

  public virtual Person Person { get; set; }

Definitely mapping to TenantId is missing. I don't know how to define it
Update
I found this. but still im not satisfied as there is additional TenantId ( PersonTenantId) as a foreign key.
 public class ProjectPerson
 {
   [Key, Column(Order = 1),]
   public Int32 Id { get; set; }
   [Key, Column(Order = 2)]
   [ForeignKey("Project")]
   public int TenantId { get; set; }

   [ForeignKey("Project")]
   public int ProjectId { get; set; }

   [ForeignKey("Person")]
   public int PersonId { get; set; }
   [ForeignKey("Person")]
   public int PersonTenantId { get; set; } // duplicate

   public DateTime AddedDate{ get; set; }

   public virtual Project Project { get; set; }
   public virtual Person Person { get; set; }

}

A: Use the fluent API to reuse the TentantId column for both FK's in the junction table.  ProjectId should also be included in the junction table's PK.  Note that I modified the order of the composite primary key columns to have TenantId as the first column.
    public class Person
    {
        [Key, Column(Order = 0)]
        public int TenantId { get; set; }
        [Key, Column(Order = 1)]
        public int PersonId { get; set; }

        public string Name { get; set; }

        public virtual ICollection<ProjectPerson> ProjectPeople { get; set; }
    }

    public class Project
    {
        [Key, Column(Order = 0)]
        public int TenantId { get; set; }
        [Key, Column( Order = 1 )]
        public int ProjectId { get; set; }

        public string Name { get; set; }

        public virtual ICollection<ProjectPerson> ProjectPeople { get; set; }
    }

    public class ProjectPerson
    {
        [Key, Column( Order = 0 )]
        public int TentantId { get; set; }
        [Key, Column( Order = 1 )]
        public int ProjectId { get; set; }
        [Key, Column( Order = 2 )]
        public int PersonId { get; set; }

        public DateTime AddedDate { get; set; }

        public virtual Project Project { get; set; }
        public virtual Person Person { get; set; }
    }

    protected override void OnModelCreating( DbModelBuilder modelBuilder )
    {
        base.OnModelCreating( modelBuilder );

        modelBuilder.Entity<Project>()
            .HasMany(pr => pr.ProjectPeople )
            .WithRequired( pp => pp.Project )
            .HasForeignKey( pp => new { pp.TentantId, pp.ProjectId } );

        modelBuilder.Entity<Person>()
            .HasMany( pe => pe.ProjectPeople )
            .WithRequired( pp => pp.Person )
            .HasForeignKey( pp => new { pp.TentantId, pp.PersonId } );
    }


text:
Q: resizing images with different names in a loop I have a set of input image (im1,im2,im3,im4,im5; all have the size of [200 200]) and I want to resize them based on the matlab code: resized = imresize(input image,[100 100],'nearest').
I want to resize them and save them in different matrices 9such as out1, out2, out3, out4, out5).
I am suing the following code but it does not work, any solution?
for i = 1:5
  varName = ['im' int2str(i)];  % output string
  eval(['out' varName ' = imresize(' varName ',[100 100], 'nearest');']);
end

A: Try this:
eval(['out' varName ' = imresize(' varName ',[100 100], ''nearest'');']);


text:
Q: Itext7 dynamic pdf download returns -Document has no pages on server I have a situation where I've used the Itext7 library for generating pdf's on a .net core app.
As far as im aware code works well when Im running the application locally i.e I can download pdf's without any issues. (This pdf is dynamically generated).
But once i deploy the application to a remote server i get an error  PdfException Document has no pages
Is there anything I need to do on  the server or does this have to do with browser policy that I may need to change ?

A: Apparently , the issue was that I  was calling into an Image file that I use for generating the pdf . This file was saved locally on my drive and wasn't available on the sever end hence the pdf doesn't get created .
I basically relocated the image file into the wwwroot/images folder and called it from there and there  you have it ... I solved my own problem


text:
Q: FileReader concatenate files I need to write my JavaScript function that will iterate over an input type file to get the content of multiple XML files (one by one) and concatenate it in such a way that first line of content in all files (except first file) is removed and rest content is in one single variable or JavaScript array or whatever works with browser. I have spent days researching all over Google but could not get it to work so, finally posting here.
function call(){
    var myFile = $('#xmlFileUploaded').get(0);
    var xml=new Array();
    for (let i = 0; i < myFile.files.length; i++) {
        (function(file){
            let reader = new FileReader();
            reader.onload = function() {
                xml.push(reader.result);
            }
            reader.readAsText(file);
        })(myFile.files[i]);
    }
        console.log(xml);
        for(let x=0;x<xml.length;x++)
            console.log(xml[x]);
}

After spending hours and days on this I have created above code. I run it and select 3 XML files. console.log in Chrome is showing empty array []. When I click on the little triangle to see details it shows correct array length i.e. 3 and content of the 3 files. Now starts the confusing statement, if I iterate over this array it gives me nothing.

Sample XML files:
one.xml:
<myroot>
<tag1>value1</tag1>
<tag2>value2</tag2>
</myroot>

two.xml
<myroot>
<tag1>value3</tag1>
<tag2>value4</tag2>
</myroot>

three.xml
<myroot>
<tag1>value5</tag1>
<tag2>value6</tag2>
</myroot>

Desired Output:
<myroot>
<tag1>value1</tag1>
<tag2>value2</tag2>
<tag1>value3</tag1>
<tag2>value4</tag2>
<tag1>value5</tag1>
<tag2>value6</tag2>
</myroot>


text:
Q: the usage of the pronoun "it"
*

*Just as the nation-state is a modern phenomenon, so is the explosive increase of the human population.

*As Lenin claimed, Marxism is strong insofar as it is true.
I would like to ask why in the first sentence the pronoun "it" is omitted ("so [it] is the explosive…") whereas in the second one is used ("insofar it is true"). In the first example "it" would represent "modern phenomenon" as in the second one "it" represents "Marxism".

A: The sentences are different because so and insofar as are different types of word. So is a proform adverb. In sentence (1) it means a modern phenomenon. When this type of so is moved to the front of the clause, we have to change the position of the Subject and the auxiliary:

*

*Mary is hungry. So is my elephant.

In the example above so means hungry. The second sentence means My elephant is hungry too. We can see that the Subject my elephant and the auxiliary verb is have changed places.
Here is the Original Poster's first sentence:

*

*Just as the nation-state is a modern phenomenon, so is the explosive increase in the human population.

The proform so in this sentence means a modern phenomenon. The subject of the second clause there is the explosive increase in the human population, but it appears after and not before the auxiliary verb. We do not need a second Subject, it, here. We already have one!
The second example is completely different:

*

*... Marxism is strong insofar as it is true.

Here the phrase insofar as can be analysed as a compound preposition. It takes as a Complement a declarative clause. In the sentence the pronoun it refers to Marxism. It comes before the verb is because there is no special reason to move it from the normal Subject position. We cannot drop it because every tensed verb in English must have a Subject.

A: The first sentence is a common expression to say "me too", or more generally, to convey the similarities between two entities (persons often, but not only as can be seen in your example. Let me be more clear :

I'm so hungry !
-So am I ! (Me too)
-So is he ! (Him too)

Etc. Hence, the first sentence didn't really omit "it", as it wouldn't have had the same meaning (and wouldn't have been correct syntaxically after that first proposition).
What puzzles me is that your English skills don't seem to be bad as you can use constructions with "would" or "whereas", but don't seem to have seen that basic English point. Interesting !

A: Oxford Online Dictionary classifies "so" as an "adverb". However, if you read the linked ELU question, So do I ( what word type is "so" functioning as?, you will notice that there are different opinions.
No matter what it is called, its primary function is not to repeat what is said before the word.

A: I love you.
B: I love you, too.

You can say "So do I" in place of "I love you, too" as "(do) so" refers to
"love".
You example sentence could be rephrased to:

Just as the nation-state is a modern phenomenon, the explosive
  increase of the human population is a modern phenomenon, too.

You don't need to repeat "a modern phenomenon" as it is repeated. "So" could replace it as long as it is inverted and placed at the beginning of the clause. The subject of the second clause is not a modern phenomenon.
You can read my answer to this question, the usage of 'so' in ' it does so very slowly'' if you are interested in learning how "so" works in different ways.


text:
Q: Using Distributed Replay Utility on 2008 r2 Client I have a DRU controller that is running on a SQL Server 2012 SP3 instance.  I have read from Boris Hristov (a former MVP that has since gone on to other things) that the DRU can replay traces from as far back as 2005.  I have a 2008 r2 instance that I have captured trace data on using the TSQL_Replay template and would like to run it against the controller to test this out in order to see how the workload will perform in 2012 prior to upgrading the server.  Does anyone know the specifics of how this works (without actually updating the client)?  I have tried running workloads on the controller from non-client servers to see if that would work with no luck.  Any help would be appreciated.

A: I was able to ask Jonathan Kehayias about this.  He recommended copying the trace file to the 2012 controller and then replaying it using a 2012 client server that is already installed.  Hopefully, this will help anyone else experiencing the same problem.


text:
Q: If memory used is higher then > perform function I've been testing my app and currently at peak points it consumes more than 450 mb of ram.
The number is astoundingly big due to AppleMaps api. Simple zoom out eats around 150 mb of ram.
After browsing i've found out a tricky solution - which is reversing the Map types for a second (from standard to satellite to standard). The following snippet code helps me achieve that:
[mapView setMapType:MKMapTypeSatellite];
[mapView setMapType:MKMapTypeStandard];

The issue is - i want to apply a rule - if my app is using equal or more than 400 mb of ram - this trick should be performed. And so far i have no clue how to do that.
NB: Tried following the article "How to programmatically retrieve the RAM memory" advised by the admin, but couldnt get the code to work.
Any ideas greatly appreciated.
Thank you!


text:
Q: Error when generating a doctrine 2 entity I have already created entities initiall on my projects creationy and now have a table i would like to automap a single entity for.
i ran: php app/console doctrine:mapping:convert xml ./src/MyBundle/Resources/config --from-database --filter="clicks"
and get:
No Metadata Classes to process.

I am looking to just generate the entity of that one table "clicks"
Can anyone explain to me why this might be happening and how I can get this command to work?

A: If you've successfully use this command to generate entities before, it should normally work.
You can get this error, when the table does not actually exist in the database.
Double check if the table "clicks" is in the database.


text:
Q: indefinite integral and inequality Let $$ f(x) \leq g(x), \forall\,  x.\hspace{0.5cm} (1)$$
Moreover, considering the indefinite integrals
$$\int f(x)\,dx= F(x) + C_1 \hbox{ and } \int g(x)\,dx = G(x) + C_2.$$
My question: If we supppose (1), is true that
$$ F(x) + C_1=\int f(x)\,dx \leq \int g(x)\,dx = G(x) + C_2? $$
If the answer is wrong, what would be a counterexample or what the inconsistency in this it?

A: Clearly false: $C_1$ and $C_2$ are as large as you like. What is true is that
$$
\int_a^x f(t)\, dt \leq \int_a^x g(t)\, dt
$$
for any $x$. In other words, you must take $C_1=C_2$.

A: Observe that $f(x) \leq g(x)$ is a statement about a single function $f$ and a single function $g$, evaluated pointwise.  On the other hand, $\int f(x) \, dx \leq \int g(x) \, dx$ is about a family of functions.
What do you mean when you say one family of functions is larger than another?  If you mean that any selection from the antiderviatives of $f$ is smaller than any antiderivative of $g$, you are incorrect, for example take $f(x) = g(x)$ and $C_1 > C_2$.


text:
Q: SQL join two SELECT statements - fairly easy I am trying to combine two query results into an output that looks like:
datetime |  BC  |  AC
----------------------
sun      |  1.0 |  0.9

through a sql call located below (in MySQL).  I can make the individual statements query properly but the combined join does not work.  Any suggestions?  Thanks!  Sorry about the formatting.
SELECT z.datetime, (z.w_1 + z.w_2 + z.w_3) as 'BC', (b.w_1 + b.w_2 + b.w_3) as 'AC'
 (FROM monitor_data a
   WHERE mon_id = "site A"
     AND datetime > "2015-04-02 04:30:00"
     AND datetime < "2015-04-02 06:30:00") z

 JOIN (SELECT b.datetime, b.w_1, b.w_2, b.w_3
   FROM monitor_data b
     WHERE mon_id = "site B"
       AND datetime> "2015-04-02 04:30:00"
       AND datetime < "2015-04-02 06:30:00") y
 ON y.datetime = z.datetime

A: You haven't got the syntax quite right. To join two derived tables (z and y), you'll need to ensure that each derived table has a syntactically complete SELECT statement. Also, remember that the second derived table is now aliased as 'y', not b:
SELECT z.datetime, (z.w_1 + z.w_2 + z.w_3) as BC,
       (y.w_1 + y.w_2 + y.w_3) as AC
FROM
(
   SELECT a.datetime, a.w_1, a.w_2, a.w_3
   FROM monitor_data a
   WHERE mon_id = 'site A'
    AND datetime > '2015-04-02 04:30:00' AND datetime < '2015-04-02 06:30:00'
) z
JOIN
(
  SELECT b.datetime, b.w_1, b.w_2, b.w_3
  FROM monitor_data b
  WHERE mon_id = 'site B'
    AND datetime > '2015-04-02 04:30:00' AND datetime < '2015-04-02 06:30:00'
) y
ON y.datetime = z.datetime;

A: Try this..
SELECT z.datetime, (z.w_1 + z.w_2 + z.w_3) as 'BC', (y.w_1 + y.w_2 + y.w_3) as 'AC'
(select a.datetime, a.w_1,a.w_2,a.w_3,
 FROM   monitor_data a
 WHERE  mon_id = "site A"
    AND datetime > "2015-04-02 04:30:00"
    AND datetime < "2015-04-02 06:30:00") z

JOIN (SELECT b.datetime, b.w_1, b.w_2, b.w_3
      FROM   monitor_data b
      WHERE  mon_id = "site B"
         AND datetime > "2015-04-02 04:30:00"
         AND datetime < "2015-04-02 06:30:00") y

ON y.datetime = z.datetime


text:
Q: Closed form / computationally efficient method for binomial + factorial sum I'm trying to evaluate the sum given below
$$
S(x,y) = \frac{1}{k!}\sum_{j=0}^k \binom{k}{j} (-x)^j y^{k-j} j!
$$
where $x,y > 0$. Is there any clever closed form way of writing this sum? If not, maybe there is a clever way of writing it as a product? I was considering products of $(y-jx)$ factors perhaps $\pm (y-x)^k$ but could not get this work. Any ideas?

A: Since ${k \choose j} = {k \choose k-j} = \frac{k!}{j!(k-j)!}$, upon making the substitution $j \leftrightarrow k-j$ you can write your sum as
$$ S(x,y) = (-x)^k \sum_{j=0}^k \frac{1}{j!} \left( - \frac{y}{x} \right)^j = (-x)^k S(1, -y/x) \; .$$
Now we recognize $S(u) := S(1, u) = \sum_{j=0}^k \frac{u^j}{j!}$ as the $k$-th partial sum of the MacLaurin expansion of $e^{u}$, which admits a closed form in terms of the (incomplete) Gamma function, as expressed in this MSE post. This gives some perspective on the other possible 'closed forms' one might expects.


text:
Q: IPTABLES issue - trying to DROP any connections to 3306 except from 127.0.0.1 and VPN I have a VPS where I have successfully set up VPN. I connect with OpenVPN client. The VPN server interface is 10.8.0.1 and the client receives 10.8.0.? IP. And I am able to ping 10.8.0.1. I also seem to be able to do telnet to 10.8.0.1:80, 10.8.0.1:443, etc standard ports with working services on them but not 10.8.0.1:3306.
This is the VPN connection as printed by ifconfig:
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:383 errors:0 dropped:0 overruns:0 frame:0
          TX packets:358 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:29356 (28.6 KiB)  TX bytes:149232 (145.7 KiB)

MySQL is not binded to any IP, so it receives connections from anywhere. I want to cut it's visibility by IPTABLES.
Then I added these rules to IPTABLES:
# allow connections from the vpn
iptables -A INPUT -s 10.8.0.0/24 -p tcp --dport 3306 -j ACCEPT
# allow local connections eg your scripts running locally
iptables -A INPUT -s 127.0.0.1 -p tcp --dport 3306 -j ACCEPT
# deny any other attempts of connecting to mysql
iptables -A INPUT -p tcp --dport 3306 -j DROP

Now I'm able to connect to 127.0.0.1 from the server itself. I'm not able to connect to the server by it's public IP. And I'm not able to connect to it through 10.8.0.1 (VPN IP).
This is my full IPTABLES:
[root@ddinvps mail]# iptables -L -n
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0           udp dpt:1723
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
icmp_packets  all  --  0.0.0.0/0            0.0.0.0/0
tcp_packets  all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     tcp  --  10.8.0.0/24          0.0.0.0/0           tcp dpt:3306
ACCEPT     tcp  --  127.0.0.1            0.0.0.0/0           tcp dpt:3306
DROP       tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:3306

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain icmp_packets (1 references)
target     prot opt source               destination
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           icmp type 0
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           icmp type 3
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           icmp type 11
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           icmp type 8
DROP       icmp --  0.0.0.0/0            0.0.0.0/0

Chain tcp_packets (1 references)
target     prot opt source               destination
ACCEPT     all  --  127.0.0.1            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:22
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:53
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0           udp dpt:53
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:25
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:26
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:443
ACCEPT     tcp  --  10.3.124.200         0.0.0.0/0           tcp dpt:9102
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:143
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:993
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:110
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:10000
DROP       tcp  --  0.0.0.0/0            0.0.0.0/0
DROP       udp  --  0.0.0.0/0            0.0.0.0/0

Any ideas?

A: The packets are being filtered by the tcp_packets chain. This is because your iptables -A command has added the new rules to the end of the INPUT chain and the filter works on first match wins. The easiest way to solve your problem is to add your rules to the beginning of the INPUT chain using the iptables -I command e.g.
iptables -I INPUT -s 10.8.0.0/24 -p tcp --dport 3306 -j ACCEPT

etc. which will insert your new rules at the beginning of the Chain.

A: It's obviuos your tcp_packets chain drops traffic before it hits your rule.
Either add this rule in the begining of tcp_packets chain, or in INPUT chain, but before jumping tcp_packets


text:
Q: Python isn't recognizing integers apart from 1 Python isn't recognizing any number apart from 1 as an integer.  When i enter a number to be multiplied the program will run the except ValueError even though i have entered an integer.  This is the code i have.
    Total = 0
    Tsl = 100
    receipt = open("Receipt.txt", "w")
    while True:
    try:
        Prod_Code = input("Enter a code or Done to get your final receipt: ")
        if len(Prod_Code) == 8:
            int(Prod_Code)
            with open("Data Base.txt", "r") as searchfile:
                for line in searchfile:
                    if Prod_Code in line:
                        print(line)
                        Quantity = input("What quantity of this product do you want? ")
                        Total += float(line.split(",")[2] * int(Quantity))
                        print(Quantity)
                        print(Total)
                        receipt.write(line)

        elif Prod_Code == "Done":
            print("Bye Bye")
            print(receipt)
            receipt.close

            exit()

        else:
            print("Incorrect length, try again")

    except ValueError:
        print("You must enter an integer")

The error occurs when i enter any other number than 1 when i enter the quantity.  If anyone can see the problem any input will be appreciated

A: The problem is that
Total += float(line.split(",")[2] * int(Quantity))

multiplies the string line.split(",")[2] by the Quantity converted to integer. And then attempts to convert the resulting string to a float.
Eg, if line.split(",")[2] is '1.2' and Quantity is '3' then
line.split(",")[2] * int(Quantity)

results in '1.21.21.2', which can't be converted to float. :)
Instead do
Total += float(line.split(",")[2]) * int(Quantity)

BTW, you aren't actually closing the receipt file. You're just emitting the method name and discarding it. So change
receipt.close

to
receipt.close()

Even better: use with blocks to open all your files so they get closed automatically.

I should also mention that the plain exit() function is primarily intended for use in the interactive interpreter, and it's not guaranteed to exist in all environments. To ensure portability use sys.exit() instead. OTOH, it's not really needed here, you can just break out of that while loop.

A: One reason can be in inputing the Promo_Code , you are using input so if your promo code is abcdefgh then you must input it as 'abcdefgh' or "abcdefgh" because input in python 2 cannot take automatic decisions . For sake of simplicity always use raw_input() for inputting strings,
Also in your elif convert reciept.close to reciept.close().


text:
Q: PDF support on OpenOffice.org programs Does OpenOffice.org have PDF capability?
Can I fill in a form or scan to PDF?

A: OpenOffice, without (fairly alpha) plugins, does little more than export to PDF. If you want to scan to PDF, use your scanner's included scanning utility or Simple Scan on Linux. Virtually all scanning programs have a PDF function.
Adobe Acrobat Reader will fill out forms fine.


text:
Q: Why does the grafana agent refuse to start? I set up grafana cloud and connected the apache http server integration, when I try to start, I get an error. I read the documentation, but unfortunately I did not learn anything sensible

error loading config file /etc/grafana-agent.yaml: yaml: unmarshal errors: line 12: field apache_http not found in type integrations.ManagerConfig
/etc/grafana-agent.yaml

  agent:
    enabled: true
    metric_relabel_configs:
    - source_labels:
      - exported_job
      target_label: job
    - source_labels:
      - exported_instance
      target_label: instance
    - action: labeldrop
      regex: (exported_instance|exported_job)
  apache_http:
    enabled: true
    instance: <yourhostname>
    scrape_uri: http://localhost:9090/server-status?auto
  node_exporter:
    enabled: true
    relabel_configs:
    - replacement: hostname
      target_label: instance
  prometheus_remote_write:
  - basic_auth:
      password: test
      username: test
    url: test
logs:
  configs:
  - clients:
    - basic_auth:
        password: test
        username: test
      url: test
    name: integrations
    positions:
      filename: /tmp/positions.yaml
    scrape_configs:
    - job_name: integrations/node_exporter_journal_scrape
      journal:
        labels:
          instance: hostname
          job: integrations/node_exporter
        max_age: 24h
      relabel_configs:
      - source_labels:
        - __journal__systemd_unit
        target_label: unit
      - source_labels:
        - __journal__boot_id
        target_label: boot_id
      - source_labels:
        - __journal__transport
        target_label: transport
      - source_labels:
        - __journal_priority_keyword
        target_label: level
    - job_name: integrations/apache_error
      pipeline_stages:
      - regex:
          expression: '^\[[^ ]* (?P<timestamp>[^\]]*)\] \[(?:(?P<module>[^:\]]+):)?(?P<level>[^\]]+)\](?: \[pid (?P<pid>[^\]]*)\])?(?: \[client (?P<client>[^\]]*)\])? (?P<message>.*)$'
      - labels:
          level: null
          module: null
      - static_labels:
          logtype: error
      static_configs:
      - labels:
          __path__: /var/log/httpd/error.log
          instance: <yourhostname>
          job: integrations/apache_http
        targets:
        - localhost
    - job_name: integrations/apache_access
      pipeline_stages:
      - regex:
          expression: '^(?P<ip>[^ ]*) [^ ]* (?P<user>[^ ]*) \[(?P<timestamp>[^\]]*)\] "(?P<method>\S+)(?: +(?P<path>[^ ]*) +\S*)?" (?P<code>[^ ]*) (?P<size>[^ ]*)(?: "(?P<referer>[^\"]*)" "(?P<agent>.*)")?$'
      - metrics:
          response_http_codes:
            config:
              buckets:
              - 199
              - 299
              - 399
              - 499
              - 599
            description: Apache responses by HTTP codes
            prefix: apache_
            source: code
            type: Histogram
      - labels:
          method: null
      - static_labels:
          logtype: access
      static_configs:
      - labels:
          __path__: /var/log/httpd/access.log
          instance: <yourhostname>
          job: integrations/apache_http
        targets:
        - localhost
    target_config:
      sync_period: 10s
metrics:
  configs:
  - name: integrations
    remote_write:
    - basic_auth:
        password: test
        username: test
      url: test
  global:
    scrape_interval: 60s
  wal_directory: /tmp/grafana-agent-wal```

A: It's bug in source and fixed in new release, but cloud use old version config.
Download installer and do manually
wget https://raw.githubusercontent.com/grafana/agent/release/production/grafanacloud-install.sh

and change line:
RELEASE_VERSION="0.25.1"

to latest https://github.com/grafana/agent/releases/
then do to make it executable
chmod +x grafanacloud-install.sh

and run install like they propose just change command from curl to local script:
sudo ARCH=amd64 GCLOUD_STACK_ID="***" GCLOUD_API_KEY="***" GCLOUD_API_URL="***" /bin/sh -c "./grafanacloud-install.sh"


text:
Q: Call an Ajax Function after ProgressBar End I have below ajax which I am calling currenlty on form submit. Based on the return result I am showing an alert message only. What I need to do - show a progressbar for some seconds on body load and at the end of the timer call below ajax and based on the return results hide the progressbar and show a success/error msg. How to do this
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

<script type="text/javascript">
$(document).ready(function() {
$('#loginform').submit(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: 'subscribe.php',
        data: $(this).serialize(),
        success: function(response)
        {
            var jsonData = JSON.parse(response);

            // user is logged in successfully in the back-end
            // let's redirect
            if (jsonData.success == "1")
            {
                alert('You Successfully Subscribed to this Topic!');
                                }
            else
            {
                alert('Unsubscribed From This Topic Successfully!');

            }
       }
   });
 });
 });
 </script>


text:
Q: How to test fragment properly in Android I have been following the single activity model and MVVM in app development; So I have a single activity and the rest of UIs are all fragments. So, each single fragment is self-contained and I would like to test each single fragment without leaking state.
@RunWith(AndroidJUnit4::class)
class SplashFragmentTest {

    @Test
    fun testVisibilityOfLogo() {
        launchFragmentInContainer<SplashFragment>()
        onView(ViewMatchers.withId(R.id.ivLogo))
                .check(matches(isDisplayed()))
    }
}

I have following test, which is throwing
Activity never becomes requested state "[RESUMED, STARTED, DESTROYED, CREATED]" (last lifecycle transition = "PRE_ON_CREATE")

I have followed the android docs as well:  https://developer.android.com/training/basics/fragments/testing
According to the docs,

After launching one of these fragment types, FragmentScenario drives
  the fragment under test to the RESUMED state. This state indicates
  that the fragment is running. If you're testing a graphical fragment,
  it's also visible to users, so you can evaluate information about its
  UI elements using Espresso UI tests.

It seems like it is not happening. Does anyone come across such a problem with UI testing with fragment?

A: The problem was that I have forgot to add the following two dependencies in app level gradle in my case.
debugImplementation 'androidx.fragment:fragment-testing:1.2.0-rc03'
debugImplementation 'androidx.test:core:1.3.0-alpha03'


text:
Q: How can I have a D-Link router intercept requests for a certain page? I have a D-Link router, and I was wondering how I could intercept requests on my router for a page. I would like to have it so whenever someone on my network goes to the page (for example, http://google.com/waffles) it returns something like "Hello!" with specific headers. How could I do this?

A: You don't need to use your router to do something like this. I suggest ARP Spoofing, and Dsniff
If you would like to go about this via more conventional means, then you will have to see if you can load custom os on your router. Check and see if your router is compatible with OpenWRT.


text:
Q: Resolve Type<> of component from string in angular2 Is it possible to get type of component (Type<T>) from string value? Smth like:
let typeStr: string = 'MyComponent';
let type: any = resolveType(typeStr); // actual type

A: Just in case anyone stumbles across this question like me. It is possible without maintaining a registry.
Full credit goes to yurzui for his solution.
Just a copy from there:
import { Type } from '@angular/core';

@Input() comp: string;
...
const factories = Array.from(this.resolver['_factories'].keys());
const factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);

A: You can't do that without maintaining a "registry" for your classes.
interface Component { }

type ComponentClass = { new (): Component };

const REGISTRY = new Map<string, ComponentClass>();

function getTypeFor(name: string): ComponentClass {
    return REGISTRY.get(name);
}

As for how to add entries to this REGISTRY, you have a few options, here are two:
(1) Manually add it after every class definition:
class ComponentA implements Component { ... }
REGISTRY.set("ComponentA", ComponentA);

Or make a function for it:
function register(cls: ComponentClass): void {
    REGISTRY.set(cls.name, cls);
}

class ComponentA implements Component { ... }
register(ComponentA);

(2) Use a decorator:
Just use the above register function as a decorator:
@register
class ComponentA implements Component { ... }


text:
Q: Wrong string library after dlopen? im currently using dlopen on a modular program and I think something is really wrong, but I cant seem to figure it out.
requirementData is a vector of a class called VoidData. It's simply a class to handle void* easily
getCopyOfData() uses memcpy to copy the data stored in the void*. Until here everthing is fine, the address of voidptr is different from the one stored in my VoidData object so the copy was a success.
Now... stringA gives me the right string. This is also okay for stringB. But then comes stringC and he gives me something weird.
void* voidptr = requirementData[0].getCopyOfData();

string stringA = *((string*) voidptr);
cout << "VoidPtr: " << stringA << endl; // VoidPtr: 'SayHey'

string stringB = *((string*) voidptr);
cout << "VoidPtr: " << stringB << endl; // VoidPtr: 'SayHey'

// load library
void *handle = dlopen("/usr/lib64/libOpcWorkingPackage.so", RTLD_LAZY);

string stringC = *((string*) voidptr);
cout << "VoidPtr: " << stringC << endl; // VoidPtr: '����'

I also tried to cast voidptr to an array of uint8_t. Every time the array gives me the same 32 numbers.
for (unsigned int i = 0; i < sizeof(stringC); i++){
    cout << to_string(((uint8_t*) voidptr)[i]) << ", ";
}
cout << endl;
// 80, 181, 228, 245, 255, 127, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 83, 97, 121, 101, 119, 121, 0, 0, 0, 183, 228, 245, 255, 127, 49, 52

Im out of ideas, maybe somebody can help me.
Thanks, Narase
Edit: Here's my getCopyOfData() function:
void* VoidData::getCopyOfData() const {
    void *data = malloc(size);
    memcpy(data, storedData, size);
    return data;
}

Edit: Got it
The data I get are a char[]. This char[] is put in a string which doesnt copy them, it just puts a pointer on it. After the char[] is released, the string works until the memory issnt used anymore after that
Thank you for the correct idea user4581301!

A: The data I get is in a char[]. This char[] is put in a string (by me) which doesnt copy them, it just puts a pointer on it. After the char[] is released, the string works until the memory issnt used anymore after that.
Thank you for the correct idea user4581301!


text:
Q: Update table using a select query So i have read a few posts on here but i cant seem to get this working on MySQL.
Pretty much I have a 'count' of records with an itemid that i want to update into my [items] table based on the itemid into [items].[popularity].
This is what i have tried:
Update items
SET items.popularity = countitems.countofscriptiD
FROM items
INNER JOIN
(SELECT Count(scripts.ScriptID) AS CountOfScriptID, scripts.ItemID
FROM scripts GROUP BY scripts.ItemID) as countitems
ON
items.itemid =  countitems.itemid

Which returns a MySQL error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near 'FROM items INNER JOIN (SELECT Count(scripts.ScriptID) AS
CountOfScriptID, scri' at line 3

If i change this to a SELECT query it works fine, either selecting from [items] or the count query however the update statement is failing!
Any advice would be great, from what i have read I can't see where I'm going wrong with this.

A: The right way to do that, doing the join of tables before SET:
UPDATE items
INNER JOIN
(SELECT Count(scripts.ScriptID) AS CountOfScriptID, scripts.ItemID
FROM scripts GROUP BY scripts.ItemID) as countitems
ON
items.itemid =  countitems.itemid
SET items.popularity = countitems.countofscriptiD

See https://dev.mysql.com/doc/refman/8.0/en/update.html


text:
Q: Convert a img src to file using jquery I have an ASP.NET MVC application to upload images to the server through a input and JQuery, this and the code:
Jquery:
function GuardarTicketsEntregados() {

    var imagefile = document.getElementById("imageFile").files[0];
    var cantidad = $("#txtCantidad").val();
    var nroSocio = $("#txtNroSocio").val();
    var descripcion = $("#txtDescripcion").val();
    var centroCosto = $("#cboListaCentrosCosto option:selected").text();
    var montoTotal = $("#txtMontoTotal").val();

    var listaTickets = [];

    var formData = new FormData();

    $(".ticket").each(function (i) {
        listaTickets.push(this.value);
    });
    formData.append("cantidad", cantidad);
    formData.append("listaTickets", listaTickets);
    formData.append("observaciones", descripcion);
    formData.append("nroSocio", nroSocio);
    formData.append("centroCosto", centroCosto);
    formData.append("montoTotal", montoTotal);
    formData.append("archivo", imagefile);
    $.ajax({
        url: "../TicketsCash/GuardarTicketsEntregados",
        traditional: true,
        type: 'post',
        dataType: 'json',
        contentType: false, // Not to set any content header
        processData: false, // Not to process data
        async: true,
        data: formData,
        success: function (data) {
            if (data.correcto) {
                swal("Exito", data.mensaje, "success");
                document.getElementById('txtCantidad').value = 0;
                document.getElementById('txtMontoTotal').value = 0;
                document.getElementById('txtDescripcion').value = "";
                document.getElementById('txtNroSocio').value = "";
                document.getElementById('cboListaCentrosCosto').value = "No especifica";
                EscanearTicketsEntrega();
                //$('#modalModificarNivelExitoso').modal({
                //    backdrop: true
                //})
            }
            else {
                swal("Atencion", data.mensaje, "warning");
            }
        },
        error: function (data) {
            swal("Error", "Error al procesar la solicitud.", "error");
        }
    });
}

and the html:
            <input id="imageFile" type="file" name="imageFile" accept="image/png, image/jpeg" />
            <button id="btnEntregarTickets" type="button" class="btn btn-lg btn-primary">Entregar</button>

Now I want to take the picture with the pluing http://www.scriptcam.com/ therefore would have to take
    <img id="image" style="width:500px;height:500px;" />

Is there any way to convert the src of the image to a file so that I do not have to change the code in the controller?
What other options do I have?
Thank you so much


text:
Q: asp Dot net core on Apache Linux ,intranet user identify like windows authentication Asp Dot net 2 core web application when deployed in Linux - Apache server .
Enable windows authentication in Vs solution, but when deployed on Linux how to identify system logged in user, like "internet information server" window authentication.
Kindly suggest i tried deployed in Linux and user.identity.name is null.
how to achieve in Linux.


text:
Q: Return nullable GCHandle from method Want to do this, but GCHandle is not nullable. I need the GCHandle to retrieve the IntPtr associated to the buffer and later free it, so its not an option to just return IntPtr.
public GCHandle PacketToGCHandle(PacketAdmin packet)
{
    byte[] data;
    bool result;
    if ((data = PacketToByteData(packet)) != null)
    {
        GCHandle pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned);
        return pinnedArray;
    }
    else
    {
        result = false;
        report.BindReport(architecture.report);
    }
    return null;
}

A: You need to make it nullable:
public GCHandle? PacketToGCHandle(PacketAdmin packet)

Which is a short version of:
public Nullable<GCHandle> PacketToGCHandle(PacketAdmin packet)

It's value (if present) can be obtained through the Value property, and the HasValue property indicates whether it's null or not.


text:
Q: Andoid FCM message show RTL I am sending FCM messages using php curl with the legacy http protocol.
https://firebase.google.com/docs/cloud-messaging/http-server-ref
I am successfully using the title_loc_key and title_loc_args fields along with the following resource strings in my android app.
<string name="fcm_msg_title">%1$s</string>
<string name="fcm_msg_body">%1$s</string>

But whatever method I use in the resource strings to make it appear RTL, it does not work.
I tried to use html with dir="rtl" and also style="direction:rtl".
I tried to use the different combinations of unicode characters as described here:
https://stackoverflow.com/a/10989502/8507634
But nothing works and the text is still showing as LTR.
Does any one know of something that can help.


text:
Q: Angle change under orthogonal projection In $\mathbb{R}^3$, consider a line segment $[AB]$ and a line $l$
containing $C$. Then we have angle $\angle ACB$ at $C$. We want to
find an angle smaller than it.
Assume that ${\rm area}\ \Delta ABC'$ is smallest s.t. $C'\in l$,
where $\Delta xyz$ is a triangle with vertices $x,\ y,\ z$ and ${\rm
area}$ is a area function. Then

$\angle AC'B \leq \angle ACB$.

Is this right ? Thank you in advance.

A: Case 1 : $ {\rm dim}\ {\rm conv}\ [AB]\cup l =3 $
Note that there is a plane $P$ containing $\Delta ABC'$ s.t. $P$ is
perpendicular to $l$.
Let $$t:=|C-C'|,\ f(t)=\angle ACB,\ |B-C|=a,\ |A-C|=b,\ |A-B|=c$$ By
Cosine Law
$$
  a^2+b^2+2t^2 -2\sqrt{a^2+t^2}\sqrt{b^2+t^2}\cos\ f=c^2 $$
So \begin{align*} & 0<f<\pi,\ -\sin\ ff' \\& \\&=   \frac{d}{dt}
\frac{c^2-a^2-b^2-2t^2}{-2
 \sqrt{a^2+t^2}\sqrt{b^2+t^2} }
    \\&\\&= \frac{t \{ -(a^2-b^2)^2 + (a^2+b^2+2t^2)c^2 \} }{4 (
    \sqrt{a^2+t^2}\sqrt{b^2+t^2})^2}
\end{align*}
Hence if $a=b$, then $f'(t)<0$ for all $t$.
By considering $a=b+c$ we have $f'(t) >0$ for $0<t<\epsilon$ if $a$
is close to $b+c$.
Case 2 : $ {\rm dim}\ {\rm conv}\ [AB]\cup l =2 $
If $l'$ is a line containing $[AB]$ and if $l'$ intersects $l$, then
$\angle AC'B=0$
If $l'$ is parallel to $l$, then $C'$ is not uniquely determined.
Consider $A=(0,0),\ B=(\varepsilon, 0),\ C=(x,1)$ Let $f(x)=\angle
ACB$. Then by Cosine Law
$$ x^2+1+(x-\varepsilon)^2 +1 -2\sqrt{x^2+1}\sqrt{ (x-
\varepsilon)^2 +1} \cos\ f=\varepsilon^2 $$
$$ -\sin\ ff' = \frac{ -\varepsilon^2(\varepsilon-2x)   }{ (\sqrt{
x^2+1}\sqrt{ (x- \varepsilon)^2 +1} )^3 } $$
Hence $f'(x)<0$ for $x> \frac{\varepsilon }{2}$.


text:
Q: Extract type of labelled generic column I have the following case class
case class Test(field1: Int, field2: String)

I want to be able to have a method that for a column name it can map that value to other, I want it to be typesafe meaning that the funtion f should accept the same type as the symbol K
def mapColumn[A, K, KV, Repr <: HList, Out](obj: A, witness: Witness.Aux[K], f: KV => Out)
  (implicit mkLens: MkFieldLens[A, K],
    gen: LabelledGeneric.Aux[A, Repr]): Out = ???

How can I make that KV is of the type of the symbol K?
For example
mapColumn(Test(1, "hello"), 'field1, (v: Int) => v + 1) // this should retrieve 2
mapColumn(Test(1, "hello"), 'field2, (v:String) => v + 1) // this should retrieve "hello1"
mapColumn(Test(1, "hello"), 'field2, (v: Int) => v + 1) // this should be a compilation error

A: I've found the way
def mapColumn[A, K, KV, Repr <: HList, Out](obj: A, witness: Witness.Aux[K], f: KV => Out)
    (implicit mkLens: MkFieldLens[A, K],
     gen: LabelledGeneric.Aux[A, Repr],
     fieldTypesRest: Selector.Aux[Repr, K, KV]): Out = ???


text:
Q: prime31. SocialNetwork iOs. Check system account is present I use SocialNetworkPlugin for iOs by Prime31 (here)
I want to use login to Fb with SystemAccount if present, but when I haven't it on device - I can't login and take Exception code 308.
I have other login logic but I need use it only when I haven't system account.
Can I check system account for Facebook before first login?
upd:
If you can write in c# please.

A: To detect about the system account for the Facebook in ios you can use :
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{

//user is already logged in using iOS integrated FB a/c

}
else
{

//user is not logged in

}

And ss per your given link for SocialNetworkPlugin Prime[31] you can use :
// Checks to see if the user is using a version of iOS that supports the Facebook composer and if they have an account setup

public static bool canUserUseFacebookComposer()


text:
Q: How to use dynamic framework inside the pod? I have a free framework (FW). It distributes via cocoapods. In this framework i use another framework. It compiled as dynamic framework (DFW).
So in my FW i need to write import DFW and after this can use it. Also the DFW is linked in Embedded Binaries and Linked Frameworks and Libraries in my project target.
After that i push my FW to cocoapods and after installing it tells Cannot find such a module near the import DFW statement.
The question is - how to properly distribute cocoapod with embedded dynamic frameworks in it?

A: There is no way to use dynamic frameworks in cocoapods, because it brings in a versioning issues. Instead of this use s.dependency in the podspec file. You can read this also.


text:
Q: yLab of plots created with forloop in plot() I produce a batch of plot from a data frame (df) with below code :
par(mfrow=c(7,8))
for (i in 1:51) plot(df[,52], df[[i]],type="p", pch=19, cex=1.6)

How to set only corresponding colnames of the df as ylab of each plots and one main xlab equal to df[,52] ?

A: You could do something like this.
plot(df[, 52], df[, i], type = "p", pch = 19, cex = 1.6,
     ylab = names(df[, i, drop = FALSE]),
     xlab = names(df[, 52, drop = FALSE]))


text:
Q: Return type from scala method Is it possible in Scala to do something like this?
def getType(name:String) = {
  name match {
    case "MyObject" => MyObject.type
    ...
    case _ => throw new Exception("Unknown")
  }
}

type o = getType("MyObject")

A: No, it isn't possible. It just doesn't fit the grammar: getType("MyObject") is an expression and evaluates to a value; right-hand side of type o = must be a type.
In Scala, you can have types depending on values, but only in a specific way (path-dependent types), and this isn't one.


text:
Q: Making query to indexed SOLR documents - using highlighting I am having a dilemma with SOLR Tika and document indexing. As this was my first contact with the SOLR and Tika, I am still in learning phase. So far I got it to work, and also it returns proper highlighting for the results. It works as expected.
Something does not make sense to me. Every time I got results back, I receive the fields that I use (id, name and some more), I also receive highlights that behave properly but I also receive content field that I really do not need. Say I upload and index a file that has 600kb of text. I get content containing text as well, and that slows things. I use default Schema.xls contained in example folder for learning purposes.
As I was struggling to make this work, I made these changes to Schema.xml (added this xml)
 <copyField source="features" dest="text"/>
<fieldType name="features" class="solr.TextField" positionIncrementGap="100">
  <analyzer>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.ManagedStopFilterFactory" managed="english" />
    <filter class="solr.ManagedSynonymFilterFactory" managed="english" />
  </analyzer>
</fieldType>

And that functions.
I POST document to SOLR in similar fashion like shown in TIKA site:
curl "http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true" -F
"myfile=@tutorial.html"

My way is dynamic as I determine literal.id based on the document name. But essentialy it is the same post.
I GET document from SOLR like this:
aws.instance:8983/solr/select?q=features:virus&hl.fragsize=50&hl=on&hl.fl=features&hl.maxAnalyzedChars=-1&hl.snippets=20&wt=json&indent=true

That returns JSON object including highlights. Trouble is I am getting content property as well, and I do not need that one.
I am getting ready to write my own Schema file and resolve this issue with wrong fields that I have used (features).
I made this work, but I know I did it the wrong way, thing is I cant see the wrong way
I know there must be another query to get highlights and also I know that features should not be used, content field is sufficient.

A: You can decide which fields gets returned by supplying the fl parameter: &fl=id,name,etc.


text:
Q: Python logging - exc_info only for file handler I define root logger and handlers for it:
_root = logging.getLogger()
_sh = logging.StreamHandler()
_fh = logging.FileHandler('./error.log', delay = True)
_root.addHandler(_sh)
_root.addHandler(_fh)

And module logger instance:
_log = logging.getLogger("Main")
# In other file
_log = logging.getLogger("Configuration")

Now i call _log.exception in try..except block:
_log.exception("Test")

Now i get traceback in console and file. I try to suppress printing of exc_info with console handler, but not with file handler:
class _TraceBackFilter(logging.Filter):
    def filter(self, rec):
        rec.exc_info = None
        return True
_sh = logging.StreamHandler()
_sh.addFilter(_TraceBackFilter())
_root.addHandler(_sh)

This works on both file and console handler, traceback is completely removed for all handlers, but i need this only for console. Is any way to suppress exc_info only for console handler, not for file handler?
EDIT:
I modify _TraceBackFilter class.
class _TraceBackFilter(logging.Filter):
    def filter(self, rec):
        if rec.exc_info:
            logging.getLogger(rec.name).log(rec.levelno, rec.getMessage())
            return False
        else:
            return True

Now its works for console handler, but in file I have doubled messages, one with and one without traceback.

A: Create a logging.Formatter subclass for your console handler which returns an empty string from its formatException method.
The exception text is cached in the record (in attribute exc_text): if this is a false value (e.g. empty string), then formatException() will be called to repopulate it, otherwise it won't be. So in your formatter class you may need to override the format() method and set record.exc_text to a false value before calling the superclass' format() method, to ensure your overridden formatException() gets called. For example (not tested):
class NoExceptionFormatter(logging.Formatter):
    def format(self, record):
        record.exc_text = '' # ensure formatException gets called
        return super(NoExceptionFormatter, self).format(record)

    def formatException(self, record):
        return ''

A: If the _sh handler is being processed first with that filter, it looks like it might be modifying the actual traceback object. Because the same traceback object is passed to both _sh and _fh, _fh receives the already-modified traceback.
You could either make a new traceback object in that filter, sans exc_info, or maybe just swap the order so addHandler is called on _fh first.


text:
Q: Is XML and SOAP over TCP stateful in a WebService? TCP is a stateful protocol and it can maintain state between client and server interaction. SOAP maintain communication neutrality and can be used over any transport protocol such as HTTP, SMTP, TCP, or JMS, so if we are using SOAP as protocol for data exchange and it is maintained over TCP protocol than whether WebService will maintain its state while doing interaction with client.

A: Depends on the service. With WCF, it is possible to create both stateful and stateless services when using TCP. See http://msdn.microsoft.com/en-us/library/ms733040.aspx and ServiceContractAttribute.SessionMode for more info.


text:
Q: Allow users to upload flash videos? I would like to allow users to upload videos to their profiles. I'm using the couponpress theme for wordpress, which is a coupon listing theme. It lets users upload images for their coupons or advertisements, but some of the users on my site have video (flv/swf) ads that they want to list instead of a still image.
I need to be able to upload a video for users. Does anyone know of a plugin or solution to achieve this?
Thanks a lot.

A: To do this you'll need a plugin that adds the flash format to the "let me in" list that WordPress has.
This may help:
http://wordpress.org/extend/plugins/easy-flash-embed/


text:
Q: scraping tables using selenium but the table's structure is messy My goal is to extract data from clinicaltrials. On each page there is a table, I try to extract the data table from each page then concatenate all the tables into one.
My code works but there are two problems, the first one is that sometimes (depending on the link) the data table has not the correct structure like the following
    Row Saved   Status      Study Title   Conditions Interventions  Locations
0   1   NaN     Completed   Pilot Survey  Arbovirus  NaN            NaN
1   Locations: Tropical Medicine centerKaohsiung c...   Locations: Tropical Medicine centerKaohsiung c...   Locations: Tropical Medicine centerKaohsiung c...   Locations: Tropical Medicine centerKaohsiung c...   Locations: Tropical Medicine centerKaohsiung c...   Locations: Tropical Medicine centerKaohsiung c...   NaN

as you can see the second row has the column Location repeated multiple times ..
here's my code :
import time
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import html5lib
from bs4 import BeautifulSoup
import pandas as pd
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support import expected_conditions as EC

ser = Service("/xxxxxxx/chromedriver") # change it to where your chromedriver is
options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver = webdriver.Chrome(service=ser, options=options)

#url =  "https://clinicaltrials.gov/ct2/results?cond=Abruptio+Placentae"

url = "https://www.clinicaltrials.gov/ct2/results?cond=%2246%2C+XX+Disorders+of+Sex+Development%22"
driver.get(url)

#select = Select(driver.find_element_by_name('theDataTable_length'))
#select.select_by_value('100')
time.sleep(1)

html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

list_table = []
#df_tables = pd.read_html(str(soup), flavor="bs4")
df_tables = pd.read_html(str(soup))[1]
list_table.append(df_tables)

xp_next = '//*[@id="theDataTable_next"]/span'

while True:
    try:
        WebDriverWait(driver, 2).until(EC.visibility_of_element_located(
            (By.CSS_SELECTOR, "[class='paginate_button next']")))
        driver.find_element_by_xpath(xp_next).click()
        html = driver.page_source
        soup = BeautifulSoup(html, 'html.parser')
        df_tables = pd.read_html(str(soup))[1]
        #display(df_tables)
        list_table.append(df_tables)
        print("Navigating to Next Page")
        time.sleep(1)
    except (TimeoutException, WebDriverException) as e:
        print("Last page reached")
        break

driver.quit()

df = pd.concat(list_table)
df

I'm thinking maybe the problem is read_html?

A: What happens?
Issue is caused in headless mode in combination with your arguments - Tables structure is swapping in responsive mode and some columns changes to rows.
How to fix?
You have to set options more strict and can force webdriver to use a specific window-size while start-maximized
options = webdriver.ChromeOptions()
options.add_argument("--window-size=1920,1080")
options.add_argument("--start-maximized")
options.add_argument("--headless")

Example
import selenium, html5lib, time
import pandas as pd
from bs4 import BeautifulSoup

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support import expected_conditions as EC

ser = Service("#####################") # change it to where your chromedriver is
options = webdriver.ChromeOptions()
options.add_argument("--window-size=1920,1080")
options.add_argument("--start-maximized")
options.add_argument("--headless")
driver = webdriver.Chrome(service=ser, options=options)

url = "https://www.clinicaltrials.gov/ct2/results?cond=%2246%2C+XX+Disorders+of+Sex+Development%22"
driver.get(url)

list_table = []

while True:
    time.sleep(1)
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')
    list_table.append(pd.read_html(html)[1])
    print("Navigating to Next Page")

    try:
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[class='paginate_button next'] span"))).click()
    except (TimeoutException, WebDriverException) as e:
        print("Last page reached")
        break

driver.quit()

df = pd.concat(list_table)
df

Outout

Row
Saved
Status
Study Title
Conditions
Interventions
Locations

0
1
nan
Recruiting
Feasibility Study of Uterine Transplantation From Living Donors in Terms of Efficacy and Safety in Patients With Mayer-Rokitansky-Küster-Hauser Syndrome (MRKH)
Mayer Rokitansky Kuster Hauser Syndrome
Procedure: Uterine transplantation
Hopital FochSuresnes, France

1
2
nan
Recruiting
Molecular Genetic Study of Mayer-Rokitansky-Kuster-Hauser Syndrome
Mayer Rokitansky Kuster Hauser Syndrome
Genetic: Biological samples for patientsGenetic: Biological samples for healthy relatives
Necker - Enfants malades hospitalParis, FranceInstitut Mutualiste MontsourisParis, France

2
3
nan
Recruiting
Uterus Transplantation From a Multi-organ Donor
Infertility, FemaleMayer Rokitansky Kuster Hauser Syndrome
Procedure: uterus transplantation
Ghent University Hospital - Women's ClinicGhent, Belgium

A: I think it may just be easer to go after the data directly. No need to use selenium then. Just need to parse some of the html:
import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'https://www.clinicaltrials.gov/ct2/results/rpc/mi0yqBc9u64Wpg4BvnGkBnjPewc9S6hHSwS3Z6p3C61JJPhHc67aZwhLzdUVp'
payload = '''draw=3&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=false&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=false&columns%5B1%5D%5Borderable%5D=false&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=2&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=false&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=3&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=false&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=4&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=false&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=5&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=false&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=6&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=false&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B7%5D%5Bdata%5D=7&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=false&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B8%5D%5Bdata%5D=8&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=true&columns%5B8%5D%5Borderable%5D=false&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B9%5D%5Bdata%5D=9&columns%5B9%5D%5Bname%5D=&columns%5B9%5D%5Bsearchable%5D=true&columns%5B9%5D%5Borderable%5D=false&columns%5B9%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B9%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B10%5D%5Bdata%5D=10&columns%5B10%5D%5Bname%5D=&columns%5B10%5D%5Bsearchable%5D=true&columns%5B10%5D%5Borderable%5D=false&columns%5B10%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B10%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B11%5D%5Bdata%5D=11&columns%5B11%5D%5Bname%5D=&columns%5B11%5D%5Bsearchable%5D=true&columns%5B11%5D%5Borderable%5D=false&columns%5B11%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B11%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B12%5D%5Bdata%5D=12&columns%5B12%5D%5Bname%5D=&columns%5B12%5D%5Bsearchable%5D=true&columns%5B12%5D%5Borderable%5D=false&columns%5B12%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B12%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B13%5D%5Bdata%5D=13&columns%5B13%5D%5Bname%5D=&columns%5B13%5D%5Bsearchable%5D=true&columns%5B13%5D%5Borderable%5D=false&columns%5B13%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B13%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B14%5D%5Bdata%5D=14&columns%5B14%5D%5Bname%5D=&columns%5B14%5D%5Bsearchable%5D=true&columns%5B14%5D%5Borderable%5D=false&columns%5B14%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B14%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B15%5D%5Bdata%5D=15&columns%5B15%5D%5Bname%5D=&columns%5B15%5D%5Bsearchable%5D=true&columns%5B15%5D%5Borderable%5D=false&columns%5B15%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B15%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B16%5D%5Bdata%5D=16&columns%5B16%5D%5Bname%5D=&columns%5B16%5D%5Bsearchable%5D=true&columns%5B16%5D%5Borderable%5D=false&columns%5B16%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B16%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B17%5D%5Bdata%5D=17&columns%5B17%5D%5Bname%5D=&columns%5B17%5D%5Bsearchable%5D=true&columns%5B17%5D%5Borderable%5D=false&columns%5B17%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B17%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B18%5D%5Bdata%5D=18&columns%5B18%5D%5Bname%5D=&columns%5B18%5D%5Bsearchable%5D=true&columns%5B18%5D%5Borderable%5D=false&columns%5B18%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B18%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B19%5D%5Bdata%5D=19&columns%5B19%5D%5Bname%5D=&columns%5B19%5D%5Bsearchable%5D=true&columns%5B19%5D%5Borderable%5D=false&columns%5B19%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B19%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B20%5D%5Bdata%5D=20&columns%5B20%5D%5Bname%5D=&columns%5B20%5D%5Bsearchable%5D=true&columns%5B20%5D%5Borderable%5D=false&columns%5B20%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B20%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B21%5D%5Bdata%5D=21&columns%5B21%5D%5Bname%5D=&columns%5B21%5D%5Bsearchable%5D=true&columns%5B21%5D%5Borderable%5D=false&columns%5B21%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B21%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B22%5D%5Bdata%5D=22&columns%5B22%5D%5Bname%5D=&columns%5B22%5D%5Bsearchable%5D=true&columns%5B22%5D%5Borderable%5D=false&columns%5B22%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B22%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B23%5D%5Bdata%5D=23&columns%5B23%5D%5Bname%5D=&columns%5B23%5D%5Bsearchable%5D=true&columns%5B23%5D%5Borderable%5D=false&columns%5B23%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B23%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B24%5D%5Bdata%5D=24&columns%5B24%5D%5Bname%5D=&columns%5B24%5D%5Bsearchable%5D=true&columns%5B24%5D%5Borderable%5D=false&columns%5B24%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B24%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B25%5D%5Bdata%5D=25&columns%5B25%5D%5Bname%5D=&columns%5B25%5D%5Bsearchable%5D=true&columns%5B25%5D%5Borderable%5D=false&columns%5B25%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B25%5D%5Bsearch%5D%5Bregex%5D=false&start=0&length=100&search%5Bvalue%5D=&search%5Bregex%5D=false'''
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36'}

jsonData = requests.post(url, data=payload, headers=headers).json()
df = pd.DataFrame(jsonData['data'])

for col in df.columns:
    df[col] = df[col].apply(lambda row: BeautifulSoup(row, 'html.parser').text.strip())

**Output:
print(df.head(5).to_string())
  0            1                   2                                                                                3                                                               4                                                                                5               6               7                                                                                8      9                                                                                10                                                                                11   12      13                                           14           15            16      17                 18                 19                20                  21                 22 23                                                                                24 25
0  1  NCT03689842          Recruiting  Feasibility Study of Uterine Transplantation From Living Donors in Terms of Efficacy and Safety in Patients With Mayer-Rokitansky-Küster-Hauser Syndrome (MRKH)                         Mayer Rokitansky Kuster Hauser Syndrome                                                         Procedure: Uterine transplantation  Interventional  Not Applicable                                                                     Hopital Foch  Other  Allocation: N/AIntervention Model: Single Group AssignmentMasking: None (Open Label)Primary Purpose: Treatment                                                                                PregnancySafety assessment of the donor, the recipient and the fœtusPsychological assessment of the donor and the recipientGraft Rejection assessment   20  Female  18 Years to 65 Years   (Adult, Older Adult)  NCT03689842       2016/26          December 14, 2017  December 14, 2024      June 1, 2025  September 28, 2018    August 14, 2019                                                                  Hopital FochSuresnes, France
1  2  NCT02967822          Recruiting                                                                                Molecular Genetic Study of Mayer-Rokitansky-Kuster-Hauser Syndrome                         Mayer Rokitansky Kuster Hauser Syndrome  Genetic: Biological samples for patientsGenetic: Biological samples for healthy relatives   Observational                  Imagine InstituteReference center for rare diseases (Rare Gynecologic Diseases)  Other                                                        Observational Model: CohortTime Perspective: Prospective                                                                                Number of identified nucleotidic variation(s) whose consequences can explain the phenotype of MRKH syndrome  410     All                    Child, Adult, Older Adult  NCT02967822  IMNIS2015-06    MRKH           May 2016           May 2031          May 2031   November 18, 2016   October 12, 2018     Necker - Enfants malades hospitalParis, FranceInstitut Mutualiste MontsourisParis, France
2  3  NCT03252795          Recruiting                                                                                Uterus Transplantation From a Multi-organ Donor      Infertility, FemaleMayer Rokitansky Kuster Hauser Syndrome                                                          Procedure: uterus transplantation  Interventional  Not Applicable                                                       University Hospital, Ghent  Other  Allocation: N/AIntervention Model: Single Group AssignmentMasking: None (Open Label)Primary Purpose: Treatment                                                                                Survival of the uterus 1 year after transplantationComplications after uterus transplantationOngoing pregnancy rateTake home baby rate   20  Female               18 Years to 38 Years   (Adult)  NCT03252795  EC/2016/0731           November 3, 2016      December 2021     December 2023     August 17, 2017  November 13, 2019                                      Ghent University Hospital - Women's ClinicGhent, Belgium
3  4  NCT03188640           Completed                                                                                Bariatric Surgery, Hormones, and Quality of Life       ObesityHormone DisturbanceQuality of LifeHyperandrogenism                                             Procedure: Laparoscopic gastric-bypass surgery  Interventional  Not Applicable                                                            Linkoeping University  Other  Allocation: N/AIntervention Model: Single Group AssignmentMasking: None (Open Label)Primary Purpose: Treatment                                                                                Sex-hormone levelsFemale sexual functionHormone-related quality of life(and 2 more...)   68  Female               18 Years to 50 Years   (Adult)  NCT03188640   2012/392-31   OBLIV      March 1, 2014   October 31, 2016  October 31, 2016       June 15, 2017      June 16, 2017
4  5  NCT04912648  Not yet recruiting                                                                                FEmale Metabolic Risk and Androgens: an Irish Longitudinal (FEMAIL) Study  HyperandrogenismMetabolic DiseaseSex Hormones Adverse Reaction                                                              Other: Longitudinal follow up   Observational                                                               Royal College of Surgeons, Ireland  Other                                                        Observational Model: CohortTime Perspective: Prospective  Correlation of sex hormone profiles and the metabolome of women across the lifespan with risk of metabolic dysfunction, cardiovascular disease and quality of life.Development of risk prediction models for development of diabetes in womenEstablishment of the longitudinal FEMAIL study database  500  Female    18 Years and older   (Adult, Older Adult)  NCT04912648         20/49  FEMAIL  September 1, 2021  September 1, 2025   August 31, 2031        June 3, 2021       June 3, 2021                                           Royal College of Surgeons in IrelandDublin, Ireland

[58 rows x 26 columns]


text:
Q: How to check that a JCheckBox is checked? How can I check if a JCheckBox is checked?

A: By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}

A: Use the isSelected method.
You can also use an ItemListener so you'll be notified when it's checked or unchecked.


text:
Q: Extreme values using Taylor Expansion.
*

*The n:th derivative of $f$ is continuous in a neighbourhood around a point $b$

*$f^{'}(b)=f^{''}(b)=...=f^{(n-1)}(b)=0$

*$f^{(n)}(b)\neq 0 $
From the conditions above I am supposed to come to the following conclusions:

*

*$n\ even\ \land f^{n}(b)<0 \implies f$ has strict maxima in $b$

*$n\ even\ \land f^{n}(b)>0 \implies f$ has strict minima in $b$

*$n\ odd \implies f$ has no extreme in $b$
My attempt is based on Taylor's formula:
$f(x) = f(b) + \sum_{k=1}^{n-1} \frac {f^{(k)}(b)}{k!} (x-b)^{k} + R_{n}(x) \iff f(x)-f(b)= R_{n}(x)$
$R_{n}(x)$ is the Lagrange remainder $\iff R_{n}(x) = \frac {f^{(n)}(b+c \ (x-b)))}{n!} \ (x-b)^{n}$ , $0<c<1$
So $f(x)-f(b) = \frac {f^{(n)}(b+c \ (x-b)))}{n!} \ (x-b)^{n}$
I stuck here and would appreciate some hints/tips on how to carry forward.

A: hint
By Taylor-Young formula, we can write
$$f(b+h)-f(b)=$$
$$\sum_{k=1}^n\frac{h^k}{k!}f^{(k)}(b)+\frac{h^n}{n!}f^{(n)}(b)\epsilon(h)$$
$$=\frac{h^n}{n!}f^{(n)}(b)\Bigl(1+\epsilon(h)\Bigr)$$
with $$\lim_{h\to 0}\epsilon(h)=0$$
and for small $ h $ we have $1+\epsilon(h)>0$.


text:
Q: Jasmine spyOn doesn't take into account angular crubbins spyOn(service, someMethod).and.callThrough();
then...
var an_object = some_objects[0];
useADirectiveThatRepeatsOver(some_objects);

expect(service.someMethod).toHaveBeenCalledWith(an_object);

fails with
Expected spy someMethod to have been called with [ Object({
   sent_date: '2016-11-18T12:06:29.712318Z',
   email: 'pigeon@wacky.races', url: '/api/v1/invites/1/' }) ]
   but actual calls were [ Object({
   sent_date: '2016-11-18T12:06:29.712318Z',
   email: 'pigeon@wacky.races', url: '/api/v1/invites/1/',
   $$hashKey: 'object:110' }) ].

The directive:

    {{ obj.email }}

The issue, AFAICT, occurs when someControllerMethod(obj) is called - outside of that method (e.g. right before the  obj does not have $$hashkey, but as soon as someControllerMethod() is called, obj has gained the errant key.
I'm assuming there's no way to prevent angular doing what it do, so what are some ways of mitigating this? Clearly I can't use angular.equals() instead of toEqual() since the toHaveBeenCalledWith() method doesn't expose a way to change the comparator.

A: Turns out this can be addressed via:

...

So for my specific case:

...