text:
Q: SPWeb.RegionalSettings.TimeZones Apparently each SPWeb can have it's own list of TimeZones (assuming that is why there is a TimeZones property on each SPWeb's RegionalSettings).
Why could/would a web/site within a site collection/farm have different collection of TimeZones (i know why a different web/site would have a different TimeZone selected, I am asking about the "collection" of time zones - i.e. the list of values that populate the TimeZone dropdown in the /_layouts/regionalsetng.aspx page)?  Wouldn't the possible list of selectable values be the same for each web across a farm?

A: The Timezones property of the SPWeb.RegionalSettings setting is the same across the entire farm:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spregionalsettings.timezones.aspx

Gets the collection of time zones used
  in a server farm.

It is, therefore, the same for all Webs. I suspect the confusion arises as the SPWeb.RegionalSettings property just gets/sets and SPRegionalSettings object. Considered from that point of view, it is reasonable that the TimeZones collection is also available from the SPRegionalSettings class - though I'm suprised it isn't static.
It does not appear to be related to the operating system, though it's hard to tell; Reflector can't decompile the COM layer.


text:
Q: Generalization of a Result on Modular Inverses Yesterday, I attempted to solve the general system of linear congruences (I'm not sure why I've never tried this before.)
\begin{align*} x &\equiv a \pmod{A} \\
 x &\equiv b \pmod{B}.\end{align*}
I let $x = a + pA$ and $x = b + qB$ for some $p,q\in\mathbb{Z}$, and I got
$$a + pA = b + qB \implies a \equiv b + qB \pmod{A} \implies q \equiv(a - b)B^{-1}_A \pmod{A}.$$
where $B^{-1}_A$ is the inverse of $B$ modulo $A$. Then $q = (a - b)\cdot B_A^{-1} + rA$ for some $r\in\mathbb{Z}$, so
$$ x = b + (a - b)B_A^{-1} B + rAB\implies x\equiv b + (a - b)B^{-1}_AB \pmod{AB}. $$
However, note that by symmetry, we can also conclude that
$$ x \equiv a + (b - a)A^{-1}_BA \pmod{AB}.$$
Thus,
$$ a + (b-a)A^{-1}_BA \equiv b + (a - b)B^{-1}_AB \pmod{AB}.$$
If $\gcd(a - b, AB) =1$, then
$$a - b = (a - b)(BB^{-1}_A + AA_B^{-1}) \pmod{AB} \implies BB^{-1}_A + AA_B^{-1}\equiv 1 \pmod{AB}.$$
Can this result be generalized to product rings? Also, if there is a generalization, does it have any uses?

A: I always use your method to solve these equations, but your result is just the standard formula for the Chinese remainder theorem.
If $\gcd(a-b,AB) = 1$:
  $\gcd(qB-pA,AB) = \gcd((x-pA)-(x-qB),AB) = 1$.
  Thus $\gcd(A,B) = 1$ and hence $A_B^{-1},B_A^{-1}$ exist [which you already assumed].
[Note that the converse is clearly not true! $A,B$ could be coprime while $a,b$ are both zero.]
If $\gcd(A,B) = 1$:
  Thus $A \mid AA_B^{-1} + BB_A^{-1} - 1$ and $B \mid AA_B^{-1} + BB_A^{-1} - 1$.
  Thus $AB \mid AA_B^{-1} + BB_A^{-1} - 1$ and hence $AA_B^{-1} + BB_A^{-1} \equiv 1 \pmod{AB}$.
[So the result you got holds under the usual more general condition that $A,B$ are coprime.]
The chinese remainder theorem also holds for principal ideal domains in the way you want, namely product rings, and generalizes to the product of any coprime quotient rings of a commutative rings. (You can take a look at the Wikipedia article.)

A: That is a simple form of CRT = Chinese Remainder Theorem  that I call Easy CRT. Below is one simple way to present it. You can find many example applications in prior posts here.
Theorem $ $ (Easy CRT) $\rm\ \ $ If $\rm\ m,\:n\:$ are coprime integers then
$$\rm \begin{eqnarray}\rm x&\equiv&\rm a\,\ (mod\ m) \\
\rm x&\equiv&\rm b\,\ (mod\ n)\end{eqnarray} \ \iff\ \ x\, \equiv\, a + m\ \bigg[\frac{b-a}{\color{#c00}m}\ mod\ n\:\bigg]\ \ (mod\ m\:n)$$
Proof $\rm\,\ m,n\,$ coprime $\:\rm\Rightarrow\, \color{#c00}{{\large\frac{1}m} = m^{-1}}\!\pmod{\! n}\, $ exists, by Bezout or Euler's $\phi$ Theorem.
$\rm\ (\Leftarrow)\ \ \ mod\ m\!:\ x \equiv a + m\left[\cdots\right] \equiv a,\ $ and $\rm\ mod\ n\!:\ x \equiv a + m\,\color{#c00}{\large\frac{1}m}\,(b-a) \equiv b$
$\rm (\Rightarrow)\ \ $ The solution is unique $\rm\, (mod\ m\:\!n)\, $ since if $\rm\ x',\,x\ $ are solutions then $\rm\ x'\equiv x\ $ mod $\rm\:m,n\:$ hence $\rm\ m,n\mid  x'-x\ \Rightarrow\ m\:\!n\mid x'-x\  $ since $\rm\ m,n\:$ coprime $\rm\:\Rightarrow\ lcm(m,n) = m\:\!n$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to transfer NSdata from one iphone to another How can I go about transferring a NSData object from 1 iphone to another? (It is an audio which I am looking to play out of iphone #2)

A: Of course there are various ways to achieve this.
My suggestion would be to look at Apple's GameKit library. This makes it trivial to establish a connection to another iOS device. You may connect via Bluetooth or Wifi (if all you need to do is 'trigger' a sound that already exists in the application bundle on both devices, bluetooth will work fine - if you actually need to transfer a sound file, you probably want to use a Wifi connection). You will have to implement the actual transmission mechanism/protocol yourself in either case.
Another option is to use Bonjour and pass your data over TCP/IP.
You may find this tutorial helpful:
Networking and Bonjour on iPhone

A: You could use the GameKit framework, you can use bluetooth to send data between iOS devices. Take a look at the Game Kit Programming Guide.

A: Options:
1. Gamekit Framework
2. Look at the open source application "Bump"


text:
Q: HTML table can't remove borders I know this might be trivial, but I really can't figure out what's going wrong.
I can't remove the borders from my table.

Here is the HTML

I also tried

but it was no use. Thanks.

A: Try border-collapse: collapse
https://developer.mozilla.org/en-US/docs/CSS/border-collapse

A: Just try this:
style="border-collapse: collapse;"

see: http://www.w3schools.com/cssref/pr_tab_border-collapse.asp

A: You should also set border:none; and outline:none; for the td element (not only for the table itself)  and border-collapse: collapse;
Since you're having the class "nothing", try:
.nothing
{
   border-collapse:collapse;
}
.nothing td
{
   border:none;
   outline:none;
}

A: Try:


text:
Q: Why is my new laptop's fan making noises? I have a 1 month old Lenovo Ideapad y410p and the fan makes a weird clicking noise. It happens sometimes when I tilt my laptop but not always, sometimes when I turn on my laptop, and usually when I'm running CPU intensive programs.
I tried opening the laptop and looking at the fan but I couldn't get the cover of the fan off because one of the screws wouldn't come out.
This is the sound it makes:
https://www.youtube.com/watch?v=SIutZZoZb_8
(the noise that starts 4 seconds in is my AC not my computer)
It sometimes gets louder when I tilt the laptop. And when I'm playing video games it usually goes on the whole time.

A: TL;DR;
Send it back.
Explanation
This is probably a manufacturing fault. A lot of PC parts are injection molded and as such, they have a small chance of having excess material.
A good example of this would be on the bottom of plastic bottles, there is a small "pip".
The chances are, this is a small piece of plastic, which when the laptop is tilted just catches on the fan.
I cannot stress enough: Do not attempt to fix it yourself, it could cause you to invalidate your warranty.


text:
Q: Accessing Radgrid items on parent page from a usercontrol I have several pages that share a user control.  When the user clicks a save button on the user control, I need to be able to loop the items of a Radgrid on the parent page and get the selected items.  The radgrid has a checkbox column.  I can see that I am getting values from the grid cells but for some reason the checked value on the checkbox is always false even when it is checked.  This same foreach code works when called from the parent page itself but not from the usercontrol.
Here is a code snippet.
RadGrid ProjectGrid = (RadGrid) this.Parent.FindControl("ProjectGrid");

        foreach (GridDataItem item in ProjectGrid.MasterTableView.Items)
        {
            string applicationPackageId = item.Cells[4].Text.ToString();

            CheckBox chbx = item.FindControl("ProjectGridCheckBox") as CheckBox;

            if (chbx != null && chbx.Checked)
            {
                numCheckedPackages++;
            }
        }

Here is my grid.
<telerik:RadGrid ID="ProjectGrid" runat="server" Skin="WF" ShowHeader="true" EnableEmbeddedSkins="false" AllowSorting="false" AllowFilteringByColumn="false" AllowMultiRowSelection="true">
    <MasterTableView Width="100%" CommandItemDisplay="None" AutoGenerateColumns="false" TableLayout="Fixed">
        <RowIndicatorColumn Visible="False">
            <HeaderStyle Width="20px" />
        </RowIndicatorColumn>
        <ExpandCollapseColumn Resizable="False" Visible="False">
            <HeaderStyle Width="20px" />
        </ExpandCollapseColumn>
        <Columns>
            <telerik:GridTemplateColumn UniqueName="SelectColumn" DataField="Id" HeaderStyle-Width="5%" >
                <ItemTemplate>
                    <asp:CheckBox ID="ProjectGridCheckBox"   runat="server"/>
                </ItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridBoundColumn DataField="Package.ProjectPackageNumberNameDisplayField" HeaderText="Project - Package" UniqueName="ProjectPackages"  HeaderStyle-Width="85%"></telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="ApplicationPackageID" HeaderText="Id" HeaderStyle-Width="15%" UniqueName="PackageId"></telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
    <ClientSettings EnableRowHoverStyle="true">
        <Selecting AllowRowSelect="True" />
    </ClientSettings>
    <HeaderStyle BackColor="#666666" Font-Names="verdana, arial" Font-Size="Small" Height="20px" />
</telerik:RadGrid>


text:
Q: How to place HTML input value as a String in Jquery object value? $("#btn_edit").click(function(){
    var token = localStorage.getItem('id_token');
    var obj = {};
    obj.subject = $("input[name=subject]").val();
    obj.description = $("textarea[name=description]").val();

    $.ajax({
       type: "PUT",
       url: "http://myurl",
       contentType: "application/json",
       dataType: "json",
       data: JSON.stringify(obj),
       success: function(jsonresponse) {
           $(document.body).append(JSON.parse(jsonresponse));
       },
       beforeSend: function(xhr, settings) {
           xhr.setRequestHeader('Authorization', 'Bearer ' + token);
       }
    });
});

but when the value is added manually it works well and even the input value is printed in the alert
alert("Text: " + $("input[name=subject]").val() + " " +  $("textarea[name=description]").val());

var obj = {};
obj.subject = "Hello";
obj.description = "Help please";


text:
Q: How can I execute python file? I made test.py and ran chmod u+x test.py. It works if I run python test.py but not ./test.py. What am I doing wrong?
./test.py: line 1: syntax error near unexpected token `"HelloWorld"'
./test.py: line 1: `print ("HelloWorld")'


text:
Q: how to do a keyboard interrupt of Python3 code in Spyder I have a simple but long loop in Python 3 that calls a simple function. I want to stop the execution, and that should be possible with Ctrl-C but that doesn't work. How to do this "manual keyboard interrupt"? I use Anconda3 for windows64, with Python 3.7.
Ctrl-C doesnt do anything, and also the red button in the IPython console doesn't do anything.
# -*- coding: utf-8 -*-
"""
Python3.7
Created on Wed Jul 24 12:59:31 2019
This proves that Ctr C doesn't work in Spyder
@author: Rob
"""

#%% loop in main program

def hello():
    print('Hello Spyder '+str(nr))

import time
nr = 0
while nr < 42:
    nr +=1
    hello()
    time.sleep(1)

#%% loop in function

def hello():
    nr = 0
    while nr < 42:
        nr +=1
        print('Hello Spyder '+str(nr))
        time.sleep(1)

import time
hello()

I expect the code to stop when using keyboard CTrl-C. But the code just keeps on executing til the end.

A: probably already solved this yourself, but try this.
import time

i = 0

try:
    while i < 100:
        print (i)
        i = i + 1
        time.sleep(1)
except KeyboardInterrupt:
    print("interrupted")


text:
Q: Where can I find a list of all 3DS titles available in the 3DS eShop? I am planning to get a 3DS, and wanted to know what sort of games are up on the 3DS eShop.
I tried checking the Nintendo website, but it only shows a list of "featured" titles, not the entire shop catalog. I assume they want you to look using the device itself (and thereby hopefully buy a game or two)
For those of us without a 3DS, is this information available elsewhere?

A: Wikipedia has a list of Virtual Consoles Games for the 3DS (which include current and upcoming games), and also a list of DSiWare Games and Applications (DSiWare works on the 3DS).


text:
Q: Creating a regex to find corruption
kŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkŸkQOzW Îžò4d1|l»ÏAñ?:"ñl¦£.._ÇŸf€À?Lƒ,ðe¿íÏ".á¢..ü¾bÜW!jà×

considered corrupted is:

kŸkŸkŸkŸkŸk
  FFFFFFF
  oŸoŸoŸoŸoŸoŸoŸoŸoŸoŸo

Pretty much any 2 bit sequence repeated.
I cant for the life of me think up a way of detecting it without detecting everything else - the real issue is not detecting (kŸ{2,}) but detecting any other possibility.

A: This regex will match a repeated two character sequence:
/(..)\1+/

Explanation:
(..) matches any two characters, putting them in the first capture group.
\1 refers to the first capture group, so it will check if the same two characters repeat


text:
Q: React Hook "useCustomFunction" cannot be called inside a callback I have been looking for a while and am not understanding how to get around this error.
I have a function that has a useEffect statement inside it.  I need to call this function from within a loop(or map).
file1
export function useCustomFunction(year: number, month: number): any {

  const customers = useAllCustomers();
  const aggregator = useCustomerAggregator(year, month);
  const [response, setResponse] = useState("" as string);

  useEffect(() => {
    console.log('i am doing stuff here')
    setResponse('hello world')
  }, [year, month, customers, aggregator]);

  return response;
}

file2
import { useCustomFunction } from "file1";

export function EMDeltaDashboardPage(){

  const dateCols = ["2022-10","2022-11","2022-12","2023-01","2023-02","2023-03","2023-04"]

  useMemo(() => {
    dateCols.forEach((element: any) => {
      let year = Number(element.split("-")[0])
      let month = Number(element.split("-")[1])
      let budgets = useCustomFunction(year, month);
      console.log(budgets)
  },[dateCols])

In this case I am using file2 to call file1 useCustomFunction in a loop and budgets should be 'hello world' and should console.log 7 times.
However I am getting the following error message and am not sure how to get around this.
React Hook "useCustomFunction" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function

A: You cant. You can only call hooks in root component function.
Instead of calling your hook each iteration you call it once and return a function which you then call:
const myCustomFn = myCustomHook();

dataCols.forEach((col) => {
  // ...
  myCustomFn(year, month));
});


text:
Q: Drop Down List with WordPress I'm trying to make a drop down list over the menu ,don't know how can i make with PHP, all the web pages or tutorials that i have seen before make it from the admin and with a template pre maked so I'm stagnant because i don't know how to make it, i'm sure that it could be something so simple i hope someone can help me, i'm using bootstrap if that helps in something
to getting the menu I'm using
<?php
    $args = array(
        'theme_location' => 'header-menu',
        'container' => 'nav',
        'container_class' => 'menu-sitio'
    );
    wp_nav_menu($args);
?>

but in my WordPress admin menu there are something like this

and in my templete looks like

and i want to know how to make it like a drop down menu
what i just have in my HTML is this

                    logo

                    <?php
                        $args = array(
                            'theme_location' => 'header-menu',
                            'container' => 'nav',
                            'container_class' => 'menu-sitio'
                        );
                        wp_nav_menu($args);
                    ?>

A: Try below piece of code which is working for me please check and let me know is it working for you or not:
lets consider your menu is primary selected from admin section:
<?php
global $post;
$locations = get_nav_menu_locations();
$primaryMenuID = $locations['primary'];
$primarMenu = wp_get_nav_menu_items($primaryMenuID);
?>

<?php
foreach ($primarMenu as $menu) {
    if ($menu->menu_item_parent == 0) {
        $menuParsentId = $menu->ID;
        $childMenu = get_nav_menu_item_children($menuParsentId, $primarMenu);
        $menuParsenttitle = $menu->title;
        if (count($childMenu) > 0) {
            $id = get_the_ID();
            ?>
            <li class="custom-dropdown
            <?php
            foreach ($child as $childobject) {
                if ($id == $childobject->object_id) {
                    echo 'active';
                }
            }
            ?>">
                <a href="javascript:void(0);" class="drop-down-sub-menu" title="<?php echo $menuParsenttitle; ?>"><?php echo $menuParsenttitle; ?>

                    <?php
                    foreach ($child as $new) {
                        $menuChildTitle = $new->title;
                        ?>

                            <a href="<?php echo $new->url; ?>" title="<?php echo $menuChildTitle; ?>">
                                <?php echo $menuChildTitle; ?>

                    <?php } //} ?>

        <?php } else {
            ?>
            <li class="<?php
            if ($id == $menu->object_id) {
                echo 'active';
            }
            ?>">
                <a href="<?php echo $menu->url; ?> " title="<?php echo $menuParsenttitle; ?>"><?php echo $menuParsenttitle; ?>

            <?php
        }
    }
    $i++;
}
?>


text:
Q: Unix, Sort by number I want to sort my file by decreasing number of the second column, but not changing the place of the header. Currently it is like this in a csv file that has two columns like this:
Person     Age

Sarah      15

Robert     23

Emma       31

Bob        9

I want it to be like this:
Person     Age

Emma       31

Robert     23

Sarah      15

Bob        9

Please help a beginner in Unix.

A: Read http://man7.org/linux/man-pages/man1/sort.1.html to learn about the sort command on UNIX/Linux. That's how I and everyone else learned.
$ sort --key 2 --reverse --numeric-sort myfile > mysortedfile

The only problem is that this sorts the line with "Person Age" as if it had the numeric value of zero, and moves it to the last line of the file. You then have to move that line after sorting the file.

A: This will do the trick except remove blank lines.
sed -n '1 ! p' sortme.txt | sort --key 2 --reverse --numeric-sort | sed '1 i\Person\tAge' > sorted.txt
~Pat

A: To solve the "header in front" problem as outlined in Bills answer, you could use awk in addition to sort:
awk 'NR==1 {print ; next } { print | "sort -n -r -k2"  }' yourfile > sorted_file

*

*the condition NR==1 applies only for the first line: it is printed

*all other line are piped to the sort command (you could do the sorting in awk itself, but that would be a bit longer )


text:
Q: Add first element of array to the same array I have an array of objects. I need to add the first element of that array to the end of it, so the first and last elements are the same. I've came up with this but I feel like there is a better solution out there.
points.Concat(new[] { points[0] }).ToArray()
Full context:
public static Vertex[] CreateLineStrip(Color color, params Vector2f[] points)
{
    return CreateVertices(color, points.Concat(new[] { points[0] }).ToArray());
}

CreateVertices projects the given array of points to an array of vertices.

A: Given the following extension method, inline with your comments, you could add some syntactical sugar
However there is nothing really gained here, apart from a shiny new extension method
public static class ArrayExtensions
{
   static public T[] Append<T>(this T[] array, T item)
   {
      return array.Concat(new[] { item }).ToArray();
   }
}

public static Vertex[] CreateLineStrip(Color color, params Vector2f[] points)
{
    return CreateVertices(color, points.Append(points[0]));
}

A:         public void MyMethod(params Contact[] contacts)
        {
            var list = new List<Contact>(contacts);
            list.Add(list[0]);

            // ... do your thing
        }


text:
Q: Cannot run Jupyter on AWS EC2 Browser says "Site can't be reached" I have set up an AWS account on their free tier and after installing Anaconda and Jupyter Notebooks I am unable to connect to Jupyter notebooks through my browser. I get the below screen:

The process I have gone about t set this up is mostly summarised at the link below:
https://medium.com/@josemarcialportilla/getting-spark-python-and-jupyter-notebook-running-on-amazon-ec2-dec599e1c297
There are a few changes I have made to the above medium article process due to it not working. The main one is that my certificate has the below commands in it
# Configuration file for jupyter-notebook.

c = get_config()

# Notebook config this is where you saved your pem cert

c.NotebookApp.certfile = u'/home/ubuntu/certs/mycert.pem'

# listen on all IPs

c.NotebookApp.ip = '0.0.0.0'

# Allow all origins

c.NotebookApp.allow_origin = '*'

# Don't open browser by default

c.NotebookApp.open_browser = False

# Fix port to 8888

c.NotebookApp.port = 8888

Everything seems to go as expected until I get to typing the necessary link in the browser. When I type Jupyter notebooks into my console I get the below (X's are alpha- numerics I don't think I should share):
[I 07:28:56.291 NotebookApp] Writing notebook server cookie secret to /run/user/1000/jupyter/notebook_cookie_secret
[I 07:28:57.297 NotebookApp] JupyterLab extension loaded from /home/ubuntu/anaconda3/lib/python3.7/site-packages/jupyterlab
[I 07:28:57.297 NotebookApp] JupyterLab application directory is /home/ubuntu/anaconda3/share/jupyter/lab
[I 07:28:57.299 NotebookApp] Serving notebooks from local directory: /home/ubuntu
[I 07:28:57.299 NotebookApp] The Jupyter Notebook is running at:
[I 07:28:57.299 NotebookApp] https://(ip-XXX-XX-XX-XXX or XXX.X.X.X):8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[I 07:28:57.299 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 07:28:57.303 NotebookApp]

To access the notebook, open this file in a browser:
file:///run/user/1000/jupyter/nbserver-29637-open.html
Or copy and paste one of these URLs:
https://(ip-XXX-XX-XX-XXX or XXX.X.X.X):8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

In the browser as well as typing what the tutorial says:
https://XXX-X-XX-X-XXX.us-east-2.compute.amazonaws.com:8888
I have also tried the below:
https://XXX-X-XX-X-XXX.us-east-2.compute.amazonaws.com
https://(ip-XXX-XX-XX-XXX or XXX.X.X.X):8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
https://ip-XXX-XX-XX-XXX:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
https://ip-XXX.X.X.X:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
None of these seem to work.
If anyone has any suggestions it would be greatly appreciated.
Thanks
Edit
After recreating the instance and this time putting the security setting to All Traffic rather than just SSH (Thanks to Lamanus) the browser now just continually trying to connect while the console gives the the output below:
Exception in callback BaseAsyncIOLoop._handle_events(5, 1)
handle: <Handle BaseAsyncIOLoop._handle_events(5, 1)>
Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/platform/asyncio.py", line 138, in _handle_events
    handler_func(fileobj, events)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/netutil.py", line 273, in accept_handler
    callback(connection, address)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/tcpserver.py", line 288, in _handle_connection
    do_handshake_on_connect=False,
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/netutil.py", line 605, in ssl_wrap_socket
    context = ssl_options_to_context(ssl_options)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/netutil.py", line 574, in ssl_options_to_context
    ssl_options["certfile"], ssl_options.get("keyfile", None)
PermissionError: [Errno 13] Permission denied
Exception in callback BaseAsyncIOLoop._handle_events(5, 1)
handle: <Handle BaseAsyncIOLoop._handle_events(5, 1)>
Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/platform/asyncio.py", line 138, in _handle_events
    handler_func(fileobj, events)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/netutil.py", line 273, in accept_handler
    callback(connection, address)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/tcpserver.py", line 288, in _handle_connection
    do_handshake_on_connect=False,
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/netutil.py", line 605, in ssl_wrap_socket
    context = ssl_options_to_context(ssl_options)
  File "/home/ubuntu/anaconda3/lib/python3.7/site-packages/tornado/netutil.py", line 574, in ssl_options_to_context
    ssl_options["certfile"], ssl_options.get("keyfile", None)
PermissionError: [Errno 13] Permission denied

A: I worked it out with some help from Lamanus.
As i said in my edit I had to recreate my instance making sure to change the security settings from SSH to All Traffic.
Then the next time I activated my terminal I had to go to the certs folder and modify some of the certificates with the below commands:

cd certs
sudo chmod 777 mycert.pem

After that I went to a screen where it asked me for a token. The one I provided was the token the console provided me on the end of the below
https://ip-XXX-XX-XX-XXX:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
So I copied and pasted the xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx part into the token area.
Thanks


text:
Q: c#, eager loading collection of collection with Nhibernate (QueryOver or Linq) return "cannot simultaneously fetch multiple bags" i read tons of answer about this but don't find a way to apply to my specific case
i simply have User object which have ICollection<Group> Groups property and each Group have a "ICollection Roles' proeprty
now i have to eager load a specific user with Groups filled and Roles of each group filled to
i try (among many other) this 3 way:
1:
 _session.Query<User>().FetchMany(u => u.Groups).ThenFetchMany(g => g.Roles)
    .SingleOrDefault();

2:
var utente = _session.QueryOver<User>()
.Fetch(x => x.Groups).Eager
.Fetch(x => x.Groups.First().Roles).Eager
.Where(x => x.IdUtente == idUtente)
.SingleOrDefault();

3:
 var query = _session.QueryOver<Utente>()
    .Where(u => u.IdUtente == idUtente)
    .Future();

Gruppo gruppi = null;
Ruolo ruolo = null;
_session.QueryOver<Utente>()
    .Left.JoinAlias(u => u.Gruppi, () => gruppi)
    .Left.JoinAlias(() => gruppi.Ruoli, () => ruolo)
    .Future();

return query.ToList().First();

but every time i get: cannot simultaneously fetch multiple bags

A: I solved it setting .AsSet on collection proeprty in nhibernate maps


text:
Q: UIStackView not showing I am trying to add a UIStackView to my window but it is not showing. As you can see below, I have already added a UINavigationBar successfully. I also tried adding various other controls but only another UIView actually showed up. I've enclosed my ViewController class:

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    var pickerData: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        pickerData = ["Select a segment..."]

        let guide = view.safeAreaLayoutGuide
        let safeHeight = guide.layoutFrame.size.height
        let safeWidth = guide.layoutFrame.size.width

        let navBar = UINavigationBar(frame: CGRect(x: 0, y: safeHeight, width: 20, height: 44))

        self.view.addSubview(navBar)

        navBar.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
        navBar.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true

        navBar.topAnchor.constraint(equalTo: guide.topAnchor, constant: 0).isActive = true

        navBar.translatesAutoresizingMaskIntoConstraints = false

        let navItem = UINavigationItem(title: "Add Binge Segment")
        let cancelItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: nil, action: #selector(cancel))
        navItem.leftBarButtonItem = cancelItem

        navBar.setItems([navItem], animated: false)

        var items:[UIView] = [UIView]()

        let picker = UIPickerView(frame: CGRect(x: safeWidth, y: navBar.frame.height + 50, width: 320, height: 230))
        picker.showsSelectionIndicator = true
        picker.delegate = self
        picker.dataSource = self

        items.append(picker)

        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fillProportionally
        stackView.alignment = .fill
        stackView.spacing = 10
        stackView.backgroundColor = .green
        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(stackView)

        stackView.topAnchor.constraint(equalTo: navBar.bottomAnchor, constant: 50).isActive = true
        stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 50).isActive = true

        stackView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: 0).isActive = true
        stackView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 0).isActive = true

        stackView.addArrangedSubview(picker)

    }

    @objc func cancel() {

        print("Clicked")

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 0
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

}

Any ideas as to why this is not showing? Most answers I saw suggested adding constraints but I already have them
EDIT: New View Controller:

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    var pickerData: [String] = [String]()

    var guide: UILayoutGuide = UILayoutGuide()
    var safeHeight: CGFloat = 0.0
    var safeWidth: CGFloat = 0.0

    var navBar: UINavigationBar = UINavigationBar()
    var stackView: UIStackView = UIStackView()

    var picker: UIPickerView = UIPickerView()

    var currentSelection: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        pickerData = ["Select a segment..."]

        guide = view.safeAreaLayoutGuide
        safeHeight = guide.layoutFrame.size.height
        safeWidth = guide.layoutFrame.size.width

        navBar = UINavigationBar(frame: CGRect(x: 0, y: safeHeight, width: 20, height: 44))

        self.view.addSubview(navBar)

        picker = UIPickerView(frame: CGRect(x: safeWidth, y: navBar.frame.height + 50, width: 320, height: 230))

        self.view.addSubview(picker)

        stackView.axis = .vertical
        stackView.distribution = .fillProportionally
        stackView.alignment = .fill
        stackView.spacing = 10
        self.view.addSubview(stackView)

    }

    override func viewWillLayoutSubviews() {

        navBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0)
        navBar.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0)
        navBar.topAnchor.constraint(equalToSystemSpacingBelow: guide.topAnchor, multiplier: 0)

        navBar.translatesAutoresizingMaskIntoConstraints = false

        let navItem = UINavigationItem(title: "Add Binge Segment")
        let cancelItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: nil, action: #selector(cancel))
        navItem.leftBarButtonItem = cancelItem

        navBar.setItems([navItem], animated: false)

        var items:[UIView] = [UIView]()

        picker.showsSelectionIndicator = true
        picker.delegate = self
        picker.dataSource = self

        items.append(picker)

        stackView.translatesAutoresizingMaskIntoConstraints = false

        stackView.topAnchor.constraint(equalTo: navBar.bottomAnchor, constant: 50).isActive = true
        stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 50).isActive = true

        stackView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: 0).isActive = true
        stackView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 0).isActive = true

        stackView.addArrangedSubview(picker)
    }

    @objc func cancel() {

        print("Clicked")

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 0
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    // The data to return fopr the row and component (column) that's being passed in
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

    // Capture the picker view selection
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        // This method is triggered whenever the user makes a change to the picker selection.
        // The parameter named row and component represents what was selected.

        currentSelection = pickerData[row]
    }

A: You need to move layout configuration to viewWillLayoutSubviews as the frame of the view has not been set correctly yet
Here is a good post explaining the View Controller lifecycle
https://medium.com/@felicity.johnson.mail/viewcontroller-lifestyle-e304e1078bc5

A: First, no need to specify frames when using constraints. Let the auto-layout engine do the work for you.
Second, constraints can all be set in viewDidLoad() -- you don't need anything in viewWillLayoutSubviews().
Third, it's not quite clear where you want the picker view to show, or why you are putting it in a stack view? I'm assuming you want the picker to start at 50-pts below the bottom of the nav bar, and that you'll be adding additional elements to the stack view?
So, a couple tips:

*

*During development, give views contrasting background colors to make it easy to see frames at run-time

*Use Debug View Hierarchy to help figure out bad / missing constraints

*Group your code by logical association. Such as

*

*instantiate objects

*set object properties

*add subviews

*set constraints

Here is what I get:

Using these modifications to your code:
class BenDentViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    var pickerData: [String] = [String]()

    // instantiate navBar, stackView and picker
    var navBar: UINavigationBar = UINavigationBar()
    var stackView: UIStackView = UIStackView()
    var picker: UIPickerView = UIPickerView()

    var currentSelection: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // sample picker data
        pickerData = [
            "Select a segment...",
            "Segment 1",
            "Segment 2",
            "Segment 3",
            "Segment 4",
        ]

        // set navBar properties
        let navItem = UINavigationItem(title: "Add Binge Segment")
        let cancelItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(cancel))
        navItem.leftBarButtonItem = cancelItem
        navBar.setItems([navItem], animated: false)

        // set picker properties
        picker.showsSelectionIndicator = true
        picker.delegate = self
        picker.dataSource = self

        // give it a background color so we can see its frame
        picker.backgroundColor = .yellow

        // set stackView properties
        stackView.axis = .vertical
        stackView.distribution = .fill
        stackView.alignment = .fill
        stackView.spacing = 10

        // add the picker to the stack view
        stackView.addArrangedSubview(picker)

        // add elements to self.view
        self.view.addSubview(navBar)
        self.view.addSubview(stackView)

        // we're using auto-layout constraints
        [navBar, stackView, picker].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }

        let guide = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([

            // constrain navBar to top, leading, trailing and height of 44
            navBar.topAnchor.constraint(equalToSystemSpacingBelow: guide.topAnchor, multiplier: 0),
            navBar.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 0),
            navBar.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: 0),
            navBar.heightAnchor.constraint(equalToConstant: 44.0),

            // constrain stackView leading and trailing
            stackView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: 0),
            stackView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 0),

            // constrain stackView top: 50-pts from bottom of navBar
            stackView.topAnchor.constraint(equalTo: navBar.bottomAnchor, constant: 50),

            // not needed, depending on desired layout
            //stackView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -50),

            ])

    }

    @objc func cancel() {
        print("Cancel Clicked")
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    // The data to return fopr the row and component (column) that's being passed in
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }

    // Capture the picker view selection
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        // This method is triggered whenever the user makes a change to the picker selection.
        // The parameter named row and component represents what was selected.

        currentSelection = pickerData[row]

        print("Selected row: \(row) value: \(pickerData[row])")
    }

}


text:
Q: Count number of movements of A to B I have the following problem.
On a chessboard, I have a knight on a given square (shown in red), and I need to find the path the knight can take to reach another square (shown in green).

I have to find the shortest path while obeying the movement rules of a knight in chess (L shaped moves) and count the number of moves:
like this:

I have tried different things, but without success.
What can I do?

A: You want to solve the problem in a finite amount of time, and want to favor short solutions. You should use a breadth-first search algorithm, trying out all possible moves from the starting point. Ignore moves that take the knight to squares that it has already visited.
Once you reach the destination point, you know you don't have to search for longer solutions, but you just finish enumerating all possible solutions with the same length as the first solution.

A: I didn't check online to find any heuristic for this, but I can give you some inside tips about it:
Every square on the diagonal of the actual square of the Knight can be reached in only two moves, provided that the Knight is not in the corner. Square (x, y) to the squares (x-1, y+1), (x+1, y+1), (x+1, y-1) and (x-1, y-1) takes 2 moves;

*

*The squares up, down, right, and left of the actual square takes 3 moves;
Every square on the diagonal of the actual square with one square between them (e.g., actual square = c4, target square a6), takes 4 moves;

*Every square on the diagonal of the actual square with a 2 squares between them (e.g., actual square = c4, target square f7), takes only 2 moves;

*Finally, if you are in a square with a given color you will take an odd number of moves to reach the opposite color square. If the target square has the same color as the square that you are in it will take an even number of moves;

*The number of steps that a Knight takes from a given position to another in a 8x8 board is at most 6.
I think you can make an algorithm that combines the above heuristics and adapted with the breadth-first search algorithm, that G. Sliepen has mentioned.
This answer might also help you. You also can find plenty of good answers here, with O(1) solutions.

A: Dynamic Programming solution has the recurrence description of:
DP(x,y)= 1 + min(
              DP(x-2,y-1),DP(x-2,y+1),DP(x+2,y-1),DP(x+2,y+1),
              DP(x-1,y-2),DP(x-1,y+2),DP(x+1,y-2),DP(x+1,y+2)
          );

If I'm not mistaken, will require O(N^2) to memoize.


text:
Q: Multiple dropdown menus using same JS code I have a simple drop-down menu using JavaScript.

Menu Name

                Option 1
                Option 2
                Option 3

And the JS:

I have multiple copies of the same menu in several adjacent divs. With this code, the menu works in the first element, but if I try to toggle it in the second, it only drops down in the first. How can I make this work for several menus on a single page?

A: To the myFunction pass this. That is:

Menu Name

Write a JavaScript function like below:
function myFunction(a) {
  a.parentNode.getElementsByClassName("dropdown-content")[0].classList.toggle("show");
}

No need of that much of JavaScript: keep as simple as possible.

A: You need two changes on your code :

*

*Make all buttons' onClick attributes same. (I guess it is "myFunction();")

*Change your handler to process the button which is actually clicked.

This is possible with event.target :
function myFunction(event) {
  event.target.classList.toggle("show");
}

A: You can simply do this without written any long javascript code.
use this

Menu Name

                Option 1
                Option 2
                Option 3

Menu Name

                Option 1
                Option 2
                Option 3

function myFunction(a) {
  a.parentNode.getElementsByClassName('dropdown-content')[0].classList.toggle("show");
}

.dropdown {
position: absolute;
right:5%;
  overflow: hidden;
}

.dropdown .dropbtn {

  font-size: 16px;
  border: none;
  outline: none;

  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.dropdown-content {
  display: none;

  background-color: #f9f9f9;
  min-width: 50px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.show {
  display: block;
}


text:
Q: Get a different image from the database depending on screen size I am starting to make a web app and the idea is that depending on the url it will be accessed from the load varying text and images from the data base.
www.mitdomæne.dk/?id=1 0.2 0.3 etc up to 50 pieces.
The problem now is that I must have the dynamic content to switch itself off depending on the mobile or pad (screen size).
Can I get the php to pick what size screen and echo the correct picture out?
So if it's an iphone that looks at the side the image that is 320px wide a loaded and if it is a ipad is 1024px wide.
I have created a date base of MySQL with these fields.
ID:
company:
Billed_fil
And the code looks like this.
html:

 <? php echo $ company?>

 <img src = "<? php echo $ billed_fil?>" alt = "" border = "0" />

PHP:
 <? php

 include 'firmaer_db_cnx.inc.php';

 $ id = $ _GET ['id'];
     $ sql = mysql_query ("SELECT * FROM info_int WHERE id = '$ id'");

     $ company list = mysql_fetch_array ($ sql);

     $ id = $ company list ['id'];
     $ company = $ company list ['company'];
     $ billed_fil = $ company list ['billed_fil'];

 ?>

Sql version
5.1.53
PHP version
5.3.4
Is it possible?
//Kasper

A: only possible way to get screen size is through javascript or some fimiliar fronend programming language, you could either use an ajax call, save it to a cookie and then read  it with php, or u could be a little smarter then that and save the image with the same name with one diffrence the ending... which would be the resolution,
for example iamge1024x123.png and then use javascript onload to add the proper image depending on resolution. then u save unneccersary calls to the database and would get a little performance boost while u'r at it. I hope you understood my idea and it was for somehelp

A: PHP runs on the server before it is given to the client browser so it has no idea about the screen size the client browser is running on. One way you could possibly do this is via JavaScript to retrieve the screensize and pass those values to PHP (via an AJAX call?). Of course, other SO people will come up with other ideas (probably better than mine) so it's your choice how you do it.

A: There might be an even easier way to do this using just CSS. Take a look at this demo:
http://www.alistapart.com/d/responsive-web-design/ex/ex-site-larger.html Hint: Resize your browser window.
And here is the Article explaining how to do it. Also some more background info.

A: just store the image outside of the database do something like this


text:
Q: Xml сериализация объектов со свойствами только для чтения
При сериализации массива из объектов этого класса все атрибуты игнорируются, если у них нет setter'а. Вопрос: как решить проблему с этим явлением; класс не предусмотрен для изменения данных.
/// <summary>
/// Представляет поля и методы для работы с абстракцией осциллятора.
/// </summary>
[Serializable]
public class Oscillator : IMixer
{
    private Boolean enable;
    /// <summary>
    /// Состояние вкл / выкл.
    /// </summary>
    [XmlAttribute]
    public Boolean Enable
    {
        get
        {
            return enable;
        }
        set
        {
            enable = value;
        }
    }

    private Int32 volume;
    /// <summary>
    /// Процентная громкость.
    /// </summary>
    [XmlAttribute]
    public Int32 Volume
    {
        get
        {
            return volume;
        }
    }

    public Oscillator()
    {

    }

    public Oscillator(Boolean enable, Int32 volume)
    {
        this.enable = enable;
        this.volume = volume;
    }
}

    //Вот, сама сериализация, если интересно.
    /// <summary>
    /// Сохраняет пресет в Xml-файл.
    /// </summary>
    /// <param name = "fileName">
    /// Путь к файлу.
    /// </param>
    /// <param name = "oscillators">
    /// Массив осцилляторов для записи его в пресет.
    /// </param>
    public void SavePreset(String fileName, Oscillator[] oscs)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Oscillator[]));
            using (Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                serializer.Serialize(stream, oscs);
                //for (Int32 i = 0; i < oscs.Length; i++)
                //{
                //    serializer.Serialize(stream, oscs[i]);
                //}
            }
        }
        catch
        {
            throw new PresetException(PresetException.SaveError);
        }
    }

A: Никак, это ограничение XmlSerializer.

Only public properties and fields can be serialized. Properties must
  have public accessors (get and set methods). If you must serialize
  non-public data, use the DataContractSerializer class rather than XML
  serialization.

В оригинальном ответе, как и в документации, советуют воспользоваться более гибким DataContractSerializer.

Вариант с вырожденным сеттером, думаю, рассматривать не будем.

A: Никак. Но вам это и не нужно. Вы должны иметь отдельные классы для сериализации/десериализации (и вообще любой транспортировки данных - DTO) и для бизнес-логики (POCO). И я рекомендую вам реализовать такое разделение как можно раньше, это позволит избежать глобальных ломающих изменений по мере развития проекта. Ссылка по теме: Наглядный пример различия DTO, POCO (POJO) и Value Object


text:
Q: Slick showing arrows as buttons I am having issue with this slick slider, I expected the arrows to show as in the demo usage, why it is showing up as buttons?
I included in my html
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css"/>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.css"/>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css.map"/>

A: Slick slider has settings called prevArrow and nextArrow, where you can pass html string, node object or even a jQuery object to replace the default arrow buttons.
Like this:
$('.slider-element').slick({
prevArrow: 'Go to previous slide',
nextArrow: 'Go to next slide',
});


text:
Q: Problem with server export when testing React with Jest and Supertest I'm testing a React app with an Express backend, using Jest and Supertest.  In my current test, I need to stub the fetch, which I'm doing with Supertest.  The problem is, I never get an answer from the agent get(), and thus never get any data back.
I think there is a problem with how I'm exporting my server.  I've tried changing around the exports, from module.exports = app, to module.exports = {app}, to const server = app.listen(port, etc), and module.exports = server.  So far none of the solutions I've found are working.
server.js:
const app = require('./app.js');
const port = process.env.PORT || 8080;
app.listen(port, () => console.log("Server running on port " + port));

app.js:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const ews = require('express-ws')(app);
const WebSocket = require('ws');
...
app.get("/menus", (req, res) => {
    const menus = MenuRepo.getMenus();
    res.json(menus)
})
...
module.exports = app;

home-test.js
test("Test that dishes displays", async () => {

    menuRepo.populateMenus();
    overrideFetch(app);

    const driver = mount(
        <MemoryRouter>
            <ShowMenus/>
        </MemoryRouter>
    );

    const predicate = () => {
        driver.update();
        const tableSearch = driver.find('#menuTable');
        const tableIsDisplayed = (tableSearch.length >= 1);
        return tableIsDisplayed;
    };

    const displayedTable = await asyncCheckCondition(predicate, 3000, 200);
    expect(displayedTable).toBe(true);
    const menus = menuRepo.getMenus();
    const html = driver.html();

    for(let i=0; i<menus.length; i++){
        expect(html).toContain(menus[i].dishes.day);
    }
});

function I'm using to stub fetch:
function overrideFetch(app){

    const agent = request.agent(app);

    global.fetch = async (url, init) => {

        let response;

        if(!init || !init.method || init.method.toUpperCase() === "GET"){
            try {
                response = await agent.get(url);
            } catch (e) {
                console.log(e)
            }

        } else if(init.method.toUpperCase() === "POST"){
            response = await agent.post(url)
                .send(init.body)
                .set('Content-Type', init.headers ? init.headers['Content-Type'] : "application/json");
        } else if(init.method.toUpperCase() === "PUT"){
            response = await agent.put(url)
                .send(init.body)
                .set('Content-Type', init.headers ? init.headers['Content-Type'] : "application/json");
        } else if(init.method.toUpperCase() === "DELETE"){
            response = await agent.delete(url);
        } else {
            throw "Unhandled HTTP method: " + init.method;
        }

        const payload = response.body;

        return new Promise( (resolve, reject) => {

            const httpResponse = {
                status: response.statusCode,
                json: () => {return new Promise(
                    (res, rej) => {res(payload);}
                )}
            };

            resolve(httpResponse);
        });
    };
}

I'm expecting that the stubbed fetch will return a list of seven json menus.


text:
Q: Does [temp.res]/8 in C++ standard make this program ill-formed? Let's consider a very basic case of a template class for which only specializations are valid:
template<bool B>
struct OnlyTrue; // { static_assert(B != B, "Only true!"; };

template<> struct OnlyTrue<true> { static constexpr bool value = true; };

static constexpr bool b = OnlyTrue<true>::value;

An example above effectively disallows using OnlyTrue<false> in the program by making it incomplete. An alternative would be uncommenting static_assert - and making it complete, albeit uncompilable. The benefit of this approach would be that a more human-friendly diagnostic would be generated if instantiated with disallowed value. (See Mapping an integral template parameter value onto a primitive type for a bit more meaningful example of the same technique).
Now to the question - would [temp.res]/8 in latest C++ standard, in particular, 8.1:

The program is ill-formed, no diagnostic required, if: ... no valid
  specialization can be generated for a template or a substatement of a
  constexpr if statement within a template and the template is not
  instantiated ...

Make the above snippet ill-formed with no diagnostic required?


text:
Q: Dual displays, one fixed, one spinning (CentOS 7) I have 2 monitors and would like to have my setup like this:

*

*Monitor = fixed desktop (only 1)

*Monitor = dynamic, spinning desktop (1+)

It was working like this at the beginning but somehow I changed that behavior. Now when I'm spinning both of them have multiple desktops which is a no no for me.
Is there any way to set it up like it was before?
I'm using latest GNOME.

A: Centos 7 - specifically CentOS-7-x86_64-Everything-1511.iso with a full development install
added gnome-tweak-tool (gnome-tweak-tool.noarch but perhaps it was already there)
then
Applications -> Utilities -> Tweek Tool
            Select workspaces on the left hand side
            Set off "workspaces only on primary display" and the dual monitors will spin together.
            I also recommend, still on workspaces, setting Workspace Creation to Dynamic
The above should allow you to toggle how the dual monitors behave

A: With gnome-tweaks. See screenshot (Workspaces):


text:
Q: Heroku deployed nodejs application has issues with page navigation //This is my server.js node file

var express=require('express')
var path=require('path')
var app=express()
var alfa=express.Router()
var port= (process.env.PORT || 5000)

app.use(express.static(__dirname+'/'))
alfa.get('/',function(req,res){

    res.sendFile(path.join(__dirname+'index.html'))
});

alfa.get('/movies',function(req,res){

    res.sendFile(path.join(__dirname+'movies.html'))
})

alfa.get('/shows',function(req,res){

    res.sendFile(path.join(__dirname+'tvshows.html'))
})

app.use('/',alfa)
app.listen(port);
console.log('Go to the port : ' + port);

The index.html has a href to movies.html file.
Findout More...

After deploying to heroku cloud when running the application, the first page loads(without proper css;linked to an external css file, which is expected to be of a similar issue).
On click of the movies href link the error appears in the browser saying internal server error or page not found.
Later I checked the Heroku logs for the application and it says as below:
/app is appended before the href path movies.html
2016-01-30T00:27:06.417098+00:00 heroku[router]: at=info method=GET path="/scrol
l.js" host=alfapalakoti.herokuapp.com request_id=6b078679-71a4-436e-9b22-ab87de6
7c534 fwd="50.156.90.248" dyno=web.1 connect=1ms service=47ms status=200 bytes=6
70
2016-01-30T00:27:06.527645+00:00 heroku[router]: at=info method=GET path="/tv.pn
g" host=alfapalakoti.herokuapp.com request_id=05d76121-4af2-4d65-8425-ff4df7684a
6f fwd="50.156.90.248" dyno=web.1 connect=1ms service=14ms status=200 bytes=1499
9
2016-01-30T00:27:06.532690+00:00 heroku[router]: at=info method=GET path="/timer
.png" host=alfapalakoti.herokuapp.com request_id=5438c650-65e2-4f21-8c10-346f71c
60182 fwd="50.156.90.248" dyno=web.1 connect=1ms service=11ms status=200 bytes=2
5665
2016-01-30T00:27:06.540491+00:00 heroku[router]: at=info method=GET path="/shows
.jpg" host=alfapalakoti.herokuapp.com request_id=7afbf80b-071d-4ab1-9c18-cb36c71
f444b fwd="50.156.90.248" dyno=web.1 connect=1ms service=33ms status=200 bytes=3
69678
2016-01-30T00:27:06.625994+00:00 heroku[router]: at=info method=GET path="/carou
selbg.jpg" host=alfapalakoti.herokuapp.com request_id=2c371ea0-d47b-46e2-b9a1-51
28fbfaba4a fwd="50.156.90.248" dyno=web.1 connect=1ms service=112ms status=200 b
ytes=2069053
2016-01-30T00:27:06.781953+00:00 heroku[router]: at=info method=GET path="/mainb
g.jpg" host=alfapalakoti.herokuapp.com request_id=e43a6ac3-0b68-40f6-95ba-edc988
a57a91 fwd="50.156.90.248" dyno=web.1 connect=1ms service=6ms status=200 bytes=1
1178
2016-01-30T00:27:06.623717+00:00 heroku[router]: at=info method=GET path="/movie
s.jpg" host=alfapalakoti.herokuapp.com request_id=61d32aa0-0158-4962-8f8c-5f1a30
2e8654 fwd="50.156.90.248" dyno=web.1 connect=1ms service=259ms status=200 bytes
=4974518
2016-01-30T00:27:16.482080+00:00 heroku[router]: at=info method=GET path="/movie
s" host=alfapalakoti.herokuapp.com request_id=efc2a66c-6ec0-4e76-9afb-39384b8513
52 fwd="50.156.90.248" dyno=web.1 connect=1ms service=14ms status=404 bytes=208
2016-01-30T00:27:16.492630+00:00 app[web.1]: Error: ENOENT: no such file or dire
ctory, stat '**/appmovies.html'**
2016-01-30T00:27:16.492634+00:00 app[web.1]:     at Error (native)
2016-01-30T01:00:47.163686+00:00 heroku[web.1]: State changed from up to down
2016-01-30T01:00:47.162812+00:00 heroku[web.1]: Idling
2016-01-30T01:00:54.049172+00:00 heroku[web.1]: Stopping all processes with SIGT
ERM
2016-01-30T01:00:57.704556+00:00 heroku[web.1]: Process exited with status 143

//can someone please help me with this?

//why is that being added? How to get rid of it?


text:
Q: HTML textarea renders much narrower than what's specified in the CSS Given the following HTML:
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='iso-8859-1' />
    <title>Test</title>
    <style>
        #IssuesListFieldSet {
            width: 52em;
            padding: 0;
            margin: 0;
        }

        #IssuesList_result {
            width: 52em;
            padding: 0;
            margin: 0;
            border: 1px solid red;
        }

        #IssuesList_result_html {
            width: 52em;
            height: 100px;
            display: block;
            padding: 0;
            margin: 0;
            border: 2px solid cyan;
        }
    </style>
</head>
<body>

<form action='#' method='post'>
    <fieldset id="IssuesListFieldSet">
        <legend>Issues:</legend>
        <div id="IssuesList_result">
            Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi.
        </div>

        <textarea readonly id='IssuesList_result_html' cols='20' height='5'>
            Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos.
        </textarea>
    </fieldset>
</form>

</body>
</html>

How do I get the textarea to be the same width as the div right above it? I'm trying to set each of the elements to roughly the same width, which for now is 52 em, but the textarea is rendering narrower than that. I understand that rendering engine minutiae can throw things off by a few pixels, but the difference here is much more than that (maybe 40% too small).
I'm testing in Safari 5.

A: The em measurement is based on the font used for the element.
By default (in Firefox 3.6.x on OS X, anyways), <textarea> elements default to a monospace font.
Make sure you have a font applied to the element, and they should match up.
Live Demo

A: Try modifying your cols attribute. That should also change the size of the textbox.

A: First, remove the cols attribute.
Then, since an em is a unit based on the size of the element's font, you need to make sure that each of the elements that you are trying to size to 52em have the same font-family and font-size css defined.
Or, use pixels for the width and you shouldn't have to worry about the font.
I tried it in Firefox and just setting the font-size:9pt for each element and leaving out the font-family worked great.


text:
Q: Fundamental theorem of calculus when endpoint is an integral I have to solve the following
$$ F(x) =\int_0^{\int_1^x \sin^{3}t\, dt} \frac{1}{1+t^{2}+\sin^{6}t}\, dt $$
using the fundamental theorem of calculus i.e I have to obtain $f(x)$ by finding $F'(x)$, so far
I tried seeing $$\int_1^x \sin^{3}t \,dt$$ as a function of $x$ but I am not sure if that is possible and haven't found a similar problem so far so I would like to have some insight on solving this kind of problem.

A: Hint
Let
$$G(x)= \int_0^{H(x)} \frac{1}{1+t^{2}+\sin^{6}t} \,\mathrm dt \\
H(x)=\int_1^x \sin^{3}t \,\mathrm dt$$
Then
$$F(x)= G \circ H(x)$$
and the FTC tells you what $G'(x)$ and $H'(x)$ are.


text:
Q: Input values in a column according to the reference from another column of the same sheet hi I have a problem in inputting values into a column with conditions and referring to the other 2 or more columns to determine the input of the other column using VBA. for example there are 3 columns called RAG cost (C), RAG Resources (R) and RAG Benefits (B). this 3 columns will determine the input value in a column called Overall RAG using VBA.
for example if column (C) or column (B) contains the value"R" , then the overall RAG Status will be input as "A" in the respective rows. I tried using the if else statement but it doesn't seems to work.
to make it clearer this is the example: if RAG Cost(C) OR RAG Resources(R) VALUES = "R" then Overall RAG status= "A".

A: You don't need vba for this you can write a simple formula like
=IF(ISERROR(MATCH("R",B2:D2,0)),"","A")

If You want code please try this
Sub rgb()
Dim lstrow As Long
Dim i As Long
Dim LastCol As Long
Dim j As Long

lstrow = Range("B" & Sheets("Sheet1").Rows.Count).End(xlUp).Row
LastCol = Sheets("Sheet1").Cells(1, Sheets("Sheet1").Columns.Count).End(xlToLeft).Column
For i = 2 To lstrow
    For j = 2 To LastCol
        If ActiveSheet.Cells(i, j).Value = "R" Then
            Range("A" & i).Value = "A"
        End If
    Next j
Next i

End Sub


text:
Q: Настройка роутера TrendNet Я правильно понимаю, что админские вопросы теперь тоже сюда?
Есть у меня давняя проблема с роутером Trendnet TEW-652BRP и внешним статическим ip. Настраиваю переброс портов. Соединения из интернета роутер перебрасывает на мой компьютер. Соединения из локальной сети на тот же статический ip закрываются с ошибкой. Как сделать, чтобы соединения из локальной сети тоже перебрасывались правильно?

A: Проблема в том, что компьюетер на запрошенные по внешнему адреса соединения отвечает со своим локальным адресом. В то же время клиент ожидает внешнего.
Для работы проброшенного адреса в локальной сети есть пара вариантов.
1) Использовать DNS имя указывающее на локальный адрес. Для большой оно должно быть прописанно на DNS сервере, для средней можно сделать статическую запись в dns-proxy (обычно это роутер), если же компьютеров всего несколько - то проще добавить в hosts файл конечных компьютеров.
2) Использовать маскировку, вроде:
iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -d 192.168.0.0/24 -j SNAT --to-source 192.168.0.1

— в этом случае ответ будет послан через роутер, где адрес подменится на внешний.
3) Использовать DMZ подсеть с другой маской, чтоб заставить локальный трафик ходить через роутер всегда. Например выдать адрес 192.168.1.12/24 для сервера и настроить соответствующую маршрутизацию.
Скорее всего понадобится перепрошить роутер в опенврт или ддврт, чтоб получить эти возможности.


text:
Q: Is the converse of Dirichlet convergence test true? Dirichlet convergence test for series says:
Condition 1: Let $\{ a_n \}$ is a monotonically decreasing sequence of real numbers
Condition 2: Let $\{ b_n \}$ is a sequence of real numbers such that for all $N,$ $ \sum_{n=1}^N b_n < M $ where is $ M $ is a constant (not dependent on $N$
Example: $ \sum_{n=1}^\infty \frac{1}{n} \sin n $ is convergent.
If conditions 1 and 2 are true, then $ S = \sum_{n=1}^\infty a_n b_n $ is convergent.
My question is: is the converse also true? That is, if $ S $ is convergent and condition 1 is true, then does it imply condition 2 is also true? Or if $S$ is convergent and condition 2 is true then does condition 1 follow?

A: No, to both.
For the first:  take $$a_n=\frac 1{n^3}\quad b_n=n$$  then $\sum a_nb_n$ converges, condition $1$ is met, but condition $2$ fails.
For the second: swap $a_n, b_n$ in the above.


text:
Q: How can i check and inform the user when connected to the ftp server successfully? In this button2 click event i'm starting a backgroundworker that will retrieve all the directories and files from my ftp server and will display them in real time on a treeView.
private void button2_Click(object sender, EventArgs e)
        {
            label13.Text = "Retrieving ftp content please wait";
            button2.Enabled = false;
            button3.Enabled = false;
            toolStripProgressBar2.Visible = true;
            backgroundWorker1.RunWorkerAsync(txtHost.Text);
        }

In the backgoundworker1 do work event i did:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var root = Convert.ToString(e.Argument);  // txtHost.Text;

            searched_until_now_dirs = 0;
            total_dirs = 1;
            max_percentage = 0;
            last_update = DateTime.Now;
            directories_real_time = new TreeNode();
            var dirNode = CreateDirectoryNode(root, "root",1);

            e.Result = dirNode;
        }

The method CreateDirectoryNode
private int total_dirs;
        private int searched_until_now_dirs;
        private int max_percentage;
        private TreeNode directories_real_time;
        private string SummaryText;

        private TreeNode CreateDirectoryNode(string path, string name , int recursive_levl )
        {
            var directoryNode = new TreeNode(name);
            var directoryListing = GetDirectoryListing(path);

        }

And GetDirectoryListing:
public IEnumerable<FTPListDetail> GetDirectoryListing(string rootUri)
        {
            var CurrentRemoteDirectory = rootUri;
            var result = new StringBuilder();
            var request = GetWebRequest(WebRequestMethods.Ftp.ListDirectoryDetails, CurrentRemoteDirectory);
            using (var response = request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append("\n");
                        line = reader.ReadLine();
                    }
                    if (string.IsNullOrEmpty(result.ToString()))
                    {
                        return new List<FTPListDetail>();
                    }
                    result.Remove(result.ToString().LastIndexOf("\n"), 1);
                    var results = result.ToString().Split('\n');
                    string regex =
                        @"^" +               //# Start of line
                        @"(?<dir>[\-ld])" +          //# File size
                        @"(?<permission>[\-rwx]{9})" +            //# Whitespace          \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<filecode>\d+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<owner>\w+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<group>\w+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<size>\d+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<month>\w{3})" +          //# Month (3 letters)   \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<day>\d{1,2})" +        //# Day (1 or 2 digits) \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<timeyear>[\d:]{4,5})" +     //# Time or year        \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<filename>(.*))" +            //# Filename            \n
                        @"$";                //# End of line

                    var myresult = new List<FTPListDetail>();
                    foreach (var parsed in results)
                    {
                        var split = new Regex(regex)
                            .Match(parsed);
                        var dir = split.Groups["dir"].ToString();
                        var permission = split.Groups["permission"].ToString();
                        var filecode = split.Groups["filecode"].ToString();
                        var owner = split.Groups["owner"].ToString();
                        var group = split.Groups["group"].ToString();
                        var filename = split.Groups["filename"].ToString();
                        var size = split.Groups["size"].Length;
                        myresult.Add(new FTPListDetail()
                        {
                            Dir = dir,
                            Filecode = filecode,
                            Group = group,
                            FullPath = CurrentRemoteDirectory + "/" + filename,
                            Name = filename,
                            Owner = owner,
                            Permission = permission,
                        });
                    };
                    return myresult;
                }
            }
        }

And last where i'm doing the ftp request:
private FtpWebRequest GetWebRequest(string method, string uri)
        {
            Uri serverUri = new Uri("ftp://"+ uri);
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                return null;
            }
            var reqFTP = (FtpWebRequest)FtpWebRequest.Create(serverUri);
            reqFTP.Method = method;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(txtUsername.Text, txtPassword.Text);
            reqFTP.Proxy = null;
            reqFTP.KeepAlive = false;
            reqFTP.UsePassive = false;
            return reqFTP;
        }

When i'm clicking the button and start the backgroundworker it takes some seconds untill it's starting to retrieve the directories and files and display them on the treeView.
What i want to do now is somehow in the GetwebRequest i think in this method to wait untill i get connected successfully to the ftp server and only then to start rerieving the directories and files.
If there was an erorr/problem connecting the server display it to the user with a label for example and stop the backgroundworker.
But the whole idea is to give the user some message if he got connected to the ftp server successfully or not before the operation started.

A: When you run into a error in your GetWebReqeust your already returning a NULL value meaning you cannot get a working connection. In your GetDirectoryListning you should catch this NULL value and throw it up to your background DoWork event. Inside there you could check for the null and if needed call the .cancel method on the background worker. this will complete the dowork event and trigger the RunWorkerComplete event.
then use the RunWorkerCompletedEventHandler to set the label to a value you like to display when the connection failed. Microsoft wrote a example how to do this here


text:
Q: How to run WebSocket (django-channels) in production Pythonanywhere? I created a simple chat app using WebSockets after following the official Django-channels tutorial. However, I can't get it to work in production. I have done a few google searching to find out a forum in Pythonanywhere saying that they don't support WebSocket, I contacted the team and they told me the same thing.
I have done even more google searching and found things related to Daphne server, Nginx, and a few other things I never heard about before.
As I'm new to Django-channels I'm currently very confused! Is there something I can do to make my WebSocket website run normally in Pythonanywhere on production (for free of course) Or I have to delete all of the WebSocket code and replace it with repetitive Http called to check of new messages (With AJAX)?
And if there is no other solution but to move to repetitive Http calls, is there any other web hosting service that offers free play which includes free SSL certification, the domain name (such as mydomain.servicename.com) instead of random characters, and WebSocket support?
Thanks
 the code i use
I don't know if it was relevant, also it's working perfect in development so i don't think there is an error in it
settings.py:
INSTALLED_APPS = [
    'channels',
    ...
    'django_cleanup',
]

ASGI_APPLICATION = 'orgachat.routing.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

main routing.py  (in route folder)
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from chat.routing import websocket_urlpatterns as chat_routing

application = ProtocolTypeRouter({
    "websocket": AuthMiddlewareStack(
        URLRouter(
            chat_routing,
        )
    )
})

routing.py for chat app
from django.urls import path
from . import consumers

websocket_urlpatterns = [
    path('ws/chat/room/<int:room_id>/', consumers.RoomConsumer),
]

consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer

class RoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.group_name = str(self.scope['url_route']['kwargs']['room_id'])
        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()

    async def disconnect(self, code):
        await self.channel_layer.group_discard(self.group_name, self.channel_layer)

    async def receive(self, text_data):
        message_json = json.loads(text_data)
        await self.channel_layer.group_send(self.group_name, {
            'type': 'send_message',
            'content': message_json['content'],
            'area': message_json['area'],
            'area_id': message_json['area_id'],
            'username': self.scope['user'].username,

        })

    async def send_message(self, event):
        await self.send(json.dumps(event))

full js script

A: Websockets, and therefore, django-channels are not supported on PythonAnywhere.


text:
Q: has_many through & Collection Select issues I'm stumped.  I'm getting an error of unknown attribute 'products_part' for Part.  I'm starting with trying to create a new part that is associated with many different products through the products_parts table.  Relevant code:
# schema.rb
create_table "products_parts", force: :cascade do |t|
  t.integer "product_id"
  t.integer "part_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

Just in case it's relevant, there is a product_id column existing on the parts table from my existing setup that only allowed one part per product.  I don't think this would interfere though?
# part.rb
class Part < ApplicationRecord
  has_many :products_parts
  has_many :products, through: :products_parts

  accepts_nested_attributes_for :products_parts, :allow_destroy => true
end

# products_part.rb
class ProductsPart < ApplicationRecord
  belongs_to :product
  belongs_to :part
end

# product.rb
class Product < ApplicationRecord
  has_many :products_parts
  has_many :parts, through: :products_parts
  accepts_nested_attributes_for :parts, :allow_destroy => true
end

--
# parts_controller.html.erb
class PartsController < ApplicationController
  before_action :set_part, only: [:show, :edit, :update, :destroy]

  def new
    @part = Part.new
    @part.uploads.build
    @products_parts = @part.products_parts.build
    @product = Product.order(brand_name: :asc).order(manufacturer_model_number: :asc)
  end

  def create
    @part = Part.new(part_params)
      if @part.save
        redirect_to part_path(@part), notice: '// Part was successfully created.'
      else
        render :new
      end
  end

  private

    def part_params
      params.require(:part).permit!
    end

end

Parameters being passed on submit:
Request
Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"f+ObKsfs2QNP6l1MEDGSj6EZERMpHT/7vVKjAumC1aQmeTKdlPJNeSv2IZwNgsVPnKt2Siqi9x5oMmD2Ti8kMQ==",
 "part"=>
  {"products_part"=>{"product_ids"=>["", "191", "7"]},
   "manufacturer_model_number"=>"Screws-HB",
   "notes"=>""},
 "commit"=>"Create Part"}

-
# _form.html.erb
<%= bootstrap_form_for @part, url: parts_path, method: :post, :html => { :multipart => true } do |f| %>
  <%= f.fields_for(@products_parts) do |ff| %>
    <%= ff.collection_select(:product_ids, @product, :id, :product_select_with_model,
                             {:placeholder => "Select Product...", hide_label: true, :selected => @part.products.map(&:id)},
                             {:multiple => true, :class => 'newPartProductSearch', :style => "width:100%;"}) %>
  <% end %>
  <%= f.submit "Create Part", :style => "float:right;" %>
<% end %>

I am basing a lot of what I did here off of help from this post.
If anybody has any ideas on what direction I can go to start fixing this, it would be appreciated!

A: Replace the _form with the following code:
# _form.html.erb
<%= bootstrap_form_for @part, url: parts_path, method: :post, :html => { :multipart => true } do |f| %>

  <%= f.collection_select(:product_ids, Product.all, :id, :name,
                          {include_blank: false, :include_hidden => false, :selected => @part.products.map(&:id)},
                          {:multiple => true}) %>

  <%= f.submit "Create Part", :style => "float:right;" %>
<% end %>

It is not tested. But hope it'll work.


text:
Q: CMD dir List video files - Not Found error I crafted some command line code (function? I don't know the technical term, my apologies) that is meant to look in a network folder (and all it's subfolders) and only list the file path for those files that are a particular type. I tried to test it on a folder with less information in it first, however I got the error File Not Found. This confused me because I looked in the folder--there were definitely .VOB and .mp4 files in the specified folder.
When I run the code included below, I don't get the error, BUT I'm getting a bunch of files I don't want (.pdf .xml .jpeg--etc.) I think because they're system files such as the .jpeg files for the .avi thumbnails.
dir "\\nas-rb4b\projectx2" /s /b *.avi *.mov *.mp4 *.wmv *.mpg *.lnk *.ldb *.rar *.mpeg *.m4v *.vob *.zip>Projx2RERUN.txt

Can anyone help me understand why I got the File Not Found error when I tried to run the exact same code but with a different more specific folder?
I also don't know how to modify the code/function to exclude files that are not the listed file types and are not system folders. Any help is, as always, much appreciated!

A: Read the newest dir command reference in Windows Commands:
Syntax:

dir [<Drive>:][<Path>][<FileName>] [...] [/p] [/q] [/w] [/d] [/a[[:]<Attributes>]][/o[[:]<SortOrder>]] [/t[[:]<TimeField>]] [/s] [/b] [/l] [/n] [/x] [/c] [/4]

Remarks:

To use multiple FileName parameters, separate each file name with a
  space, comma, or semicolon.

The command in question dir "\\nas-rb4b\projectx2" /s /b *.avi *.mov *.mp4
 (truncated) says and performs the following:

*

*dir "\\nas-rb4b\projectx2" /s /b, (i.e. all files in "\\nas-rb4b\projectx2"), then

*dir /s /b *.avi (i.e. all .avi files in the current directory), then

*dir /s /b *.mov (i.e. all .mov files in the current directory), then

*dir /s /b *.mp4 (i.e. all .mp4 files in the current directory), …

Solution (read pushd and popd reference as well):
pushd "\\nas-rb4b\projectx2"
dir /s /b *.avi *.mov *.mp4 *.wmv *.mpg *.lnk *.ldb *.rar *.mpeg *.m4v *.vob *.zip>Projx2RERUN.txt
popd

A: Following some advice from Ken White along with a combination of the answers given here, here, and information from here I made the expression below which eventually worked for me.
dir /b /s \\nas-rb4b\projectx2\*.avi \\nas-rb4b\projectx2\*.mov \\nas-rb4b\projectx2\*.mp4 \\nas-rb4b\projectx2\*.wmv \\nas-rb4b\projectx2\*.mpg \\nas-rb4b\projectx2\*.rar \\nas-rb4b\projectx2\*.mpeg \\nas-rb4b\projectx2\*.m4v \\nas-rb4b\projectx2\*.vob \\nas-rb4b\projectx2\*.zip

It is not pretty but it allowed me to search for multiple file types using only one expression and have their paths all sent to one txt file rather than searching each file extension individually.
So far it is working as intended.


text:
Q: Mobicents DTMF rtp event detection I found in Mobicents MMS description (http://www.mobicents.org/mms/mms-main.html) i found that it supports DTMF inband and also RFC2833.
In practical tests I found that MS prefer inband DTMF. Is there configuration option to force RFC2833, or is it hardcoded? And if is hardcoded, cound you give me a hint, where should I change it in the code? Example of SDP with codec list looks like:
m=audio 11284 RTP/AVP 8 0 101
a=rtpmap:8 PCMA/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
a=sendrecv


text:
Q: Doctrine selected joined objects I have two two related entery (class):
First class (Todo class):
class Todo
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
}

And Comment class(part):
class Comment
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * ID человека
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Todo")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="postid", referencedColumnName="id")
     * })
     */
    private $postId;
}

How I can select comment's by Todo id?
In Controller I try :
$todos=$this->getDoctrine()
    ->getRepository('AppBundle:Todo')
    ->find($id);
//   var_dump($todos);
$em=$this->getDoctrine()->getManager();
$comments=$em->createQueryBuilder()
    ->select('c')
    ->from('Comment','c')
    ->leftJoin('')
    ->where('postid',':postID')
    ->orderBy('postid', 'ASC')
     ->setParameter('postID', $id)
     ->getQuery()
     ->getResult();

How to choose Comment on the connection with Todo?

A: Perhaps these changes will do what you want:
class Comment
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * ID человека
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Todo")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="postid", referencedColumnName="id")
     * })
     */
    private $post;
}

and...
$todos = $this->getDoctrine()
    ->getRepository('AppBundle:Todo')
    ->find($id);

$em = $this->getDoctrine()->getManager();
$comments = $em->createQueryBuilder()
    ->select('c')
    ->from('Comment', 'c')
    ->leftJoin('AppBundle:Todo', 't')
    ->where('c.post = :todo')
    ->orderBy('post', 'ASC')
    ->setParameter('todo', $todos)
    ->getQuery()
    ->getResult();


text:
Q: restrict x-axis zoom & pan Flot time based chart I'm trying to use time based data in flot.
I have the chart plotting the data correctly and I have enabled panning and zooming.
My problem is that I cannot restrict the pan and zoom to a reasonable time period, for example, my data might span March 2011, but I am able to zoom out to a range from january 1900 to january 2100 and beyond.  The same with panning.
What I'd like to do is restrict panning and zooming to the year over which the data is available.  for the above example, zoom would be restricted to the year 2011 and a max zoom in of 1 day.  Panning would be restricted to the year 2011.
How can this be done?

A: Look at the zoomRange and panRange options to the navigate plugin.


text:
Q: Avalanche runout analysis within the latest TauDEM-package does not work (Error 000732: Parameters are not vaild) I am trying to calculate the runout of avalanches with the TauDEM-toolbox (Version 5.3.7). I am running ArcGIS 10.4 and Windows 10.
I have tried using the sample data provided, following their tutorial and and it worked. When I am using my data (which I converted from .asc into .tif format with QGIS beforehand) I get the following message: ExecuteError: Failed to execute: Parameters are not valid.

All data have the same coordinate system as well as the same projection.

A: After each TauDEM function is run, the Python script that wraps this calculates uses an arcpy.calculateStatistics_management function on the results so that when they are added to ArcGIS they display nicely.  In this case this function is indicating that the file it needs was not found, which means it was not written by the TauDEM function.  Text in the tool output window above the text shown in the screen shot may indicate the problem.
A common problem with setting up inputs for a tool like this for TauDEM is that the dimensions (rows, columns, cell size) of the input grids have to match exactly (TauDEM does not do interpolations when doing cell by cell calculations).  It is likely that your avalanche source site "Ass" grid (because you have to provide this independently of any other TauDEM results) has different dimensions.  Try use the Environment Setting -> Processing Extent option to set the Extent and Snap Raster the same as one of the TauDEM rasters. A Raster Calculator Map Algebra expression that just evaluates your current input with TauDEM raster used in the Environment Settings could achieve this.

A: David Tarboton provided me the following answer: Rows and columns have to match exactly in both data sets. Normally there is an error message if these parameters don´t match but in my case the program was aborting before printing this message.

A: A little follow up in case anyone else runs across this problem:
All three inputs - the Pit Filled Elevation Grid,  the Flow Direction Grid and the Avalanche Source Site Grid - have to have the same exact size. This means that the number of columns and rows have to be identical PLUS the extent has to start on the same pixel (origin).
If the extent is off, even by a fraction of a meter (e.g. 100000 v. 100000.00001 for UTM) then the process will return ERROR 000732 and fail.


text:
Q: App Inventor : background I recently installed a background for my project on app inventor, and then after I tried running the background behind the text in the emulator. On my designer screen I have put the background image behind the text which is the normal condition?

A: it's hard to understand, what you are saying... but try to set Screen1.BackgroundColor to none

A: rephrasing your question might help
yes, you can set the screen background from the designer view by uploading an image at BackgroundImage textfield and if there are many uploaded image, choose the right one.
any component added will be displayed above the image !
with blocks you can do :
when screen1.Initialise
do:
    set screen1.BackgroundImage to |your-uploaded-image|


text:
Q: Why this type of PySpark isin mapping is not Working Here's my code
listOTHERS_hpos = ['BLACKBERRY 7', 'SYMBIAN', 'NOKIA OS', 'BLACKBERRY 10', 'WINDOWS']
lastvalue_month = lastvalue_month.withColumn('handset_type',
                        when(col('handset_os').isin(listOTHERS_hpos) , lit('OTHERS')))
lastvalue_month.groupBy('handset_os').count().orderBy('count').show()

Here's the Output
+-------------+-----+
|   handset_os|count|
+-------------+-----+
|      WINDOWS|    6|
|BLACKBERRY 10|    8|
|     NOKIA OS|   15|
|      SYMBIAN|   39|
| BLACKBERRY 7|   43|
|    UNDEFINED| 1218|
|    APPLE IOS| 1496|
|        OTHER| 3705|
|      ANDROID|13218|
+-------------+-----+

As by code it should be
+-------------+-----+
|   handset_os|count|
+-------------+-----+
|       OTHERS|  111|
|    UNDEFINED| 1218|
|    APPLE IOS| 1496|
|        OTHER| 3705|
|      ANDROID|13218|
+-------------+-----+

A: You should group columns using a correct column. Moreover using .otherwise() is helpfull in when:
lastvalue_month = lastvalue_month.withColumn('handset_type',
                        when(col('handset_os').isin(listOTHERS_hpos) , lit('OTHERS')).otherwise(col('handset_type')))
lastvalue_month.groupBy('handset_type').count().orderBy('count').show()


text:
Q: Renaming file ending with MMDDYY.xls I need help renaming some files in mmddyy format. I have a batch file to move files ending in mmdd and am trying to expand off it but I'm having some troubles. Here is how it looks at the moment:
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

rename C:\tim\example.xls example%mm%%dd%yy%.xls

When I run the batch file it will rename it, example1031yy.xls. I suspect it has to do with the first half, but somebody gave me those line of code to move files just ending in mmdd.
What I want to achieve is rename example.xls to example103114.xls (today date)

A: You missed a percent-sign:
rename C:\tim\example.xls example%mm%%dd%%yy%.xls
                                         |
                                         Here!


text:
Q: Help With Do While Loops I understand this question has been asked before but for some reason I can't get it to work also I'm new to stackexchage so I apologize if everything I write is not up to standards.
That being
While[procedure;test]
In the code I'm currently working on I'm trying to make a matrix but only if it makes certain conditions.
The Code as it currently stands is
x=Table[RandomChoice[{1-alpha*E^(-1/Total[listA]),alpha,alpha*E^(-1/Total[listA]}->{-1,0,1}]*ListB[[i]]*ListB[[j]],{i,Length[ListB]},{j,Length[ListB]}]
and I'm trying to make the code cycle through till it hits condition of Det[%]>0

A: I've just made up listA and listB:
listA = {1, 2, 3, 4, 5};
listB = {8, 7, 6, 5, 4}; alpha = 1;
x := Table[RandomChoice[{1 - alpha*E^(-1/Total[listA]), alpha,
      alpha*E^(-1/Total[listA])} -> {-1, 0, 1}]*listB[[i]]*
      listB[[j]], {i, Length[listB]}, {j, Length[listB]}]
While[m = x; Det[m] <= 0];
m

The final m is a matrix with positive Det. Because of the := definition, each time through the While, a different m is produced.


text:
Q: Dataframe to dictionary when dealing with sparse vectors I have a pandas dataframe with about 3000 columns.
The first column lists a category (the values can be repeated).
The second column all the way to the last column lists 1s and 0s (its somewhat of an indicator matrix). There are 20 or less 1s per row, so I am dealing with a sparse matrix.
I want to create a dictionary such that, when given a particular category, it gives you a matrix of the cosine distances of all the indicator vectors in the category (with the order from the data frame preserved). My data has about 100,000 rows as well, so I'm looking for an efficient way to do this.
Thanks