text:
Q: working with a UIScrollView I have an UIScrollView when I present a form to the user. You can see a screenshot of my storyboard over here. Below the pickers there is a submit button.

What I want to do now is, when a user presses submit. On top of the tableview appears a uitableview with all the previous set exceptions.
My question is now, how can I put a tableview on top of the scrollview when the submit button is pressed?
Hope anyone can help me!

A: use this code...
[scrollView addSubView:tableView];
[scrollview bringSubviewToFront:tableView];

A: If you adding UIScrollView and UITableView on any base view then you should use or adding table on scroll,
in any case this must work..
[tableview.superView bringSubviewToFront:tableView];


text:
Q: Source bashrc from script failing I've written a simple bash script that adds an alias to my .bashrc automatically, and when it finishes, I would like it to source the .bashrc
It works fine as of now, for example
./addalias.sh ls 'ls -l'

properly appends 'alias ls='ls -l' to the .bashrc, but doesn't source it.
The code is as follows:
#!/bin/bash
FIRST=$1

SECOND=${2:-cd `pwd`}

echo alias $FIRST="'$SECOND'" >> /home/oscar/.bashrc
echo alias $FIRST="'$SECOND'"

source /home/oscar/.bashrc

That doesn't work, nor does running an alias ("sourcebash") to source the bash instead of the last line.
Any thoughts on how this could be fixed?

A: The shell that runs 'addalias.sh' does source the .bashrc file; it then exits.  It does not and cannot affect the parent shell's environment.
You'd have to invoke the command as:
source ./addalias.sh ls 'ls --color=auto'

Or:
. ./addalias.sh ls 'ls --color=auto'

(Now fixed: And I'm not convinced that, even in a question, playing with sudo rm -fr /* is remotely sensible.  There's too much risk of an idiot copying and not realizing.)

A: Maybe you can make it a function or an alias instead of a bash script. Doing that might cause the changes to occur in the same shell.

A: i'd make an alias which calls this 'addalias' script, then sources the newly-modified file.
something like
alias really_add_alias="addalias.sh; . .bashrc"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Command line join of password protected wireless networks in Ubuntu, Arch Linux, or other distros? Is there a way to join a password protected wireless network via the command line in installations of Ubuntu or Arch Linux with no desktop environment or any GUI installed?
Also, could this be done during a text-based installation and set up of those systems? Just for example, this might be important when installing (without a GUI) from a live CD where many packages need to be downloaded, but only a password protected wireless network is available.
Thanks.

A: wicd-curse is good for you if you install wicd!

A: The package you are looking for is called wpa_supplicant, it handles logging into protected wireless networks.
If you use it from Ubuntu (or other debian based distributions) it's fairly easy to set up and the process is rather simple (check the debian wiki for a few pointers). I don't know much about arch linux but it shouldn't differ too much.
If you still want the convenience you know from desktop environments or are for some other reason tied to network-manager you can use the cnetworkmanager (website) package that allows you to talk to the network-manager daemon from a terminal.

A: As tante said, use wpa_supplicant.
Here is the  ArchLinux wiki on it.
have fun :)


text:
Q: Join table not being created when adding a list of IdentityUser to an entity in Entity Framework Core I have two different types of users that have different properties so I created 2 new classes and each of them inherit from AppUser. I am aware that EF uses a discriminator column in the AspNetUsers table when doing this. Additionally, a student has many teachers so I expect a join table to be created that will have TeacherUserId and StudentId.
When I run Update-Database, it adds a StudentId column to the AspNetUsers table.
Where is my StudentTeachers table? It seems like it is trying to handle it in AspNetUsers table with many rows which would be horrible. I don't want to create a new identity user for every single student.teacher.
Here are my model classes:
public class AppUser : IdentityUser
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
}

public class TeacherUser : AppUser
{
    public string TeacherSpecificProperty { get; set };
}

public class StudentUser : AppUser
{
    public string StudentSpecificProperty { get; set };
}

public class Student
{
    public Student()
    {
        this.Teachers= new List<TeacherUser>();
    }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<TeacherUser> Teachers{ get; set; }
}


text:
Q: SSIS 2016 - ErrorColumn is 0 (zero) I have a package with a bunch of oledb Destinations, using SSIS 2016 - which is supposed to show the exact column that generated the error.The ErrorColumn shows (0) zero, therefore I am unable to trap the column that generated the error.
Using the script below (with code that assigns "Unknown column" but it does not help, it just avoids the script fail):
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    //IDTSComponentMetaData130 componentMetaData = ComponentMetaData as IDTSComponentMetaData130;
    //var component130 = this.ComponentMetaData as IDTSComponentMetaData130;
    //if (component130 != null)
    //{
    //    System.Windows.Forms.MessageBox.Show(component130.GetIdentificationStringByID(Row.ErrorColumn));
    //    Row.ErrorColumnName = component130.GetIdentificationStringByID(Row.ErrorColumn);
    //}
    IDTSComponentMetaData130 componentMetaData = ComponentMetaData as IDTSComponentMetaData130;
    if (componentMetaData != null)
    {
        //
        if (Row.wkpErrorColumn != 0)
            Row.wkpErrorColumnName = componentMetaData.GetIdentificationStringByID(Row.wkpErrorColumn);
        else
            Row.wkpErrorColumnName = "Unknown column";
    }
    else
    {
        Row.wkpErrorColumnName = "Cannot determine";
    }
    Row.wkpErrorDescription = ComponentMetaData.GetErrorDescription(Row.wkpErrorCode);
}

A: In SSIS 2008 (and I believe also SSIS 2016), a zero error column identifies an error that affects the entire row. In the example below, I have created a package that contains only 1 data flow task in the control flow and redirecting all errors and truncations to the error output. Placed a row count task just to have somewhere to send them to.
Also placed data viewers in both error flows to see the data coming out of it.
In a package consuming data from a flat file into an OLE DB Destination:

Using these values as input data

And having name as the PK of the table

We get a PK violation, check the error description and the error column

So when the error affects the entire record, it gets an error column value of 0.
Hope this helps.

A: I found that
When the error is generated by the PK, the error affect the entire row, and the error column is 0
When the error is generated by a Fk, The error affect only the column, and you get the error column value different then 0


text:
Q: Group DriveItem not converting to PDF Microsoft Graph allows downloading documents and conversion to PDF. This functionality works well for me when downloading it from OneDrive for Business, but when used with Groups, the format parameter is ignored and I just get original content (no conversion).
A request with URL constructed as /drive/root:/{path and filename}:/content?format=pdf works and the doc is converted to PDF before downloading.
A request with a URL constructed  as /groups/{group-id}/drive/root:/{path and filename}:/content?format=pdf, however, ignores the conversion request.
I've tried with both /v1.0 and /beta endpoints.
Relevant API doc is Download the contents of a DriveItem and next topic for content conversion.


text:
Q: List in C# - passing multiple entries as a single object I have a method (C#)
public void MethodName(List<Order> Order, int ID)

I need to pass this to a main page, in which i know to pass integer value to ID, am not able to pass multiple items in a single list.
The List order should have two number entries, (ie. Order.number1 and Order.number2)
How should i pass a single list as a parameter to this method containing multiple entries of number1 and 2, so that i can loop thro' and find it.
Thanks.

A: If I understand this correctly, you have:
class Order
{
  public int number1 { get; set; }
  public int number2 { get; set; }
  ...
}

List<Order> orders = new List<Order>
{
  { number1 = 123, number2 = 234 },
  { number1 = 321, number2 = 432 }
};

You want to be able to search orders to find the one where number1 == ID || number2 == ID.  Assuming there is only one Order with the given ID or you are OK using the first one you find you can do:
public Order FindOrderById(List<Order> orders, int id)
{
  foreach (Order order in orders)
  {
    if (order.number1 == id || order.number2 == id)
    {
      return order;
    }
  }

  // None found.  Return null, throw exception, etc.
  return null;
}

...

List<Order> orders = new List<Order> { ... };
Order foundOrder = FindOrderById(orders, 123);
if (foundOrder == null)
{
  //Not found
}
else
{
  //Found
}

You can also use LINQ to shorten this dramatically.  I have included some variations.
List<Order> orders = new List<Order> { ... };
int id = 123;

// Throw exception if exactly one order was not found (none or more than one)
Order foundOrder = orders.Single(o => o.number1 == id || o.number2 == id);

// Return null if exactly one order was not found
Order foundOrder = orders.SingleOrDefault(o => o.number1 == id || o.number2 == id);

// Return all orders that matched
IEnumerable<Order> foundOrders = orders.Where(o => o.number1 == id || o.number2 == id);

A: You can use a class that implements the IList interface. Such as list.
You could do something like:
List<Order> myOrders = new List<Order>();

Then pass this in to the method.
Where Order is the order object that you are trying to access.

A: You can return a list from your method (if I'm understanding you correctly)
Edited now that I think I understand better
public void MethodName(List<item> order, int ID) {
foreach(Order O in Order)
  {
   RunQuery(O.num1, O.num2);
  }
}

Without some knowledge of how your database is set up it's tough to write the query code; I leave that to you.


text:
Q: Error when counting group by columns in Python-TypeError: only integer scalar arrays can be converted to a scalar index I want to count the duplicate rows per hour.
My data frame:
 hour         index    name
08:00:00      1442       x
08:45:00      3434       y
08:30:00      1442       x
08:00:00      1442       x
08:45:00      3434       y
08:00:00      1442       x

My code: I tried to group the data per hour and count. transform didn't help.
df_count= df.groupby('hour')[['index','name']].count()

This is the error:
TypeError: only integer scalar arrays can be converted to a scalar index

This is the output I want:
 hour         index    name   count
08:00:00      1442       x       3
08:30:00      1442       x       1
08:45:00      3434       y       2

A: I'm not sure what's going on with your data. When I set one up like this:
df = pd.DataFrame({
    'hour': ['08:00:00', '08:45:00', '08:30:00', '08:00:00', '08:45:00', '08:00:00'],
    'index': [1442, 3434, 1442, 1442, 3434, 1442],
    'name': ['x', 'y', 'x', 'x', 'y', 'x'],
})

Then your code works fine (it doesn't do what you want, but it runs without issues):
>>> df.groupby('hour')[['index','name']].count()
          index  name
hour
08:00:00      3     3
08:30:00      1     1
08:45:00      2     2

In any case, once you fix your DataFrame content, the following should get the expected result:
>>> df.groupby(['hour', 'index', 'name']).size()
hour      index  name
08:00:00  1442   x       3
08:30:00  1442   x       1
08:45:00  3434   y       2

You can also add: .to_frame('count').reset_index() if you like.


text:
Q: Squared Series Fourier
Possible Duplicate:
Fourier 1st step?

How to  find fourier transform of a series of the such form:
$$y_k=\left[f(x) \right]^{2},$$
but I am not sure of the step by step for going about this computation.
how is the first step??
thank you very much!!

A: Integration by parts.  You're doing an integral of the form
$$ \int (f(x))^2 \exp(i\xi x) dx $$
Let $u = (f(x))^2$ and $dv = \exp(i \xi x)$.


text:
Q: SAP UI5: Re-align simple form label and fields to left side I need to move all these highlighted elements to left side of the page(Screen attached). Below is the code for simple form in my xml view:
<---XML View--->

<f:SimpleForm id="SimpleFormDisplay354" minWidth="1024" maxContainerCols="3" editable="false" layout="ResponsiveGridLayout"
    title="{i18n>searchFormTitle}" labelSpanL="3" labelSpanM="3" emptySpanL="4" emptySpanM="4" columnsL="1" columnsM="1">
    <f:content>
     <Label text="{i18n>labelDate}" labelFor="datePickerId" design="Bold" >
      <layoutData>
       <l:GridData span="L2 M3 S6"/>
      </layoutData>
     </Label>
     <DatePicker id="datePickerId" visible="true" displayFormat="MMM dd,yyyy" valueFormat="dd-MM-yyyy" placeholder="{i18n>dateInput}"
      change="handleChange">
      <layoutData>
       <l:GridData span="L2 M3 S6"/>
      </layoutData>
     </DatePicker>
     <Button text="{i18n>search}" id="searchButton" width="50%" type="Emphasized" class="Button" press="OnDateSearch">
      <layoutData>
       <l:GridData span="L2 M3 S6"/>
      </layoutData>
     </Button>
    </f:content>
   </f:SimpleForm>

Can anyone help me with what GridData span setting I should make in order to move these elements to left most corner?
enter image description here

A: If you want to use the existing properties for the Grid Data, you can use indentL property.
<Label text="{i18n>labelDate}" labelFor="datePickerId" design="Bold" >
    <layoutData>
        <l:GridData span="L1 M3 S6" indentL="0"/>
    </layoutData>
</Label>

Give one column (out of 12) to your label and then indent it to 0 (span value=0 for the Large screen), similarly, you can do it for different screen sizes.

A: You have to set labelSpanL/labelSpanM to 1 or 2 to decrease left space, but SimpleForm always align the label to right and put colon ":" between Label and Control.
If labelSpan 1 or 2 dont resolve. The only way i know is trying use CSS.


text:
Q: cmake: how to pass a list of variables (from set) to code I have been experimenting a bit with cmake recently and came across the project definition, where you can specify the name, version, description and languages.
I then learned that you can pass this information to the code, to print for example when the program starts, with the following lines:
add_compile_definitions( PROJECT_NAME="${PROJECT_NAME}" )
add_compile_definitions( PROJECT_VERSION="${PROJECT_VERSION}" )
add_compile_definitions( PROJECT_DESCRIPTION="${PROJECT_DESCRIPTION}" )

I have been wondering how I can expand this to include the author's name(s) and/or license information. I started with the following:
set (
    PROJECT_AUTHORS
    fname1 lname1
    fname2 lname2
)
add_compile_definitions( PROJECT_AUTHORS="${PROJECT_AUTHORS}" )

This resulted in:
$ make src/main.i
Preprocessing C source to CMakeFiles/cmake_test.dir/src/main.c.i
/usr/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/usr/bin/sh: -c: line 1: syntax error: unexpected end of file
make[1]: *** [CMakeFiles/cmake_test.dir/build.make:87: CMakeFiles/cmake_test.dir/src/main.c.i] Error 1
make: *** [Makefile:187: src/main.c.i] Error 2

If I then change the definition line to add_compile_definitions( PROJECT_AUTHORS=${PROJECT_AUTHORS} ) (removed the "'s around the variable).
This results to just fname1 in the code (as plain text, not a string)...
I then changed the CMakeLists.txt to:
set (
    PROJECT_AUTHORS
    "fname1 lname1"
    "fname2 lname2"
)
add_compile_definitions( PROJECT_AUTHORS="${PROJECT_AUTHORS}" )

Which resulted in:
$ make src/main.i
Preprocessing C source to CMakeFiles/cmake_test.dir/src/main.c.i
/usr/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/usr/bin/sh: -c: line 1: syntax error: unexpected end of file
make[1]: *** [CMakeFiles/cmake_test.dir/build.make:87: CMakeFiles/cmake_test.dir/src/main.c.i] Error 1
make: *** [Makefile:187: src/main.c.i] Error 2

Any ideas or suggestions on how I could go about this?
For information:

*

*cmake --version -> cmake version 3.19.2

*gcc --version -> gcc.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0

*bash --version -> GNU bash, version 4.4.23(1)-release (x86_64-pc-msys)

A: Note that the compile definitions basically work like preprocessor #defines; you need to make sure the compiler will be able to use the valus in a menaningful way. Note using a list variable like
set (
    PROJECT_AUTHORS
    "fname1 lname1"
    "fname2 lname2"
)

in a string will result in the elements being semicolon separated; PROJECT_AUTHORS="${PROJECT_AUTHORS}" has the same effect as PROJECT_AUTHORS="fname1 lname1;fname2 lname2" and you probably won't be able to use fname1 lname1;fname2 lname2 somewhere in your code.
If you want to use a string, you need to make the quotation marks part of the compile definition.
target_compile_definitions(myTarget PRIVATE "PROJECT_AUTHORS=\"${PROJECT_AUTHORS}\"")

Depending on your requirements you may want to generate code instead though and write it to a source file:
set(PROJECT_INFO
"
#include <vector>
#include <string>

std::vector<std::string> GetProjectAuthors()
{
    return {"
)

foreach(_AUTHOR IN LISTS PROJECT_AUTHORS)
    set(PROJECT_INFO "${PROJECT_INFO}
        \"${_AUTHOR}\",")
endforeach()

set(PROJECT_INFO "${PROJECT_INFO}
    };
}
")

file(WRITE ${PROJECT_INFO_FILE} ${PROJECT_INFO})

A: I think a simple way would be to use a configure_file. Create a file:
# authors.h.in
#cmakedefine PROJECT_AUTHORS "@PROJECT_AUTHORS@"

Then:
$ cat CMakeLists.txt
cmake_minimum_required(VERSION 3.11)
project(test)
set(PROJECT_AUTHORS "fname1 lname1" "fname2 lname2")
configure_file(authors.h.in ${CMAKE_CURRENT_BINARY_DIR}/gen/authors.h)
add_executable(main main.c)
target_include_directories(main PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/gen)
include(CTest)
add_test(NAME main COMMAND main)

and:
#include <authors.h>
#include <stdio.h>
#include <string.h>
int main() {
    char authors[] = PROJECT_AUTHORS;
    for (char *author = strtok(authors, ";"); author; author = strtok(0, ";")) {
        printf("%s\n", author);
    }
}

and after compilation:
$ build_dir/main
fname1 lname1
fname2 lname2

The problem is the ; character that comes from concatenating the list variable in cmake into a string. Whereas ; is the separator of arguments in CMake. You could replace ; for example by \; and of course pass a value that is a C string literal. For example:
cmake_minimum_required(VERSION 3.11)
project(test)
set(PROJECT_AUTHORS "fname1 lname1" "fname2 lname2")
# TODO: I think also escape "" or for example newline
# ie preprocess the value so that all is nicely parsed
string(REGEX REPLACE ";" "\\\\;" val "${PROJECT_AUTHORS}")
add_executable(main main.c)
target_compile_definitions(main PRIVATE "PROJECT_AUTHORS=\"${val}\"")
include(CTest)
add_test(NAME main COMMAND main)

with same main.c except #include <authors.h> and it also works fine:
$ cmake -S . -B _build -G Ninja && cmake --build _build --verbose && ( cd _build && ctest -V )
...
[1/2] /usr/bin/cc -DPROJECT_AUTHORS="\"fname1 lname1;fname2 lname2\""   -MD -MT CMakeFiles/main.dir/main.c.o -MF CMakeFiles/main.dir/main.c.o.d -o
....
1: Test command: /tmp/10/_build/main
1: Test timeout computed to be: 1500
1: fname1 lname1
1: fname2 lname2
1/1 Test #1: main .............................   Passed    0.00 sec


text:
Q: How can I install my extension with the status disabled? This is my XML file for the extension:
<?xml version="1.0" encoding="UTF-8" ?>
<extension method="upgrade" type="component" version="2.5">
<name>CS_KIALAPLUGIN</name>
<creationDate>March 17 2013</creationDate>
<author>Complusoft</author>
<authorUrl>http://www.complusoft.es</authorUrl>
<copyright></copyright>
<license>http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL</license>
<version>2.0.22c</version>
<description>VMKIALA_PLUGIN_DESC</description>

<administration>
        <files>
                <filename>kialaplugin.php</filename>
        </files>

</administration>

</extension>

Im looking for a parameter that installs this extension disabled instead of enabled.

A: Finally got round to testing the code I send you earlier and it's working fine:
script.php
<?php
defined('_JEXEC') or die('Restricted access');

class com_kialapluginInstallerScript
{
    function install($parent)
    {
        echo '
Install Successful
';
    }

    function postflight( $type, $parent )
    {
        $db = JFactory::getDbo();

        $query = $db->getQuery(true);

        $fields = array(
            $db->quoteName('enabled') . ' = 0'
        );

        $conditions = array(
            $db->quoteName('element') . ' = ' . $db->quote('com_kialaplugin')
        );

        $query->update($db->quoteName('#__extensions'))->set($fields)->where($conditions);

        $db->setQuery($query);

        $result = $db->query();
    }
}

?>

Hope this helps and will send you the zip when you're back on chat

A: So such parameter exists in the xml file. So you have two main options

*

*You must either disable it in the Extension Manager Component of Joomla.

*You can perform a db request to unpublish the extension in the script file


text:
Q: LotusNotes: API support for directly uploading the ID file to Vault without saving it in a file When we register a user using Admin console of LotusNotes with IDVault configured, it asks if we want to set the location of the ID file for the user (we can browse and set the location of the file). If we do not select the check-box, it uploads the ID file in Vault and does not create it's copy anywhere else.
But, when we do it through the Registration class (JAVA API NCSO.jar), it asks for idfilepath paramter while registering the user(registerNewUser() method).
Is there any way by which we can programatically register the user with it's ID file directly getting uploaded in Vault and we do not have to provide the path for the directory?


text:
Q: changing view background according to value I want to have a textview which represents a rating, and I wanted the background to go from light to dark according to the value. meaning 1=white background and 5=red background. What do you think the best way of doing this would be?
Thanks
Amit

A: For binding BackgroundColor:

*

*MvvmCross includes a BackgroundColor binding and there is an example of it being used with a TextView in ValueConversion sample in View_Colors.axml
<TextView
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    local:MvxBind="BackgroundColor Color, Converter=NativeColor; Text Color; TextColor Color, Converter=ContrastColor"
/>

For converting from an int to an colo(u)r:

*

*I'd recommend you use a ValueConverter which inherits from MvxColorConverter.vs - e.g. something like:
     public void RatingColorConverter : MvxColorConverter
     {
         protected override MvxColor Convert(object value, object parameter, System.Globalization.CultureInfo culture)
         {
             switch ((int)value)
             {
                 case 1:
                    return new MvxColor(255,255,255);
                 case 2:
                    return new MvxColor(255,200,200);
                 // etc
             }
         }
     }


text:
Q: Problematic vertical alignment using cases and/or aligned environment I'd like for all of my minipages to be aligned at the top, but the cases environment is causing a few issues:

\documentclass{exam}

\usepackage{amsmath}

\begin{document}

\begin{figure}[h]

\begin{minipage}[t]{0.0075\textwidth}
\raggedright
(a)
\end{minipage}%
\hfill
\begin{minipage}[t]{0.6\textwidth}
\raggedright
{$\begin{aligned}[t]
f(x)
&= 6\biggl[1-\frac{x}{3}+\frac{x^2}{2!3^2}-\frac{x^3}{3!3^3}+
\cdots+\frac{(-1)^n x^n}{n!3^n}+\cdots\biggl]\\[0.5em]
&= 6-2x+\frac{x^2}{3}-\frac{x^3}{27}+\cdots+\frac{6(-1)^nx^n}{n!3^n}+\cdots
\end{aligned}$}
\end{minipage}%
\hfill
\begin{minipage}[t]{0.3\textwidth}
\raggedright
$3:\left\{\!\begin{aligned}
1 : & \text{two of}\ 6, -2x, \frac{x^2}{3}, -\frac{x^3}{27}\\
2 : & \text{remaining terms}\\
3 : & \text{general term}\\
\end{aligned}\right.$\newline

$\langle -1\rangle$ missing factor of 6
\end{minipage}

\end{figure}

\end{document}

I'd like for the curly brace in the right minipage to be at the same height as the large brackets for the expression contained in the middle minipage. Using either aligned (which is what I have above) or cases gives me the vertical alignment issue above. Is there an easy way to fix this?

A:
image of equations is obtain with use of \raisebox for last equation and tabularx instead of minipages (for slightly shorter code):
\documentclass{exam}
\usepackage{amsmath}
\usepackage{tabularx}

\begin{document}

\begin{figure}[ht]
\begin{tabularx}{\linewidth}{@{}l>{\hsize=0.6\hsize}X
                                 >{\hsize=0.3\hsize}X
                             @{} }
    \hline % remove in real document!
(a) &   $\begin{aligned}[t]
    f(x) & = 6\biggl[1-\frac{x}{3} + \frac{x^2}{2!3^2}-\frac{x^3}{3!3^3}+
            \cdots+\frac{(-1)^n x^n}{n!3^n}+\cdots\biggl]   \\
         &= 6-2x+\frac{x^2}{3}-\frac{x^3}{27}+\cdots+\frac{6(-1)^nx^n}{n!3^n}+\cdots
        \end{aligned}$
    &   \raisebox{-0.8\baselineskip}{$3:\begin{cases}
        1 : & \text{two of}\ 6, -2x, \frac{x^2}{3}, -\frac{x^3}{27}\\
        2 : & \text{remaining terms}\\
        3 : & \text{general term}
        \end{cases}$}
        \vspace{1ex}

        $\langle -1\rangle$ missing factor of 6
\end{tabularx}
\end{figure}

\end{document}


text:
Q: throw er; // Unhandled 'error' event . Loading images from MongoDB with a promise I am trying to load in data from MongoDB. I am very to new to "Promises". I am getting a "throw er; //Unhandled 'error event" exception thrown. What is wrong with my code? Is the promise handled correctly?
events.js:187
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::4000
    at Server.setupListenHandle [as _listen2] (net.js:1300:14)
    at listenInCluster (net.js:1348:12)
    at Server.listen (net.js:1436:7)
    at Function.listen (/Users/alexbrito/Documents/VisualStudioCode/theSkyDoesNotExist/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/Users/alexbrito/Documents/VisualStudioCode/theSkyDoesNotExist/server.js:40:5)

Images.controller.js
 const IMAGE_MODEL = require('./../model/Images.model');
    const MongoDatabase = require('./../MongoDatabase');

    let pathToImages = [];

    function getImages() {
      return new Promise((resolve, reject) => {
        if (MongoDatabase.openConnection) {
          resolve('Images inserted in array');
        } else {
          reject('Images were not inserted');
        }
      });
    }

    getImages()
      .then(fromResolve => {
        IMAGE_MODEL.find({}).exec((error, images) => {
          if (error) {
            console.log();
          } else {
            images.forEach(x => {
              pathToImages.push(x.path);
            });
            console.log(pathToImages);
            console.log(fromResolve);
          }
        });
      })
      .catch(fromReject => {
        console.log(fromReject);
      });

   module.exports.getImages = getImages;


text:
Q: Alias resource file namespace in C# I have an ASP.net MVC 3 project with resource files setup in folders like:
/Resources/EntityName/Views/
/Resources/EntityName/Models/

This means the namespace to access the strongly typed resource values is:
Resources.EntityName.Models.ModelA.Property1
Visual studio gives a compile time error if I try to include the namespace "resources.xxx" and it won't allow the using alias syntax either.
Is there anyway to include or atleast alias the strongly typed namespace of a resource file like it was a normal namespace?

A: There should be no reason why you can't use one of these objects within a class:
using YourProject.Resources.EntityName.Models;

A: You might try something like this (not tested, just an idea)
public class myModelA : Resources.EntityName.Models.ModelA
{ /*Leave empty here, nothing to do*/ }

Then you may be able to call the shortest myModelA instead of the complete, verbose name of the resource. Watch out because you'll not be able to access private members of your original model if you inherit it like thi.


text:
Q: Subtracting average values from columns in pandas DataFrame I am making a code in python with pandas dataframe that averages values in hourly data from 12am-3am for a month and then subtracts that monthly average from each column.  The code reads the data from a csv file.
Sample of data
DateTime         C1      C2      C3      C4      C5      V
11/1/2014 0:00  1.12    0.96    1.11    0.95    0.93    4.06
11/1/2014 1:00  1.12    0.96    1.11    0.95    0.93    4.06
11/1/2014 2:00  1.12    0.95    1.11    0.95    0.93    4.06
11/1/2014 3:00  1.12    0.95    1.11    0.95    0.93    4.06
11/1/2014 4:00  1.12    0.95    1.11    0.95    0.93    4.06
11/1/2014 5:00  1.12    0.95    1.11    0.95    0.93    4.06
11/1/2014 6:00  1.12    0.95    1.11    0.96    0.93    5.24
11/1/2014 7:00  1.14    0.96    1.12    0.98    0.95    498.64
11/1/2014 8:00  1.22    1.04    1.20    1.05    1.02    623.51
11/1/2014 9:00  1.46    1.28    1.43    1.27    1.25    641.80

So the code I am using to get the average is
df.ix[:,1:5].between_time('0:00', '3:00').resample('1M').mean()

This code gives me the average from 12-3am for the month for columns 1-5.  Now how can I subtract those average values from each value in columns 1-5?

A: Is this what you're looking for?
month_av = df.ix[:,1:5].between_time('0:00', '3:00').resample('1M').mean()
df.ix[:, 1:5] = df.ix[:, 1:5] - month_av.values


text:
Q: I need a one stop solution for my background image in CSS to be in the entire window of my computer and my cell phone I put this code in my demo .html file
body{
      background-image: url('https://i0.wp.com/www.socialnews.xyz/wp-content/uploads/2020/10/26/5573c6f0bee7ca021f4a8aecbaf6cbeb.jpg?quality=80&zoom=1&ssl=1');

     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
       background-size: cover;
       background-repeat: no-repeat;
       background-size:cover;
       background-position:relative;

 }

This image fills the entire Browser window in my desktop but I get some white space below this image when I try to run this code in my Google chrome in my cell phone. I need help regarding this matter

A: Add:
min-height: 100vh;
And background-position: center;
to your css.
Also you can use CSS Media queries to control behaviors on multiple screen sizes.

A: its all about
height:100%;
width:100%;

if the image is contained in something, make sure that has height and width set to 100% too.
then you set your html tag's style to have margin:0, and ur picture should cover the entire screen:
html, body {
   margin: 0;
}


text:
Q: Heroku apps automatically redirected to HTTPS I have a Rails 4 app, deployed on Heroku. I want my app to be served via pure HTTP, not HTTPS. So I haven't done anything special to configure HTTPS redirect (at least I think so). But nevertheless,
my app got a redirect to https every time I visit it. It behaves the same way in both cases, via subdomain.herokuapp.com and via my-subdomain.mydomain.tld, e.g. prepends https:// to the address. Which in turn (naturally) causes browser warnings about security.
Can I disable such behaviour?
By the way, mydomain.tld and www.mydomain.tld both work without this strange redirection, as well as a dummy app generated just for this purpose.

A: It caused by config.force_ssl = true in production.rb


text:
Q: EMF2DOMAdapterImpl_ERROR_0 Websphere Application Server WAS (V8.5) DeploymentDescriptorLoadException: WEB-INF/web.xml Websphere Application Server V 8.5 fails to startup with certain web.xml structure.

Current DOCTYPE uses http://java.sun.com/dtd/web-app_2_3.dtd .

A: This error mainly occurs when there is a problem with the web.xml deployment descriptor.
This problem is caused because of invalid tag in the web.xml which can be due to multiple different things such as:
There should be no duplicate tages for

*

*session-config

*welcome-file-list

*jsp-config

*login-config

*locale-encoding-mapping-list

Web.xml is not supposed to have multiple url-pattern under one servlet-mapping tag in deployment descriptor. If you have around 3 - 4 url-patterns under one servlet-mapping, move this to multiple servlet mapping containing one url-patterns.
For more debug information you can check the logs in AppServer\profiles\AppSrv01\logs\server1\SystemErr


text:
Q: How do you configure the FROM field in a jetty email configuration? I'm configuring version 1.4-M3 of Archiva running standalone with Jetty.
The configuration works (I get the emails). However, they're being reported from "root@localhost". As you can see in the configuration below I have mail.from defined, but somehow it is not being picked up. No mail header contains the address archiva@mymailserver.com.
What is the correct configuration so emails are shown as being sent from archiva@mymailserver.com?
  <New id="validation_mail" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>mail/Session</Arg>
<Arg>
  <New class="org.eclipse.jetty.jndi.factories.MailSessionReference">
    <Set name="user">myuser</Set>
    <Set name="password">OBF:1yxf1vnw1v1p1vu51vv51v2p1vn61ym5</Set>
    <Set name="properties">
      <New class="java.util.Properties">
        <Put name="mail.smtp.host">mail.server</Put>
        <Put name="mail.smtp.auth">true</Put>
        <Put name="mail.port">25</Put>
        <Put name="mail.from">archiva@mymailserver.com</Put>
        <Put name="mail.mime.address.strict">false</Put>
        <Put name="mail.debug">false</Put>
        <Put name="mail.transport.protocol">smtp</Put>
      </New>
    </Set>
  </New>
</Arg>

A: According to Archiva's documentation, the email address is configured using the following property:

*

*email.from.address=$user.name@localhost
  Blockquote

*

*All emails sent by the system will be from the following address

As of Archiva 2.1.x and 2.2.x, I don't see that property listed within the Properties tab of the Users Runtime Configuration section.  That means that you'll need to manually set this property in archiva.xml.  In case you're using a servlet container, such as Tomcat, I don't mean the archiva.xml that's located within conf/Catalina/localhost.  I'm referring to the archiva.xml that's located immediately within the conf directory.
Source - Archiva's Email Configuration page


text:
Q: Multiple Businesses and addresses that are no longer in business but I can't get them off google maps I own or have been part of three separate businesses. One of those I have moved three times. Each time I try to change the location of the business.  I've had mixed success, currently google is asking me to verify the new business location by sending a postcard to the old location.  I'm not there any more and have no way of getting the postcard, and they won't let me change the info or delete the old addresses.  Please help, I just want my business to show up where I'm actually operating so people can find me, and I want my old locations listed as permanently closed at the very least.  One of the businesses still exists, moved to a different location, and I'm not part of it, but I'm still the person managing it.
I've tried using the available google business editing, but when I suggest a business is closed or moved it doesn't change anything.


text:
Q: How to move the marker in Google map when the latitude and longitude changes in webservices? In my application am plotting a set of latitude and longitude from web services to  Google map but when the Latitude and longitude changes in the web services the marker is not moving. when I close and open the application  it updates the changes, but I need to move the marker without closing and restarting the application. My Updated code is given below .
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);

        MapsInitializer.initialize(getActivity());

        mMapView = (MapView)rootView.findViewById(R.id.mapView);
        mMapView.onCreate(mBundle);

        MapsInitializer.initialize(getActivity());

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        /* new DownloadJSON().execute();
        setUpMapIfNeeded(rootView); */
        /*
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                 new DownloadJSON().execute();
                    setUpMapIfNeeded(rootView);

                 Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
                 Log.d("Data in Log", "");
            }
        }, 10*1000);*/

        new DownloadJSON().execute();
        setUpMapIfNeeded(rootView);

        LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        //locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
        locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 000, 10, this);

        return rootView;
    }

    private void setUpMapIfNeeded(View inflatedView) {
        if (mMap == null) {
            mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
            mMap.setMyLocationEnabled(true);

            Location myLocation = mMap.getMyLocation();
            if (mMap != null) {
                // setUpMap();
                mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                    @Override
                    public void onMyLocationChange(Location arg0) {

                        // TODO Auto-generated method stub

                        final LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (int i = 0; i < arraylist1.size(); i++) {
                            final LatLng position = new LatLng(Double
                                    .parseDouble(arraylist1.get(i).get("Latitude")),
                                    Double.parseDouble(arraylist1.get(i).get(
                                            "Longitude")));
                            String ime1 = arraylist1.get(i).get("IME");
                            final MarkerOptions options = new MarkerOptions()
                            .position(position);

                            mMap.addMarker(options);
                            mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
                            //options.title(ime1);
                            builder.include(position);
                        }
                        LatLng latLng = new LatLng(arg0.getLatitude(), arg0
                                .getLongitude());

                        mMap.setMyLocationEnabled(true);

                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                        // mMap.setOnMapClickListener(null);
                        mMap.setOnMarkerClickListener(null);

                        mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
                    }
                });

            }
        }
    }

    /*  protected void retrieveAndAddCities() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {

            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        new DownloadJSON().execute();

    } */

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {
        String result="";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                arraylist1 = new ArrayList<HashMap<String, String>>();

                JSONParser jParser = new JSONParser();
                String result = "";

                json = jParser.getJSONFromUrl(SERVICE_URL);

                try {
                    arraylist1.clear();

                    jsonarray = json.getJSONArray("SingleIMEs");
                    Log.d("Haaaaaaaaaaaa", "" + json);

                    for (int i = 0; i < jsonarray.length(); i++) {
                        Log.d("H11111111111111111111111111",
                                "" + jsonarray.length());
                        map = new HashMap<String, String>();
                        json = jsonarray.getJSONObject(i);

                        // pubname = json.getString("PubName");
                        latitude = json.getDouble("Latitude");
                        longitude = json.getDouble("Longitude");
                        ime = json.getString("IME");
                        //  map.put("PubName", json.getString("PubName"));
                        //map.put("PubID", json.getString("PubID"));
                        map.put("Latitude", json.getString("Latitude"));
                        map.put("Longitude", json.getString("Longitude"));
                        map.put("IME", json.getString("IME"));
                        arraylist1.add(map);
                    }

                } catch (JSONException e) {
                    Log.e("log_tag", "Error parsing data " + e.toString());
                    result="Error";
                    e.printStackTrace();
                }
            }catch(Exception e){
                result="Error";
            }

            return null;
        }

        protected void onPostExecute(Void args) {

            // mProgressDialog.dismiss();

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
        Log.d("onLocationUpdated!!!","");
        new DownloadJSON().execute();
        setUpMapIfNeeded(rootView);

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {

        // TODO Auto-generated method stub

    }

}

A: You can use handler for updating the location.Inside run() just call that webservice.And just put the marker in current location.
// Call current location API after 3 Min
    handler.postDelayed(run, 3000 * 60);

    Runnable run = new Runnable() {
            @Override
            public void run() {
                if (isConnected(context)) {
                    new CurrentPosTask().execute();
                } else {
                    Toast.makeText(context, "No internet connection",
                            Toast.LENGTH_LONG).show();
                }

            }
        };

Don't forget call below method into onDestroy() method
 // Stop the handler
        handler.removeCallbacks(run);

Hope it will help you. Let me know once done.

A: You have to set repeat alarm to check the web service at intervel
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() +
    60 * 1000, alarmIntent);

 // Set the alarm to start at approximately 2:00 p.m.
 Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(System.currentTimeMillis());
 calendar.set(Calendar.HOUR_OF_DAY, 14);

// With setInexactRepeating(), you have to use one of the AlarmManager     interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,   calendar.getTimeInMillis(),
    5000, alarmIntent);

and in alarm reciever class call web service and update the map position
public class AlarmReceiverextends WakefulBroadcastReceiver {
    new DownloadJSON().execute();
    setUpMapIfNeeded(rootView);
}

for full tutorial look developers.android
https://developer.android.com/training/scheduling/alarms.html


text:
Q: Redirecting is not properly in django admin panel I have a method that has the task of redirecting the page in the admin panel from:
http://127.0.0.1:8000/admin/events/event/

to:
http://127.0.0.1:8000/admin/events/event/?date__lt=2018-6-11

I got an information instead of page:
The page isn't redirecting properly

Here is my code:
admin.py
First version of code:
def changelist_view(self, request, extra_context=None):
    if not request.method != 'GET':
        url = '{}?date__lt={}'.format(reverse('admin:events_event_changelist'), date.today())
        return HttpResponseRedirect(url)

code after edit
def changelist_view(self, request, extra_context=None):
    q = request.GET.get('date')
    if not q:
        url = '{}?date__lt={}'.format(reverse('admin:events_event_changelist'), date.today())
        return HttpResponseRedirect(url)

Please some hint where can be a wrong code.

A: The error message your browser is showing indicates that your site is stuck in an infinite redirect loop. Looking at your condition, it is clear why:
if not request.method != 'GET':

is equivalent to
if request.method == 'GET':

A redirect always results in a GET request, so your view will redirect again and again...
I assume what you actually want to achieve is to redirect only if there is no URL parameter. Those are stored in request.GET, so your condition would look like this:
if not request.GET:

A: If you always want to restrict the events that you display, it might be easier to override the get_queryset method instead of redirecting.
class EventAdmin(admin.modelAdmin):
    def get_queryset(self, request):
        qs = super(EventAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            # Allow superusers to see all events
            return qs
        else:
            return qs.filter(date__lt=date.today())

admin.site.register(Event, EventAdmin)


text:
Q: What's wrong with my array_chunk? Someone showed me how to use PHP's array_chunk feature @ Splitting Display into 3 or 4 equal columns The general consensus was that my question was answered, and the problems I was still having had something to do with my database or code. I wasn't sure if I should ask another question there or start a new thread.
Anyway, I continued working on my code and have actually made some small improvements, but the main problems are still there: 1) I can't control the number of columns that display; if I set the value at 2, it will display four columns; 2) it alphabetizes the data HORIZONTALLY. For example, the first word in each column ends with an A (e.g. Adams, Akron, Ammon and Azazi), and the last word in each column ends with W.
I'd like to alphabetize the first column FIRST; if the last word in that column is Bruin, then the first word in the second column should be whatever comes next (e.g. Cato). And if the last word in the second column is Marsh, then the first word in the third column might be Marto. In other words, it flows from top to bottom, one column at a time.
I pasted my query into phpMyAdmin > SQL and it displays perfectly. I also echoed this...
echo join($List)

above the foreach statement, and it displays a single column in alphabetical order.
So my best guess is that the problem is in one of these two lines of code:
$roster_chunks = array_chunk($List, $how_many_chunks, true);

foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value)

Can anyone see what I did wrong? I posted the entire code below.

$stm = $pdo->prepare("SELECT P.N, P.URL, P.Title, P.Site, P.Live,
 PB.Common, ART.URL, ART.Site, ART.Brief, ART.Article
 FROM people P
 LEFT JOIN people_bios PB ON PB.URL = P.URL
 LEFT JOIN people_articles ART ON ART.URL = P.URL
 WHERE P.Site = 'PX' AND ART.Site = 'PX' AND ART.Brief !='' AND P.Live = 1
 ORDER BY P.N");
 $stm->execute(array(
));

while ($row = $stm->fetch()) {
   $URL = $row['URL'];
   $Common = $row['Common'];

   $List[] = ''.$Common.'
';
}

// Set how many chunks you want to break the array into.
$how_many_chunks = 3;

// Break the '$Roster' array into '$roster_chunks'
$roster_chunks = array_chunk($List, $how_many_chunks, true);

// Roll through the '$roster_chunks'
foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) {
    echo '
';
    echo join($roster_chunk_value);
    echo '
';
}

A: In that case, array_chunk() is not for you.
array_chunk() will give you
1 2 3
4 5 6
7 8 9

While  you want
1 4 7
2 5 8
3 6 9

You need to make a custom function that will split your array into arrays in this way. array_chunk() will not help you if that's how you want to order it.


text:
Q: How to package a python project that depends on an external executable? I'm writing python bindings for an executable written in haskell. How should I handle the dependency on the executable regarding packaging and distribution ?
I could just write the python packages that calls the external command as a supbrocess and crash if it's not found at runtime, but is there a solution that either:

*

*check during package installation that the executable is available on the host,

*triggers the installation of the executable if it is not found

I couldn't find any in the python packaging documentations.
Should this be handled one level up, for example at the os distribution level (apt, nix, docker,…) ?


text:
Q: Data from MySQL changing from no data into zero I have this table of "score" in my database
!  id   !  A   !
-----------------
!  01   !  10  !
!  02   !      !
!  03   !      !
!  04   !  5   !

$mySql = "SELECT score.id, score.A
          FROM score
          ORDER BY score.id ASC";
$myQry = mysql_query($mySql, $koneksidb)  or die ("Query salah : ".mysql_error());
    while ($myData = mysql_fetch_array($myQry)) {
        $id=$myData['id'];
        $A=$myData['A'];
 }

When I call with
<?php echo $A; ?>

It came out with zero instead of no data,
!  id   !  A   !
-----------------
!  01   !  10  !
!  02   !  0   !
!  03   !  0   !
!  04   !  5   !

What should I change?

A: Well if they are null values they will be echoed as 0.
You can do this ternary hack:
<?php echo ($A==0)?' ':$A; ?>

I didn't test, but I believe it will work. Maybe you could do that, also:
<?php echo (isset($A))?$A:' '; ?>

Also, quit using mysql_* functions, please!

A: That's all right. Simplify,
$any_empty_var == false == 0

So, you can just add the condition
if ($A == 0) echo " ";
else echo $A;

A: !.) You should use mysqli as mysql is obsolete.
2.) set score.A so that it can simple diplay null values
ALTER TABLE score CHANGE A INT(11) NULL;
the mysql will return a  null value


text:
Q: Trying to do a NOT IN query I am new to SQL and I am trying to design a database in relation to a vehicle leasing company. At the moment I am trying to check if a vehicle is available for renting (i.e. has it been rented out already). I have two different tables one for bookings where the dates of the vehicle being rented is being stored and then one for where all my vehicles are being stored. I think I currently got them to connect but can't seem to get the dates to work for me so I must have something wrong.  I will also include a picture of the tables so you can see where I am getting the field names from. Any help is much appreciated.
Table fields name
 SELECT *
 FROM Vehicles
 WHERE Vehicles.vehicle_id NOT IN (
 SELECT Booking.[vehicle id]
 FROM Booking
 WHERE (
    [Enter Start Date] BETWEEN booking.start_rent_date
        AND booking.end_rent_date
    )
 OR (
    [Enter End Date] BETWEEN booking.start_rent_date
        AND booking.end_rent_date
    )
  );

A: The main issue I see is that you're testing whether the start date or the end date occurs within the booking period, but you probably should be checking whether the period [start_date, end_date] overlaps the booking period at all.  If that accounts for the error you're seeing, then try changing the date logic in the inner query to
    start_date <= booking.enter_end_date
and end_date >= booking.enter_start_date

If that's not the issue, then you probably need to be more specific about what you're getting and how it differs from what you expect.

A: Shouldn't it be Booking.vehicle_id
SELECT *  FROM Vehicles
WHERE Vehicles.vehicle_id NOT IN (
SELECT Booking.vehicle_id
FROM Booking
WHERE (
        start_date BETWEEN booking.enter_start_date
            AND booking.enter_end_date
        )
    OR (
        end_date BETWEEN booking.enter_start_date
            AND booking.enter_end_date
        )
    OR (
        booking.enter_start_date BETWEEN start_date
           AND end_date
    )
);


text:
Q: Conditions that imply $P(A \cap B) = P(B)$ Am trying to figure out if all three of these expressions:
1) $B \subseteq A$
2) $B \subset A$
3) $B = A$
imply that 4) $P(A \cap B) = P(B)$  ?
My thinking is as follows:
1) follows from here
2) is just a more restricted condition than 1), so the implication should hold here as well.
3) because if B = A, then P(A) = P(B) = $P(A \cap B)$
I can't see why 1-3 would not imply 4) from my by Venn diagram sketches except if I'm not handling the case where A is the empty set.  If I'm missing something, could someone set me straight?

A: If $B\subseteq A$, then $A\cap B = B$. The same applies to the other two conditions. Thus, if any of them is satisfied, then you have $\textbf{P}(A\cap B) = \textbf{P}(B)$. In order to prove it, you may consider the following reasoning. Clearly, $A\cap B\subseteq B$. Based on the assumption of $B\subseteq A$, one has
\begin{align*}
x\in B \Longrightarrow x\in A\Longrightarrow x\in A\cap B \Longrightarrow (B\subseteq A\cap B).
\end{align*}
from whence it results that $A\cap B = B$.


text:
Q: Cadastrar no Spring Boot Boa Tarde pessoal.
Estou tendo dificuldades pra implementar o meu Cadastrar no Spring Boot. Estou querendo fazer o método com três formas(if,else if,else) que se estiver tudo certo ele cadastra, que se já existir alguém com aquele email então da "Existente" e o erro qualquer é "Inválido". Porém não esta funcionando, o método que eu fiz pra ver se já existe no banco a Pessoa que estou cadastrando esta correto? Alguém pode me ajudar como eu coloco mensagem e se o código esta certo ou se tem algum jeito de melhorar. Obrigado.

Repository.
String findByEmail(String email)

------
Controller.

@PostMapping
public ResponseEntity<Pessoa> cadastrar(@RequestBody Pessoa p) {
        if(p.getEmail() == repository.findByEmail(p.getEmail())){
            return ResponseEntity.status(400).build();
        }else if(p != null) {
            return ResponseEntity.ok().body(repository.save(p));
        }else {
            return ResponseEntity.badRequest().build();
        }
    }

A: Oi,
Eu não colocaria essa lógica de existente ou novo cadastro no mesmo serviço (rest) eu acho que o controller deveria ter um método para cadastrar novo (POST) e um método para atualizar um existente (PUT), até mesmo para aproveitar a semantica (significado dos métodos HTTP, PUT = atualizar, POST = inserir, DELETE = remover, etc)
Ficaria algo assim
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> cadastrar(@RequestBody Pessoa p) {
    try {
        Pessoa novaPessoa = service.save(p);
        return ResponseEntity.created(new URI("/pessoas/" + novaPessoa.getId())).build();
    } catch (Exception e) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "Ocorreu um erro ao tentar salvar uma essoa", e);
    }
}

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> atualizar(@RequestBody Pessoa p, @PathVariable("id") Integer id) {
    try {
        p.setId(id);
        service.save(p);
        return ResponseEntity.noContent().build();
    } catch (Exception e) {
        throw new ResponseStatusException(HttpStatus..BAD_REQUEST,
                "Ocorreu um erro ao tentar atualizar os dados da pessoa de id " + id, e);
    }
}

E para testar a sua API
POST /pessoas - adiciona uma pessoa
PUT /pessoas/{1} - atualiza os dados da pessoa de id 1


text:
Q: Intellij 13.1.2 not unpacking exploded (sub-) artifacts With Intellij < 13.1.2 we were able to locally have a exploded artifact with exploded subartifacts for development, the actual version 13.1.2 is putting out *.jar and *.war files instead of directories.
I found this workaround in their bugtracker: http://youtrack.jetbrains.com/issue/IDEA-124353
but was wondering how to achieve this for all modules, instead of having to list all of them?

A: Ok, I found my workaround by adding a maven profile for intellij and enabling it:
 <profiles>
        <profile>
            <id>intellij</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-ear-plugin</artifactId>
                        <configuration>
                            <unpackTypes>war,ejb</unpackTypes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>


text:
Q: Type constraint for C# class I am trying to write a matrix class in C#, and want to cover just integral types. Yes, I know, there are probably a bunch of other libraries out there that provide this functionality already - I just wanted to give it a try myself to apply some of the math I'm learning in school.
Anyway, the real problem here: I have my constructor:
public class Matrix {
    private int[,]    __matrix;

    Matrix(int rows, int columns) {
        /* ... some logic here ... */
        __matrix = new int[row , columns];
    }
}

I know you can constrain to just structs, but that also means that things like DateTime could end up in the matrix. Any suggestions on how to solve this, or has anyone seen this done elsewhere? I was thinking of writing a generic class, but I'm almost leaning on an attribute that declares allowable types, and then just checking that attribute in code at this point, but am also not at all stoked about the prospect of the boxing/unboxing overhead of using an object[] for my matrix.

A: You won't be able to simply restrict to Int32, or any of these primitive numeric types.
Take a look at this question: Is there a constraint that restricts my generic method to numeric types?
The workaround seems way more complicated than we would expect. Deferring arithmetic operations to some other generic class...
Read on for more details.


text:
Q: How does the CPU and GPU interact in displaying computer graphics? Here you can see a screenshot of a small C++ program called Triangle.exe with a rotating triangle based on the OpenGL API.

Admittedly a very basic example but I think it's applicable to other graphic cards operations.
I was just curious and wanted to know the whole process from double clicking on Triangle.exe under Windows XP until I can see the triangle rotating on the monitor. What happens, how do CPU (which first handles the .exe) and GPU (which finally outputs the triangle on the screen) interact?
I guess involved in displaying this rotating triangle is primarily the following hardware/software among others:
Hardware

*

*HDD

*System Memory (RAM)

*CPU

*Video memory

*GPU

*LCD display

Software

*

*Operating System

*DirectX/OpenGL API

*Nvidia Driver

Can anyone explain the process, maybe with some sort of flow chart for illustration?
It should not be a complex explanation that covers every single step (guess that would go beyond the scope), but an explanation an intermediate IT guy can follow.
I'm pretty sure a lot of people that would even call themselves IT professionals could not describe this process correctly.

A: To keep things simple we can describe it like this. Some memory addresses are reserved (by BIOS and/or operating system) not for RAM but for the video card. Any data written at those values (pointers) goes to the card. So in theory any program can write directly to the videocard just by knowing the address range and this is exactly how it was done back in the old days. In practice with modern OSes this is managed by the video driver and/or the graphics library on top (DirectX, OpenGL etc.).

A: GPUs are usually driven by DMA buffers. That is, the driver compiles the commands it receives from the user space program into a stream of instructions (switch state, draw this in that way, switch contexts, etc.), that are then copied to device memory. It then instructs the GPU to execute this command buffer via a PCI register or similar methods.
So on every draw call etc. what happens is that the user space driver will compile the command, which then calls the kernel space driver via an interrupt and that one finally submits the command buffer to device memory and instructs the GPU to start rendering.
On consoles you even can have the fun to do all of that yourself, especially on PS3.

A: I decided to write a bit about the programming aspect and how components talk to each other. Maybe it'll shed some light on certain areas.
The Presentation
What does it take to even have that single image, that you posted in your question, drawn on the screen?
There are many ways to draw a triangle on the screen. For simplicity, let's assume no vertex buffers were used. (A vertex buffer is an area of memory where you store coordinates.) Let's assume the program simply told the graphics processing pipeline about every single vertex (a vertex is just a coordinate in space) in a row.
But, before we can draw anything, we first have to run some scaffolding. We'll see why later:
// Clear The Screen And The Depth Buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Reset The Current Modelview Matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// Drawing Using Triangles
glBegin(GL_TRIANGLES);

  // Red
  glColor3f(1.0f,0.0f,0.0f);
  // Top Of Triangle (Front)
  glVertex3f( 0.0f, 1.0f, 0.0f);

  // Green
  glColor3f(0.0f,1.0f,0.0f);
  // Left Of Triangle (Front)
  glVertex3f(-1.0f,-1.0f, 1.0f);

  // Blue
  glColor3f(0.0f,0.0f,1.0f);
  // Right Of Triangle (Front)
  glVertex3f( 1.0f,-1.0f, 1.0f);

// Done Drawing
glEnd();

So what did that do?
When you write a program that wants to use the graphics card, you'll usually pick some kind of interface to the driver. Some well known interfaces to the driver are:

*

*OpenGL

*Direct3D

*CUDA

For this example we'll stick with OpenGL. Now, your interface to the driver is what gives you all the tools you need to make your program talk to the graphics card (or the driver, which then talks to the card).
This interface is bound to give you certain tools. These tools take the shape of an API which you can call from your program.
That API is what we see being used in the example above. Let's take a closer look.
The Scaffolding
Before you can really do any actual drawing, you'll have to perform a setup. You have to define your viewport (the area that will actually be rendered), your perspective (the camera into your world), what anti-aliasing you will be using (to smooth out the edged of your triangle)...
But we won't look at any of that. We'll just take a peek at the stuff you'll have to do every frame. Like:
Clearing the screen
The graphics pipeline is not going to clear the screen for you every frame. You'll have to tell it. Why? This is why:

If you don't clear the screen, you'll simply draw over it every frame. That's why we call glClear with the GL_COLOR_BUFFER_BIT set. The other bit (GL_DEPTH_BUFFER_BIT) tells OpenGL to clear the depth buffer. This buffer is used to determine which pixels are in front (or behind) other pixels.
Transformation

Image source
Transformation is the part where we take all the input coordinates (the vertices of our triangle) and apply our ModelView matrix. This is the matrix that explains how our model (the vertices) are rotated, scaled, and translated (moved).
Next, we apply our Projection matrix. This moves all coordinates so that they face our camera correctly.
Now we transform once more, with our Viewport matrix. We do this to scale our model to the size of our monitor. Now we have a set of vertices that are ready to be rendered!
We'll come back to transformation a bit later.
Drawing
To draw a triangle, we can simply tell OpenGL to start a new list of triangles by calling glBegin with the GL_TRIANGLES constant.
There are also other forms you can draw. Like a triangle strip or a triangle fan. These are primarily optimizations, as they require less communication between the CPU and the GPU to draw the same amount of triangles.
After that, we can provide a list of sets of 3 vertices which should make up each triangle. Every triangle uses 3 coordinates (as we're in 3D-space). Additionally, I also provide a color for each vertex, by calling glColor3f before calling glVertex3f.
The shade between the 3 vertices (the 3 corners of the triangle) is calculated by OpenGL automatically. It will interpolate the color over the whole face of the polygon.
Interaction
Now, when you click the window. The application only has to capture the window message that signals the click. Then you can run any action in your program you want.
This gets a lot more difficult once you want to start interacting with your 3D scene.
You first have to clearly know at which pixel the user clicked the window. Then, taking your perspective into account, you can calculate the direction of a ray, from the point of the mouse click into your scene. You can then calculate if any object in your scene intersects with that ray. Now you know if the user clicked an object.
So, how do you make it rotate?
Transformation
I am aware of two types of transformations that are generally applied:

*

*Matrix-based transformation

*Bone-based transformation

The difference is that bones affect single vertices. Matrices always affect all drawn vertices in the same way. Let's look at an example.
Example
Earlier, we loaded our identity matrix before drawing our triangle. The identity matrix is one that simply provides no transformation at all. So, whatever I draw, is only affected by my perspective. So, the triangle will not be rotated at all.
If I want to rotate it now, I could either do the math myself (on the CPU) and simply call glVertex3f with other coordinates (that are rotated). Or I could let the GPU do all the work, by calling glRotatef before drawing:
// Rotate The Triangle On The Y axis
glRotatef(amount,0.0f,1.0f,0.0f);

amount is, of course, just a fixed value. If you want to animate, you'll have to keep track of amount and increase it every frame.
So, wait, what happened to all the matrix talk earlier?
In this simple example, we don't have to care about matrices. We simply call glRotatef and it takes care of all that for us.

glRotate produces a rotation of angle degrees around the vector x y z . The current matrix (see glMatrixMode) is multiplied by a rotation matrix with the product replacing the current matrix, as if glMultMatrix were called with the following matrix as its argument:
x 2  1 - c + c x  y  1 - c - z  s x  z  1 - c + y  s 0 y  x  1 - c + z  s y 2  1 - c + c y  z  1 - c - x  s 0 x  z  1 - c - y  s y  z  1 - c + x  s z 2  1 - c + c 0 0 0 0 1

Well, thanks for that!
Conclusion
What becomes obvious is, there's a lot of talk to OpenGL. But it's not telling us anything. Where is the communication?
The only thing that OpenGL is telling us in this example is when it's done. Every operation will take a certain amount of time. Some operation take incredibly long, others are incredibly quick.
Sending a vertex to the GPU will be so fast, I wouldn't even know how to express it. Sending thousands of vertices from the CPU to the GPU, every single frame, is, most likely, no issue at all.
Clearing the screen can take a millisecond or worse (keep in mind, you usually only have about 16 milliseconds of time to draw each frame), depending on how large your viewport is. To clear it, OpenGL has to draw every single pixel in the color you want to clear to, that could be millions of pixels.
Other than that, we can pretty much only ask OpenGL about the capabilities of our graphics adapter (max resolution, max anti-aliasing, max color depth, ...).
But we can also fill a texture with pixels that each have a specific color. Each pixel thus holds a value and the texture is a giant "file" filled with data. We can load that into the graphics card (by creating a texture buffer), then load a shader, tell that shader to use our texture as an input and run some extremely heavy calculations on our "file".
We can then "render" the result of our computation (in the form of new colors) into a new texture.
That's how you can make the GPU work for you in other ways. I assume CUDA performs similar to that aspect, but I never had the opportunity to work with it.
We really only slightly touched the whole subject. 3D graphics programming is a hell of a beast.

Image Source

A: It's hard to understand exactly what it is you don't understand.
The GPU has a series of registers that the BIOS maps. These permit the CPU to access the GPU's memory and instruct the GPU to perform operations. The CPU plugs values into those registers to map some of the GPU's memory so that the CPU can access it. Then it loads instructions into that memory. It then writes a value to a register that tells the GPU to execute the instructions the CPU loaded into its memory.
The information consists of the software that the GPU needs to run. This software is bundled with the driver and then the driver handles the responsibility split between the CPU and GPU (by running portions of its code on both devices).
The driver then manages a series of "windows" into GPU memory that the CPU can read from and write to. Generally, the access pattern involves the CPU writing instructions or information into mapped GPU memory and then instructing the GPU, through a register, to execute those instruction or process that information. The information includes shader logic, textures, and so on.

A:
I was just curious and wanted to know the whole process from double clicking on Triangle.exe under Windows XP until I can see the triangle rotating on the monitor. What happens, how do CPU (which first handles the .exe) and GPU (which finally outputs the triangle on the screen) interact?

Let's take the assumption you actually know how an executable runs on an operating system and how that executable is sent from your GPU to the monitor, but don't know about what is happening in between. So, let's take a look from a hardware aspect and extend further on the programmer aspect answer...
What is the interface between CPU and GPU?
Using a driver, the CPU can talk through motherboard features like PCI to the graphics card and sent commands to it to execute some GPU instructions, access / update the GPU memory, load in a code to be executed on the GPU and more...
But, you can't really talk straight to the hardware or driver from code; so, this will have to happen through APIs like OpenGL, Direct3D, CUDA, HLSL, Cg. While the former run GPU instructions and / or update the GPU memory, the latter will actually execute code on the GPU as they are physics / shader languages.
Why run code on the GPU and not on the CPU?
While the CPU is good at running our daily workstation and server programs, there wasn't thought much about all those shiny graphics you see in games of these days. Back in the days there were software renderers which did the trick from some 2D and 3D things, but they were very limiting. So, here is where the GPU came into play.
The GPU is optimized for one of the most important calculations in graphics, Matrix Manipulation. While the CPU has to compute each multiplication in a matrix manipulation one-by-one (later, things like 3DNow! and SSE catched up), the GPU can do all those multiplications at once! Parallelism.
But parallel computations isn't the only reason, another reason is that the GPU is much closer to the video memory which makes it much faster than having to do round trips through the CPU, etc...
How do these GPU instructions / memory / code show graphics?
There is one missing piece to make this all work, we need something we can write to which we can then read and sent to the screen. We can do this by creating a framebuffer. Whatever operation you do, you will eventually update the pixels in the framebuffer; which besides location also hold information about color and depth.
Let's give you an example where you wanted to draw a blood sprite (an image) somewhere; first, the tree texture itself is loaded into GPU memory which makes it easy to redraw it at wish. Next, to do actually draw the sprite somewhere we can translate the sprite using vertexes (putting it in the right position), rasterising it (turning it from a 3D object into pixels) and update the framebuffer. To get a better idea, here is an OpenGL pipeline flow chart from Wikipedia:

This is the main gist of the whole graphics idea, more research is homework for the reader.

A: I think the CPU sends video data to GPU through the bus and then GPU displays it. So faster GPU can handle more data from the CPU. In this way some of the processing of cpuoffload to GPU. Therefore you get faster speed in games.
It's kind of like the  RAM where CPU stores stuff so it can load  and process quickly. Both make games faster.
Or sound card or net card work on same principle, that is get data and offload some work of CPU.

A: I think op isn't sure what exactly the cpu is telling the graphics card to do and why the graphics related commands(like opengl or direct3d commands) aren't sent directly to the GPU.
The CPU just tells the GPU what to render.  All instructions first go through the CPU where they get setup/initialized for the GPU to actually do rendering.


text:
Q: When I do command as "npm install" it comes npm ERR code ENOENT npm ERR npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\hp\Downloads\Direct-messaging-app-app/package.json npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\hp\Downloads\Direct-messaging-app-app\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent
npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\hp\AppData\Local\npm-cache_logs\2022-11-24T06_46_21_615Z-debug-0.log
this is the problem, because of this I cant command npm Install Npm

A: Are you sure you in the right folder?? because it seems like you running the npm in Direct-messaging-app-app folder and npm not able to find the package.json file in it , that's why you getting this error I think
you need to be in chat-app folder or where your package.json file is , to run the npm command


text:
Q: Flex 3.5 Validator Error Message Repeats Anybody have any idea why the error message repeats in Flex SDK 3.5 (but not in 3.4) and have a good way to make it stop repeating? See screenshots:

You can also see the different apps here:
http://www.flexdevelopers.com/examples/validator/3.4/Tester.html
http://www.flexdevelopers.com/examples/validator/3.5/Tester.html
[View source is enabled on both apps]
To make this happen, leave the textInput field empty and hit save multiple times. Then mouseover the textInput.
I can think of a couple of solutions but they seem pretty hacky.
Thanks,
Jeremy Mitchell

A: Here's a hack to fix this in 3.5.
View the source of this file: http://www.flexdevelopers.com/examples/validator/3.5/Tester.html
Change the saveMessage() method to read like this:
public function saveMessage(event:Event):void
        {
            setupValidators();

            var failedValidations:Array = new Array();
            failedValidations = Validator.validateAll(_formValidators);

            if (failedValidations.length == 0)
            {
                Alert.show("save it");
            }
            else
            {
                for each (var validationResultEvent:ValidationResultEvent in failedValidations)
                {
                    hackForSDK35Bug22911ToRemoveRepeatingErrorMessages(validationResultEvent);
                }
            }
        }

then add this method:
private function hackForSDK35Bug22911ToRemoveRepeatingErrorMessages(failedValidation:ValidationResultEvent):void
        {
            var uiComponent:UIComponent = failedValidation.target.source as UIComponent;
            var errorString:String = uiComponent.errorString as String;
            uiComponent.errorString = errorString.split("\n")[0];
        }

that should remove the repeating error messages and leave just one...


text:
Q: Change value of $_SERVER['HTTP_HOST'] on Bitnami Wordpress behind Azure CDN I have WordPress behind Azure CDN.
The current $_SERVER['HTTP_HOST'] points to the CDN's origin server resulting bypassing of the CDN.
I want to know what the best way of changing $_SERVER['HTTP_HOST'] is so that it defaults to the public URL?
Currently, I modified wp-config.php and added the following
$_SERVER['HTTP_HOST'] = 'FrontEndWebsite.com';

It appears to resolve the problem as the website paths are now correct.
I was wondering if this is the best practices way of doing it?
Thanks in advance.


text:
Q: Having trouble with HTML/PHP upload I'm a student making a simple file upload page with PHP.
But it doesn't work when I upload the actual file on the form and submit it.
I need some help to find what is gone wrong.
uploadProfilePicture.php (I used some bootstrap components)
<?php

    session_start();
    header('Content-Type: text/html; charset=utf-8');

?>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Change profile picutre</title>
        <link rel="stylesheet" href="../../../css/font.css">
        <link rel="shortcut icon" href="../../../favicon/favicon.ico">

        <link rel="stylesheet" href="./css/uploadProfilePicture.css">

    <?php include('../../../common/resource.html'); ?>

Change Profile Picutre

            <form id="profileImageUploadForm" method="POST" action="processProfileImage.php" enctype="multipart/form-data">

                Upload your image!
                <input type="file" class="form-control" id="formFile">
                <input class="button-30" role="button" type="submit"></input>

            </form>

processProfileImage.php

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Change profile picutre</title>
        <link rel="stylesheet" href="../../../css/font.css">
        <link rel="shortcut icon" href="../../../favicon/favicon.ico">

        <link rel="stylesheet" href="./css/uploadProfilePicture.css">

<?php

    session_start();
    header('Content-Type: text/html; charset=utf-8');

    var_dump($_FILES);
    var_dump($_POST)

?>

When I tried to check $_FILES and $_POST, only void arrays returned and I couldn't find what was wrong. I think there's been a mistake in a small part, but I haven't dealt with PHP a lot, so I don't have a good sense of it.
If you have identified the problem with this code, please let me know. Thanks.


text:
Q: Why can't I see any results in the Go To navigation popup? When I search for files or symbols via Edit -> Go To there are no results. How can I fix this?

A: You may just need to resize it. Enter something into the search that will have results. Then move the cursor from the text edit to the bar just underneath it until you get the resize cursor. Then resize the results window.


text:
Q: How to simplify $\tan{\arcsin{\frac{y}{R}}/2}$? I have verified with Mathematica that, for $R>0, y \in \mathbb{R}$:
$$ \tan{\frac{\arcsin{\frac{y}{R}}}{2}} = \frac{R - \sqrt{R^2 -y ^2}}{y}$$
using
Assuming[Element[y, Reals] && R > 0,
 FullSimplify[TrigToExp[Tan[ArcSin[y/R]/2]]]]

How can I prove this withouse messing with complex exponentials and logarithms?

A: Create a right triangle with sides $x,y$, and hypotenuse $R$. In the diagram below, $\phi = \arcsin(y/R) / 2$, So you are looking to find $\tan \phi$ in terms of $R$ and $y$.
For this purpose, you may find the angle bisector theorem useful, as it tells you how the two sections of $y$ are related:
$$\tan \phi = \frac{y_1}{x}=\frac{y_2}{R}$$
Or that:
$$y_1 = \left(\frac{R}{x}+1\right)^{-1}y \quad\longrightarrow\quad
\tan \phi=\frac{y}{\sqrt{R^2-y^2}+R}$$
Now multiply the denominator by it's conjugate to obtain your result.
$\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad\quad$

A: Let  $\displaystyle\arcsin\frac yr=\phi\implies \sin\phi=\frac yR\ \ \ \ (1)$
and based on the definition of principal value, $\displaystyle-\frac\pi2\le\phi\le\frac\pi2\ \ \ \  (2)$
So, we need to find $\displaystyle\tan\frac\phi2$
Using Weierstrass substitution, $\displaystyle\sin\phi=\frac{2\tan\frac\phi2}{1+\tan^2\frac\phi2}$
So, using  $\displaystyle(1),\frac{2\tan\frac\phi2}{1+\tan^2\frac\phi2}=\frac yR\implies y\tan^2\frac\phi2-2R\tan\frac\phi2+y=0\  \ \ \ (3)$
Solving the Quadratic Equation for $\displaystyle\tan\frac\phi2=\frac{R\pm\sqrt{R^2-y^2}}y$
Now using $\displaystyle(2), -\frac\pi4\le\frac\phi2\le\frac\pi4\implies -1\le\tan\frac\phi2\le1$
Observe that for real $\displaystyle\phi, R^2\ge y^2\implies R\ge |y|$ as $R>0$
If $\displaystyle R=|y|,\tan\frac\phi2=\pm1$ where both roots are same
Else  $\displaystyle\frac{R+\sqrt{R^2-y^2}}{|y|}> \frac R{|y|}>1,$ hence  should be discarded.

Observe that if $\displaystyle\tan\frac{\phi_1}2,\tan\frac{\phi_2}2$ are the roots of $(3),$
using Vieta's formula, $\displaystyle\tan\frac{\phi_1}2\tan\frac{\phi_2}2=1$
$\displaystyle\implies\tan\frac{\phi_1}2=\frac1{\tan\frac{\phi_2}2}=\cot\frac{\phi_2}2=\tan\left(\frac\pi2-\frac{\phi_2}2\right)=\tan\frac{\pi-\phi_2}2$
$\displaystyle\implies\frac{\phi_1}2=\frac{\pi-\phi_2}2\iff\phi_1=\pi-\phi_2 $
$\displaystyle\implies\sin\phi_1=\sin\left(\pi-\phi_2\right)=\sin\phi_2 $
Also,  $\displaystyle\sin\phi=\frac{2\tan\frac\phi2}{1+\tan^2\frac\phi2}=\frac{2\cot\frac\phi2}{1+\cot^2\frac\phi2}$ (multiplying the numerator & the denominator by $\displaystyle\cot^2\frac\phi2$)


text:
Q: Why is sed removing the greater than symbol The less-than symbol is removed when I run my sed command.
a::b<type::value> & d
a::b<ns::type::value>& d

sed -i 's/[^:]type/changed::type/g'

results in
a::bchanged::type::value> & d
a::b<ns::type::value>& d

I expected to actually get the following:
a::b<changed::type::value> & d
a::b<ns::type::value>& d

Why is the less-than symbol removed? How can I keep it?

A: The symbol gets removed because it matches [^:] "not a colon", as part of the string to be replaced. You can bypass that by capturing it and putting it back:
sed -i 's/\([^:]\)type/\1changed::type/g'


text:
Q: Subversion Checkout Yields Could Not Open the Requested Subversion System I've installed subversion on our RHEL server and also installed dav_svn_module.  My location tag in httpd.conf is as follows:
<Location /subversion>
DAV svn
SVNPath /subversion
AuthType Basic
AuthName "Subversion Repository"
AuthUserFile /etc/svn-auth.htpasswd
Require valid-user
</Location>

I've setup a password for svnuser with
htpasswd -c -m /etc/svn-auth.htpasswd svnuser

After restarting httpd, I try to checkout files from the subversion repository to my local machine and receive the error message above.  Note that when I try to view the repository via HTTP, I recieve a HTTP 500 error as well.
The httpd error log shows the following entries:
error: Can't open file /subversion/format No such file or directory
Could not fetch resource information [500, #0]
Could not open the requested SVN filesystem [500, #2]

Note that /subversion/format doesn't exist.  Not sure why error log is referencing this non-existent file??
What changes are needed to ensure I can both checkout/commit and authenticate via http?
Thanks!

A: Well, if /subversion is a subversion repository (as you've configured it to be in your Apache config), then it sure better have a format directory.
How did you create the repository, or where did you create the repository?
If you intended for /subversion to be the repo itself, then it wasn't created correctly.  Run svnadmin create /subversion.
If you intended for /subversion to be a directory which contains repos, then your Apache config should be SVNParentPath /subversion instead of SVNPath /subversion - and the repositories in that location still need to be created with svnadmin create.

A: I have seen this before, I believe it was related to a permissions problem when I created the svn filesystem. From memory I am thinking permissions of 644 are correct.
Also take a look at your apache logs when you make an svn co or svn list call to your new repository. If something is wrong with permissions at the apache level (as the 500 implies) you will see it in the error log (usually /var/log/apache2/error-log or some similar path).
Good luck.


text:
Q: Calling setsockopt many times I have application which uses sockets to transfer data between two clients. It uses a single socket to communicate control and data traffic (over UDP).
Qos and tos fields of IP header can be changed using
setsockopt(sockfd, IPPROTO_IP, IP_TOS,  &tos, toslen);
setsockopt(sockfd, SOL_SOCKET, SO_PRIORITY, &cos, coslen);

But how many calls to setsockopt (to the same socket) is too many?
For example, lets assume it will be called every 1ms.
To narrow question scope, I am asking about modern linux system (generic explanation is more than welcomed).
Here is an example to demonstrate it (this is the sending-only part of the application):
#include <stdlib.h>
#include <memory.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#define NPACK 10000
#define PORT 44444
#define BUFLEN 128

void diep(char *s) {
    perror(s);
    exit(1);
}

#define SRV_IP "12.34.56.78"

int main(void) {
    struct sockaddr_in si_other, si_me;
    int s, i, slen = sizeof(si_other);
    int toss[2] = { 56, 160 }, coss[] = { 1, 3 };
    char buf[BUFLEN];

    //Create UDP socket
    if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
        diep("socket");

    //Create remote socket
    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);
    if (inet_aton(SRV_IP, &si_other.sin_addr) == 0) {
        fprintf(stderr, "inet_aton() failed\n");
        exit(1);
    }

    //Create local socket and bind to it.
    memset((char *) &si_me, 0, sizeof(si_me));
    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(PORT);
    si_me.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(s, &si_me, sizeof(si_me)) == -1)
        diep("bind");

    //Loop on number of packets
    for (i = 0; i < NPACK; i++) {
        sprintf(buf, "This is packet %d, %d\n", i, toss[i % 2]);
        printf("Sending packet %d. %s", i, buf);

        //Change tos and cos. odd packets high priority , even packets low priority.
        setsockopt(s, IPPROTO_IP, IP_TOS, &toss[i % 2], sizeof(int));
        setsockopt(s, SOL_SOCKET, SO_PRIORITY, &coss[i % 2], sizeof(int));

        //Send!
        if (sendto(s, buf, strlen(buf), 0, &si_other, slen) == -1)
            diep("sendto()");
    }

    close(s);
    return 0;
}

NOTES:

*

*Both control and data should share the same socket (same UDP source port).

*Multiple threads will use the same socket (so some locking mechanism needed between setsockopt and sendto; but this is outside the scope of the question).

*SO_PRIORITY is linux only.


text:
Q: Show Fancy Product Design image URL of elements in woocommerce cart I'm trying to get the images (or the image URLS) of the elements that are added in the fancy product designer. I've found the following code, but this one is written for the current color instead of current image. The title of the elements are shown, but I cannot find a solution to find the images (or the image URLS).
Thanks in advance!
add_filter( 'woocommerce_get_item_data', 'wc_checkout_description_tp', 10, 2     );
 function wc_checkout_description_tp( $other_data, $cart_item ){
 //re-convert the fpd dtails from the json sting to an array
 $fpd_detail_arr = json_decode( html_entity_decode( stripslashes(   $cart_item['fpd_data']['fpd_product'] ) ), true );
 //remove the first element as we are not dealing with shadows
 $fpd_elems_arr = array_slice($fpd_detail_arr[0]['elements'], 1);

 //loop each element and set the details to a var
 foreach($fpd_elems_arr as $elem_key => $element_arr){
     foreach($element_arr as $key => $value){
         //the currentColor value is set inside yet another array
         if(is_array($value)){
             foreach($value as $val_key => $val_val){
                 if( $val_key == 'currentColor' && !empty($val_val) ){
                     $fpd_detail_value = $val_val;
                 }
             }

         }
         //set the title value
         else{
             if( $key == 'title' && !empty($value) ){
                 $fpd_detail_name = trim($value);
             }
         }
     }
    //add the name and value pair to the detail array
     $other_data[] = array(
         'name' => $fpd_detail_name,
         'value' => $fpd_detail_value
     );

 }
 //return the final detail array
 return $other_data;
}


text:
Q: Understanding the relation between UNION and ORDER BY? Here are 2 queries -
select * --1
from Employee --2
where HireDate < '7/1/2001' --3
order by HireDate --4

--5 gap

select top(2) * --6
from Employee --7
where HireDate >= '7/1/2001' --8
order by HireDate --9

I want to do a UNION on them. When i put UNION in 5, why do i get an error?
When, I remove 4 and put UNION in 5, I get a result, but not the same as when I execute the two queries individually. Can you tell me why this happens?
To make this work correctly, I have to remove 4, make derived tables of both queries, put 4 after 9 and then perform a UNION of both derived tables.

A: remove the ORDER BY before UNION. (it causes Syntax Error)
select *
from Employee
where HireDate < '7/1/2001'
UNION
select top(2) *
from Employee
where HireDate >= '7/1/2001'
order by HireDate

the ORDER BY clause takes place after the UNION

A: This will help you I guess for your question

Combining ORDER BY AND UNION in SQL Server
select first.Id, first.Name
from (
    select top 1 *
    from Locations
    order by Id) first
union all
select last.Id, last.Name
from (
    select top 1 *
    from Locations
    order by Id desc) last


text:
Q: Set focus after jAlert I am using jQuery plugin jAlert to show alert box.
I want to focus a textbox after showing jAlert, like this:
jAlert("Error", "Please enter EmailID.", function(){
  document.getElementById('txtEmail').focus();
}, 1);

But this code doesn't wait for user to click OK button and textbox gets focus before clicking OK button.
So how to focus it after user clicks, like a callback function.
Thanks in advance.

A: jAlert doesn't operate like JavaScript alert and jAlert has a callback function  and take refrence from enter link description here
 $("#txtEmail").focus();


text:
Q: How to move tick mark labels away from axis using boxplot() Here is a toy example to use for demonstration:
boxplot(1:90 ~ c({1:90} %% 3),names=c("A","B\nB","C\nC\nC"))

If you plot, you will see the motivation for my query.  I would like to move the tick mark labels for the groups away from the axis.  And, for my own reasons, I do not want to "print nothing" & use axes() function...instead, I want to know how to do this by passing parameters to subroutines called by boxplot(). My understanding is that this should be doable, but I have proven unsuccessful to date.
For example, the solution presented here is far too inelegant for my purposes:
R, Change distance between axis tick marks and tick mark labels
¿Does anyone know how to do this?

A: Function boxplot() after checking the syntax of the input arguments calls "bxp" function. Here you can see the arguments it is passing to it:
if (plot) {
    if (is.null(pars$boxfill) && is.null(args$boxfill))
        pars$boxfill <- col
    do.call("bxp", c(list(z, notch = notch, width = width,
        varwidth = varwidth, log = log, border = border,
        pars = pars, outline = outline, horizontal = horizontal,
        add = add, at = at), args[namedargs]))
    invisible(z)
}

Function bxp in its turn calls function "axis" and it looks only at "xaxt", "yaxt", "xaxp",
            "yaxp", "las", "cex.axis", "col.axis" arguments to draw the axis:
if (axes) {
    ax.pars <- pars[names(pars) %in% c("xaxt", "yaxt", "xaxp",
        "yaxp", "las", "cex.axis", "col.axis", "format")]
    if (is.null(show.names))
        show.names <- n > 1
    if (show.names)
        do.call("axis", c(list(side = 1 + horizontal, at = at,
            labels = z$names), ax.pars))
    do.call("Axis", c(list(x = z$stats, side = 2 - horizontal),
        ax.pars))
}

As you can see from the above, there are no parameters that can change the offset of the X labels that can be passed to boxplot.
With ggplot by default displays the labels the way you want:
df <- data.frame( x= as.factor(c({1:90} %% 3)), y = 1:90 )
ggplot(df,aes(x=x, y=y) ) +
  geom_boxplot()+
  scale_x_discrete(labels=c("A","B\nB","C\nCC\nCCC"))


text:
Q: Conversion of Oracle query to teradata query How to convert this below query to equivalent teradate query. I tried but results varies a lot.
select il.domainN as listname, il.SourceID, ns.sourcename, cbo.customerid, cu.username, hv.domainN as HTname
,  nvl((select 1
        from mydb.customerPP cpp
        where cbo.customerid = cpp.customerid
          and NOT EXISTS (select 1 from mydb.customerPI cpt where cpp.customerid = cpt.customerid)
          and trunc(cpp.startdate) <= sysdate
        group by cpp.customerid),0) as BBID
from mydb.customerBO cbo
  join mydb.customers cu on cbo.customerid = cu.customerid
  join mydb.inv il on cbo.domainN = il.domainN
  join mydb.Sources ns on il.SourceID = ns.SourceID
  left join mydb2.HT hv on (il.domainN = hv.domainN
                                  and hv.sDate+1 >= il.dDate
                                  and il.dDate+1 >= hv.sDate)
where cbo.customerBOID = 1
  and cu.statusid = 1
  and il.sourceTID = 2
  and il.joinbydate >= cbo.cDate
  and trunc(il.dDate) = trunc(sysdate)

Thanks.

A: Use coalesce instead nvl and compare explain statements to see whether you have left outer joins converted to inner joins for nvl on Teradata.


text:
Q: Multiple listeners / go blocks for channel in ClojureScript Given a channel in ClojureScript
(def navigation (chan))

Is it possible to have multiple go blocks that pull values off it? E.g.
(go
 (while true
   (secretary/dispatch! (<! navigation))))

(go
 (while true
   (println (<! navigation))))

The putting a value in with:
(put! channels/navigation "/styles")

This doesn't seem to work and only executes within the first Go block. This is a bit of a contrived example but I do want to use this pattern to have multiple listeners to a channel that will return JSON from a socket.io service.

A: Reading from a channel will return the value and remove it from the channel. If you want multiple readers to read the same values you need multiple channels; take look at the core.async mult and tap functions.

A: You might want to look into the pub and sub functions in core.async. This still means multiple channels as @Joost mentioned.


text:
Q: Probability Scores threshold usually used in Deep Learning for an Object Recognition task I am working on a Faster RCNN project.
I have launched the algorithm and obtained all the bounding box proposals. Each one has a certain probability score:

My question is: What is the probability score threshold usually used by the Deep Learning scientific community in the Object Detection field in order to say if an object inside a bounding box belongs to a class ? Do you think that 60% is a good threshold ?
The authors are using the Multi-Task loss:

Thank you very much for all your answers


text:
Q: Is $f(x) = x\sin x$ is uniformly continuous on $ [0,\infty)$?
Is $f(x) = x\sin x$ is  uniformly continuous on $ [0,\infty)$?

My attempts:
I know that composition  of uniform continuous function is uniform as $g(x) = x$ and $f(x) = \sin x$
Now $g(f(x)) = f(g(x)) $  so it  is uniformly continuous...

A: $f$ is not uniformly continuous. Suppose it is. Then there exists $\delta >0$ such that $|f(x)-f(y)|<1$ whenever $|x-y|\leq \delta$. Consider $|f(2n\pi)-f(2n\pi +\delta)|$ This must be less than 1 for every $n \in \mathbb N$. However $f(2n\pi)=0$ and $|f(2n\pi+\delta)|=(2n\pi +\delta) \sin (\delta) \to \infty$ as $n \to \infty$.