text:
Q: Time and work . Men and women working.
It takes six days for three women and two men working together to
  complete a work. Three men would do the same work five days sooner
  than nine women. How many times does the output of a man exceed that
  of a woman?

Question?
The statement "Three men would do the same work five days sooner
 than nine women."
Does this mean that three men would complete "any amount" of the "given type of work" five days earlier than 9 women? By which I mean to say if there are 100 units of work, then three men would complete the work 5 days earlier than 9 women. Also if there are 1000 units of work, then also three men would complete the work 5 days earlier than 9 women.Is this the case?How?
If this is the case then we can write:
Let a man do $m$ units of work/day and a woman do $w$ units of work/day.
Let the time taken by 9 women to do the entire work be $t$ days.
$(3w+2m)*6=1$
$3m(t-5)=1$
$9w*t=1$
If this is not the case then we have:
$(3w+2m)*6=1$
$3m(t-5)=9w*t$
In this case where is the 3rd equation that we need to find the variables?

A: Let one woman complete the job in $w$ days $\implies$ rate of woman's work is $\frac{1}{w}$ job/day.
Let one man complete the job in $m$ days $\implies$ rate of man's work is $\frac{1}{m}$ job/day.
Your mistake is in the step: $(3w+2m)\times 6=1$. It should instead be $$(\frac{3}{w}+\frac{2}{m})\times 6 = 1$$
Now, as three men would do the work five days sooner than nine women, we have, $$\frac{m}{3}+5=\frac{w}{9}$$
Solving the quadratic, we have, $m=15$ and thus, $w=90$, giving us, $\frac{w}{m}=6$.

A: m - amount of work one man can do per day
w - amount of work one woman can do per day
1 - amount of the work when it has been fully completed (100% of the work is done)
x - number of days it takes 3 men to complete the job (100% of it or 1)
Our conditions:
$$
6(2m+3w)=1 \text{ (1)}\\
x\cdot 3m =1 \text{ (2)}\\
(x+5)9w=1 \text{ (3)}
$$
In equation 1, let's express the amount of work a man can do per day in terms of the amount of work a woman can do per day:
$$
m=\frac{1-18w}{12}
$$
Now, in equation 2, let's express the number of days, $x$, in terms of $w$:
$$
x\cdot 3m =1\implies x=\frac{1}{3m}\implies x=\frac{1}{3\left(\frac{1-18w}{12}\right)}\implies x=\frac{4}{1-18w}
$$
Let's plug in $x$ into equation 3, simplify and solve the resulting quadratic equation for $w$:
$$
(x+5)9w=1\implies \\
\left(\frac{4}{1-18w}+5\right)9w=1\implies\\
810w^2-99w+1=0 \implies \\
w_{1}=\frac{1}{9}\\
w_{2}=\frac{1}{90}
$$
Let's now find $x$:
$$
x=\frac{4}{1-18\cdot 1/9}=-4 \text{ (meaningless solution)}\\
x=\frac{4}{1-18\cdot 1/90}=5
$$
Now, let's find $m$ and $w$:
$$
m=\frac{1}{3x}\implies m=\frac{1}{15}\\
w=\frac{1}{9(x+5)}\implies w=\frac{1}{90}
$$
And now let's compare their rates of work by diving a man's amount of work done per day by that of a woman:
$$
\frac{m}{w}=\frac{1/15}{1/90}=6
$$
This can be interpreted as saying that a man can accomplish six times as much work per day as a woman.
Answer: The output of a man exceeds the output of a woman $6$ times.


text:
Q: adding multiple mapbox markers I am trying to add multiple static markers in my mapbox webapp but it only shows the first data. my code is:
{% for dat in data %}
var marker = new mapboxgl.Marker({color: 'red'})
        .setLngLat([{{dat.latitude}}, {{dat.longitude}}])
        .addTo(this.map);
    this.markers.push(marker);
{% endfor %}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluating $\int_0^{\pi /2} \frac{ \log (1+\cos a \cos x)}{\cos x} dx$ The question is to evaluate $$\int_0^{\pi /2} \frac{ \log (1+\cos a \cos x)}{\cos x} dx$$
I tried using leibnitz rule
$$F'(a)=\int_0^{\pi /2} \frac{ -\sin a}{(1+\cos a \cos x)}dx$$ Now I used the substitution $\tan(x/2)=t$ to get $$-2 \sin a \int_0^1 \frac{ dt}{1+t^2 +\cos a (1-t^2)} $$ which can be rewritten as
$$-2\frac{\sin a} {1- \cos a}\int_0^{1} \frac{ dt}{t^2 +\frac{1+ \cos a}{1-\cos a}} $$ which evaluates to $-a$.i am not sure where I went wrong.Any ideas?

A: Hint:
Put $b= \sqrt{\frac{1+ \cos a}{1-\cos a} }$
Then,
$$\int_0^{1} \frac{ dt}{t^2 +\frac{1+ \cos a}{1-\cos a}}  =\int_0^{1} \frac{ dt}{t^2 +b^2} = \frac1b\arctan{\frac{t}{b}}\bigg|_{t=0}^{t=1}= \frac1b\arctan{\frac{1}{b}} $$
Therefore, $$ F'(a) =-2\frac{\sin a} {\sqrt{(1-\cos a)(1+ \cos a)}}  \arctan{\left(\sqrt{\frac{1- \cos a}{1+\cos a} }\right)} \\= -2\frac{\sin a} {|\sin a|}  \arctan{\left(\sqrt{\frac{1- \cos a}{1+\cos a} }\right)}$$
That is  $$ F'(a)= \color{blue}{ -2\frac{\sin a} {|\sin a|}  \arctan{\left(\sqrt{\frac{1- \cos a}{1+\cos a} }\right)}}$$

A: Well, as you did:
$$\mathscr{I}:=\int\frac{1}{1+\text{n}\cdot\cos\left(x\right)}\space\text{d}x\tag1$$
Substitute $\text{u}:=\tan\left(\frac{x}{2}\right)$:
$$\mathscr{I}=\frac{2}{1+\text{n}}\cdot\int\frac{1}{1+\frac{1-\text{n}}{1+\text{n}}\cdot\text{u}^2}\space\text{d}\text{u}\tag2$$
Substitute $\text{s}:=\text{u}\cdot\sqrt{\frac{1-\text{n}}{1+\text{n}}}$:
$$\mathscr{I}=\frac{2}{\sqrt{1-\text{n}}\cdot\sqrt{1+\text{n}}}\cdot\int\frac{1}{1+\text{s}^2}\space\text{d}\text{s}=\frac{2\cdot\arctan\left(\text{s}\right)}{\sqrt{1-\text{n}}\cdot\sqrt{1+\text{n}}}+\text{C}=$$
$$\frac{2\cdot\arctan\left(\tan\left(\frac{x}{2}\right)\cdot\sqrt{\frac{1-\text{n}}{1+\text{n}}}\right)}{\sqrt{1-\text{n}}\cdot\sqrt{1+\text{n}}}+\text{C}\tag3$$
So, for the definite integral:
$$\int_0^\frac{\pi}{2}\frac{1}{1+\text{n}\cdot\cos\left(x\right)}\space\text{d}x=\frac{2\cdot\arctan\left(\sqrt{\frac{2}{\text{n}^2}-1}\right)}{\sqrt{1-\text{n}^2}}\tag4$$

A: Using Feynman's Technique Integration by differentiating w.r.t. $a$,
$$I(a)=\int_{0}^{\frac{\pi}{2}} \frac{\ln (1+\cos a \cos x)}{\cos x} d x,$$
we obtain $$
I^{\prime}(a)=\int_{0}^{\frac{\pi}{2}} \frac{-\sin a}{1+\cos a \cos x} d x
$$
Letting $t=\tan \dfrac{x}{2}$ yields $$
\begin{aligned}
I^{\prime}(a) &=-2 \sin a \int_{0}^{1} \frac{d t}{(1+\cos a)+(1-\cos a) t^{2}} \\
&=-2 \sin a \int_{0}^{1} \frac{d t}{2 \cos ^{2} \frac{a}{2}+2 t^{2} \sin ^{2} \frac{a}{2}} \\
&=-2 \cos \frac{a}{2} \int_{0}^{1} \frac{d\left(t \sin \frac{a}{2}\right)}{\left(t \sin \frac{a}{2}\right)^{2}+\cos ^{2} \frac{a}{2}} \\
&=-2\left[\tan ^{-1}\left(t \cdot \tan \frac{a}{2}\right)\right]_{0}^{1} \\
&=-2 \tan ^{-1}\left(\tan \frac{a}{2}\right) \\
&=-a
\end{aligned}
$$
Now we can get $I(a)$ by integrating $I^{\prime}(y)$ w.r.t $y$ from $\dfrac{\pi}{2} $ to $a$.
$$
I(a)=\int_{\frac{\pi}{2}}^{a} I^{\prime}(y) d y=\int_{\frac{\pi}{2}}^{a}-yd y=\boxed{\frac{\pi^{2}}{8}-\frac{a^{2}}{2}}
$$
For example, $$
\int_{0}^{\frac{\pi}{2}} \frac{\ln \left(1+\frac{1}{2} \cos x\right)}{\cos x} d x=\frac{5 \pi^{2}}{72}
$$
:|D Wish you enjoy my solution!


text:
Q: How to add cell without using indexPath I have a UICollectionView which loads a custom collectionViewCell every 7 cells. The problem with this is that it takes away from the content of the main array.

(ie. if mainArray.count == 17 only 15 is displayed because indexPaths
  have to be specified for the customCollectionViewCells being loaded.)

I don't want to use sections either. I was wondering if these was a way to load these cells without taking away from the main content?
What I've tried
 func collectionView(_ collectionView: UICollectionView,
    numberOfItemsInSection section: Int) -> Int {
    let counter == 0;
    if (index == 7 || index == 14) {
      counter = customCellsArray.count
     }
    else{
      counter = mainArray.count
     }
    return counter;
 }

A: In your data source, return the number of cells you actually want, including the custom cells.  E.g.:
func collectionView(_ collectionView: UICollectionView,
    numberOfItemsInSection section: Int) -> Int {

    return customCellsArray.count + mainArray.count;
}

Then when you provide your cell:
func collectionView(_ collectionView: UICollectionView,
    cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    if (indexPath.item % 7 == 0 && indexPath.item > 0) {
        // Return cell from customCellsArray.
    } else {
        // Return cell from mainCellsArray.
    }
}

You will have to map the indexPath.item to the proper index you need in your two arrays.


text:
Q: Django import into many to many relationship with custom through table I am not sure the proper way to import using django-import-export tsv files into many to many relationship tables.  What I have done is create a books table, a genre table and a bookgenre through table which contains the foreignkeys to each of the other tables.  So what I have is:
class Book(models.Model):
   title = models.CharField(max_length=255)

class Genre(models.Model):
    genre = models.CharField(max_length=64)

class BookGenre(models.Model):
    book_id = models.ForeignKey('Book', on_delete=models.CASCADE)
    genre_id = models.ForeignKey('Genre', on_delete=models.CASCADE)

Then I import all three tables and the relationships are working but I can't figure out a way to make a view or template that works effectively.  I am thinking there must be a better way to create a many to many relationship and import data into it.  Any Ideas?

A: You don't need to create a pivot table, use many-to-many relationships.
UPDATE
You do not create a m2m model, but a many-to-many relationship that points to a specific model. Below is the implementation.
class Abc(models.Model):
    field = models.TextField()

class Xyz(models.Model):
    other_field = models.TextField()
    m2m_field = models.ManyToManyField(Abc)

If you want to get related data, you will use:
object_xyz.abcs.all()
or object_abc.xyz_set.all()
As I wrote earlier, you can find more detailed information in the documentation.


text:
Q: Non Executing Loop and Sub Array I am trying to find the most number of consonants in a row for a specific word in an array. I have a while loop in the middle that I have commented, but for some reason it does not execute. Does anyone know why? Also you might notice that I have an int spaces because I am trying to find a sub array of String[] words. How might I do that as well?
import java.io.*;
import java.util.*
import java.util.Arrays;

public class Main
{
  public static void main (String[] args)
  {
    System.out.print("Please enter a phrase to translate: ");
    Scanner scan = new Scanner(System.in);
    String str = scan.nextLine();
    String[] words = str.split("\\s+");
    int spaces = (word.length - 1);
    for (int i = 0; i < words.length; i++)
    {
        String a = words[i].substring(0,1);
        int k = a.length();
        int n = words[i].length();
        if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
        {
            while (k < 5) // start while
            {
                if (n > k)
                {
                    a = words[i].substring(0,k);
                    k = k + 1;
                    }
                }
            } // end while
        if (words[i].startsWith("a") || words[i].startsWith("e") || words[i].startsWith("i") || words[i].startsWith("o") || words[i].startsWith("u"))
        {
            System.out.print(words[i] + "way");
            }
        else if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
        {
            String answer = words[i].substring(k,n);
            System.out.print(answer + a + "ay");
            }
        }
    }
}

A: Given your description of "trying to find the most number of consonants in a row for a specific word in an array", I would think something along these lines (not compiled or tested - just to show the approach) would be a lot simpler to follow/debug/test/maintain (also only looks at the current word[i] - an outer loop to iterate over your words is still needed:
String consgroups[] = word[i].split("[aeiou]"); // split on all vowels
int maxlen = consgroups[0].length, maxidx = 0;
for (int j = ; j < consgroups.length; ++j)    // iterate over groups and find max
  if (consgroups[j].length > maxlen)
  { maxidx = j;
    maxlen = consgroups[i].length;
  }

Given your comment about pig latin, I'm not sure why consonant groups other than at the beginning of the word are important, but perhaps I'm misunderstanding your description...
Edit: Now that I've looked a little harder, I think this approach might be more useful:
String vowels = "aeiou";
int i = 0;
while ((i < word.length) && (!vowels.contains(word.subSequence(i, i + 1))))
  ++i;
// now word[i] is the first non-vowel character in word
if (i == word.length) // word was all consonants
{ ...
}
else
  if (i) // word has a consonant prefix
  { ...
  }
  else // word starts with a vowel
  { ...
  }


text:
Q: for f(x,y,z) find point on surface nearest to origin $f(x,y,z)=x^2+2y^2-z^2$, $S=\{(x,y,z): f(x,y,z)=1\}$ find point on S nearest to origin.
I thought I would use Lagrange multipliers to solve this problem, but when I use $f(x,y,z)=x^2+2y^2-z^2$ and $g(x,y,z)=x^2+2y^2-z^2-1$, along with,
$$g(x,y,z)=0$$
$$f_x=\lambda g_x$$
$$f_y=\lambda g_y$$
$$f_z=\lambda g_z$$
I am getting not so good answers.  How to solve this type of problem

A: The distance from $(x,y,z)$ to the origin is $\sqrt{x^2+y^2+z^2}$.
We therefore want to minimize $\sqrt{x^2+y^2+z^2}$, or equivalently $x^2+y^2+z^2$, subject to the condition $x^2+2y^2-z^2-1=0$. So $x^2+y^2+z^2$  should be your $f$. Now the usual process should work well.


text:
Q: Determine the state $|\psi \rangle$ The question is:

The angular momentum components of an atom prepared in the state $|\psi\rangle$ are measured and the following experimental probabilities are obtained:
\begin{equation} P(+\hat{z}) = 1/2, P(−\hat{z}) = 1/2,
\end{equation}
\begin{equation}
P(\hat{x}) = 3/4, P(−\hat{x}) = 1/4,
\end{equation}
\begin{equation}
P(+\hat{y}) = 0.067, P(−\hat{y}) = 0.933.
\end{equation}
From this experimental data, determine the state $|\psi \rangle$. Note that in performing the measurements, the state $|\psi \rangle$ is prepared again and again.

My attempt:
$$
 P(+\hat{z}) = 1/2 = P(−\hat{z})
$$
$$
|\langle {\uparrow}_z|\psi\rangle|^2=1/2 =|\langle {\downarrow}_z|\psi\rangle|^2
$$
$$
|\psi \rangle =\alpha |{\uparrow}_z\rangle+ e^{iδb} \beta|{\downarrow}_z\rangle
$$
$$
|\langle {\uparrow}_z|\psi\rangle|= \alpha = 1/\sqrt(2).
$$
Similarly,
$$
|\langle {\downarrow}_z|\psi\rangle|= \beta = 1/\sqrt(2).
$$
However, I don't know how to find $e^{iδb}$ term. Could someone please give a hint?

A: REFERENCE : My answer here Understanding the Bloch sphere
$=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=\!=$
Equation (24) in my answer above is
\begin{equation}
\vert\psi\rangle \boldsymbol{=}\cos\left(\dfrac{\theta_3}{2}\right)\vert u_3\rangle \boldsymbol{+} e^{i\phi_3}\sin\left(\dfrac{\theta_3}{2}\right)\vert d_3\rangle
\tag{24}\label{24}
\end{equation}
where $\vert u_3\rangle ,\vert d_3\rangle $ are yours $|{\uparrow}_z\rangle,|{\downarrow}_z\rangle$ respectively.
From the given probabilities $P(+\hat{z}) = 1/2, P(−\hat{z}) = 1/2
$ the state lies on the "equator" of the Bloch sphere. So from Figure-01 in my REFERENCED answer $\theta_3=\pi/2$. The angle $\phi_3=\boldsymbol{-}\pi/3$ could be found from one only of the probabilities  $P(\hat{x}) = 3/4, P(−\hat{x}) = 1/4,P(+\hat{y}) = 0.067$, $P(−\hat{y}) = 0.933$ and Figure-02  in my REFERENCED answer.
Note : I suggest you to "study" the excellent @CR Drost's answer about the Bloch sphere in above link.

See a 3d view of Figure-03 here


text:
Q: SQL Agent PowerShell task never finishes I'm quite new to PowerShell, and now I've found dbatools.io, where I would like to run a PowerShell task in SQL Agent like
$ExportPath = $env:TEMP + '\DriveSpace.csv'
$datatable = Import-Csv $ExportPath | Out-DbaDataTable
Write-DbaDataTable -SqlServer MyServer -Database Utils -InputObject  $datatable -Table dbo.FreeSpaceOnDiskDrive -AutoCreateTable

It starts, but it never finishes.
I've also tried to have a task that is doing this:
Get-DbaDatabaseSpace -SqlServer MyServer -IncludeSystemDBs | Out-DbaDataTable | Write-DbaDataTable -SqlServer MyServer -database utils -Table dbo.DiskSpaceExample -AutoCreateTable

Same problem. It runs ok in Windows PowerShell ISE, but just hangs in SQL Agent.
So now it has created a new table for me, and populated it with data, but the job just keep on running.

A: The problem you are experiencing is with the PowerShell subsystem in SQL Server Agent. It is a bit flakely with using other modules becuase you are put in the context of the SQL Server PowerShell Provider (SQLPS.exe). So it works the same way as if you opened up sqlps.exe and then try to execute your code.
One thing to keep in mind with dbatools module is that it will conflict with both SQLPS and the sqlserver module that MS now maintains separate for SQL Server. Last I checked the main thing that it conflicted against was TEPP that we have in the module now, it just can't load that code. [Caveat: I'm a major contributor to this module.]
The dbatools module has custom types and styles built in so when you run the scripts under PowerShell host that also has SQLPS or the SQLServer module imported your results will vary.
To utilize dbatools in a SQL Agent step make sure you only use the CmdExec subsystem (step type) and then call PowerShell host to execute your code. If you do not want to maintain a file for each script you can put your code in a SQL Agent CmdExec step in the manner illustrated below, but more complex script it is easier to maintain via files.
USE [msdb]
GO

/****** Object:  Job [dbatools_example]    Script Date: 2017-08-30 8:53:15 AM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]    Script Date: 2017-08-30 8:53:15 AM ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'dbatools_example',
        @enabled=1,
        @notify_level_eventlog=0,
        @notify_level_email=0,
        @notify_level_netsend=0,
        @notify_level_page=0,
        @delete_level=0,
        @description=N'No description available.',
        @category_name=N'[Uncategorized (Local)]',
        @owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [dbatools_command]    Script Date: 2017-08-30 8:53:15 AM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'dbatools_command',
        @step_id=1,
        @cmdexec_success_code=0,
        @on_success_action=1,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'CmdExec',
        @command=N'powershell.exe -ExecutionPolicy Bypass -Command "Import-Module dbatools; $server = ''manatarms''; Get-DbaDatabaseSpace -SqlInstance $server -IncludeSystemDbs | Out-DbaDataTable | Write-DbaDataTable -SqlInstance $server -Database db1 -Table dbo.FreeSpaceOnDiskDrive -AutoCreateTable"',
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO

Running the job above gives me this in my database and table db1.dbo.FreeSpaceOnDiskDrive

A: You misunderstand how the SQL Agent works. The powershell is run under its own window outside the Instance.
This means until the operation reports back as finished or a failure error occurs, the powershell operation will sit in perpetuaty. If you were to attempt to close the session, it would hang indefinitely until you closed the shell. In a few cases, this might even be impossible if you do not correctly stop the right process that the shell is firing from.
For example, and don't do this, if you ran a powershell with the pause operation, your poor shell would just hang indefinitely since you do not have access to the console that the Agent opened the powershell from.

*

*Use SQLCMD

Not only is this supported right in the docs, it will specifically close after the operation is finished. You can even set all kinds of steps, too, and documentation is rich.

*

*Continue the use of powershell

Only, hard-code an exit path. Do not rely on an operation to return back to the caller. You make sure it does.
In fact, this is the number one rule of coding: Do not assume your code works unless explicitly guaranteed.

*

*Use another method.

Whatever the approach: DAC, ODBC, bcp, connections, Integration Services (SSIS) connections
SSIS uses packages, great for repeating operations, too.
AND MORE...

A: These did not work for me:

*

*exit

*Exit-PSHostProcess

One that worked is:

*

*[Environment]::Exit(0)

A: Here is an example of copying a database from one server to another.
You must use the (cmd) type for the Agent job
powershell.exe -ExecutionPolicy Bypass -Command "Copy-DbaDatabase -Source ServerA -Destination ServerB\InstanceName -WithReplace -Database DatabaseToCopy -BackupRestore -SharedPath ""\\backuphostname\Backups"""

You also must have DBA tools installed on the server.  Using Powershell just run these commands:
Install Chocolatey:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Install DBA Tools:
choco feature enable -n useFipsCompliantChecksums
Choco install dbatools


text:
Q: Calculating the base charge in project 1 draft rental car in python I am trying to output 300.00 for the base charge for my rental car project in python but using codio. 300.0 is the result i receive for the below code, what am i missing??
baseCharge = 0
if rentalCode == "B":[enter image description here][1]
    baseCharge = (rentalPeriod) * (budgetCharge)
elif rentalCode == "D":
    baseCharge = float(rentalPeriod) * float(dailyCharge)
elif rentalCode == "W":
    baseCharge = float(rentalPeriod) * float(weeklyCharge)
print(baseCharge)

LAST RUN on 1/28/2019, 9:37:55 AM
Check 1 failed
Output:
(B)udget, (D)aily, or (W)eekly rental?
Number of Days Rented:
D
5
300.0
Expected:
(B)udget, (D)aily, or (W)eekly rental?
Number of Days Rented:
D
5
300.00

A: You need to enter:
print("{0:.2f}".format(baseCharge))
in order for Python to output the float in two digits.
Basically add ("{0:.2f}".format) in front of the baseCharge print command.


text:
Q: How can I register an angularjs factory after the app has "started" / been loaded? I've got the guts of a routing architecture in Angular that will dynamically download and inject Angular Controllers and Services ... the Controller part works fine, and I'm trying to download dependant services via $route's .resolve property.
Now, say if I have a factory declared in scope while the page starts up, it registers fine and Controllers that use it resolve fine, e.g:
myModule.factory('MyInjectedDep', function() {
    return {};
});

....

MyController = function(MyInjectedDep)

But if I try and register that dependency at "run time" (for want of a better phrase), I get a Circular Dependency error. e.g:
$route.routes[routeItem.route] = {
   resolve: {
      MyInjectedDep: ['$injector', function($injector) {
          // In real code I download/eval this via $http but same behavior occurs
          myModule.factory('MyInjectedDep', function() {
              return {};
          });
      }]
   }
}

So when my Controller is then initiated:
MyController = function(MyInjectedDep)

I get a circular dependency error, but no dependency trace in the error message?
Error: Circular dependency:

Any ideas appreciated

A: The key is latching onto $provide at configuration time.  If you grab $provide at configuration time and maintain a reference to it, you can use it to register your factory like:
$provide.factory.apply(null, ['MyInjectedDep', [function() {
   return {};
]}]);

I have a provider/service designed to do this, adapted from some other samples on github: https://github.com/afterglowtech/angular-couchPotato .
It's primarily designed to load from AMD, but you could probably use it's registerXXX functions with $http, or at least copy the relevant portions of its code.  Don't let the size of the repository fool you -- the actual provider/service is about one page of code https://github.com/afterglowtech/angular-couchPotato/blob/master/src/couchPotato.js .


text:
Q: Where did Bronn shoot the arrow from? In the episode "Blackwater" (S02EP09) of Game of Thrones, Bronn releases a single arrow and ignites the wildfire in the Blackwater Bay.
Where was Bronn standing when he released the arrow?
Was he on the shore near Mud Gate and did he shoot the arrow into Blackwater Bay or into Blackwater Rush?
For that matter, where did the Lannister ship come from? Did it approach Stannis via the Blackwater Rush or did it set sail from Blackwater Bay and never enter the rush?
Maybe this is described in the book?

A: Somewhere downstream of the Mud Gate
Sorry, can't seem to give you anymore information than that.
As you can see in this video, Bronn is standing on what seems to be a rock bank down stream of the Mud Gate, close enough that he can see Tyrion's fire signal, and far enough out that he could hit the wildfire soaked water near the bulk of the Baratheon fleet.
Tyrion and Joffrey's party are seen standing atop the battlements, near a gate, that gate was predicted by Tyrion to be the focal point of the Baratheon fleet's attacking point during the Battle of the Blackwater. A clever half-man who predicted this correctly.

Whether the wildfire laden ship approaces from the Blackwater Rush or merely in the Bay is irrelevant, as not enough detail is shown about this area or scene. Most likely though, it would have approached from the Rush, or even simply from the gate.

An addendum about the books
As pointed out in the comments by TLP, Bronn has nothing to do with the lighting of the wildfire, it is in fact a burning ship that plows into the wildfire laden one which triggers the explosion.
Stannis' fleet is allowed to come into the Bay, lured in fact by the entirety of Joffrey's fleet. They are cut off from escape by a gigantic chain, so they are well into the Bay.


text:
Q: Item is not getting visible in Flat list When my flat list is rendered...i am getting same item(item at index 0) in my rendered Item function and no data is visible in my flat list. I am new to react native...any help would be appreciated.
This is my Class which contains Flat List  and in Render item function i am passing the item to another component which i have named as ListviewItem.
import React,{Component} from 'react';
import {FlatList,Text} from 'react-native';
import {connect} from 'react-redux';
import ListItem from './LibraryList';

class LibraryList extends Component{

  componentWillMount(){
     console.log(this.props);
   }

   renderItem({item, index}) {
     console.log('render item called');
     console.log(item);
      return (
         <ListItem item={item} />
      );
    }

  render(){
    return(
      <FlatList
        data={this.props.libraries}
        renderItem={this.renderItem.bind(this)}
      />
    );
  }
}

const mapStateToProps = state =>{
  console.log(state.libraries);
  return {libraries:state.libraries};
}

export default connect(mapStateToProps)(LibraryList);

  ListviewItem Class
import React,{Component} from 'react';
import {Text} from 'react-native';
import {CardSection} from './common';

class ListviewItem extends Component {
    render(){
      return(
         <CardSection>
            <Text>{this.props.item.title}</Text>
         </CardSection>
      );
    }
}

export default ListviewItem;

A: try this please:
<View>
   <FlatList
       data={this.props.libraries}
       renderItem={({ item }) => (
              <ListItem item={item} />
       )}
    />
</View>

And the item like this:
import React,{Component} from 'react';
import {Text} from 'react-native';
import {CardSection} from './common';

class ListItem extends Component {
    render(){
      return(
         <View>
            <Text>{this.props.item.title}</Text>
         </View>
      );
    }
}

export default ListItem;

So first remove the CardSection from your list item, check if is working, and if this is working take a look at CardSection where you add a text which has some props form his parent.

A: Try this for item:
import React,{Component} from 'react';
import {Text} from 'react-native';
import {CardSection} from './common';

class ListviewItem extends Component {
    render(){
      return(
         <CardSection>
            <Text>{this.props.item.item.title}</Text>
         </CardSection>
      );
    }
}

export default ListviewItem;


text:
Q: Can I add an include path in a distutils command? I'm working on packaging a Python interface to a C library. The C library comes as a binary distribution tarball with headers and the compiled library. I want to make a bdist_wheel out of it, along with my built Python extensions, and the headers.
I've written a couple of distutils commands for extracting and installing the library like so:
from distutils.core import Command
from distutils.command.build import build

import os
import tarfile

class ExtractLibraryCommand(Command):
    description = 'extract library from binary distribution'

    def initialize_options(self):
        self.build_lib = None
        self.build_temp = None
        self.library_dist = os.environ.get('LIBRARY_DIST')

    def finalize_options(self):
        self.set_undefined_options('build',
                                   ('build_lib', 'build_lib'),
                                   ('build_temp', 'build_temp'))

        assert os.path.exists(self.library_dist), 'Library dist {} does not exist'.format(self.library_dist)

    def run(self):
        with tarfile.open(self.library_dist, 'r') as tf:
            tf.extractall(path=self.build_temp)

class InstallLibraryCommand(Command):
    description = 'install library from extracted distribution'

    def initialize_options(self):
        self.build_lib = None
        self.build_temp = None

    def finalize_options(self):
        self.set_undefined_options('build',
                                   ('build_lib', 'build_lib'),
                                   ('build_temp', 'build_temp'))

    def run(self):
            self.copy_tree(
                os.path.join(os.path.join(build_temp, 'my_library')),
                os.path.join(self.build_lib, os.path.join('my_package', 'my_library'))
            )

Then I override the build step to include my new commands.
class BuildCommand(build):
    def run(self):
        self.run_command('extract_library')
        self.run_command('install_library')
        build.run(self)

The problem is, I'm not sure how to get the path to the headers for the library to build my extensions, as they're installed to a directory specified by distutils.
from setuptools import setup, find_packages
from setuptools.extension import Extension
from Cython.Build import cythonize

extensions = [
    Extension(
        'package.library.*',
        ['package/library/*.pyx'],
        include_dirs=???,
    ),
]

setup(
    packages=find_packages(),
    ...
    ext_modules=cythonize(extensions),
)

EDIT: To clarify, this is one setup.py script.

A: You can modify the extensions in the InstallLibraryCommand, after the library becomes available. I'd probably also move the extraction/installation code to finalize_options instead of run as installing the library in building stage is somewhat late in my opinion (makes the library unavailable in the configuration stage). Example:
class InstallLibraryCommand(Command):
    def finalize_options(self):
        ...
        with tarfile.open(self.library_dist, 'r') as tf:
            tf.extractall(path=self.build_temp)
        include_path = os.path.join(self.build_lib, os.path.join('my_package', 'my_library'))
        self.copy_tree(
                os.path.join(os.path.join(build_temp, 'my_library')),
                include_path
        )
        for ext in self.distribution.ext_modules:
            ext.include_dirs.append(include_path)

A: After deliberating on this problem a little more, I've decided to commit the library's headers with the Cython interface, as they're part of the interface, and required for building. This way, the code documents and uses a particular fixed version, and can be distributed with compatible binaries.


text:
Q: Google PubSub throttling I have a chain of data pipelines communicating to each other through pipeline-specific Pub/Sub topics.
[pipeline #1] -> [pipeline #2] -> [pipeline #3] -> ...

Each pipeline is totally stateless and can scale horizontally based on the respective pub/sub queue size.
Each pipeline has its own throughput.
The pipeline #2 uses a 3rd party API. This API has hourly/daily rate limit.
Sometimes I have spikes in the workload. All pipelines but API pipelines can scale up to handle the workload. But not the API pipeline. It can eventually catch up, but not right away.
Is there a way to throttle down a pub/sub topic/subscription throughput to a specific number of messages per hour/day?
Pretty sure the answer is NO. If so, what are my other options?

A: You are right, the answer is no. Cloud Task has that throttling feature (named rate limit).
One solution design could be:

*

*PubSub invokes the next step

*Processing (Cloud Functions/Cloud Run/Something else) that stack the request in Cloud Task

*Cloud Task invokes the next step

*Processing (Cloud Functions/Cloud Run/Something else) that call your 3rd party API

Quite dirty, but you haven't other built-in solution on Google Cloud.


text:
Q: Error when trying to hide columns straight after binding data to datagrid So I have an XML file which I read in then display the data onto a DataGrid. Once I bind the DataView of the XML file to the ItemsSource of the datagrid I then attempt to hide the 4th column that will be created (it's an ID which I don't want to show) but receive an error
System.Windows.Markup.XamlParseException
  HResult=0x80131501
  Message='The invocation of the constructor on type 'MoneyLog.MainWindow' that matches the specified binding constraints threw an exception.' Line number '6' and line position '9'.
  Source=PresentationFramework
  StackTrace:
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)

Inner Exception 1:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

The Code I use:
DataGrid.Columns[4].Visibility = Visibility.Collapsed;

From the error I can see that apparently my number (4) was out of range therefore I assume the table must not of been create yet. To fix this i wrote a crude hack that delays the chunk of code by half a second and this fixes the problem...?
DataGrid.ItemsSource = dataView;
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
timer.Start();
timer.Tick += (sender, args) =>
{
     timer.Stop();
     DataGrid.Columns[3].Width = 250;
     DataGrid.Columns[4].Visibility = Visibility.Collapsed;
     DataGrid.CanUserAddRows = false;
     DataGrid.IsReadOnly = true;
};

My question is there another way to do this without this whole timer workaround?


text:
Q: Python list of combinations of positions I'm trying to generate a list of all possible 1-dimensional positions for an arbitrary number of identical objects.  I want it formatted so each coordinate is the distance from the previous object, so for 3 objects (0,5,2) would mean one object is at position 0, another is at position 5 and another is at position 7.
So the main restraint is that the sum of the coordinates is <=D.  Nested for loops works well for this.  For example, with 3 objects with maximum coordinate D:
def positions(D):
    output=[]
    for i in range(D+1):
        for j in range(D+1-i):
            for k in range(D+1-i-j):
                 output.append((i,j,k))
     return(output)

What's the best way to extend this to an arbitrary number of objects?  I can't find a good way without explicitly writing a specific number of for loops.

A: I think you can combine itertools.combinations, which will give you the locations, with taking the difference, which should give you your "distance from the previous object" behaviour.  For example, using
def diff(loc):
    return [y-x for x,y in zip((0,) + loc, loc)]

we have
In [114]: list(itertools.combinations(range(4), 3))
Out[114]: [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]

for the possible positions, and then
In [115]: [diff(x) for x in itertools.combinations(range(4), 3)]
Out[115]: [[0, 1, 1], [0, 1, 2], [0, 2, 1], [1, 1, 1]]

for your relative-distance version.


text:
Q: flash as3 first time a button pressed has no reaction I am trying to make my first game in actionscript 3 and using 3 keyframes. this is the code from my first keyframe:
gamestart.addEventListener(MouseEvent.MOUSE_DOWN, start);

function start(e:MouseEvent):void
{
gotoAndStop(2);
}

And in my second keyframe, I have a keyboard listener.
stage.addEventListener(KeyboardEvent.KEY_DOWN ,pressButton);

function pressButton(e:KeyboardEvent):void
{
trace("aaa");
}

My problem is that, after entering the second frame, the second frame doesn't seem to get "focused on", which means I still need to click it to be able to use its keyboard events. Anyway to force focus on a frame?

A: Setting stage focus is as simple this:
stage.focus = stage;


text:
Q: For $n \in \mathbb{N}$, show that $4^n + 10 \times 9^{2n-2}$ is divisible by 7 For $n \in \mathbb{N}$, show that $4^n + 10 \times 9^{2n-2}$ is divisible by 7.
I'm not sure how to do this proof so any help would be appreciated.

A: Induction can certainly be used, but a more direct method will also work as follows - (The trick here is to get to 7 as far as possible, so 9 = 7+2, etc)
$4^n + 10 \times 9^{2n-2}$
= $4^n + 3 \times (7 + 2)^{2n-2}$  (mod 7)
= $4^n + 3 \times 2^{2n-2}$ (mod 7)
= $4^n + 3 \times 4^{n-1}$ (mod 7)
= $4^{n-1}(4 + 3)$ (mod 7)
= $4^{n-1}(0)$ (mod 7)
= $0$ (mod 7)
Edit:-  In fact, because the expression is even, $14$ divides it for all $n$

A: $\begin{align}{\rm mod}\,\ 7\!:\quad\ \ & 4^{\large N} + \color{#c00}{10}\, (\color{#0a0}{9^{\Large 2}})^{\large N-1}\\
\equiv\ & 4^{\large N}\, -\: \color{#c00}4\:(\,\color{#0a0}4\,)^{\large N-1}\\ \equiv\ & 0\end{align}\ \ $
by
$\ \ \ \begin{align} &\color{#c00}{10\equiv -4}\\ &\color{#0a0}{9^{\large 2}\equiv 4}\\ \phantom{.}\end{align}$

A: We have
$$9^{2n-2} = (7+2)^{2n-2} = \sum_{k=0}^{2n-2} \dbinom{2n-2}k 7^k2^{2n-2-k} = 2^{2n-2} + 7M$$
Hence, we have
\begin{align}
4^n+10 \cdot 9^{2n-2} & = 4^n + 10 \cdot (2^{2n-2}+7M) = 4^n+10\cdot 4^{n-1} + 70M = 4^{n-1}(4+10)+70M\\
& = 14(5M+4^{n-1})
\end{align}
Hence, in fact we have that $14$ divides $4^n+10 \cdot 9^{2n-2}$ for all $n \in \mathbb{Z}^+$

A: $9\equiv2\pmod7\implies9^{2m}\equiv2^{2m}\equiv4^m$
$$4^{m+1}+10\cdot9^{2m}\equiv4^{m+1}+10\cdot4^m\equiv4^m(4+10)\equiv0\pmod{14}$$

A: If $n=1$, then
$$
4^{n} + 10\cdot 9^{2n-2} = 4+10 = 14,
$$
divisible by $7$;
if $n \geq 1$ is an integer such that $4^{n} + 10\cdot 9^{2n-2} = 7k$ for some integer $k \geq 1$, then
$$
4^{n+1} + 10\cdot 9^{2(n+1) - 2} = 4\cdot 4^{n} + 10\cdot 9^{2n} = 4(4^{n} + 10\cdot 9^{2n-2}) = 28k,
$$
divisible by $7$.

A: $\underline{\text{Proof by induction:}}$
First, show that this is true for $n=1$:
$4^1+10\cdot9^{2-2}=14$
Second, assume that this is true for $n$:
$4^n+10\cdot9^{2n-2}=7k$
Third, prove that this is true for $n+1$:
$4^{n+1}+10\cdot9^{2(n+1)-2}=$
$4^{n+1}+10\cdot9^{2n+2-2}=$
$4^{n+1}+10\cdot9^2\cdot9^{2n-2}=$
$4\cdot4^n+810\cdot9^{2n-2}=$
$4\cdot(\color\red{4^n+10\cdot9^{2n-2}})+770\cdot9^{2n-2}=$
$4\cdot\color\red{7k}+770\cdot9^{2n-2}=$
$28k+770\cdot9^{2n-2}=$
$7\cdot(4k+110\cdot9^{2n-2})$
Please note that the assumption is used only in the part marked red.

A: $4^n+10\cdot 9^{2n-2}=4\cdot 4^{n-1}+(7+3)(9^2)^{n-1}=4\cdot 4^{n-1}+(7+3)(81)^{n-1}$
$=4\cdot 4^{n-1}+7(81)^{n-1}+3(81)^{n-1}=4\cdot 4^{n-1}+7(81)^{n-1}+3(81^{n-1}-4^{n-1}+4^{n-1})$
$=4\cdot 4^{n-1}+7(81)^{n-1}+3(81^{n-1}-4^{n-1})+3\cdot 4^{n-1}=7\cdot 4^{n-1}+7(81)^{n-1}+3(81^{n-1}-4^{n-1})$
$=7\cdot 4^{n-1}+7(81)^{n-1}+3((77+4)^{n-1}-4^{n-1})$
$=7\cdot 4^{n-1}+7(81)^{n-1}+3(\sum_{k=0}^{n-1}{{n-1}\choose k}77^k4^{n-1-k}-4^{n-1})$
$=7\cdot 4^{n-1}+7(81)^{n-1}+3(4^{n-1}+\sum_{k=1}^{n-1}{{n-1}\choose k}77^k4^{n-1-k}-4^{n-1})$
$=7\cdot 4^{n-1}+7(81)^{n-1}+3(\sum_{k=1}^{n-1}{{n-1}\choose k}77^k4^{n-1-k})$


text:
Q: Graph API search by metadata / column value I'm developping an application using MS Graph API on a sharepoint site.
I'm trying to build the URL that allow me to find a drive item in a library with a colum param.
Actually I built this get URL to retrieve the drive items in the library:
https://graph.microsoft.com/v1.0/sites/{mainSite}:/sites/{subsite}:/lists/{libname}/items
I obtain a JSON with all files.
{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.list)('myLib')/items",
    "value": [
    ...

        {
            "@odata.etag": "\"7773c0de-bed1-425b-9065-2310c600757b,6\"",
            "createdDateTime": "2019-11-21T09:19:57Z",
            "eTag": "\"7773c0de-bed1-425b-9065-2310c600757b,6\"",
            "id": "24",
            "lastModifiedDateTime": "2020-05-27T09:09:05Z",
            "webUrl": "https://xxxx.sharepoint.com/sites/SUBSITE/myLib/Cartouche.docx",
            "createdBy": {
                "user": {
                    "email": "xxx@xxx.fr",
                    "id": "5fe24d57-1357-4fef-9cae-bfd79b0bf831",
                    "displayName": "David Vera"
                }
            },
            "lastModifiedBy": {
                "user": {
                    "email": "dvera@dsidiff.fr",
                    "id": "5fe24d57-1357-4fef-9cae-bfd79b0bf831",
                    "displayName": "David Vera"
                }
            },
            "parentReference": {
                "id": "1836034d-8a35-4488-995e-a7fe9cd30b4c",
                "siteId": "xxx.sharepoint.com,82a2327c-e2cf-4d30-b529-31c3bcdcda5e,fbi3zrs9-b07a-4777-945b-3b42c5c876d"
            },
            "contentType": {
                "id": "0x010100E4AD49D3A8873645A2803D49D2A4BF60"
            }
        },
    ...
    ]
}

I tried to use filter :
https://graph.microsoft.com/v1.0/sites/{mainSite}:/sites/{subsite}:/lists/{libname}/items?expand=fields(select=CODE_ANNONCEUR,val)&filter=fields/val eq 'myself'
It returns me :
{
    "error": {
        "code": "-1, Microsoft.SharePoint.Client.InvalidClientQueryException",
        "message": "The expression « fields (select ») is not valid.",
        "innerError": {
            "request-id": "c3edc510-2d63-4f21-86cd-a377fb02d324",
            "date": "2020-05-27T09:44:23"
        }
    }
}

A: I solved the issue this way :
https://graph.microsoft.com/v1.0/sites/xxx.sharepoint.com:/sites/yyy:/lists/zzz/items?expand=fields/CODE_ANNONCEUR&filter=fields/CODE_ANNONCEUR eq 'stringExpected'


text:
Q: Onclick scroll to next div class in Laravel/Blade Alright so I have a 'Concept' page which has 6 elements, div classes, called Paragraphs. Each paragraph has a heading, a body and a read more link (shown below). Now when I click on that read more link, I want the page to scroll to the next paragraph but I don't really know how I can get my page to do this. Any help would be appreciated. Below is the code I'm currently having.

{{ $element['title'] }}

{!! $element['textfield'] !!}

So the div class 'read-more-trading' should be linked to the next element called 'media-heading' or 'media-content'. I tried using jquery and javascript but for some reason I'm not getting any further.
Thanks in advance!

A: I think this is what you are looking for:
jQuery scroll to element
$('html, body').animate({
    scrollTop: $("{{ str_replace(' ', '-', $element['title']) }}").offset().top
}, 2000);


text:
Q: Detect corrupted Indexes How to detect corrupted indexes in PostgreSQL?
When I pull data from a column with primary key attribute in a table with where condition, it brings incomplete results. Likewise, when I sort with order by in the relevant column, the data is missing. When you dump the table and press it to another database or transfer the table to another table by changing its name, the data comes back healthy. In this case I suspect the primary key is corrupt. What do I need to do to scan the whole database for corrupt primary keys.

A: Run the bt_index_parent_check function from the amcheck extension. That can detect most cases of data corruption in a given index.


text:
Q: ¿Cómo imprimir en pantalla en intervalos de tiempo con Python? Estoy tratando de escribir con Python un programa que imprima en pantalla elementos de una lista en intervalos de dos segundos. He intentado lo siguiente:
a=0.0
b=0.0
c=0.0

i=0

import time

a=time.time()

while i<5:
    b=time.time()
    c=b-a
    if c>=2.0:
        a=time.time()
        i=i+1
        print (i)
    else:
        continue

Funciona, pero ¿hay alguna forma más directa o eficiente de hacer esto?

A: Y si usas sleep()?
i=0

import time

while i<5:
    print (i)
    i=i+1
    # tiempo en segundos
    time.sleep(5)


text:
Q: kubernetes autoscaling error custome metriccs apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: busy-autoscaler
spec:
   behavior:
     scaleDown:
       stabilizationWindowSeconds: 10
       policies:
       - type: Percent
         value: 50
         periodSeconds: 15
   scaleTargetRef:
     apiVersion: apps/v1
     kind: Deployment
     name: busy-worker
   minReplicas: 1
   maxReplicas: 2
   metrics:
   - type: Resource
     resource:
       name: cpu
       target:
         type: Utilization
         averageUtilization: 50

error: error validating "hpa.yml": error validating data: ValidationError(HorizontalPodAutoscaler.spec): unknown field "behavior" in io.k8s.api.autoscaling.v2beta2.HorizontalPodAutoscalerSpec; if you choose to ignore these errors, turn validation off with --validate=false

$ kubectl version --short

Client Version: v1.18.0
Server Version: v1.14.9-eks-502bfb

A: you can check available fields by running:
kubectl explain --api-version=autoscaling/v2beta2 HorizontalPodAutoscaler.spec

which are:

A: Firstly ensure that does kubectl api-versions show autoscaling/v2beta2 enabled.
You might also have a problem with your server version- v1.14.9-eks-502bfb.
See more: metrics-server.
Please let me know if it helps.


text:
Q: Python equivalence of C++ protobuf message differencer I am trying to compare two protobuf messages in Python for equality, ignoring the order elements in lists and so on.
For C++, I found the MessageDifferencer (https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.util.message_differencer)
Now I'm looking for something similar in Python, but can't really find anything. Any suggestions what I can use?
Thanks

A: I don't think anything exists. You can probably wrap the C++ implementation in python using CLIF or something similar.
I implemented a version myself (with only basic set of features) in https://github.com/dayfine/proto-matcher


text:
Q: Is there a way of removing quotation marks when using the quote crate? use quote::quote; // 1.0.7
use syn; // 1.0.40

fn main() {
    let foo = "foo";
    let foobar = syn::Ident::new(&format!("{}bar", foo), syn::export::Span::call_site());
    let testing = format!("self.{}.is_some()", foobar);
    let q = quote! {#testing};
    println!("{}", q);
}

playground
The stdout is
"self.foobar.is_some()"

I need
self.foobar.is_some()

A: If you don't want to treat something as a string, don't use a string. Instead, quote the source code directly:
use quote::{format_ident, quote}; // 1.0.7

fn main() {
    let foo = "foo";
    let foobar = format_ident!("{}bar", foo);
    let q = quote! { self.#foobar.is_some() };
    println!("{}", q);
}

self . foobar . is_some ()

If your data has to be a string (e.g. you read it from a configuration file), then you can use syn to parse the string back into the AST and the apply the above solution. This does require that you need to know what to parse the string as.
In this case, we want to parse the whole string as an expression:
use quote::quote; // 1.0.7
use syn; // 1.0.40

fn main() {
    let foobar = "self.foobar.is_some()";

    let e: syn::Expr = syn::parse_str(foobar).expect("Unable to parse");
    let q = quote! { #e };

    println!("{}", q);
}


text:
Q: Does Angular component from lazy loaded module gets copy of the global service? Angular docs I'm not sure if I understand
Angular providers documentation states:

When the Angular router lazy-loads a module, it creates a new
  injector. This injector is a child of the root application injector.
  Imagine a tree of injectors; there is a single root injector and then
  a child injector for each lazy loaded module. The router adds all of
  the providers from the root injector to the child injector. When the
  router creates a component within the lazy-loaded context, Angular
  prefers service instances created from these providers to the service
  instances of the application root injector.
Any component created within a lazy loaded module's context, such as
  by router navigation, gets the local instance of the service, not the
  instance in the root application injector. Components in external
  modules continue to receive the instance created for the application
  root.

Question
Does it mean that when I access any globally declared provider in a lazy loaded module, I access it's copy, which is separate from the instance created in the root injector?
Let's say I have 2 situations:
Situation A

*

*root module AppModule

*

*provides ProviderX

*declares AppComponent

*

*injects ProviderX

*lazy loaded module SubpageModule

*

*no providers

*declares SubpageComponent

*

*injects ProviderX
Situation B

*

*root module AppModule

*

*provides ProviderX

*declares AppComponent

*

*injects ProviderX

*lazy loaded module SubpageModule

*

*provides ProviderX

*declares SubpageComponent

*

*injects ProviderX
In situation A does the instance of ProviderX in SubpageComponent is the same instance as in AppComponent or a different one? I understand in situation B they're not.

A: Situation A
AppComponent and SubpageComponent get the same instance injected
Situation B
AppComponent and SubpageComponent get different instances injected
With your setup you get an injector hierarchy like
- AppModule
 |- AppComponent
 |- SubPageModule
   |- SubpageComponent

Angular searches from the location where it needs to inject a value the tree structure upwards until it finds the first matching provider. Then it injects the instance provided by the first found provider.


text:
Q: Issue with subquery in mongoDB I wanted to do a simple subquery with MongoDB, however, after reading plenty of documentation, still don't get it :(
I was using similar code as without success: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
select count(*) from Table1 where Field1 in (SELECT Field2 FROM Table2 where Field3 in ('QWERTY','ASDDF'));

Can you please help on this?
Thank you.
Edited:
I've tried something like the below, but still missing the filter of the field3 in ...
db.getCollection("Table1").aggregate(
    [
        {
            "$group" : {
                "_id" : {

                },
                "COUNT(*)" : {
                    "$sum" : NumberInt(1)
                }
            }
        },
        {
            "$project" : {
                "COUNT(*)" : "$COUNT(*)",
                "_id" : NumberInt(0)
            }
        },
        {
        "$lookup": {
            "from": "Table2",
            "localField": "Field1",
            "foreignField": "Field2" ,
            "as": "data"
            }
        },
{"$match": { "data.Field3": { "$in" : [ "QWERTY", "ASDDF" ]  } }}
    ],
    {
        "allowDiskUse" : true
    }
);

A: If I understand correctly you have two collections like this
collection1
[
{
    "c" : 3,
    "field" : 3
},
{
    "b" : 2,
    "field" : 2
},
{
    "a" : 1,
    "field" : 1
}
]

collection2
[
{
    "field1" : 4,
    "field2" : "kghjfdsa"
},
{
    "field1" : 3,
    "field2" : "dsfdgfdghdf"
},
{
    "field1" : 2,
    "field2" : "fdsfsd"
},
{
    "field1" : 1,
    "field2" : "adasd"
}
]

For query your data you just need to run this query
db.collection2.aggregate([
    {
        $match: {
            field2: {
                $in: ["kghjfdsa", "fdsfsd", "adasd"]
            }
        }
    },
    {
        $lookup: {
            from: "collection1",
            localField: "field1",
            foreignField: "field",
            as: "data"
        }
    },
    {
        $match: {
           "data.field": 1
        }
    }
])

If I can help with anything else let me know:)


text:
Q: Решение уравнений высших степений Прошу подсказать алгоритм для поиска корней уравнения высшей степени. Конкретней: есть многочлен вида k[0] * x^n + k[1] * x ^ (n - 1) + ... + k[n - 1] k[i] принадлежит Z и |k[i]| <= 10^9.Известно, что все корни целые.

A: Все целые корни многочлена с целыми коэффициентами являются делителями его свободного члена.
Поэтому есть такой путь:
 1. Провести факторизацию свободного члена.
 2. Найти все делители свободного члена как произведения его простых множителей (взятых в степенях не выше, чем в каноническом разложении),  со знаками плюс и минус.
 3. Отобрать все корни среди делителей.
На самом деле главная проблема - в нахождении одного корня x=a, поскольку в соответствии с теоремой Безу многочлен разделится на x-a, и следующий корень можно будет подставлять в частное. При этом повторная факторизация также получается путём несложного пересчёта.

A:
То, что корни общего уравнения пятой степени[en] и выше не выражаются при помощи рациональных функций и радикалов от коэффициентов, было доказано норвежским математиком Нильсом Абелем в 1826 году.

*

*взято из Википедии.
Это я имел ввиду когда говорил что алгоритма нет.

Это вовсе не значит что корни можно найти, например подбором, или графическим методом (если они есть).

A: Перебираем все корни по небольшим простым модулям, затем используем китайскую теорему об остатках для получения самих корней уравнения (произведение модулей должно быть достаточно большим).


text: Q: How to get the screenshot of SVG on Safari? I used dom-to-image to get the screenshot of svg, it worked successful on Chrome, but it will lost some svg layers on Safari. Is there any way to get screenshot of svg on Safari?


text:
Q: Can I use my own object in args when using Aspectj? I'm new with AspectJ and I tried to do this:
public class MyDBDAO {
    public boolean update(MyObject myObject) {}
}

And  Aspect:
@Aspect
@Component
public class AspectJClass {
   @Pointcut("execution(* com.myclass.MyDBDAO.update()) && args(myObject)")
    public void update(MyObject myObject) {}
 }

Should I only use Absoulute Type?
Are there any ways to solve this problem?

A: have you tried this ?
@Pointcut("execution(void com.myclass.MyDBDAO.update(MyObject)) && args(myObject)")
public void update(MyObject myObject) {}

if you want poincut to all of the methods in the class you can do this :
@Pointcut("this(com.myclass.MyDBDAO)")
public void isMyDBDAO() {}


text:
Q: nginx proxy pass ip from url I have multiple web servers with IP address say 172.18.1.1 to 172.18.1.20, hosting different website on 443(https) and A nginx server which I need to use for proxying above servers.
Example :
My nginx server IP is https://10.220.5.39:9200 by giving web server in URL , I need to show the websites
i.e. https://10.220.5.39:9200/proxy/172.18.1.1, should get website of https://172.18.1.1
AND
https://10.220.5.39:9200/proxy/172.18.1.2, should get website of https://172.18.1.2
location /proxy/(?<uniqueId>[^/]+).* {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass    https://$uniqueId/;
}

But it is not working , I can not use redirect , since client will not have access to web servers directly
Also some website use css file from route i.e. href="/static/theme.css"
because of which in browser console we are getting
not found https://10.220.5.39:9200/static/theme.css

Is this even possible with nginx


text:
Q: Make texcount ignore appendices Is it possible to tell texcount to stop counting when it reaches appendices? (i.e. the \appendix command)?
I'm using texcount. to check my thesis which is organised so that each chapter has its own \input{blah.tex}.
I need the count excluding appendices and biblography but including footnotes and captions.
Now I think most of this is done by texcount by default (please correct my if I'm wrong) except for the appendices part. Can't figure out an option to tell texcount to stop. I wonder if it's possible to drop some kind of comment into the document or if there is an option that I have overlooked.
I can, of course do the adding up by hand. But that feels a little clunky.

A: Just enclose the region not to be counted (the appendix stuff here) with %TC:ignore and %TC:endignore
\documentclass{article}
\begin{document}

And now for something completely different

%TC:ignore
\appendix
And now for something completely different
%TC:endignore
\end{document}

This should give:
File: texcountexample.tex
Encoding: ascii
Words in text: 6
Words in headers: 0
Words outside text (captions, etc.): 0
Number of headers: 0
Number of floats/tables/figures: 0
Number of math inlines: 0
Number of math displayed: 0


text:
Q: Cannot Get RazorView from Windsor Container using MVC 3 Beta This is how my Application_Start looks:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    _container.Register(Component.For<IWindsorContainer>()
        .Instance(_container),
        Component.For<IView, IViewPageActivator>()
            .ImplementedBy<RazorView>(),
        Component.For<IFilterProvider>()
            .ImplementedBy<WindsorFilterAttributeFilterProvider>(),
        Component.For<IControllerFactory>()
            .ImplementedBy<WindsorControllerFactory>(),
        Component.For<ControllerContext>()
            .ImplementedBy<ControllerContext>()
    );

    _container.Register(
        AllTypes.Of<IController>()
            .FromAssembly(Assembly.GetExecutingAssembly())
            .Configure(c => c.LifeStyle.Transient)
    );

Yet when trying to run the solution I get the following error:
Can't create component 'System.Web.Mvc.RazorView' as it has dependencies to be
satisfied.
System.Web.Mvc.RazorView is waiting for the following dependencies:

Keys (components with specific keys)
- viewPath which was not registered.
- layoutPath which was not registered.
- runViewStartPages which was not registered.
- viewStartFileExtensions which was not registered.

How do I setup the container such that it can get the required information dynamically at run time? As I assume at the very least viewPath will change for each Controller.

A: I'm still playing around with MVC, but I think I can point you in the right direction.
When you registered the component for RazorView you want to use the DynamicParamters method - eg:
Component.For<IView>().ImplementedBy<RazorView>()
    .DynamicParameters((kernel, dict) => {
        dict["viewPath"] = "~";
        dict["layoutPath"] = "~";
        dict["runViewStartPages"] = true;
        dict["viewStartFileExtensions"] = new List<string>() { "cshtml"};
    })

I also didn't have Windsor cast RazorView as an IViewPageActivator since it does not implement that interface. If you read The post from Brad Wilson your implementation of IDependencyResolver should return null for the IViewPageActivator if you don't have one.


text:
Q: Not able to display image in the browser for a simple express code I have my express code::
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var mysql=require('mysql');
var async=require('async');

var app=express();

var connection=mysql.createConnection({
        host: 'localhost',
        user: '************',
        password: '************',
        database: 'ImagePostingDB'
});

connection.connect(function(err) {
        if ( !err ) {
                     console.log("Connected to MySQL");
                    } else if ( err )
                    {
                         console.log(err);
                    } });

app.set('port',process.env.PORT||7004);
app.use('/Details',express.static(__dirname+'/public/images'));
app.use(express.bodyParser());

app.get('/DescriptionSortedPrice/',function(request,response){
  connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields) {
    if (err) {
      return response.send(500, err.message);
    }
        console.log('Found results:', rows);
    response.json({
      'restaurants' : rows
    });
  });
});

app.post('/Details/',function(req,res,next) {
  var file_name=req.files.key.originalFilename;
  var file_name1=req.body.key1;

  var name;

  console.log(file_name);
  console.log(file_name1);

  async.series( [
    // Get the first table contents
    function ( callback ) {
      crypto.randomBytes(8, function(ex, buf) {

        var array = req.files.key.originalFilename.split('.');
        var type  = array[array.length - 1];
        name  = buf.toString('hex') + '.' + type;

        fs.rename(req.files.key.path, './public/images/' + name, function(e) {

          if (e) {
            res.send(500, e.message);
          } else {
            res.send("I got the message - This i confirm");
          }

          return callback(null);
        });
      });
    },

    // Updating the database
    function ( callback ) {
      connection.query('INSERT INTO ImagePostingtable (Image_Name,Person_Name) VALUES (?,?)', [name,file_name1], function (err, rows, fields) {
        console.log('Connection result error ' + err);
        return callback(null);
      });
    }
  ]);
});

app.get('/Details/',function(req,res){
        res.send("Image displayed");
});

http.createServer(app).listen(app.get('port'),function(){
        console.log('Express server listening on port'+app.get('port'));

});

Snapshot shows i am connected to mysql and to server

I already have few images as shown in the snapshot below in the location /public/images

Now if i test in my browser for one of the images
http://54.218.73.244:7004/c92beeaf5ba50e65.jpg

i get error as below and image is not displayed in browser
Cannot GET /c92beeaf5ba50e65.jpg

HOW TO RESOLVE THIS ! ! !

A: Hoping this might help someone
With the help of Andrew in one of the answers i resolved this
I just changed the line of code to below::
app.use(express.static(__dirname+'/public/images'));


text:
Q: Retrieving list of items in creating a sales order using Suitescript I was able to fetch the options for select type of fields using the following code.
 for(index in fieldNames) {
     var selectFields = {};
     var field = record.getField(fieldNames[index]);

     if(field != null) {
        var id = field.getName();
        var field_details = {}

        field_details['Type']=  field.getType();
        field_details['Label'] =  field.getLabel();

        if(field.getType() == 'select') {
            var Options = field.getSelectOptions();
            var selectOptions = {};

            for(var i in Options) {
                var opt_id = Options[i].getId();
                selectOptions[opt_id] = Options[i].getText();
            }
            field_details['Options'] =  selectOptions;
        }

        selectFields[id]=field_details;
    }
}

I can successfully fetch options such as customform, salesrep, and shipmethod. What I cannot retrieve is the item list to be added in the sales order. Based from what I can see in the docs, there's a sublist and subrecord, but there's no similar method to what I'm using right now which is the getSelectOptions method.
By the way, I'm using this as a RESTlet.


text:
Q: Will_paginate gem is not installing - Rails 4 for something reason will_paginate is not installed.
i have put the line
gem 'will_paginate', '~>3.0.6'

in my gemfile,
i even ran "gem install will_paginate" in the console.
it says installed sucessfully but using the instructions to check if will_paginate is indeed install returns false nil
reference:
>> defined? WillPaginate
>> ActiveRecord::Base.respond_to? :paginate
If any of these lines return nil/false, will_paginate has not properly loaded in your app.

and i get this error when implemented
undefined method `total_pages' for #<Post::ActiveRecord_Relation:0x007fa40773bc18>

UPDATE:
I specifically stated in my gemfile to install version 3.0.5 not the latest version(3.0.7) and the gem is loaded properly. BUT the error with the total_pages still remains.
more info:
controller:
@posts = Post.paginate(:page => params[:page])

view:
<%= will_paginate @posts %>

UPDATE 2:
FIXED the error (had a typo) BUT i cannot see visually the gem anywhere on the page.


text:
Q: Address table to access heterogeneous struct fields by their index I have a structure of heterogenous data:
struct Data {
    a: i16,  // index "0"
    b: i32,  // index "1"
    c: u8,   // index "2"
}

Is there a good way to create an "access table" (can be done at compile time with a build tool) which allows me to access references to the underlying data by index rather than field name?  The data will be a nested struct of non-homogenous data (u8, i8, u16, i16, etc).  The "indexs" are basically the number corresponding to each item of the nested struct were flattened.
The application is for schema-based communication. We have a run-time database consisting of a static hierarchical struct and a lightweight communication protocol for reading and writing to the run-time database using power-line communication. Due to bandwidth limitations, we use a schema system where we access the structure by index rather than name.
#################### UPDATE (My Solution) ########################
Thanks to those who provided the links below.  They helped give me ideas but were not perfect fits to my problem.  A little bit more background first, this is a rather large hierarchical struct with around 1000 "items".  Each "item" is going to be primitive type of u8, i8, u16, i16, u32, i32, u64, i64, or char.  We treat this struct as like a run-time database for shared resources between embedded applications running on an ARM M4.
We have a protocol specification for reading/writing 1 or several values of this runtime database over UART and over our own Powerline Communication modem.  For bandwidth reasons, we create a schema system similar to protobuf for accessing individual items by index rather than name.  In our C implementation, we have a Python library that generates an "Access Table" at compile time.  This "Access Table" contains fixed size array of structs, where each struct contains access info including pointer address and number the size of the item.  We then have an access function that is able to fill a buffer with the raw contents of the data using a memcopy.  It is important that the access table use pointers, as the application has access to this runtime database and is making changes to the values as the application runs.
Since we only have 9 different variants for the "items" the solution I came up with was to simply encapsulate each item in an Enum.  Here is a syntactically correct (tested) implementation.  I can then use pattern matching to fill my buffer in the protocol code.  I am curious what more experienced Rustaceans think of this solution.
// This is the runtime database struct
#[derive(Debug)]
struct Data {
    a: i32,
    b: u8
}

#[derive(Debug)]
enum Item<'a> {
    U8(&'a u8),
    I8(&'a i8),
    U16(&'a u16),
    I16(&'a i16),
    U32(&'a u32),
    I32(&'a i32),
    U64(&'a u64),
    I64(&'a i64)
}

fn main() {
    // initialize the data in the runtime database
    let data = Data{a:2001, b:42};

    // this "access table" generated by Python script at compile time
    // allows indexed access to the data by reference
    let table: [Item; 2] = [Item::I32(&data.a),
                            Item::U8(&data.b)];

    let item:&Item = &table[1];

    println!("Struct data => {:?}", data);
    println!("The second value of the struct is {:?}", item);
}

A: My best approach so far is to encapsulate with an Enum.
enum Item<'a> {
    I16(&'a i16),
    U32(&'a u32),
    U8(&'a u8)
}

let access_table: [Item; 3] = [Item::I16(&data.a),
                               Item::U32(&data.b),
                               Item::U8(&data.c)];


text:
Q: Perl, read from two files and write to a third I am having trouble getting my program to work. Basically, I read in from two files, then write the data into one. Can anyone point out what the problem is? I keep getting errors about instantiation on the print OUT statements where I am trying to write to the file. Here is my code:
print "Please input file name \n";
$infile=<DATA>;
$infile2=<DATA>;

open IN, "$infile";
open JUNK, "$infile2";
open OUT, '>' ,'convertedback.txt';

$line = <IN>;
$line2 = <JUNK>;

#pull first line from sample (name 1)
print OUT "$line";
$line =<IN>;
#pull sequence line from FASTQ
print OUT "$line";
#pull line from quality file *2
print OUT "$line2";
$line2 =<JUNK>;
print OUT "$line2";

#Repeat until EOF
while($line =<IN>) {#for lines 5 to end

#Build Line 1
print "line 1 inf (name) is\n";
print $line2;
print OUT "$line2";

#Build Line 2
print "line 2 inf (seq) is\n";
print $line;
print OUT "$line";

#Build Line 3
$line2 =<JUNK>;
print "line 3 inf (quality) is\n";
print $line2;
print OUT "$line2";

#Build Line 4
$line2 =<JUNK>;
print "line 3 inf (quality) is\n";
print $line2;
print OUT "$line2";

}#while $line=<IN>
close (IN);
close (OUT);

print "Done!\n";

__DATA__
outfilenew.txt
sample.qualities

A: use strict and use warnings in the beginning of the script.
use three argument open, like
open(my $fh, '<', "input.txt") or die $!;

use while loop to read lines from files like,
while(my $line = <>){
   #do something
}

script looks like,
use strict;
use warnings;
print "Please input file name \n";
my $infile=<DATA>;
my $infile2=<DATA>;

open(my $in,'<', "$infile") or die $!;
open(my $junk,'<',"$infile2") or die $!;
open(my $out, '>' ,'convertedback.txt') or die $!;

my $line = <$in>;
my $line2 = <$junk>;

#pull first line from sample (name 1)
print $out "$line";
$line =<$in>;
#pull sequence line from FASTQ
print $out "$line";
#pull line from quality file *2
print $out "$line2";
$line2 =<$junk>;
print $out "$line2";

#Repeat until EOF
while($line =<$in>) {#for lines 5 to end

#Build Line 1
print "line 1 inf (name) is\n";
print $line2;
print $out "$line2";

#Build Line 2
print "line 2 inf (seq) is\n";
print $line;
print $out "$line";

#Build Line 3
$line2 =<$junk>;
print "line 3 inf (quality) is\n";
print $line2;
print $out "$line2";

#Build Line 4
$line2 =<$junk>;
print "line 3 inf (quality) is\n";
print $line2;
print $out "$line2";

}#while $line=<IN>
close ($in);
close ($out);

print "Done!\n";

__DATA__
outfilenew.txt
sample.qualities


text:
Q: Error in sei^2 : non-numeric argument to binary operator, in metafor I'm trying to run a fixed effect meta analysis, using SMDs and the SE with metafor. I'm using an rma.uni-function:
metafor::rma.uni(yi="SMD12", sei="SE12",  data=SMDpainmeta, method="FE")

R gives me the following error message:

Error in sei^2 : non-numeric argument to binary operator.

I set SE12, which is the standard error at 12 months as the sei value. The values are clearly numeric, although some NAN values are also present in this column.
When I use the vi value and set the corresponding Variance instead of SE12
metafor::rma.uni(yi="SMD12", vi="Variance12", method="FE", data=SMDpainmeta)

I get the follow error:

error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
    NA/NaN/Inf in 'y'

So either way there seems to be a problem with my NAN values, which are a result of my missing data in this studies at timepoint 12.
Could anyone help me with this issue?

A: Don't put the variable names in quotes. So, just use:
rma.uni(yi=SMD12, sei=SE12, data=SMDpainmeta, method="FE")


text:
Q: Videojs not working with dynamic URL but working with static URL I am tryign to implement videojs in my reactjs project. I am providing "src" to video component as props. The plauer "No compatible source was found for this media.". Below is my code
initVideoJS = () => {
        let self = this;
        let that = this;
        const options = {
            fluid: true,
            preload: "auto",
            autoplay: false,
            controls: true,
            aspectRatio: "16:9",
            loop: false,
           // playVideo: false
        }

        myPlayer = videojs('video-el-p', options)
    }

render () {
        return (

                    <section className="video-container" id="video-container" style={{height: `${this.state.video_container_height}px`}}>

                            <video onContextMenu="return false;"
                                   ref={node => this.video_el = node}
                                   className="video-js video-el vjs-big-play-centered vjs-default-skin"
                                   id="video-el-p" loop={false} controls>
                                <source src={this.props.assetVersion && this.props.assetVersion.video.file} type="video/mp4"/>
                                Your browser does not support HTML5 video.
                            </video>

But the same code works when I give a static video url as src. Also
this.props.assetVersion.video.file

is a valid video url. This url works on normal html5 video component. What am I doing wrong?
p.s. There is another videojs player instance used in some other page of the application. But that has different id. So I don't think that is affecting it.
I have implemented videojs multiple times but this is the first time I am coming accros this issue. Thanks in advance.

A: I think the issue is in the fact that the video source might be undefined as you are using a conditional <source src={this.props.assetVersion && this.props.assetVersion.video.file} type="video/mp4"/>
Perhaps try to only render the video element when ever the video src is not undefined. It would look something like this.
render() {
    let video;
    if (this.props.assetVersion) {
        video = (
            <video onContextMenu="return false;"
                ref={node => this.video_el = node}
                className="video-js video-el vjs-big-play-centered vjs-default-skin"
                id="video-el-p" loop={false} controls>
                <source src={this.props.assetVersion.video.file} type="video/mp4" />
                Your browser does not support HTML5 video.
             </video>
        );
    }
    return (

                <section className="video-container" id="video-container" style={{ height: `${this.state.video_container_height}px` }}>

                        {video}


text:
Q: Prompt when click on a link and modify it I have a link on my page and i want that on click an prompt will show, i'll write there something and then it will change the href of the link and move on the page. But i have something like this:
var link="index.php?s=podporaf&act=close";
function editLink() {
var x = prompt("Note":, "");
link+="&note=" + x;

window.location=link;

And then link:
Close

All i want is before going to the page change the href to
href="index.php?s=podporaf&act=close&note=something"

And then go on that page. So I have two questions. Is it even possible? And if so then how? My solution does not work, it just goes follow the link, but the prompt does not show.

A: prompt("Note":, ""); is a syntax error. The : is in the wrong place.
prompt("Note:", "");

Also, make sure that editLink is defined before your  is defined. So put your


text:
Q: Ensuring that the entire string is used when it contains a period I'm having some trouble with the DataBinder.Eval(Object, String) method.
https://msdn.microsoft.com/en-us/library/4hx47hfe(v=vs.110).aspx
Generally the method works but not in case, when the string value contains a .
Example:
string DataField = "Trans. Due";
var value = DataBinder.Eval(container.DataItem, DataField);

I receive the following error;
{"DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Trans'."}

Have tried putting the string between square brackets and escaping the period. Have also tried casting it to a string thusly to no avail;
var value = DataBinder.Eval(container.DataItem, DataField.toString());

So I figure something in the method is confusing the string for a property? How can I make sure it uses the value simply as a string?

A: You can do this by using DataRowView. Get the DataRowView from current row then access value of the property by name which you want from DataRowView.
DataRowView rowView = (DataRowView)e.Row.DataItem;
String transDue = rowView["Trans. Due"].ToString();


text:
Q: Flutter Scaffold allow child behind the system Navigation Bar I post this question due to the difficult to find the response I need, but I guess it must have been replied somewhere. If it indeed was asked and replied somewhere else, please point me to the right direction
See the image below, taken from a kitkat device. The Scaffold has a red background, and it's body a green one. I need the green to cover all scaffold, including the area behind the Navigation Bar.

Ps.: Code, as requested
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.red,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Container(
        color: Colors.green,
        child: Center(

        ),
    ),
      // Set bg to blue, to show that the Scaffold is indeed behind the Nav Bar...
      backgroundColor: Colors.blue,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

Ps².: To make things clear, my problem is that I'm trying to draw behind the Navigation Bar. The Scaffold clearly draws itself behind it, but it doesn't let me do this, and if I use SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]); the Navigation Bar is hidden, and I need it to be visible, like the Status Bar is.

A: You can use the Stack widget, to make the container cover the scaffold.
read here: https://docs.flutter.io/flutter/widgets/Stack-class.html
you can write something like this
Stack(
  children: [
     Scaffold(...),
     Container(..., height: double.infinity, width: double.infinity),
  ]
)

The container should cover the scaffold since it's sitting on top of it :)

A: You must center your container not warping your Center with Container widget.
Center(
  child: Container(
    color: Colors.green,
  ),
);

By defualt, Center widget will match it's child size.

A: Adding: extendBody: true, on Scaffold works here. Body will extend under bottomNavigationBar.


text:
Q: Поиск по связанной таблице yii2, есть модель поиска:
class ProductsBarcodesSearch extends ProductsBarcodes
{

    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['barcode','product_id', 'code', 'name'], 'safe'],
        ];
    }

    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = ProductsBarcodes::find()->joinWith('product');

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }
        $query->andFilterWhere(['product_barcode.id' => $this->id]);

        // grid filtering conditions
        $query
            ->andFilterWhere(['like', 'product.name', $this->product_id])
            ->andFilterWhere(['like', 'product_barcode.barcode', $this->barcode]);

        return $dataProvider;
    }
}

так все работает (поиск по имени из связанной таблицы), но стоит сделать так:
    $query
        ->andFilterWhere(['like', 'product.name', $this->product_id])
        ->andFilterWhere(['like', 'product.code', $this->product_id]) //вот это добавил
        ->andFilterWhere(['like', 'product_barcode.barcode', $this->barcode]);

и все ломается, перестает искать как по имени, так и по полю code
как правильно тянуть эти данные из связанной таблицы, чтобы работал поиск?

A: нашел решение.

*

*нужно добавить новые свойства классу:
class ProductsBarcodesSearch extends ProductsBarcodes
{
    public $pname;
    public $pcode;

*задать значение, по которому будут искаться данные:
    ->andFilterWhere(['like', 'product.name', $this->pname])
    ->andFilterWhere(['like', 'product.code', $this->pcode])

*прописать во view в атрибутах эти свойства
    [
        'attribute' => 'pcode',
        'label' => 'Внутренний код',
        'value' => function($model){
            if ($model->product_id){
                return $model->product->code;
            }
            return 'Нет кода';
        }
    ],
    [
        'attribute' => 'pname',
        'label' => 'Название продукта',
        'format' => 'html',
        'value' => function($model){
            if ($model->product_id){
                return Html::a($model->product->name, \yii\helpers\Url::to(['/products/view?id=' . $model->product->id]));
            }
            return 'Нет имени';
        }
    ],

единственное что я пока не пока как сделать, это сортировка по этим полям.
если знаете как реализовать, напишите.


text:
Q: how to use file upload in jquery modal popup? I have created jquery modal popup with post back events using bellow code
<div id="divPopup" style="display: none">
        <asp:UpdatePanel ID="upnlLessonDetails" runat="server">
            <ContentTemplate>

            </ContentTemplate>
        </asp:UpdatePanel>
    </div>

$('#divPopup').parent().appendTo($('#aspnetForm'));
$('#divPopup').parent().before($(".ui-widget-overlay,ui-front"));

I need to use file upload in that jquery modal popup. but in here i cannot make full page full postback to upload a file. Please give me any solution.


text:
Q: Asp.net upload file using XMLHttpRequest c# server I have the following client side function:
function UploadFile() {
    var formData = new FormData();
    var file = document.getElementById("file").files[0];
    formData.append("file", file);
    var uploadServerSideScriptPath = "Login.aspx/Img_Upload";
    var xhr = new XMLHttpRequest();

    xhr.open("POST", uploadServerSideScriptPath, true);
    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.setRequestHeader("X-File-Name", file.name);
    xhr.setRequestHeader("X-File-Size", file.size);
    xhr.setRequestHeader("X-File-Type", file.type);
    xhr.send(formData);
}

the server-side is:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Img_Upload()
{
    HttpContext postedContext = HttpContext.Current;
    HttpPostedFile file = postedContext.Request.Files[0];

    string name = file.FileName;
    byte[] binaryWriteArray = new
    byte[file.InputStream.Length];
    file.InputStream.Read(binaryWriteArray, 0,
    (int)file.InputStream.Length);

    FileInfo file_Info = new FileInfo(file.FileName);
    string ext = file_Info.Extension;

    string file_Name = Guid.NewGuid().ToString() + "_" + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + ext;

    FileStream objfilestream = new FileStream(Server.MapPath("img//profilePIC//" + file_Name), FileMode.Create, FileAccess.ReadWrite);
    objfilestream.Write(binaryWriteArray, 0,
    binaryWriteArray.Length);
    objfilestream.Close();

}

I put a break-point inside Img_Upload but it never hits.
I used fiddler and the request seems ok.
any ideas why?
If I use var uploadServerSideScriptPath = "Login.aspx", I get to the page_load function.
The problem is to call a specific method on that page.

A: Try clientID for getElementByID() method as
...

    function UploadFile() {
        var formData = new FormData();
        var file = document.getElementById("<%=file.ClientID%>").files[0];
...

A: I solved the issue by creating .axd handler and use ProcessRequest


text:
Q: Modyfing code completion in PhpStorm 5 After entering first characters of <textarea> tag and using autocomplete ( e.g. <texta and hitting ENTER) editor generates following snippet: <textarea rows="" cols=""
It's extremely unhelpful since I don't use rows and cols attributes.
How can I modify those snippets ?
I tried "Live templates" section but it's not there.

A: In this case code completion is performed according to the DTD, which defines rows and cols attributes of the textarea tag as Required.
Most likely your file starts with:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

or the default HTML language level defines it.
To address this problem you can create HTML 5 files with <!DOCTYPE html> and PhpStorm will stop completing these attributes.
See also the related IDE setting:


text:
Q: Passing DropDownList value into SQL command in ASP.net I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
    sqlConnection1 = new SqlConnection(@"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
    SqlCommand Command = null;

        Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
        Command.Connection.Open();
        SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
        DataTable dataTble1 = new DataTable();
        dataAdapter.Fill(dataTble1);

        if (dataTble1.Rows.Count > 0)
        {
            foreach (DataRow row in dataTble1.Rows)
            {
                ListItem course1 = new ListItem(row["Course"].ToString());
                if (!DropDownList1.Items.Contains(course1))
                {
                    DropDownList1.Items.Add(course1); // showing the 2 courses
                }
            }
        }
        Command.Connection.Close();

    }
}

Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection sqlConnection1;
    sqlConnection1 = new SqlConnection(@"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
    SqlCommand Command = null;

        Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = @course", sqlConnection1);
        Command.Parameters.AddWithValue("@course", DropDownList1.SelectedItem);
        Command.Connection.Open();
        SqlDataReader sqlDataReader1 = Command.ExecuteReader();

        if (sqlDataReader1.Read())
        {
            LabelAverage.Text = sqlDataReader1[0].ToString();
        }
        else
        {
            LabelAverage.Text = "No Data"; // doesn't get into here anyhow
        }
   }

EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = @course" and Command.Parameters.AddWithValue("@course", DropDownList1.SelectedItem.Text), or  DropDownList1.SelectedValue
 I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
 Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.

A: I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the  AutoPostBack="true"
Adding that to DropDownList solved the problem.

A: // query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
            {
                Label = s.Adi,
                Value = s.ID.ToString()
            }).ToList();


text:
Q: MongoDB $addToSet not writing to database I am not sure why but I am having a really hard time getting the $addToSet working for my sub array items.
This is what it should look like:
{
  "items": [
    {
      "id": "510bca8138fc5d6e38000000",
      "quantity": "1"
    },
    {
      "id": "51011a8138fc5d6348000000",
      "quantity": "1"
    }
  ],
  "session": "1359948849.291898629576",
  "status": "cart"
}

However, it seems to only allow the first:
{
  "items": [
    {
      "id": "510bca8138fc5d6e38000000",
      "quantity": "1"
    }
  ],
  "session": "1359948849.291898629576",
  "status": "cart"
}

and it just won't insert another sub array.
My code:
$document = $collection->findOne(array('session' => $_SESSION["redi-Shop"]));

        //print_r($document);
        if (null !== $document) {
            $collection->update(
                array('session' => $_SESSION["redi-Shop"]),
                array(
                    '$addToSet' => array(
                        'items' => $_POST['item']
                    ),

            ));
            print_r($_POST['item']);
        }
        else
        {
            $collection->insert(
                array('session' => $_SESSION["redi-Shop"],
                'status' => "cart",
                    'items' => $_POST['item'])
                );
        }

A: I changed the $addToSet to $Push and it works fine


text:
Q: Select the month with the most recent data available and the previous month I have a table that is analogous in structure to the one defined below. The PK is the first 4 columns, the last column is the actual score. Each row is populated fully with the 12 months of the fiscal year, scores are filled in as the become available that month. Each month, we want to report on what the most recent available score is (some scores lag behind a month or two so we can't use the current month) and what the previous one was. Given the data supplied below, I would like the results to appear as such:
+--------+--------+--------+-----------+----------+---------------+
|ScoreKey|DeptName|TestName|ScorePeriod|ScoreValue|CurrentPrevious|
+--------+--------+--------+-----------+----------+---------------+
|    1   |  'abc' |  'def' |  201707   |   1      |   Current     |
|    1   |  'abc' |  'def' |  NULL     |   NULL   |   Previous    |
|    2   |  'abc' |  'def' |  201801   |   7      |   Current     |
|    2   |  'abc' |  'def' |  201712   |   6      |   Previous    |
+--------+--------+--------+-----------+----------+---------------+

I tried doing a GROUP BY with MAX() then UNION and filter out the MAX value but that doesn't account for ones with only one row of data (it returns no row).
Code to provide the table and values:
    create table #scores (
        ScoreKey INT,
        DeptName VARCHAR(10),
        TestName VARCHAR(10),
        ScorePeriod INT,
        ScoreValue INT
    )

    insert into #scores values (1,'abc','def',201707,1)
    insert into #scores values (1,'abc','def',201708,NULL)
    insert into #scores values (1,'abc','def',201709,NULL)
    insert into #scores values (1,'abc','def',201710,NULL)
    insert into #scores values (1,'abc','def',201711,NULL)
    insert into #scores values (1,'abc','def',201712,NULL)
    insert into #scores values (1,'abc','def',201801,NULL)
    insert into #scores values (1,'abc','def',201802,NULL)
    insert into #scores values (1,'abc','def',201803,NULL)
    insert into #scores values (1,'abc','def',201804,NULL)
    insert into #scores values (1,'abc','def',201805,NULL)
    insert into #scores values (1,'abc','def',201806,NULL)
    insert into #scores values (2,'abc','def',201707,1)
    insert into #scores values (2,'abc','def',201708,3)
    insert into #scores values (2,'abc','def',201709,4)
    insert into #scores values (2,'abc','def',201710,5)
    insert into #scores values (2,'abc','def',201711,5)
    insert into #scores values (2,'abc','def',201712,6)
    insert into #scores values (2,'abc','def',201801,7)
    insert into #scores values (2,'abc','def',201802,NULL)
    insert into #scores values (2,'abc','def',201803,NULL)
    insert into #scores values (2,'abc','def',201804,NULL)
    insert into #scores values (2,'abc','def',201805,NULL)
    insert into #scores values (2,'abc','def',201806,NULL)

A: select *
from
( select *
       , row_number over (partition by ScoreKey, DeptName, TestName order by ScorePeriod desc) as rn
  from table
) aa
where rn <= 2


text:
Q: Cell overlay in beamer I used the code posted in this thread to highlight cells in a table:
\documentclass[xcolor=table]{beamer}

\rowcolors{1}{gray!30}{gray!10}

\makeatletter
\def\rowcolor{\noalign{\ifnum0=`}\fi\bmr@rowcolor}
\newcommand<>{\bmr@rowcolor}{%
    \alt#1%
        {\global\let\CT@do@color\CT@@do@color\@ifnextchar[\CT@rowa\CT@rowb}%
        {\ifnum0=`{\fi}\@gooble@rowcolor}%
}

\newcommand{\@gooble@rowcolor}[2][]{\@gooble@rowcolor@}
\newcommand{\@gooble@rowcolor@}[1][]{\@gooble@rowcolor@@}
\newcommand{\@gooble@rowcolor@@}[1][]{\ignorespaces}
\makeatother

\makeatletter
\def\cellcolor{{\ifnum0=`}\fi\bmr@cellcolor}
\newcommand<>{\bmr@cellcolor}{%
    \alt#1%
        {\global\let\CT@do@color\CT@@do@color\@ifnextchar[\CT@rowa\CT@rowb}%
        {\ifnum0=`{\fi}\@gooble@cellcolor}%
}

\newcommand{\@gooble@cellcolor}[2][]{\@gooble@cellcolor@}
\newcommand{\@gooble@cellcolor@}[1][]{\@gooble@cellcolor@@}
\newcommand{\@gooble@cellcolor@@}[1][]{\ignorespaces}
\makeatother

\begin{document}
\begin{frame}{The MWE}%

\only<2>{\rowcolors{1}{blue!30}{blue!10}}
\only<1,3>{\rowcolors{1}{gray!30}{gray!10}}

\begin{center}
\begin{tabular}{cc}
    A & B \\
    A & B \\
    A & B \\
    \rowcolor<4>{green} C & D \\
    \rowcolor<4,5>{yellow} E & F \\
    \rowcolor<4-6>{green} G & H \\
    \rowcolor<6>{red} Y & S \\
    A & B \\

\end{tabular}
\end{center}

\par
\visible<1>{Testing default row colouring ... \\}
\visible<2,3>{Testing change of default colors ...\\}
\visible<4-6>{Testing in-out of custom colors ...\\ (caution: The order of defaults colors can change)\\}

\vfill
\scriptsize{
 Based of answer of Martin Scharrer
 \url{https://tex.stackexchange.com/questions/18427/why-cant-i-wrap-rowcolor-in-only-beamer}}

\end{frame}

\begin{frame}{Cell Coloring with In-out Effects}
   \begin{center}
   \begin{tabular}{cc}
    A & B \\
    C & \cellcolor<3>{green} C \\
    D & E \\
    F & G \\

    \end{tabular}
    \end{center}
    \end{frame}

\end{document}

But if I change the last frame to
\begin{frame}{Cell Coloring with In-out Effects}
\begin{center}
\begin{tabular}{cc}
A & B \\
\cellcolor<3>{green} C &  C \\
D & E \\
F & G \\

\end{tabular}
\end{center}
\end{frame}

then the whole second row gets highlighted. Can somebody tell me how to redefine \cellcolor above to make sure that only one cell will be highlighted?

A: A simple redefinition can make \cellcolor overlay-aware:
\documentclass[xcolor=table]{beamer}
\renewcommand<>\cellcolor[1]{\only#2{\beameroriginal\cellcolor{#1}}}

\begin{document}

\begin{frame}

   \begin{tabular}{cc}
        A & B \\
        \cellcolor{green}C &  C \\
        D & E \\
        \cellcolor<2>{red}F & G \\
    \end{tabular}

\end{frame}

\end{document}


text:
Q: Php read file contents of network share file I'm looking for a way to read the file contents of a file located on a network share.  I can use the IP Address of the share host and the share folder to get to the location but I don't know the correct command and syntax to do that file_get_contents? fopen?
$text = fopen('//128.251.xxx.xxx/Common/sample.txt', 'r');

or something like that?
UPDATE*
I also cannot access the file through a browser window although I know the file is located in that exact directory...

A: The best way (depending on your needs) is to simply mount it on your local machine, and then read from the mount.  That lets all the network interaction be abstracted away.
So, in Linux:
mount -t cifs //192.168.XXX.XXX/share /path/to/mount -o user=username,password=password

Then, in php, just access it from the mount point:
$data = file_get_contents('/path/to/mount/path/to/file.txt');

A: According to PHP Filesystem manual UNC/SMB files should be accessible. Try the following:
\\server\share\file.txt

It may be one of those cases where the // may be mistook as a reference to the root directory. And given this is an SMB path, I would use the traditional backslashes.