text:
Q: customize mikrotik hotspot firewall rules I have a router os installed on a virtual server, with 3 interfaces:

lan-192.168.1.1/24
wan-192.168.2.1/24
wifi-192.168.3.1/24

I have a PPOE client to connect over WAN to ISP and get static public IP

x.x.x.x

I have a windows server with DNS, HTTP services on LAN interface, and 1 wireless access point on WIFI interface.
I have created rules for block incoming connection from internet, except 80,53,...
I have created dst-nat from my public IP x.x.x.x to local server IP.
Another dst-nat from LAN to server LAN IP address.
Also SRC NAT to masqurade, LAN and WIFI connections to server.
Another SRC-NAT masqurade for access internet.
Also mikrotik DNS service used to get records and catch from my local server DNS service.
All things work good, until, I want create hotspot service on WIFI interface.
dynamic firewall filters and NATs destroy all things work.

Scenario is access WIFI users to internet by authentication and access local server locally and free.
Also internet access for lan users free.
Also public web access to my server from internet.
Thanks in advance!

A: NOTE: Skip to TLDR if you just want the direct answer.
This configuration has been made far more complicated than necessary. I'm going to write this up from memory because I don't have an unused router handy at the moment, but this should work.
I'm going to make some assumptions here:

*

*You do not want anyone from the WAN or PPPoE to be able to reach your LAN.

*You don't want anyone from the WIFI to be able to reach your LAN except for HTTP or DNS.

*You FULLY intend to circle back once everthing is working and ENABLE HTTPS on your server. THIS IS IMPORTANT!!!

First, set up everything to work without restriction. No rules except for a single masquerade entry. You want to masquerade all traffic NOT destined for 192.168.0.0/16. This rules is all you will need. the DST-NAT rules are unnecessary unless you want to provide service to traffic on the PPPoE interface.
Next, add the following firewall rules under the FORWARD chain:

*

*ACCEPT all Established and all Related traffic (no other restrictions).

*ACCEPT FROM 192.168.3.0/24 TO TCP 80,53,443 destined for your Windows Server IP address.

*ACCEPT FROM 192.168.3.0/24 TO ICMP destined your Windows Server IP address.

*ACCEPT FROM 192.168.1.0/24 TO !192.168.0.0/16. This allows Internet access for the LAN.

*ACCEPT FROM 192.168.3.0/24 TO !192.168.0.0/16. This allows Internet access for the WIFI.

*DROP everything else.

Make sure everything still works. These basic rules will give you at least some protection on your LAN from random people connecting to your WIFI. This way, if you ever disable your Hotspot to allow unrestricted access through your Wifi, you're LAN is still protected.
* TLDR *
Now you can set up your hotspot. The most important part is on your Walled Garden IP list tab, under IP -> Hotspot. You must add entries here allowing access to whatever servers you want to function before someone logs on, specifically your server's HTTP, DNS, etc services. The Hotspot will translate these into automatically-created firewall rules for you.
Finally, I would remiss if I didn't tell you that this is not a complete firewall setup, and there's all sorts of stuff that can go wrong here if things are not implemented properly. My email is in my profile here if you are interested in paid assistance.


text:
Q: How to plot heatmap based on GradientBoost results? I want to print a heatmap of a confusion matrix based on my results of y_predict and y_train.
I'm a bit stuck and I already looked up the pandas documentation of the heatmap, but still don't know how to apply it on my results. The dataset I used is about incomes and has categorical and numerical data. I've already applied the GB classifier and I got an result.
The only thing that remains is the heatmap.
print(confusion_matrix(y_train,y_pred_train))
print(y_train)

this was the outcome
Confusion Matrix:

[[14151   710]
 [ 1844  2831]]
Name: income, Length: 19536, dtype: int64

this was an attempt to make a heatmap
import seaborn as sns
class_names = y_train, y_pred_train

def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
    df_cm = pd.DataFrame(
        confusion_matrix, index=class_names, columns=class_names,
    )
    fig = plt.figure(figsize=figsize)
    try:
        heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
    except ValueError:
        raise ValueError("Confusion matrix values must be integers.")
    heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
    heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    return fig

which returned
NameError                                 Traceback (most recent call last)
<ipython-input-36-3bd0e9ee90a4> in <module>()
     18     plt.xlabel('Predicted label')
     19     return fig
---> 20 print(fig)

NameError: name 'fig' is not defined

So what am I missing when I'm making the heatmap of the confusion matrix on my results?

A: You can call your print_confusion_matrix function with the confusion matrix and class names list as parameters:
def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):
    df_cm = pd.DataFrame(
        confusion_matrix, index=class_names, columns=class_names,
    )
    fig = plt.figure(figsize=figsize)
    try:
        heatmap = sns.heatmap(df_cm, annot=True, fmt="d")
    except ValueError:
        raise ValueError("Confusion matrix values must be integers.")
    heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)
    heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    return fig

confusion_matrix = np.array([[14151, 710], [1844, 2831]])
fig = print_confusion_matrix(confusion_matrix, ['0', '1'])

Output:

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to prevent the browser from opening new sessions for images loaded by javascript and php I have designed a system to get some user data(screen resolution and etc) by javascript.
In HTML files, by javascript, screen resolutions will be send to server via get parameters of a url(an image).
the problem is that when the image is requested from server, a new session instance will be created, while I expect that the session for getting the image would be the same as the session of the parent page.
please, if you have any idea how could I resolve this problem.
thank alot.
the codes I am using are as follows:
I have put a javascript in all of my web pages to get screen resolution. Here is the javascript code:
 <script language="JavaScript">
 document.getElementById("mypictureid").src="http://www.mywebsite.com/getresolutionpic.php?w="+screen.width+"&h="+screen.height;
</script>

and the html of the pages includes:
<img id="mypictureid" src="http://mywebsite.com/otherimage.gif"

and the following php code will be executed with each page loading to store user data in $_SESSION.
$some_name = session_name("generalvisit");
session_start();
$_SESSION['entertime']=new DateTime();

and to track the user a userid is created by a mysql database and stores in $_SESSION['userid']
if(!is_numeric($_SESSION['userid'])) $_SESSION['userid']=getNewUserID();

now, when the  getresolutionpic.php is triggered by javascript,  store screen resolution of that user stores in the $_SESSION variable of the same user. In getresolutionpic.php we have:
$some_name = session_name("generalvisit");
session_start();
if(!is_numeric($_SESSION['userid']))
{
    $_SESSION['userid']=getNewUserID();
    $_SESSION['entertime']=new DateTime();
}
$_SESSION['width']=$_GET['w'];
$_SESSION['height']=$_GET['h'];

The problem is that when getresolutionpic.php is called, $_SESSION['userid'] is empty and a new userid will be created while the user is not actually new.
Do you have any idea where it goes wrong?


text:
Q: Spring applicationcontext loading hooks Are there any hooks into the Spring ApplicationContext loading process?
I want to run a piece of code just before the application context loads (before any beans/properties/aspects/etc... are instantiated).
thanks in advance

A: Maybe BeanFactoryPostProcessors will suite your needs? They are run after the whole XML configuration files are read, but before any (other) beans are instantiated.

A: You can also use the ApplicationListener to receive notification of events like ContextClosedEvent, ContextStartedEvent or ContextStoppedEvent.
More information in the IoC Container chapter.

A: I just declared my own ContextLoaderListener in order to perform the desired work before loading the Spring context. It suits for web-apps, just declare it before the Spring context listener:
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        //Perform your stuff here
    }

}

<listener>
    <listener-class>
        com.myCompany.listeners.MyServletContextListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


text:
Q: Meaning of the term "concentrated in degree zero" I am studying about Koszul complex from an article, to describe this the Author used

Consider the ring $R$ as a differential Graded Algebra concentrated in degree zero, . . .

I searched google for the term "concentrated in degree zero", but didn't find anything satisfactory.
Can anyone please explain the term to me?
Thanks in advance..


text:
Q: Clean Instantiation of a Vector in the Base Class I'm working on code in C++11 and part of the code related to class construction and vector values has gotten out of hand. How can I make this more concise?
My work is related to version and have created a vector of version numbers of type std::vector<uint16_t> to hold an array of values to represent the version of format 1.0.0.25. I would like all classes to have a Version so I placed this in the base class. The children then inherit for Base and instantiate the version.
Currently, my code has a Version class, a Base class, and a Child class. The developer will hardcode the version in by setting the value in a define variable in the Child class. I would like that to be easy to see and read.  My issue is that the part where the Child class passes the value is currently very ugly and I'm hoping to make it more concise and readable.
The code is:
#include <vector>

namespace CodeStuff
{
namespace VersionStuff
{

typedef uint16_t VersionType;

class Version
{

public:
    Version(const std::vector<VersionType> & aNumbers, const VersionType aType = -1)
    {
        numbers_ = aNumbers;
        type_ = aType;
    }
private:
    std::vector<VersionType> numbers_;
    VersionType type_;
};

} // end namespace VersionStuff
} // end namespace CodeStuff

class Base
{
public:
    Base(const CodeStuff::VersionStuff::Version & aVersion) : version_(aVersion)
    {
    }

    const CodeStuff::VersionStuff::Version getVersion() const {return version_;}

private:
    const CodeStuff::VersionStuff::Version version_;
};

#define CHILD_VERSION {1, 0, 0, 25}

class Child : public Base
{
public:
    Child() : Base(CodeStuff::VersionStuff::Version{std::vector<CodeStuff::VersionStuff::VersionType>{CHILD_VERSION}}) {}
};

int main(int argc, const char * argv[]) {

    Child myChild();
}

And my issue is that while I like have an easy way to see the Version as in #define CHILD_VERSION {1, 0, 0, 25}, the constructor call is incredibly ugly:
 Child() : Base(CodeStuff::VersionStuff::Version{std::vector<CodeStuff::VersionStuff::VersionType>{CHILD_VERSION}}) {}

I would like to do this:
Child() : Base(CHILD_VERSION) {}

But in XCode this results in an error of "No Matching Constructor for initialization of type Base". Because this is valid syntax:
std::vector<uint16_t> v({1, 0 ,0 ,25});

I'm unsure why the short Base(CHILD_VERSION) doesn't work in c++11.
How can I shorten this?

A: I dealt with something very like this recently, and rather than passing around a vector, I used std::initializater_list as my route to simple constant version numbers.  Here is an example:
class Version {
  std::vector<unsigned> version;
 public:
  Version(const std::string & s);
  Version(std::initializer_list<unsigned> list) : version(list) {}
  bool operator== (const Version & other) const {
    return version == other.version;
  }
  bool operator< (const Version & other) const {
    return version < other.version;
  }
};

Here a Version can be created like this:
Version v{1, 0 ,0 ,25};

You can make your base class have a std::initializer_list constructor as well, and pass it on to your version_ object.


text:
Q: Error: Too many re-renders in my react app I tried to update the loading state to false after fetching data from database. Is there anything I am missing?
The error occurred in the setLoading function inside useEffect.
    const SingleProduct = ({ productName }) => {
      const [product, setProduct] = useState([]);
      const [loading, setLoading] = useState(true);

      // The line of code helps to convert hyphenated text to a spaced out text for database reading.
      const convertedProductName = convertToDefaultProductName(productName);

      useEffect(() => {
        const getProduct = async () => {
          try {
            const result = await publicRequest.get(
              `products/find/${convertedProductName}`
            );

            setProduct(result.data);
            setLoading(false); // BIG BUG IN THIS LINE.
          } catch (err) {
            setLoading(false);
          }
        };

        getProduct();
      }, [productName]);

      console.log(product, loading);
      const reOrderedProduct = sortSimilarProduct(product);

      return (
        <Container loading={loading}>
          {loading ? (
            <CircularProgress size="8rem" />
          ) : (
            <SingleProductDetails
              productName={convertedProductName}
              productDetails={reOrderedProduct}
            />
          )}
        </Container>
      );
    };

Here is the parent component of the SingleProduct Component
import React from 'react';
import Navbar from '../components/Navbar/Navbar';
import PageTitle from '../components/PageTitle/PageTitle';
import SingleProduct from '../components/SingleProduct/SingleProduct';
import Footer from '../components/Footer/Footer';
import Announcement from "../components/Announcement/Announcement";
import { useParams } from 'react-router-dom';
import { splitAndSpace } from '../usefulFunc';

const Product = () => {
    const { productName } = useParams();

    return(
        <>
            <Announcement />
            <Navbar />
            <PageTitle title={splitAndSpace(productName, "-")} pageLocation={"Home | Shop | ... | " + productName} params={productName}/>
            <SingleProduct productName={productName}/>
            <Footer borderTop/>
        </>
    );
};

export default Product;


text:
Q: Find equation of intersection of $2x + y - z = -1$ and $x + y -z = 1$ $2x + y - z = -1$, and $x + y -z = 1$. I'm trying to find the parametric form.
When I solve these, I get $x = -2$, but not sure where to go from there.

A: As you said, $x=-2$ and so $z = y-3$. To find the parametric equation of a line, you just need two points on the line. We can take $P=(-2,0,-3)$ and $Q=(-2,3,0)$, for instance. Then a vector directing the line is given by $v=Q-P = (0,3,3)$, and a general parametric equation for the line is $P +tv = (-2,3t,-3+3t)$.

A: The respective  normal vectors to the two planes are
$u=(2,1,-1)$ and $v=(1,2,-2)$
the cross product gives the vector director of the intersection line.
we get
$w=(0,1,1)$
the parametric equations of the line have following form
$x=x_0$,
$y=y_0+t$, and
$z=z_0+t$.
on the other hand the point $(x_0,y_0,z_0)$ is in the intersection if $x_0=-2$ and $y_0-z_0=3$.
so, let us take for example $z_0=0$.
this gives $y_0=3$.
finally, the parametric equations are
$x=-2$
$y=3+t$
$z=t$
$t$ is the paremeter.


text:
Q: Prerender header and footer components in NextJS We have HEADER and FOOTER components inside _app.tsx and we are using SSR and SSG.
But we want to prerender html for HEADER and FOOTER components also like the pages (for effective SEO).
As we cant do use getServerSideProps and getStaticProps inside _app.tsx, we are using HEADER and FOOTER components in each and every page and calling the APIs for HEADER and FOOTER in getServerSideProps inside every page.
But which is leading to render HEADER and FOOTER components in every page.
So is there any way to make HEADER and FOOTER components in one file and still get prerendering for them too?

A: You can create a layout component and add it inside your "_app.ts" file, so the layout is shared throughout your application.
You can find more information about this on Next Js documentation
https://nextjs.org/docs/basic-features/layouts


text:
Q: Testing active ssh keys on the local network I am trying to complete my bash script in order to find which SSH servers on LAN are still active with the ssh keys, but i am frozen at this step:
#!/bin/bash

# LAN SSH KEYS DISCOVERY SCRIPT

</etc/passwd \
grep /bin/bash |
cut -d: -f6 |
sudo xargs -i -- sh -c '
     [ -e "$1" ] && cat "$1"
' -- {}/.ssh/known_hosts |
cut -d' ' -f1 |
tr ',' '\n' |
sed '
     /^\[/{
          s/\[\(.*\)\]:\(.*\)/\1 \2/;
          t;
     };
     s/$/ 22/;
' |
sort -u |
xargs -l1 -- sh -c '
    if echo "~" | nc -q1 -w3 "$1" "$2" | grep -q "^SSH"; then
          echo "#### SUCCESS $1 $2";
    else
          echo "#### ERROR $1 $2";
    fi
' --

# TIME TO TEST WHICH SSH servers are still active with the SSH keys
# AND THIS IS WHERE I AM FROZEN...
# Would love to have bash script that could
# ssh -l $users_that_have_/bin/bash -i $ssh_keys $ssh_servers
# Would also be very nice if it could save active
# SSH servers with the valid keys in output.txt in the format
# username:local-IP:/path/to/SSH_key

there is also another one simpler to read (but with some temp files getting created):
#!/bin/bash

# LAN SSH KEYS DISCOVERY SCRIPT
# TRYING TO FIND THOSE SSH KEYS NOW

cat /etc/passwd | grep /bin/bash > bash_users
cat bash_users | cut -d ":" -f 6 > cutted.bash_users_home_dir
for bash_users in $(cat cutted.bash_users_home_dir)
do
ls -al $bash_users/.ssh/*id_* >> ssh-keys.txt
done

# DISCOVERING THE KNOWN_HOSTS NOW

for known_hosts in $(cat cutted.bash_users_home_dir)
do
cat $bash_users/.ssh/known_hosts | awk '{print $1}' | sort -u >>
hosts_known.txt
sleep 2
done
hosts_known=$(wc -l hosts_known.txt)
echo "We have $hosts_known known hosts that could be still active via SSH
keys"

# TIME TO TEST WHICH SSH servers are still active with the SSH keys
# AND THIS IS WHERE I AM FROZEN...
# Would love to have bash script that could
# ssh -l $users_that_have_/bin/bash -i $ssh_keys $ssh_servers
# Would also be very nice if it could save active
# SSH servers with the valid keys in output.txt in the format
# username:local-IP:/path/to/SSH_key

So right now, as stated in the bash script above, I am trying to find how to do some sort of a ssh -l $users_that_have_/bin/bash -i $ssh_keys $ssh_servers and dump the positive logins in an output.txt file in the following format:
username:local-IP:/path/to/SSH_key

To answer DopeGhoti comment:
I'm now trying to figure out how to integrate this into my bash script.
Here is my current attempt:
users=$(cat cutted.bash_users)
ssh_keys=$(cat ssh-keys.txt)

if ssh -l $users -i $ssh_keys $hosts_known -o BatchMode=yes -o
ConnectTimeout=5
then echo $users:$hosts_known:$ssh_keys SUCCESS >> results.txt
else
echo FAILED
fi

A: Unfortunately, it seems I cannot add a comment (need 50 reputation points), this is why I am adding my reply to you guys. Also, I've previously edited my question but I received this notification:
Your suggested edit is pending review.
Patrick Mevzek reviewed this 2 hours ago: Reject
This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer.
welcome to U&L, you know ssh have a return code ? along with -o BatchMode=yes this can help automatize test. (e.g. if ssh ... ; then echo good for ... >> good.txt ; else echo bad for ... >> bad.txt ; fi) – Archemar 54 mins ago Also that cat|grep|cut|for can be boiled down to for homedir in $(awk -F: '$7 ~ //bin/bash/ { print $6 }' /etc/passwd); do.... – DopeGhoti 1 min ago
So just to clarify: what you are trying to do is, for each user, for every host in their known_hosts, attempt to log into each host with each presumptive private key found in ~username/.ssh? – DopeGhoti 25 mins ago : YES
here;
So now I'm trying to figure out how I could make this idea integrate itself into my bash script, something like;
users=$(cat cutted.bash_users)
cat ssh-keys.txt | awk '{print $9}' > cutted.ssh_keys.txt
ssh_keys=$(cat cutted.ssh_keys.txt)

if ssh -l $users -i $ssh_keys $hosts_known -o BatchMode=yes -o ConnectTimeout=5
then echo $users:$hosts_known:$ssh_keys SUCCESS >> results.txt
else
echo $users:$hosts_known:$ssh_keys FAILED >> not-active.txt
fi

If you guys have an idea on how to make this possible, I would be very happy to learn on how to do it
Thanks


text:
Q: perl: cannot unlink file: Permission denied at C:/Strawberry/perl/lib/File/Temp.pm I am trying to run a perl script using selenium webdriver.
After successful execution of script, I am getting following error:
*

cannot unlink file for
  C:\Users\\AppData\Local\Temp\89qNk6oDJh\cert8.db: Permission
  denied at C:/Strawberry/perl/lib/File/Temp.pm line 1616.

*
And the line 1616 in Temp.pm looks like this:
eval { rmtree($self->{REALNAME}, $File::Temp::DEBUG, 0); };

What can be the cause?
My script is simple perl program, it creates a webdriver object and open a URL and gets the title.

A: In Windows a file cannot be deleted while it is open.


text:
Q: Dealing with data in Single page App (Hybrid mobile app & PHP server) I am developing a hybrid app using intel xdk with PHP server. My app already had a login page(index.html). When the user logged in it will redirect to user.html page.
In user.html, It consists of different div's for user's data.
Example:

the navigation

 -some data content here-

 -some data content here-

 -some data content here-

 -some data content here-

 -some data content here-

 -some data content here-

So when I logged in to the app the home will be the main page. And the data should be loaded in home page, user-account, messages, transactions etc..
I am thinking that I should run ajax request upon logging in of a user. Requesting to the server to get all the data of this logged in user.
This could be:
SELECT
    `user`.*
    , `user-transactions`.*
    , `user_products`.*
FROM
    `db`.`user`
    INNER JOIN `db`.`user_transactions`
        ON (`user`.`user_id` = `user_transactions`.`transaction_user_id`)
    INNER JOIN `db`.`user_products`
        ON (`user`.`user_id` = `user_products`.`uproducts_user_id`);)

Then the server respond the json data to the App. So now I have all the user's data I needed to display in the App.
So when the user go to other div page the data was already loaded. I am also thinking to save this data to localStorage so that when the remember me option was selected upon logging in, the user can still view the data in offline mode. And it can be updated(send ajax request again) by refreshing the page.
Am I going to the right direction? What are different approaches in dealing with data in a Hybrid app (in terms of displaying)?

A: There is a lot of frameworks to create hybrid mobile app. It's better to use one ;)
See : http://noeticforce.com/best-hybrid-mobile-app-ui-frameworks-html5-js-css
Maybe, if you can use a plugin to store your datas in SQLite database it will be better (and faster if you have a lot of datas) than localStorage.
Hope to be helpful !


text:
Q: What does it mean when conditional mean is linear in predictors? I am trying to understand this equation:

If conditional mean is linear in $x$, so that $E[y|x] = x'\beta$...

I don't understand why conditional mean ($E[y|x]$) should be equal to $x'\beta$ if its linear in predictors.
Also if conditional mean is non linear in predictors why would it lose structural or causal interpretation?

A:
I don't understand why conditional mean ($E[y|x]$) should be equal to
  $x'\beta$ if its linear in predictors.

It does not have be equal to it. It can have any form. Using linear regression is just one of many ways to approximate conditional mean. You can choose to use it as model, you can choose something else.

Also if conditional mean is non linear in predictors why would it lose
  structural or causal interpretation?

Even if it is linear, it does not tell you anything about causality. I don't know what you mean by "structural interpretation".


text:
Q: Is there any way to update the JSON file in Azure Blob storage whenever new data is added to JSON file in github or locally? I am creating Azure Search Service and my dataset is a JSON file in Azure Blob Storage. I want to update it time to time so that the Search service is up to date.
I cant find any way of doing so. Is it possible?

A: You can use the Azure Search SDK to do this. See https://learn.microsoft.com/en-us/azure/search/search-howto-dotnet-sdk

*

*Create an application that deserializes your JSON file to a collection of objects.

*Use the Azure Search SDK to submit those objects to search.

*Repeat as required to refresh the index.

A: Assuming your data is in the correct format, you can use the JSON one to many indexer and set it to a regular schedule so that it will regularly and automatically refresh your data. See https://learn.microsoft.com/en-us/azure/search/search-howto-index-json-blobs and https://learn.microsoft.com/en-us/azure/search/search-howto-index-one-to-many-blobs


text:
Q: login page via popu-up window Is there an example login page via a pop-up window?
Also, if the user performs some operation on the site that requires authentication, then show the login screen (if user not authorized).

A: You should just create you Login view, as you would implement it usually. And then apply fancybox (http://fancybox.net/) or bootstrap-modal(http://twitter.github.com/bootstrap/javascript.html) to make it work as modal.
Regarding re-direction: as soon as you use [Authorize] attribute as controller attribute and not-authorized user tries to hit its action, he will be redirected automatically;

A: you may use modal box plugins for jquery to create pop-up and place your log-in form in the pop-up.
Check out this modal window plugin which support html markup in the popup.
http://www.zurb.com/playground/reveal-modal-plugin


text:
Q: Function to check if number is stepping returns false I've written a function to check if a number is stepping: each consecutive digit differs from the last by exactly 1.
def isStep(num):
    num = str(num)
    prevDigit = int(num[0])-1

    for i in str(num):
        if (int(i)-1 == prevDigit or int(i)+1 == prevDigit):
            prevDigit = i
            continue
        else:
            print(int(i)-1, prevDigit)
            return False

    return True

I've tried it for the number 1234. For some reason, it returns False when it gets to the second digit, thinking 2-1 does not equal 1. (See the print statement in the else).
Why is this? Is there a bug in my code somewhere that's causing this?

A: Another way to calculate this is to subtract the number from the same number shifted one digit to the right (and disregarding the first and last digits)
1232     (a)
 1232    (b)
-----
_111_    (abs(a-b) per digit)

by subtract I here mean the absolute difference abs(2-1)==1, abs(3-2)==1, and abs(2-3)==1 (i.e. differ by 1, either up or down).
In Python this would look like:
def isStep(n):
    a = map(int, str(n)[1:])   # convert to a list of integer digits
    b = map(int, str(n)[:-1])
    return all(abs(a_digit - b_digit) == 1 for a_digit, b_digit in zip(a, b))


text:
Q: Proof of the distribution of sample variance I'm reading Probability and Statistics by DeGroot and Schervish, and I got stuck on one particular line of the proof of the distribution of the sample variance $\hat{\sigma}$ of a random sample of $n$ many i.i.d. standard normal random variables $X_{i}$.  The sample has sample mean $\bar{X}_n$.
The equality that I can't follow is $(\sum_{i=1}^n X_i^2) - n\bar{X}_n^2 = \sum_{i=1}^n (X_i - \bar{X}_n)^2$
I understand that you can rewrite $n\bar{X}_n^2 = \sum_{i=1}^n \bar{X}_n^2$, which then turns the left term of the first equality to $(\sum_{i=1}^n X_i^2) - (\sum_{i=1}^n \bar{X}_n^2) = \sum_{i=1}^n (X_i^2 - \bar{X}_n^2)$.  But for the life of me, I can't figure out how you get from that result to the right term of the first equality.  What am I missing here?
Thanks in advance!

A: Note that the expression being summed in $\sum_{i=1}^n \bar X_n^2$ does not depend on $i$, and thus it is just the sum of $n$ copies of $\bar X_n^2$; i.e. $n \bar X_n^2$.

A: It is easier to go from right to left.
Note that $(X_i-\bar{X})^2=X_i^2-2X_i\bar X+\bar{X}^2$.
Summing, we get
$$\sum_1^n(X_1-\bar{X})^2=\sum_1^n X_i^2-2\bar{X}\sum_1^n X_i +\sum_1^n \bar{X}^2.$$
The middle term is $-2n \bar{X}^2$ because $\sum_1^n X_i=n\bar{X}$.  The last term is $n\bar{X}^2$.
Remark: I find it easier to see things by calling $\bar{X}$ by the name $\mu$.

A: Hmm... the difference between your two expressions is
$2\sum_{i=1}^n X_i \bar{X}_n = \frac{2}{n} \sum_{i=1}^n X_i \sum_{j=1}^n X_j = \frac{2}{n} \left( \sum_{i=1}^n X_i \right)^2$
but that could be nonzero. Something else must be missing.


text:
Q: Is $f$ reduced if and only if the derivations $\gcd(\frac{\partial f}{\partial x},\frac{\partial f}{\partial y})=1$ under some conditions? I have encountered the following problem. I have no ideas to prove it or disprove it.

Suppose that $f\in \mathbb{C}[x,y]$, $f(0,0)=0$, $\frac{\partial f}{\partial x}(0,0)=0, \frac{\partial f}{\partial y}(0,0)=0$. Suppose $f$ is square-free—for simplicity we may first assume that $f$ is irreducible.
  Then $\frac{\partial f}{\partial x}$ and $\frac{\partial f}{\partial y}$ have no non-trivial common factor, in other words, the greatest common factor of $\frac{\partial f}{\partial x}$ and $\frac{\partial f}{\partial y}$  is 1.

Thanks.

A: This is not true. Consider for instance
$$f(x,y)=(x^2+1)^2(y^2+1)^3-1.$$
But you can correct the statement by assuming $f(x,y)+c$ is square-free for all $c\in \mathbb C$ (no condition at $(0,0)$).
Proof: Suppose $\gcd(f_x, f_y)\ne 1$. Let $p(x,y)$ be an irreducible factor and let $C=Z(p(x,y))$ be the irreducible algebraic curve in $\mathbb C^2$ defined by $p(x,y)$. It is contained in the set of critical points of $f(x,y)$. By Sard's theorem, $f(C)$ has measure $0$. By Chevalley's theorem (or the openess of non-constant homolorphic functions defined on the smooth part of $C$), $f(C)$ either contains an open subset or is finite. So it is finite (and connected because $C$ is connected). Therefore $f(C)=c$ for some $c\in\mathbb C$.
This implies that $p(x,y) \mid f(x,y)-c$. Replacing $f$ by $f-c$ (which doesn't change the partial derivatives), we get $p(x,y)\mid f(x,y)$. So $p$ is an irreducible factor of $f$. Write $f=pg$ with $g$ prime to $p$ ($f$ is square-free after any translation). As $f_x=p_xg+pg_x$ and $f_y=p_yg+pg_y$, we get $p \mid \gcd\{ p_x, p_y\}$. But $p(x,y)$ is irreducible, so $p_x=p_y=0$ and $p(x,y)$ is constant, impossible.
Remark: this remains true over any field of characteristic $0$. But the example $f(x,y)=x^{p+1}+y^p$ shows that it fails in characteristic $p>0$.
Edit With some algebraic geometry background, the statement is clear: consider $f$ as a morphism from the affine plane to the affine line. Then the set of common zeros of the its partial derivatives is the set $S$ of non-smooth points of $f$. As we are in characteristic $0$, the generic fiber of $f$ is smooth, so $S$ is contained in the union of finitely many fibers of $f$. So $S$ is finite if and only if every fiber has only finitely many singular points. Equivalently, every fiber is reduced. But a fiber $f^{-1}(c)$ is just the scheme defined by $f(x,y)-c=0$. This fiber is reduced if and only if $f(x,y)-c$ is square-free. Finally, $S$ is finite iff $\gcd\{ f_x, f_y\}=1$.


text:
Q: 'click' called on an object that does not implement interface HTMLElement In my HTML page i have a button which on click fetches the elements in the page and passes them on to the server.
 <button type="button" class="btn btn-default" id="filter_btn" onclick="on_submit()">Submit</button>

the function call is handled by my js code like this below.
function on_submit()
{
 var $start_date=document.getElementById("datepicker1").value;
 var $end_date=document.getElementById("datepicker2").value;
 var $vid1 = $('#vid1');
 var $vid2 = $('#vid2');
 var $vid1_name = $('#vid1').text();
 var $vid2_name = $('#vid2').text();
 var $metric = $('#metric').val();
 var $frequency = $('#freq').val();
  $.get('../content_focus',{type:"getData",vid1_name:$vid1_name, vid2_name:$vid2_name, vid1:$vid1, vid2:$vid2, start_date:$start_date, end_date:$end_date, metric:$metric, frequency:$frequency}, function(responseData){
  alert('im done');
 });
   }

Now the borwer console throws an error stating "'click' called on an object that does not implement interface HTMLElement."
And none of my print statements or alert statements get executed i would like some help with this

A: It seems to be the problem is with,
 var $vid1 = $('#vid1');
 var $vid2 = $('#vid2');

$vid1 and $vid2 are HTML elements.
If you want to pass the html use,
var $vid1 = $('#vid1').outerHTML();
var $vid2 = $('#vid2').outerHTML();


text:
Q: LDREX/STREX with Cortex M3 and M4 I was reading up on the LDREX and STREX to implement mutexes.  From looking at the ARM reference manual:
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.100166_0001_00_en/ric1417175928887.html
It appears that LDREX/STREX only store address granularity is the whole memory space, hence you are only allowed to use LDREX/STREX on at maximum one 32bit register.
Is this correct or am I missing something? If so it kind of makes the LDREX/STREX very limited. I mean you could do a bit mapped mutex and maybe get 32 mutexes.
Does anyone use the LDREX/STREX on a M3 or M4 and if so how do they use it?

A: So I contacted ARM and got some more information.  For example if you did this it LDREX/STREX would fail:
LDREX address1
LDREX address2
STREX address1
The STREX to address1 would pass even though the last LDREX was not for address1. This is correct as that the LDREX/STREX address resolution is the entire memory space.
So I was worried that if you have a two tasks: and the first one got interrupted after the first LDREX, and then the second task got interrupted after the second LDREX to address2 and then the first task got processor back and tried the STREX it would cause a problem.  However it appears that ARM issues CLREX on every exception/interrupt entry and exit. Therefore the STREX would fail as that the tasks had to be preemptive by an interrupt.  That is if any interrupt occurs between LDREX and STREX the STREX will fail. So you want to keep the code as small as possible between LDREX and STREX to reduce the chances of interrupt. Additionally if the STREX fails you most likely want to try the LDREX/STREX process once or twice more before giving up.
Again this is for a single core M3/M4/M7.
Note the only place I found the reference to the CLREX being cleared with exception was in the ArmV7-M Architecture Reference Manual in section A3.4.4 Context switch support.  This document is much better than anything I found online describing how the LDREX/STREX actually works.


text:
Q: simple mutiprocessing on numpy array I want to speed up the computation of  u ** 2 where u is a numpy array, using the multiprocessing module.
Here is my attempt (file name multi.py) :
# to compile on Windows/Ipython  : import multi  then  run -m multi

from multiprocessing import Pool
import numpy as np

if __name__ == '__main__':
 u=np.arange(6e7)
 def test(N):
    pool = Pool(N)
    v=len(u)//N
    tasks = [ u[k*v:(k+1)*v] for k in range(N)]
    res = pool.map_async(np.square,tasks).get()
    return res

Here are the benchmarks :
In [25]: %time  r1=test(1)
Wall time: 13.2 s

In [26]: %time  r2=test(2)
Wall time: 7.75 s

In [27]: %time  r4=test(4)
Wall time: 8.29 s

In [31]: %time r=u**2
Wall time: 512 ms

I have 2 physical cores on my PC, so test(2) running faster than test(1) is encouraging.
But for the moment, numpy is faster. The multiprocessing add big overload.
So my question is : How (or is it possible) to speed up u ** 2, with multiprocessing ?
EDIT
I realize that all process work is done in his own memory space, so necessarily a lot of copy arise  (See here for example). So no hope to speed simple computation this way.

A: Multiprocessing in CPython is intrinsically costly because of the Global Interpreter Lock, which prevents multiple native threads from simultaneously executing the same Python bytecode. multiprocessing works around this limitation by spawning a separate Python interpreter for every worker process, and using pickling to send arguments and return variables to and from the workers. Unfortunately this entails a lot of unavoidable overhead.
If you absolutely must use multiprocessing, it's advisable to do as much work as possible with each process in order to minimize the relative amount of time spent spawning and killing processes. For example, if you're processing chunks of a larger array in parallel then make the chunks as large as possible, and to do as many processing steps as you can in one go, rather than looping over your array multiple times.
In general, though, you will be much better off doing your multithreading in a lower-level language that isn't limited by the GIL. For simple numerical expressions, such as your example, numexpr is a very simple way to achieve a significant performance boost (~4x, on an i7 CPU with 4 cores and hyperthreading). As well as implementing parallel processing in C++, a more significant benefit is that it avoids allocating memory for intermediate results, and thus makes more efficient use of caching.
In [1]: import numexpr as ne

In [2]: u = np.arange(6e7)

In [3]: %%timeit u = np.arange(6e7)
   .....: u**2
   .....:
1 loop, best of 3: 528 ms per loop

In [4]: %%timeit u = np.arange(6e7)
ne.evaluate("u**2")
   .....:
10 loops, best of 3: 127 ms per loop

Other options suited to more complicated tasks include Cython and numba.
Finally, I should also mention that there are other Python implementations besides CPython that lack a GIL, for example PyPy, Jython and IronPython. However, these all suffer from their own limitations. To my knowledge, none of them offer proper support for numpy, scipy or matplotlib.

A: I answer myself :
From scipy-cookbook,  an IMHO underrated feature:

while numpy is doing an array operation, python also releases the GIL.

So multithread is not a problem for numpy operations.
from threading import Thread
import numpy as np

u=np.arange(6*10**7)

def multi(N):
    n=u.size//N
    threads = [Thread(target=np.ndarray.__ipow__,
               args=(u[k*n:(k+1)*n],2)) for k in range(N)]
    for t in  threads: t.start()
    for t in  threads: t.join()

with a nearly 2x gain on a 2 cores processor:
In [7]: %timeit test(1)
10 loops, best of 3: 172 ms per loop

In [8]: %timeit test(4)
10 loops, best of 3: 92.7 ms per loop


text:
Q: pointer events won't toggle through javascipt? I am trying to fade in and out a drop down menu on click. Currently using CSS animation to fade it out in and using JS to toggle the class for the animation. I have created a variable in js to check if the object contains the fade class - if the class opacity of element is 0, I want the pointer events of the element to be set to none and set to all if the element if the element is visible, however the variable doesn't update and remains false. I am new to javascript.
HTML
<button class="mobile__more">+</button>

  Show
  About
   Research Film
   Stills
   Lookbook

css
.mobile__process-nav {
   display:flex;
   flex-direction: column;
   justify-content: space-evenly;
   height: 30vh;
   opacity: 0;
   transition: opacity 0.3s ease-in-out;
   -moz-transition: opacity 0.3s ease-in-out;
   -webkit-transition: opacity 0.3s ease-in-out;
   -ms-transition: opacity 0.3s ease-in-out;
   -o-transition: opacity 0.3s ease-in-out;
}

.mobile__process-nav.fade {
   opacity: 1;
}

JS
const morebtn = document.querySelector('.mobile__nav');
const processMenu = document.querySelector('.mobile__process-nav');
if (window.matchMedia("(max-device-width: 850px)").matches) {

let menuOpen = processMenu.classList.contains('fade');

   morebtn.addEventListener('click', () => {
      processMenu.classList.toggle('fade');
      if (!menuOpen) {
         console.log(menuOpen);
         processMenu.style.pointerEvents = "none";
      } else {
         console.log(menuOpen);
         processMenu.style.pointerEvents = "all";
      }
})
}

A: You should update the variable menuOpen inside click callback


text:
Q: WPF C# image and file inegration into application Hi I am developing a WPF c# project and want to attach a text file and image file integrated into it so that if I export executable file to any other PC, It will run easily...

A: you are thinking about this in the wrong way, Visual Studio doesn't manage installation on Client machines it only handles building the code for you to run, the thing that manages the installation is the installer
if you want to use a publish installer like click once then you can use Visual Studio to set the publication rules (see https://msdn.microsoft.com/en-us/library/142dbbz4%28v=vs.90%29.aspx), otherwise you actually need to create an installer (see https://msdn.microsoft.com/en-us/library/gg513936.aspx)
EDIT: If i'm misunderstanding your question which i took as how do you get your resourced files to be on the client machine with the exe file, if your question is how to Embed thee resource in the first place then How to refer to Embedded Resources from XAML? provides a very good answer


text:
Q: Define pointer to memory with the size of union I'm struggling with the demo code like below:
typedef volatile union
{
  unsigned U;
  int I;
  struct
  {
    unsigned some_array:32;
  } B;
} bar;
#define foo (*( bar*) 0xABCDU)

I know that 0xABCDU is some address in memory.
How can I read the foo in English?

A: ( bar*) 0xABCDU is 0xABCDU reinterpreted as a pointer to bar.
*( bar*) 0xABCDU is dereferenced pointer (a reference if it was C++).
(Outer braces are to prevent it from possible misinterpretation due to operators precedence)

A: foo is the object referenced by the pointer to union bar. Pointer to bar has a value converted from the integer constant.


text:
Q: Python - tuples and memory management While answering a Python-related question I did some experimenting and found a tuple-related thing that I can't figure out: I have difficulties understanding why an empty tuple takes more space then a tuple with a single element in it (according to sys.getsizeof()). The code below has been executed using the upstream version of Python 2.7.9 on a 64 bit Debian Jessie systems (also tested with Python 3.4.2 where values are slightly different but the overall behaviour that I'm talking about is still there):
>> sys.getsizeof(())
56
>> sys.getsizeof((1))
24
>> sys.getsizeof((1,2))
72

As you can see there is quite a difference (factor 2.3 to be more precise) in an empty vs. a single-item tuple. Any ideas what is happening here? Since tuples are recursive data structures I assume that the values that sys.getsizeof() returns is the amount of memory the tuple object itself is taking plus the references to the objects it contains (if tuples store elements as references and not as values - that I don't know).My initial thought was that like dictionaries tuples are created in memory with a certain default size that can hold a couple of elements. I forgot the exact number of elements that an empty dictionary has reserved memory for but here is what I mean with a small example:
>> sys.getsizeof({})
280
>> sys.getsizeof({"a":0})
280
>> sys.getsizeof({"a":0, "b":1})
280

Looking a the tuples however doesn't seem to show the same behaviour since a tuple shrinks after the first element is added to a smaller size and then grows (as expected) with each element added to it. In addition to that lists don't seem to suffer from the same behaviour:
>> sys.getsizeof([])
72
>> sys.getsizeof([1])
80
>> sys.getsizeof([1,2])
88

Empty list memory-wise is smaller then a list with 1 or more elements - perfectly normal.
My second thought was that a single-element tuple is converted somehow into the single object it contains and all that is somehow wrapped so that it seems that it is actually a list (that is why len() works). Example:
>> sys.getsizeof((1))
24
>> sys.getsizeof(1)
24

This seems possible however I'm not convinced that it's actually happening.

A: You are not creating single-item tuples.  Any expression can be wrapped in parentheses without changing its meaning, so (1) is just the same as 1.  To make a single element tuple, write (1,).  When you do this, the memory consumption should become more reasonable.

But how can an integer require 24 bytes?  Aren't integers usually 8 bytes at most?

In Python 3, all integers are arbitrary precision, and even in Python 2, all objects including integers have a certain amount of overhead for reference counting, type information, and other metadata.  24 bytes is actually quite reasonable for a full-blown Python object.
(Technically, small integers are interned, so the reference count is arguably unnecessary in this particular case, but removing it would complicate other parts of the interpreter for no significant benefit.)
While I'm answering, I'd also like to clear a few things up:

(if tuples store elements as references and not as values - that I don't know)

Python, generally speaking, does not allow Python objects to actually contain one another.  In the C source, you will see a lot of PyObject* variables, but no PyObject variables.  Python objects live on the heap, totally independent of one another.  In other words, yes, the tuple is storing references, not the actual objects.

My initial thought was that like dictionaries tuples are created in memory with a certain default size that can hold a couple of elements.

There is no reason to do this.  Tuples have a fixed size.  Officially, they are immutable and do not change after creation.  Unofficially, they can be altered at the C level, but these alterations are not supposed to be visible to Python code; you modify the tuple once after you've created it but before you've used it for anything, and thereafter you don't modify it again.  Furthermore, these alterations do not actually change the size, they just fill in the array slots which already exist.
Because of this immutability, there is no reason for tuples to store more elements than they actually have.  They don't need to support fast appends or other size-changing operations.

A: The code (1) is not a tuple! Python will just regard the parentheses as a way to express operational priority. If you want a tuple, there must be at least a comma in it.
>>> type(1)
<type 'int'>
>>> type((1))
<type 'int'>
>>> type((1,))
<type 'tuple'>

Then the size of tuple will be a linear function of number of elements in it.
>>> sys.getsizeof(tuple())
28
>>> sys.getsizeof((1,))
32
>>> sys.getsizeof((1,2))
36
>>> sys.getsizeof((1,2,3))
40


text:
Q:  in Fragment I have a fragment VideoListPagerFragment. It was VideoListDemoActivity from YoutubePlayer API Android sample. I made fragment from that sample activity, but i need to fix one error.
I init my Fragment like:
Code:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      View view=inflater.inflate(R.layout.videos_fragmentpage,container,true);
someAnotherMethods();
returt view;
}

FRAGMENT XML(R.layout.videos_fragmentpage):
<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    >
    <fragment
        class="com.alexpoltavets.fifacommunity.videos.VideoListPagerFragment$VideoListFragment"
        android:id="@+id/list_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:id="@+id/video_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="vertical">

        <ImageButton
            android:id="@+id/close_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:src="@android:drawable/btn_dialog"
            android:onClick="onClickClose"/>

        <fragment
            class="com.alexpoltavets.fifacommunity.videos.VideoListPagerFragment$VideoFragment"
            android:id="@+id/video_fragment_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>
</merge>

But, when i start my Activity:
  Code of adding fragment:
FragmentManager fragmentManager=getFragmentManager();
    fragmentManager.beginTransaction()
.add(R.id.videos_container,VideoListPagerFragment.newInstance(),"test")
            .commit();

Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/videos_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

I have an error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.alexpoltavets.fifacommunity/com.alexpoltavets.fifacommunity.videos.VideosActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

If i change:
  View view=inflater.inflate(R.layout.videos_fragmentpage,container,true);

to:
  View view=inflater.inflate(R.layout.videos_fragmentpage,container,false);

i will have:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.alexpoltavets.fifacommunity/com.alexpoltavets.fifacommunity.videos.VideosActivity}: android.view.InflateException: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true

If i change <marge> to another container like <FrameLayout> it fix this error, but when screen rotate to landscape, i have another bug with 2 similar fragment on one screen.
How i can fix it?


text:
Q: How to store React Refs in functional components In my Photos/Main component I am mapping through an object, which is from my state called filteredImages, containing instances of image data that's being retrieved from a database. For each instance I am dynamically generating a React component 'ImageItem' which will display an image to the DOM. What I need to do is to store the DOM elements that are generated by the 'ImageItem' Component in the Main Component. I've come across being able to use Reacts' ref, and useRef and forwardRef Hooks but I'd like to know how store these refs in a array. Any help would greatly be appreciated!!!
Photos.js
const Photos = ({ photos: { albums, images, filteredImages, loadingAlbums, loadingImages, currentAlbum }, getAlbums, getImages }) => {

    const imageElement = useRef(null);

    // When photos page is initially loaded
    useEffect(() => {
        getAlbums();
        getImages();
        // eslint-disable-next-line
    }, []);

    // When filteredImages is changed
    useEffect(() => {
        if (filteredImages !== null) {
            console.log(imageElement.current);
        }
    }, [filteredImages]);

    return (

            <Masonry breakpointCols={breakpointColumnsObj} className="my-masonry-grid mx-5" columnClassName="my-masonry-grid_column">
                { filteredImages.map(image => <ImageItem ref={imageElement} image={image} key={image._id} />)}
            </Masonry>

    );
};

// imports from our state and brings it into the component as a prop
const mapStateToProps = state => ({
    photos: state.photos
});

export default connect(mapStateToProps, { getAlbums, getImages })(Photos);

ImageItem.js
const ImageItem = ({image}, ref) => {

    return (

    )
}

]

const forwardedImageElement = React.forwardRef(ImageItem)

export default forwardedImageElement;


text:
Q: How would I print two diagonals of a square? So for a example, if a user had input 2, the output will be xo ox and if the user inputs 3 it will output xox oxo xox etc. The code I have so far only outputs the diagonal of a square in the opposite direction.
size = int(input("Size of the square: "))

for i in range(size):
    line = ""

    for j in range(size):
        if i+j == size-1:
            line += "x"
        else:
            line += "o"

    print(line)

In this example, when you input 3 for example, you will get as an output:
oox
oxo
xoo

A: size = int(input("Size of the square: "))

for i in range(size):
    line = ""

    for j in range(size):
        if i == j:               # main diagonal
            line += "x"
        elif i + j == size - 1:  # secondary diagonal
            line += "x"
        else:
            line += "o"

    print(line)

A: You can use numpy fill_diagonal for a more efficient approach
size = 3
a = np.chararray((size, size))
a[:] = 'o'
np.fill_diagonal(a, 'x')
np.fill_diagonal(np.fliplr(a), 'x')

output
a = chararray([[b'x', b'o', b'x'],
               [b'o', b'x', b'o'],
               [b'x', b'o', b'x']], dtype='|S1')

A: In case you're in love with generators
square = "\n".join(["".join(["x" if i == j or i == size - j - 1 else "o" for j in range(size)]) for i in range(size)])

A: You can solve it using one loop as follows:
size = 3
result = []
for x in range(size)[::-1]:
    line = list("o" * size)
    line[x] = "x"
    result.append("".join(line))
print(*result)


text:
Q: Insert boolean datatype data from datagridview into SQL Server database How do I insert the boolean type data from datagridview into SQL Server? When I unchecked the check box in the datagridview, and insert the data:

the error conversion of from type DBNull to type String is not valid.

Dim index As Integer
Dim selectedRow = Quantum_GR.DataGridView1.Rows(index)

Try
    For I = 0 To Quantum_GR.DataGridView1.Rows.Count - 2
        'Dim GRNo As String
        Dim StockCode As String = Quantum_GR.DataGridView1.Rows(I).Cells("STKID").Value
        Dim StockName As String = Quantum_GR.DataGridView1.Rows(I).Cells("STKNAME").Value
        Dim GRQuantity As Double = Quantum_GR.DataGridView1.Rows(I).Cells("GRQTY").Value
        Dim StockCost As Double = Quantum_GR.DataGridView1.Rows(I).Cells("COST").Value
        Dim BatchControl As Boolean = Quantum_GR.DataGridView1.Rows(I).Cells("BATCHCTR").Value
        Dim StockBatchID As String = Quantum_GR.DataGridView1.Rows(I).Cells("BATCHID").Value
        Dim StockExpDate As Date = Quantum_GR.DataGridView1.Rows(I).Cells("EXPDATE").Value
        Dim StockTaxCode As String = Quantum_GR.DataGridView1.Rows(I).Cells("TAXCODE").Value
        Dim StockTaxAmount As Double = Quantum_GR.DataGridView1.Rows(I).Cells("TAXAMT").Value

        sqlcon.Open()
        If StockCode <> "" Then
            Dim grquery As String = "INSERT INTO GRT(GRNO,STKID,STKNAME,GRQTY,COST,BATCHCTR,BATCHID,EXPDATE,TAXCODE,TAXAMT) VALUES ('" & GRID & "','" & StockCode & "','" & StockName & "'," & GRQuantity & "," & StockCost & ",'" & BatchControl & "','" & StockBatchID & "','" & StockExpDate & "','" & StockTaxCode & "'," & StockTaxAmount & ")"
            Dim sqlcmd As New SqlCommand(grquery, sqlcon)
            sqlcmd.ExecuteReader()
            sqlcmd.Dispose()
        End If
        sqlcon.Close()

        sqlcon.Open()
        SQLcmd = New SqlCommand("UPDATE GRT SET TCOST=ROUND(GRQTY*COST,2)", sqlcon)
        sqlda = New SqlDataAdapter(SQLcmd)
        sqldataset = New DataSet
        sqlda.Fill(sqldataset)
        sqlcon.Close()
    Next
Catch ex As Exception
    MsgBox(ex.Message)
End Try

A: try this code.
  Dim index As Integer
        Dim selectedRow = DataGridView1.Rows(index)

        Try
            For i = 0 To DataGridView1.Rows.Count - 2
                'Dim GRNo As String
                Dim StockCode As String = DataGridView1.Rows(i).Cells("STKID").Value
                Dim StockName As String = DataGridView1.Rows(i).Cells("STKNAME").Value
                Dim GRQuantity As Double = DataGridView1.Rows(i).Cells("GRQTY").Value
                Dim StockCost As Double = DataGridView1.Rows(i).Cells("COST").Value
                Dim BatchControl As Boolean = Convert.ToBoolean(DataGridView1.Rows(i).Cells("BATCHCTR").Value)
                Dim StockBatchID As String = DataGridView1.Rows(i).Cells("BATCHID").Value
                Dim StockExpDate As Date = DataGridView1.Rows(i).Cells("EXPDATE").Value
                Dim StockTaxCode As String = DataGridView1.Rows(i).Cells("TAXCODE").Value
                Dim StockTaxAmount As Double = DataGridView1.Rows(i).Cells("TAXAMT").Value

                sqlcon.Open()
                If StockCode <> "" Then
                    Dim grquery As String = "INSERT INTO GRT(GRNO,STKID,STKNAME,GRQTY,COST,BATCHCTR,BATCHID,EXPDATE,TAXCODE,TAXAMT) VALUES ('" & GRID & "',@StockCode,@StockName,@GRQuantity,@StockCost,@BatchControl,@StockBatchID,@StockExpDate,@StockTaxCode," &  & ")"
                    Dim sqlparams(8) As SqlClient.SqlParameter
                    sqlparams(0) = New SqlClient.SqlParameter("@StockCode", SqlDbType.VarChar)
                    sqlparams(0).Value = CType(StockCode, String)
                    sqlparams(1) = New SqlClient.SqlParameter("@StockName", SqlDbType.VarChar)
                    sqlparams(1).Value = CType(StockName, String)
                    sqlparams(2) = New SqlClient.SqlParameter("@GRQuantity", SqlDbType.Float)
                    sqlparams(2).Value = CType(GRQuantity, Double)
                    sqlparams(3) = New SqlClient.SqlParameter("@StockCost", SqlDbType.Float)
                    sqlparams(3).Value = CType(StockCost, Double)
                    sqlparams(4) = New SqlClient.SqlParameter("@BatchControl", SqlDbType.Bit)
                    sqlparams(4).Value = CType(BatchControl, Boolean)
                    sqlparams(5) = New SqlClient.SqlParameter("@StockBatchID", SqlDbType.VarChar)
                    sqlparams(5).Value = CType(StockBatchID, String)

                    sqlparams(6) = New SqlClient.SqlParameter("@StockExpDate", SqlDbType.Date)
                    sqlparams(6).Value = CType(StockExpDate, Date)
                    sqlparams(7) = New SqlClient.SqlParameter("@StockTaxCode", SqlDbType.VarChar)
                    sqlparams(7).Value = CType(StockTaxCode, String)
                    sqlparams(8) = New SqlClient.SqlParameter("@StockTaxAmount", SqlDbType.Float)
                    sqlparams(8).Value = CType(StockTaxAmount, Double)
                    Dim sqlcmd As New SqlCommand(grquery, sqlcon)

                    sqlcmd.ExecuteNonQuery()
                    sqlcmd.Dispose()
                End If
                'sqlcon.Close()

                'sqlcon.Open()
                SQLcmd = New SqlCommand("UPDATE GRT SET TCOST=ROUND(GRQTY*COST,2)", sqlcon)
                sqlcmd.ExecuteNonQuery()
                sqlcon.Close()
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try


text:
Q: How to use custom JTable cell editor and cell renderer I have created a JTable with a custom table render and custom cell editor which gives the result in the image

I created the panel shown in the first table cells using a separate class which extended JPanel. and add table values as,
        tbl.setCellEditor(new customCell());
        tbl.getColumnModel().getColumn(0).setCellRenderer(new customCell());

        DefaultTableModel dtm = (DefaultTableModel) tbl.getModel();

        Vector v = new Vector();
        v.add(new Panel());
        v.add("Test");
        dtm.addRow(v);

        v.clear();
        v.add(new Panel());
        v.add("Test 2");
        dtm.addRow(v);

And this is my table custom class to create this table,
class customCell extends DefaultTableModel implements TableCellRenderer, TableCellEditor {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Panel p = new Panel();
            table.setRowHeight(row, p.getHeight());
            return p;
        }

        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {

            return new Panel();
        }

        public Object getCellEditorValue() {
            return "";
        }

        public boolean isCellEditable(EventObject anEvent) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        public boolean shouldSelectCell(EventObject anEvent) {
            return true;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }

        public boolean stopCellEditing() {
            return true;
        }

        public void cancelCellEditing() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void addCellEditorListener(CellEditorListener l) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void removeCellEditorListener(CellEditorListener l) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }

My problem is thought the panel is shown as I expected I can't type into the text field or change check box or click the button. please tell me how to solve this.

A: I would strongly suggest to reuse the functionality made available in the default table renderers and editors, as there are many things wrong with your code

*

*Please split your editor, renderer and table model. Having them all in the same class is just weird

*For your renderer, do not create new instances of a Component each time. Instead, reuse the same component and just modify that Component in the getTableCellRendererComponent method

*Same goes for the editor Component

*Extend a default editor instead of implementing the methods with UnsupportedOperationExceptions or by just returning empty Strings

To back-up my forth point, a little quote from the Editors part in the JTable tutorial:

What if you want to specify an editor other than a text field, check box, or combo box? As DefaultCellEditor does not support other types of components, you must do a little more work. You need to create a class that implements the TableCellEditor interface. The AbstractCellEditor class is a good superclass to use. It implements TableCellEditor's superinterface, CellEditor, saving you the trouble of implementing the event firing code necessary for cell editors.
Your cell editor class needs to define at least two methods — getCellEditorValue and getTableCellEditorComponent. The getCellEditorValue method, required by CellEditor, returns the cell's current value. The getTableCellEditorComponent method, required by TableCellEditor, should configure and return the component that you want to use as the editor.

As clearly explained there you must implement the event firing code:

saving you the trouble of implementing the event firing code necessary for cell editors.

which you clearly neglected. Therefore my advise to start from AbstractCellEditor instead of implementing the interface from scratch

A: have to add proper LayoutManager, Editable/non_Editable properties for already visible JPanel
let enjoy
import java.awt.*;
import java.awt.event.*;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.table.*;

public class PanelInTable {

    private JFrame frame;
    private JTable compTable = null;
    private PanelTableModel compModel = null;
    private JButton addButton = null;

    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception fail) {
        }
        SwingUtilities.invokeLater(() -> {
            new PanelInTable().makeUI();
        });
    }

    public void makeUI() {
        compTable = CreateCompTable();
        JScrollPane CompTableScrollpane = new JScrollPane(compTable,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JPanel bottomPanel = CreateBottomPanel();
        frame = new JFrame("Comp Table Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(CompTableScrollpane, BorderLayout.CENTER);
        frame.add(bottomPanel, BorderLayout.SOUTH);
        frame.setPreferredSize(new Dimension(800, 400));
        frame.setLocation(150, 150);
        frame.pack();
        frame.setVisible(true);
    }

    public JTable CreateCompTable() {
        compModel = new PanelTableModel();
        compModel.addRow();
        JTable table = new JTable(compModel);
        table.setRowHeight(new CompCellPanel().getPreferredSize().height);
        table.setTableHeader(null);
        PanelCellEditorRenderer PanelCellEditorRenderer = new PanelCellEditorRenderer();
        table.setDefaultRenderer(Object.class, PanelCellEditorRenderer);
        table.setDefaultEditor(Object.class, PanelCellEditorRenderer);
        return table;
    }

    public JPanel CreateBottomPanel() {
        addButton = new JButton("Add Comp");
        addButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Object source = ae.getSource();
                if (source == addButton) {
                    compModel.addRow();
                }
            }
        });
        JPanel panel = new JPanel(new GridBagLayout());
        panel.add(addButton);
        return panel;
    }
}

class PanelCellEditorRenderer extends AbstractCellEditor implements
        TableCellRenderer, TableCellEditor {

    private static final long serialVersionUID = 1L;
    private CompCellPanel renderer = new CompCellPanel();
    private CompCellPanel editor = new CompCellPanel();

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        renderer.setComp((Comp) value);
        return renderer;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int row, int column) {
        editor.setComp((Comp) value);
        return editor;
    }

    @Override
    public Object getCellEditorValue() {
        return editor.getComp();
    }

    @Override
    public boolean isCellEditable(EventObject anEvent) {
        return true;
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
        return false;
    }
}

class PanelTableModel extends DefaultTableModel {

    private static final long serialVersionUID = 1L;

    @Override
    public int getColumnCount() {
        return 1;
    }

    public void addRow() {
        super.addRow(new Object[]{new Comp(0, 0, "", "")});
    }
}

class Comp {

    public int type;
    public int relation;
    public String lower;
    public String upper;

    public Comp(int type, int relation, String lower, String upper) {
        this.type = type;
        this.relation = relation;
        this.lower = lower;
        this.upper = upper;
    }
}

class CompCellPanel extends JPanel {

    private static final long serialVersionUID = 1L;
    private JLabel labelWith = new JLabel("With ");
    private JComboBox typeCombo = new JComboBox(new Object[]
    {"height", "length", "volume"});
    private JComboBox relationCombo = new JComboBox(new Object[]
    {"above", "below", "between"});
    private JTextField lowerField = new JTextField();
    private JLabel labelAnd = new JLabel(" and ");
    private JTextField upperField = new JTextField();
    private JButton removeButton = new JButton("remove");

   public CompCellPanel() {
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        relationCombo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                enableUpper(relationCombo.getSelectedIndex() == 2);
            }
        });
        enableUpper(false);
        removeButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JTable table = (JTable) SwingUtilities.getAncestorOfClass(
                        JTable.class, (Component) e.getSource());
                int row = table.getEditingRow();
                table.getCellEditor().stopCellEditing();
                ((DefaultTableModel) table.getModel()).removeRow(row);
            }
        });
        add(labelWith);
        add(typeCombo);
        add(relationCombo);
        add(lowerField);
        add(labelAnd);
        add(upperField);
        add(Box.createHorizontalStrut(100));
        add(removeButton);
    }

    private void enableUpper(boolean enable) {
        labelAnd.setEnabled(enable);
        upperField.setEnabled(enable);
    }

    public void setComp(Comp Comp) {
        typeCombo.setSelectedIndex(Comp.type);
        relationCombo.setSelectedIndex(Comp.relation);
        lowerField.setText(Comp.lower);
        upperField.setText(Comp.upper);
        enableUpper(Comp.relation == 2);
    }

    public Comp getComp() {
        return new Comp(typeCombo.getSelectedIndex(),
                relationCombo.getSelectedIndex(),
                lowerField.getText(), upperField.getText());
    }
}


text:
Q: Microsoft HPC Scheduler not getting connected I have this code:
static void Main(string[] args)
        {
            Microsoft.Hpc.Scheduler.Scheduler scheduler =
                new Microsoft.Hpc.Scheduler.Scheduler();

            Console.Write(scheduler.ClusterParameters + "\n" +
                scheduler.EnvironmentVariables + "\n");

        }

This is generating an exception. After the scheduler object is created, the properties ClusterParameters and EnvironmentVariables are holding exceptions.
The exception is, "Microsoft.Hpc.Scheduler.SchedulerException - The operation failed because you are not connected to the scheduler"
Any ideas?

A: The docs suggest you do not use the Scheduler class directly.  Do this instead:
IScheduler scheduler = new Scheduler();

Once you've done this you would have to Connect to be able to use the properties.  That's why you get that exception.

After creating an instance of this
  interface, call the IScheduler.Connect
  method to connect to a cluster. You
  can then create and schedule jobs, run
  commands, and retrieve information
  about nodes in the cluster.


text:
Q: String Insertion won't take any effect Inserting a string into a string doesn't appear to have any effect. I'm using the following code:
string stNum = string.Format("{0:00}", iValue);
DesiredCode.Insert(0, stNum);
txtCode.Text = DesiredCode;

Breakpoints show stNum has the desired value, and DesiredCode is also as we would expect before insertion.
But after insertion, nothing will happen and the DesiredCode is the same as before!
Can someone please point me in the right direction as to what I'm doing wrong?

A: Strings are immutable. All the methods like Replace and Insert return a new string which is the result of the operation, rather than changing the data in the existing string. So you probably want:
txtCode.Text = DesiredCode.Insert(0, stNum);

Or for the whole block, using direct ToString formatting instead of using string.Format:
txtCode.Text = DesiredCode.Insert(0, iValue.ToString("00"));

Or even clearer, in my opinion, would be to use string concatenation:
txtCode.Text = iValue.ToString("00") + DesiredCode;

Note that none of these will change the value of DesiredCode. If you want to do that, you'd need to assign back to it, e.g.
DesiredCode = iValue.ToString("00") + DesiredCode;
txtCode.Text = DesiredCode;

A: Strings are immutable!
DesiredCode = DesiredCode.Insert(0, stNum);

A: Strings are immutable in C#. What this means is that you need to assign the return value of String.Insert to a string variable after the operation in order to access it.
string stNum = string.Format("{0:00}", iValue);
DesiredCode = DesiredCode.Insert(0, stNum);
txtCode.Text = DesiredCode;


text:
Q: is it possible to read the text in a pdf file using perl? I want to parse the  text from a pdf file in perl without converting the pdf into any other format . Is it possible ?

A: Yes you can.
Take a look at the CAM::PDF package.
You can use this module to pull the text out.
 my $pdf = CAM::PDF->new($filename);
 my $pageone_tree = $pdf->getPageContentTree(1);
 print CAM::PDF::PageText->render($pageone_tree);


text:
Q: file upload work localhost but doesn't work on server in asp.net core I can add localde when uploading files. But when I try it on the server, I get a 404 not found error.
Normally, when redirecting url in my project, I do it as "url:" @ ViewBag.UrlPath / api / AddDocument / GetTechDocCode / ",".
While uploading the file, I used "url:" / DokumanEstablishment / Test ",".
Am I having an error while redirecting, what could be caused by this problem?


text:
Q: multiple rest api calls to third party is giving time out issue we are getting time out issue while doing multiple restful api calls to a third party.
The scenario(giving an example) is that we need to call one restful api(say REST1) to get all the employee IDs and for every employee ID we need to call another restful api(say REST2) to get the employee detail.Since we are having around 10000 employee IDs we have to make 10000 calls to REST2 which is resulting in time out issue.
The current JDK version being used is JDK6. Please suggest if there is any good approach to handle this situation.


text:
Q: What is the simplest way to solve this circular dependency? I ran into circular dependency when designing two classes, let's call them Foo and Baz, that both contain function templates. To solve it I removed the include statements from the top of both the headers, and then used .inl-files to implement the function templates, that I then included at the bottom of the class headers. The headers could then simply have forward declarations and the .inl files could do the including, making sure that both classes were defined before any member functions were implemented.
Simple enough, right? Well, not quite.
Foo needs to have one of Baz's member functions as a friend (for the purpose of this question, assume that this is a requirement and not something that I can change). Meaning I can't use a forward declaration of Baz to declare the friendship, I need the actual header where the Baz is defined.
class Baz;

class Foo
{
    template<typename T>
    friend void Baz::templateFunc(Foo&); // Error
};

After a long series of attempted solutions, I've come up with the following:
baz.h
#pragma once

class Foo;

class Baz
{
public:
    template<typename T>
    void templateFunc(Foo& f);
};

#ifndef FOO_H // If this header was not included by foo.h...
#include "baz.inl" // ...then include the inline file
#endif

baz.inl
#define BAZ_INL

#include "foo.h"

template<typename T>
void Baz::templateFunc(Foo& f)
{
    ...
}

foo.h
#ifndef FOO_H
#define FOO_H

#include "baz.h"

class Foo
{
    template<typename T>
    friend void Baz::templateFunc(Foo&);

    ...
    // Some function templates that are implemented in foo.inl
};
#include "foo.inl"

#ifndef BAZ_INL
#include "baz.inl"
#endif

#endif

(foo.inl is not important here)
This solution works but I'm not very satisfied with it. First of all, it looks very messy to me. Someone going through these headers would probably be confused as to why baz.h checks if another header has been defined before implementing its functions and why foo.h is including the implementation of baz.h. It seems like a busy solution just for satisfying a friend declaration.
Is there a simpler solution for this type of circular dependency?


text:
Q: Overflow-x : scroll works but items not aligned I have a fixed div and inside of it an x-scrollable div which contains many items.
this is my code :

....

....

....

....

....

....

....

.gallery-items {
    position: fixed;
    .....
}

.scrollable {
    overflow-x: scroll;
    overflow-y: hidden;
    width: 100%;
    height: 100%;
    white-space: nowrap;
}

.gallery-items-item {
    height: 130px;
    width: 150px;
    cursor: pointer;
    padding-left: 5px;
    padding-right: 5px;
    padding-top: 5px;
    margin-right: 10px;
    position: relative;
    background-color: #4d4d4d;
    display: inline-block;
}

but the items are not aligned on the same scrollable line.. (http://croisentoi.com/cafe/menu/ when clicking on a picture)
Is there something I miss ? Thank you.

A: Try using
vertical-align:medium;
Hope it helps you..

A: Add vertical-align: top; to .gallery-items-item to align them all to the top of gallery-items.


text:
Q: What is the link (discrepancy?) between these PDF/CDF and p-value distributions? I have created a mixed distribution model comprising 80% $H_0$ plus 20% $H_1$ to illustrate the link between the expected proportions of true and false positives and negatives in the PDF, CDF and p-value distributions.
When the effect size is small (25% increase in expected correlations vs $H_0$), everything looks consistent:

However, when I increase the effect size to 75% by separating $H_1$ from $H_0$, things don't seem to add up because I get apparent false negatives (grey area) in the p-value distribution, which are no longer there in the PDF and CDF distributions:

Conversely, when I reduce the effect size to 0% (so that $H_1$ = $H_0$), the grey area disappears altogether from the p-value distribution, whereas it is even more prominent in the PDF and CDF distributions:

Now, I'm sure I have done all the maths right and the actual distribution curves are correct and consistent, but perhaps I am misinterpreting the areas between these curves?
What do these four different coloured areas mean in each chart, and how do they relate to the expected proportions of true and false positives and negatives?
How can I show the link between these proportions in the three distributions, and why don't they correspond with each other as shown?
Please help me understand the apparent discrepancy, thanks!

A: So I have worked at this problem from the opposite end, by calculating the proportions of true and false positives and negatives directly from the CDF (rather than from the p-values) and then "normalizing" these proportions to the diagonal line that represents the p-values under the null hypothesis.  From this, it is clear that these proportions do not correspond to the areas between the p-value distribution curves as I had previously thought:

But that still leaves the question of what do the areas between the p-value curves represent, which I posed in a separate thread here:
What do the four coloured areas of this p-value distribution actually represent?


text:
Q: Problems to create a dynamic link for one of my menu buttons in a wordpress website The link is to a page with a booking widget and needs to include the text ?certificate= and the current users email address. The email address gets passed to the booking widget which then allows the user to book appointments they've already purchased.
I found a suggestion and some code but cannot make it work. The suggestion was to:

Make a custom menu link in the wordpress admin panel with a # for the
  Url.

Then the code is suposed to do the rest. Ive tried putting the code in the header.php file as well as making it into a plugin but in each case it breaks the website. Here's the code I have so far...

<?php
if (is_user_logged_in()){ ?>
  <script>
    $(document).ready(function(e) {
      var targetNav = $('li.menu-item menu-item-type-custom menu-item-object-custom menu-item-557 a');
   var userEmail = '<?php $current_user = wp_get_current_user(); echo $current_user->user_email;?>';
   var userUrl = 'https://www.ourlinguafranca.com/book/' + '?certificate=' + userEmail/;
      targetNav.attr('href',userUrl);
    });
  </script>
<?php }  else { ?>
  <script>
    $(document).ready(function(e) {
      var targetNav = $('li.menu-item menu-item-type-custom menu-item-object-custom menu-item-557 a');
      targetNav.attr('href','https://www.ourlinguafranca.com/my-account/');
    });
  </script>
<?php } ?>

A: Try to use jQuery instead of $ sign bcoz sometimes $ is not working in wordpress


text:
Q: Retrieve contacts from Outlook Contact Group not Contact List using C# I need to retrieve the email addresses from a user specified Outlook 2013 Contact Group. This VBA code I found elsewhere works perfectly but I need to convert it to C#. All of the C# examples I've found pull the addresses from the Contact List instead of the user created Contact Group. Any help will be appreciated.
    Public Function GetContactGroupAddresses()
        Dim I As Integer
        Dim AddressList As String
        Dim Group As String
        Dim olApp As Outlook.Application
        Dim myNamespace As Object
        Dim myFolder As Object
        Dim myItem As Object
        Dim WordApp As Object

        AddressList = " "
        Group = "EmailTest"

        Set olApp = New Outlook.Application
        With olApp
            Set myNamespace = .GetNamespace("MAPI")
            Set myFolder = myNamespace.GetDefaultFolder(olFolderContacts)
            Set myItem = myFolder.Items(Group)
            For I = 1 To myItem.MemberCount
                    AddressList = AddressList & myItem.GetMember(I).Address
        End With

        GetContactGroupAddresses = AddressList

    End Function


text:
Q: NFS+Kerberos+AD Исходные данные:
srv1 - Ubuntu 14.04 NFS server
clent1 - Ubuntu 14.04 NFS client
Оба узла введены в AD, доменная авторизация работает, uid везде одинаковые.
Что хотелось бы получить:
доменный пользователь Vasya после логина на client1 мог бы смонтировать только свою папку srv1:/export/Vasya. На сколько я понимаю для этого используется NFS+Kerberos. Нормального руководства найти не удалось (или они не совместимы с руководством по вводу в AD).
Если кто решал подобную задачу прошу помочь:-)

A: Добавьте сетевую шару в /etc/fstab - тогда Вася сможет ее смонтировать. Конечно, смонтировать ее сможет и Петя - но у Пети все равно не будет доступа к файлам.
Надо понимать, что NFS - вещь довольно низкоуровневая, и не следит за тем, какой пользователь что монтирует, в принципе. На уровне NFS авторизация если и происходит - то авторизуется компьютер clent1 на сервере srv1, авторизация пользователей - это уже задача других слоев ОС.
Отсюда следствие - если client1 - не ваш компьютер (права рута не нем есть у кого-то кроме вас), то к вашей NFS-шаре ему доступ давать нельзя, ведь подменить uid при наличии прав рута - раз плюнуть.
Если требуется авторизация именно уровня пользователя, а не компьютера - используйте протокол SMB, а не NFS. Не смотря не все его недостатки, он лучше приспособлен для таких задач.


text:
Q: Docker+Java. Не работает Сервер - Клиенты Всем привет! Разбираюсь сейчас с докером и столкнулся со следующей проблемой:
Во время практики с Docker Compose не удалось создать контейнеры. Суть задачи:
Существует Сервер (на языке Java). Оно просто запускается и ждет, когда на него кто-то что-то пришлет. Сервер самый примитивный, без пулов потоков и всяких наворотов модных, так как сейчас для задачи это не особо важно. Код Сервера:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class Server {
    public static void main(String[] args) throws IOException {
        System.out.println("Server was started!");
        try (ServerSocket serverSocket = new ServerSocket(8899)) {
            while (true) {
                try (Socket client = serverSocket.accept()) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    String line = reader.readLine();
                    System.out.println(client.getInetAddress().getHostAddress() + " - " + line);
                } catch (Exception e) {
                    System.out.println("Dops");
                }
            }
        }
    }
}

Существуют 2 клиента. Также на языке Java. Также максимально простые:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

class Client {
    public static void main(String[] args) throws IOException, InterruptedException {

        String ip = "app_server";
        while (true){
        try (Socket socket = new Socket(ip, 8899)) {
            System.out.println("An attempt...");
            Thread.sleep(10000);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String message = "Hello from client_1\n";
            writer.write(message);
            writer.flush();
            System.out.println("The package was sent!");
        }
        }

    }
}

Второй клиент абсолютно такой же, только отправляет сообщение "Hello from client_1\n".
Идея такая: создать 3 контейнера (Сервер, клиент№1, клиент№2). И чтобы клиенты раз в 10 сек отправляли сообщение на сервер.
Испытал у себя на компе. Все работает прекрасно. Сообщения доходят. (Правда ip я задавал жестко в коде клиентов).
Создал структуру папок:

Содержимое докер файлов ниже:
клиент1:
FROM openjdk:11

WORKDIR /app_client1

COPY . .

RUN javac Client.java

CMD [ "java", "Client" ]

клиент2
FROM openjdk:11

WORKDIR /app_client2

COPY . .

RUN javac Client.java

CMD [ "java", "Client" ]

Сервер:
FROM openjdk:11

WORKDIR /app_server

COPY . .

RUN javac Server.java

CMD [ "java", "Server" ]

и docker-compose:
version: '3'

services:
  app_server:
    build: ./app_server
  app_client1:
    build: ./app_client1
  app_client2:
    build: ./app_client2

Отправляю команду docker-compose up и получаю вот такой вывод:
PS D:\it\dockerNet\docker-compose-app> docker-compose up
[+] Running 3/3
 - Container docker-compose-app-app_server-1   Cr...                                             0.6s
 - Container docker-compose-app-app_client2-1  C...                                              0.6s
 - Container docker-compose-app-app_client1-1  C...                                              0.6s
Attaching to docker-compose-app-app_client1-1, docker-compose-app-app_client2-1, docker-compose-app-app_server-1
docker-compose-app-app_client1-1  | Exception in thread "main" java.net.ConnectException: Connection refused (Connection refused)
docker-compose-app-app_client1-1  |     at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
docker-compose-app-app_client1-1  |     at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412)
docker-compose-app-app_client1-1  |     at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255)
docker-compose-app-app_client1-1  |     at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237)
docker-compose-app-app_client1-1  |     at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
docker-compose-app-app_client1-1  |     at java.base/java.net.Socket.connect(Socket.java:609)
docker-compose-app-app_client1-1  |     at java.base/java.net.Socket.connect(Socket.java:558)
docker-compose-app-app_client1-1  |     at java.base/java.net.Socket.<init>(Socket.java:454)
docker-compose-app-app_client1-1  |     at java.base/java.net.Socket.<init>(Socket.java:231)
docker-compose-app-app_client1-1  |     at Client.main(Client.java:15)
docker-compose-app-app_server-1   | /bin/sh: 1: [java,: not found
docker-compose-app-app_client1-1 exited with code 1
docker-compose-app-app_server-1 exited with code 127
docker-compose-app-app_client2-1  | Exception in thread "main" java.net.NoRouteToHostException: No route to host (Host unreachable)
docker-compose-app-app_client2-1  |     at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
docker-compose-app-app_client2-1  |     at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412)
docker-compose-app-app_client2-1  |     at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255)
docker-compose-app-app_client2-1  |     at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237)
docker-compose-app-app_client2-1  |     at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
docker-compose-app-app_client2-1  |     at java.base/java.net.Socket.connect(Socket.java:609)
docker-compose-app-app_client2-1  |     at java.base/java.net.Socket.connect(Socket.java:558)
docker-compose-app-app_client2-1  |     at java.base/java.net.Socket.<init>(Socket.java:454)
docker-compose-app-app_client2-1  |     at java.base/java.net.Socket.<init>(Socket.java:231)
docker-compose-app-app_client2-1  |     at Client.main(Client.java:15)
docker-compose-app-app_client2-1 exited with code 1

Теперь мучают 2 вопроса:

*

*Могу ли я именем сервиса заменить IP адрес сервера, как я сделал в строке
String ip = "app_server";
Так как на ютубе видел, что это якобы возможно. Если не могу, то как понять с каким IP создастся контейнер сервера?

*Не могу найти ошибку, почему не создаются контейнеры??

Подскажите пожалуйста. Приветствуются ЛЮБЫЕ идеи и советы. Заранее всем благодарен за помощь!!


text:
Q: how to extract strings My data is like below
sp|Q9H9K5|MER34_HUMAN(9-21)
sp|Q9H9K5|MER34_HUMAN(493-507)
sp|Q9H9K5|MER34_HUMAN(524-539)
sp|P31689|DNJA1_HUMAN(22-33)
sp|P31689|DNJA1_HUMAN(66-82)
sp|P31689|DNJA1_HUMAN(93-104)
sp|P08246|ELNE_HUMAN(7-27)
sp|P08246|ELNE_HUMAN(72-83)
sp|P10144|GRAB_HUMAN(5-13)

I am trying to extract the string between ||
sed -n " ||" file
grep "||" file

did not work .
desire output is like this
Q9H9K5
Q9H9K5
Q9H9K5
P31689
P31689
P31689
P08246
P08246
P10144

Then I want to make them unique
 Q9H9K5
 P31689
 P08246
 P10144

A: You can use cut here to nice effect.
cut -d\| -f2 myfile.txt

Produces the following output:
Q9H9K5
Q9H9K5
Q9H9K5
P31689
P31689
P31689
P08246
P08246
P10144

The -d tells cut to look out for the pipe character to delimit the columns of your output (in this case we must escape it). The -f specifies which column (or columns) of your input you want back. Columns are numbered starting with 1.
If you only want the unique values, you can pipe that output into sort and uniq as follows:
cut -d\| -f2 myfile.txt | sort | uniq

This produces:
P08246
P10144
P31689
Q9H9K5

A: You can try something like:
awk -F\| '{print $2}' input_file|sort -u


text:
Q: Proof of flat base change: reduction to affines I'm trying to understand the proof of flat base change. I refer to https://stacks.math.columbia.edu/tag/02KH for the statement and the notation. The first line of the proof says:

Namely, part (1) is local on $S′$ and hence we may assume $S$ and $S′$ are affine.

I understand that I can assume $S'$ to be affine. Indeed, the natural morphism
\begin{equation}
g^* R^i f_* F \to R^i f'_* F'
\end{equation}
is an isomorphism if and only if for any $u \colon U \to S'$ with $U$ affine we have that
\begin{equation}
u^* g^* R^i f_* F \to u^* R^i f'_* F'
\end{equation}
is an isomorphism. So, if we can prove flat base change with $S'$ affine, we can prove the general statement. However, I don't understand how we can assume also $S$ to be affine. Why and how is this possible?


text:
Q: Where should i put my uploaded images on server in java application? Am having  project structure in eclipse as shown below (using struts ). I have to upload a lot of item images  in WebContent/images . The volume of images can increase with time to somewhere around 10000 to 15000 . My question is that each time I would be deploying a war file on the server the old data would be over written and all of the uploaded images would be gone . So what is the best way to implement this upload thing . What I have think of is making a seprate images folder on the machine and create a sym-link to it in my server directory . But if there is any better option available , or even if someone can add some comments on my exiting solution it would be better .

A: Store the images on your machine. Let's say, /var/project/images. If you have multiple servers running you can add a mount point using for example nfs or cifs. Writhe a image servlet that returns the data from this location. Just add the servlet to your web.XML and use /resources/images/* as servlet location. You can then usethe path information to locate the image in /var/project/images/.

A: You can use the Symbolic Links/ alias direcory of linux filesystem to do this [folder short cuts in windows]
keep all the images outside webapps, like
usr/local/tomcat/itemimage/

and create a alias directory(Symbolic Links- like folder shortcut in windows) to webapps/<application>/image direcory to link usr/local/tomcat/itemimage/

A: One Suggestion, If you are going to have a large amount image data, better to load directly into an Amazon S3 bucket. S3, is a "highly durable and available store" and can be used to reliably store application content such as media files, static assets and user uploads. It allows you to offload your entire storage infrastructure and offers better scalability, reliability, and speed than just storing files on the filesystem.


text:
Q: Which fires first? ASP SQLDataSource OR a C# Query string? I have a GridView where the user clicks on a delete button. When that delete button is pressed it's attached to an SQL datasource on the ASP page itself. Doing it this way alleviates having to select the row then delete.
I also have in the GridView an
OnRowDeleting="GridView1_RowDeleting"

call. This method is rather simple in the code behind. The ASP SQL datasource checks a value in a table using a CASE WHEN and executes an update off of that or not.
I realized after that OnRowDeleting will always happen before the GridView control actually deletes it. It works correctly when the SQL data source doesn't fire execute. (I don't want it to based on that CASE WHEN clause) the OnRowDeleting method then fires and calls the Javascript call I have .. looks like this.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        ClientScript.RegisterStartupScript(GetType(), "hwa", "Ealert();", true);
    }

The problem sits when the SQL datasource executes correctly as it's supposed to, the OnRowDeleting (GridView1_RowDeleting) still fires.
Is there a way to fire that Javascript only when the SQL datasource didn't execute?

A: I'm not sure whether I asked the correct question or not. However, doesn't matter. I found the answer I was looking for. Basically, I needed a way to access a certain cell in a row form GridView without selecting it. When pressing a delete button within GridView it calls its OnRowDeleting method I have setup. From there I select and compare its value like this:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        TableCell cell = GridView1.Rows[e.RowIndex].Cells[12];
        if(cell.Text == "Yes")
        {
            //Do Nothing
        }
        else
        {
            ClientScript.RegisterStartupScript(GetType(), "hwa", "Ealert();", true);
            e.Cancel = true;
        }

    }

I didn't realize I could access the cell in this way. My original question might not make sense and doesn't seem applicable, but I asked it thinking I would have to run an SQL query on the code behind versus using the ASP SQL data source. Doing it this way solves everything in one.


text:
Q: How to use if statements with pandas/ csv files i want to check if the string data in a series is equal to a given string.
but this returns:
    The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
i know that to use and/or i use & / | but i don't understand how to do this with an if statement
for i in range(len(data)):
    if (data.Sex == 'female'):
        if data.Survived == 1:

EDIT
so what i want to do is check if the Sex column is set female for each row in the data set. what is the best way of doing this.
here is an example of what the data looks like:
PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S
2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs

i might be doing this all wrong. please tell me if i am.

A: You can use np.where
Ex:
import pandas as pd
import numpy as np

df = pd.DataFrame({"sex": ['female', 'male', 'male' , 'female', 'female'],
                   "Survived": [0, 0, 0, 0, 0]})
df["Survived"] = np.where(df["sex"] == 'female', 1, 0 )
print(df)

Output:
   Survived     sex
0         1  female
1         0    male
2         0    male
3         1  female
4         1  female