text:
Q: How to do phong shading in POV-ray I am using POV-ray raytracer for rendering. I have a mesh of triangles, when I render that using :
 mesh
{
    triangle
   {
           < corner_1>, <corner_2>, <corner_3>
   }

}

I am not getting smooth shading, there is also a provision for smooth shading in POV-ray which is using :
smooth_triangle
{
    <Corner_1>, <Normal_1>, <Corner_2>,
    <Normal_2>, <Corner_3>, <Normal_3>
    [OBJECT_MODIFIER...]
}

But the problem is that it requires normal of corners of triangle ( it uses phong shading ), How to calculate normal at corners of triangle? How to have a smooth shading in POV-ray?
NOTE: triangles sharing common vertices will have same normal at those vertices


text:
Q: How to obtain a lowercase cursive "o"? The problem is how to print the following math symbol.  I cannot find it among the Greek symbols.

here is where the "o" i find. I guess it's a special mathfont , and your anwser is very well and i will adopt your solution, but we can go head and find the best solution. thanks again.

A: @egreg's solution is as close as one is going to get to the symbol you displayed, but here's an alternative.

\documentclass{article}

\usepackage{dutchcal}

\begin{document}

$\mathcal{abcdefghijklmnopqrstuvwxyz}$

\end{document}

A: This is a lowercase "o" in a script alphabet; the best approximation I can offer is via the mathalfa package:
\documentclass{article}

\usepackage[scr=boondox]{mathalfa}

\begin{document}

$\mathscr{o}$

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Login Endpoint not working on my machine, but it does elsewhere Ok, so at this point I am very curious and I would love to find out what is wrong with my code or machine. I am working on a team project; I am part of the back-end with someone else; we started testing endpoints and they all work, except for me the /api/auth/login endpoint. Insommia gives me a 500 fatal error, with no message. The thing is , the exact same code , when cloned in another person's computer works.
I went ahead, and even deleted my local repository and created a new one and I am still getting the error. I have no idea what is going on. The project is a NodeJs Express Back End application.
Here is the repo in case someone wants to test it out for themselves. Funny thing, the deployed version of the api, works perfectly , including log in.
https://github.com/Build-Week-Secret-Family-Recipes-2/Back-End

Here is my auth router code for login

router.post('/login', (req, res) => {
    let { username, password } = req.body;

    Users.findByFilter({ username })
        .first()
        .then((user) => {
            if (user && bcrypt.compareSync(password, user.password)) {

                const token = signToken(user);
                res.status(200).json({
                    token: token,
                    message: `Welcome ${user.username}!`,
                });
            } else {
                res.status(401).json({ message: 'Invalid Credentials' });
            }
        })
        .catch((err) => {
            res.status(500).json(err);
        });
});

function signToken(user) {
    const payload = {
        username: user.username,
    };
    const secret = process.env.JWT_SECRET || 'it is a secret, is it safe?';
    const options = {
        expiresIn: '1h',
    };
    return jwt.sign(payload, secret, options);
}

A: Ok, guys, I finally found out what the problem was. The reason the code was working for everyone but me, it is because I had the header type turned off in Insomnia. So it was not receiving a JSON object.


text:
Q: Placing the value inside the text field loads the entire page, So Is there any function which will wait for the page load? Placing the value inside the text field loads the entire page, So Is there any function which will wait for the page load?
There are certain kind of a text_field which I am automating in which when I place the value like
b.text_field(:id,'something').set 'hi'

It refresh the entire page or it reloads the page, but the above code only wait until element present and place the value inside the text field but it doesn't take care of what happens after that.
Is there any function I can write like given below,
b.text_field(:id,'something').set 'hi'

b.waitForPageToLoad # Code like this?

Or it there any function to check whether the page got loaded completely?
I have put this question in watir-general as well, but I find no reply, so I am writing here.

A: With dynamic website implementations, the phrase "the page has finished loading" doesn't really mean anything any more.
The best practice is to wait for the thing you are interacting with next. Watir 6 has made this much more automatic, but some additional logic may still be required to accomplish what you need.
Since the details that have been provided do not make sense any longer, here are a few generic principles that might help.
Watir & Selenium will both automatically wait for a page to finish reloading once it detects that it has started to reload.
Watir will automatically wait for an element to be in a state to interact with it if you take an action on that element.
Element#set is a combination of Element.clear and Element.send_keys
If the javascript on your page does things when an element is or is not the active element, it might be necessary to click on the element before or after sending text to it.
It is possible to send symbols representing keys, like browser.text_field(name: 'first').set "foo", :tab
If you need to be able to know that a page has been refreshed in order to continue your test, you can create a variable that stores the element locators, then take an action on that element variable (which actually looks up the element), and then wait for that element to go stale like this:
element = browser.text_field(name: 'first')
element.set "foo"
# do something that causes the page to be refreshed
element.wait_until(&:stale?)

Hopefully some combination of these things related to your concerns will help you figure out a solution to your problem.


text:
Q: Nornalize nested dict to a single dict I have an actual structure I am reading from a file :
{
  "id": 1,
  "name": "Explosives",
  "category_id": 1,
  "average_price": 294,
  "is_rare": 0,
  "max_buy_price": 755,
  "max_sell_price": 1774,
  "min_buy_price": 99,
  "min_sell_price": 18,
  "buy_price_lower_average": 176,
  "sell_price_upper_average": 924,
  "is_non_marketable": 0,
  "ed_id": 128049204,
  ** "category": {
    "id": 1,
    "name": "Chemicals"
  } **
}

I am trying to create one single list to insert in a database after. The data in the dictionary at the end should be also at the end of my list.
As you can see below, I have dict inside my dict at the end. My actual code - which is working - is :
 for v in d:
        commodities_reference = []
        for k, g in v.items():
            if isinstance(g, dict):
                dict1 = g
                my_value1 = dict1.get("id")
                my_value2 = dict1.get("name")

        for s, i in v.items():
            if not isinstance(i, dict):
                commodities_reference.append(i)
        commodities_reference.append(my_value1)
        commodities_reference.append(my_value2)

Nevertheless, I would like to know if there is a more "pythonic" way to do it since it looks a bit ugly to me.
Thank you in advance.

A: v = {
    "id": 1,
    "name": "Explosives",
    "category_id": 1,
    "average_price": 294,
    "is_rare": 0,
    "max_buy_price": 755,
    "max_sell_price": 1774,
    "min_buy_price": 99,
    "min_sell_price": 18,
    "buy_price_lower_average": 176,
    "sell_price_upper_average": 924,
    "is_non_marketable": 0,
    "ed_id": 128049204,
    "category": {
        "id": 1,
        "name": "Chemicals"
    }
}

commodities_reference = []

for val in v.values():
    if isinstance(val, dict):
        commodities_reference.extend(val.values())
    else:
        commodities_reference.append(val)

print(commodities_reference)

Or if you want to be really concise but less readable:
for val in v.values():
    commodities_reference += val.values() if isinstance(val, dict) else [val]


text:
Q: InvalidQueryException despite of correct query I am using SpringBoot connceted with Hibernate and Cassandra Database. I made couple of methods using ResultSet and everything works perfect till now. I create another method, create query and then ResultSet.
String queryString = query.toString().replace("?", dayList.toString());
ResultSet rS = dataSource.executeQuery(queryString);

It throws me:
com.datastax.driver.core.exceptions.InvalidQueryException: No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename

Query is correct. When I execute query in database it returns me proper data.
It is wierd because I use same implementation in previous method and it works.
Here is my query:
SELECT * FROM object_action_statistics WHERE day IN ('2018-04-29','2018-04-30') AND action_id=14 AND timestamp_from>=1525099500073 AND timestamp_from<1525120897000 ALLOW FILTERING

A: Correct query should be like this:

SELECT * FROM KEYSPACE_NAME.object_action_statistics WHERE day IN ('2018-04-29','2018-04-30') AND action_id=14 AND timestamp_from>=1525099500073 AND timestamp_from<1525120897000 ALLOW FILTERING

I guess you forgot to put keyspace name ahead of table name.


text:
Q: How to transfer parameters to a dataset in a shared explore link I made and shared a chart link like http://localhost:8080/superset/explore/p/g6xky0yBdoL/,
There is a dynamic condition "where engid = {{engid}}" in the data set in the chart. How can I append the parameter "engId" when using the chart link to access, so that the same chart can display different data by "engId".


text:
Q: No clue.. Overflow, Microsoft VBScript runtime error '800a0006' I'm receiving suddenly this error on a Win2003 Server Web Application:
Microsoft VBScript runtime error '800a0006'
Overflow: 'Appname'
A bunch of updates where performed on this server but I have rolled them back all.
The page is old ASP code and if i run file monitor utility it will show the BUFFER OVERFLOW when it hits a GIF.
Any ideas?

A: Microsoft VBScript runtime error '800a0006' almost always indicates a divide by zero error.

A: You can reproduce the Overflow error like this :
Dim testVar
testVar = 99999
testVar = CInt(testVar)

So, maybe this indicates there are some problems with the data types where you are setting some variables on that file?

A: Can you figure out where in the file the error is happening?  You can use
Response.Write "here"
Response.End
And then load the page to see what point it gets to.  Then you can post the code that is crashing and we may be able to help you more.

A: You may have a function with Out of Range variable
If you used integer variable and the variable posses greater than
integer range then its shows error.
Explanation:
Dim IntVar AS Integer
IntVar = 50000

Then it must show overflow error
So you can use following code instead of given code
Dim LongVar As Long
longVar = 50000


text:
Q: Mouse over javascript function is not working on another PC except mine I have this code to change the image into a gif when the user hover the mouse to that image, I'm using two different file type, a png when it's static then when hover it turns into another file that is a gif. I'm coding inside the header file of the stack theme on wordpress, it works perfectly on my PC but if we open it on another PC the hover effect won't work.
I tried another code it's a jQuery also but it still doesn't work on another PC
This is the code for the div

    Safe & Secure

then here's my JavaScript code

then I tried this code too
 jQuery(function($){
   $("#static").on({
     mouseenter: function(){
       $(this).attr('src','http://codingcom.lumikha.net/wp-content/uploads/2019/10/Book_4-1.gif');
     },
     mouseleave: function(){
        $(this).attr('src','http://codingcom.lumikha.net/wp-content/uploads/2019/10/Book_4_reverseAnimation.png');
     }
   });
 });

A: By the way you can do it simply in CSS.


text:
Q: Is there any website having command line environment of Linux, for practicing commands? I was wondering whether I could practice Linux commands and shell scripting, online, over a website which could provide me an editor to practice them. And I know that probably the easiest thing to do would be to download a Linux LIVE CD and then practice shell scripting, but apart from it, I want to practice them online, anywhere I want, anytime I want and on any system, without bothering about booting from a LIVE CD.

A: A nice tool that you could put on a USB key : MobaXterm.
  This will give you, in windows, a bash shell, and many unix tools (close to the linux ones, but much slower as many things that are usually builtin in bash induce re-invocation of the shell in mobaXterm. And also the pipes are emulated, making reinvocation much more often than in a real unix/linux. But it's still useable, and quite nice.). And a lot of tools to connect to other servers (ssh, scp, etc).
Another way: a real linux within windows : Many exists, such as the minimal PuppyLinux or the bigger/faster (and more complexly mixed with windows) AndLinux ... Put them also on a USB key/disk, and you'll have it with you almost anywhere.
Finally, to more closely match your request, you have online shells listed in this thread

A: You are looking for this: http://bellard.org/jslinux/
It's an online linux terminal, all done in javascript.
It runs in your browser and has some functionality for you to paste/retrieve large ammounts of text (e.g. scripts you create).

A: You can get a free instance on Amazon EC2 for a year.  Simply register and create a t1.micro instance, which is quite capable of running a decent little website.


text:
Q: Reset overlay button (cronjobs) Inside System > Scheduler > Job Configuration: then you click on a specific cronjob.
What does the button reset overlay do inside that panel?
Magento ver. 1.14.1.0

A: It sets the schedule back to the original cron expression.


text:
Q: How to get messages of a subscritpion on the cloud pub/sub? I want to notice messages remaining which can not be dealed with on subscribers in Cloud Pub/Sub(GCP).
I don't want the pub/sub lose some messages without notifications.
I know that I can't set deadletter queue in Cloud Pub/Sub(GCP).
So I'm trying to develop the tool or batch to watch messages of subscriptions by the api which is projects.subscriptions.pull(https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/pull?hl=ja).
But I don't know how to call the api with the google-cloud-pubsub:0.26.0-beta.
In addition, I'm developing the batch with scala + play.
I found that I can get messages with "gcloud beta pubsub subscriptions pull" command but I didn't get the publish-time in which the program can check whether the message is not dealed with for a while.
Please help me somebody!

A: The Cloud Pub/Sub client library does not directly expose the pull method, instead offering an asynchronous API designed for efficiently receiving messages. You could use this asynchronous API to receive your messages. The Java documentation demonstrates how to create a subscriber using this API. If you have specific reasons to want to call the synchronous pull method, then you'll need to generate the gRPC-based library. You can find the instructions on the Service APIs Overview page.


text:
Q: ESXi network setup for isolated internal virtual machines Using ESXi v5.1 and vSphere, my networking is setup like so:

*

*One standard Switch: vSwitch0

*vSwitch0 has one uplink physical adapter (Internet connected)

*vSwitch0 VM Network has 3 virtual machines (Web Accessible)

I'd like to add several "internal" VMs that are accessible only to the 3 Public facing VMs that are currently on vSwitch0.  How should I do this?  I know I could add a another "internal" vSwitch that is not bound to a physical uplink, then employ a "gateway" VM that is dual-homed, but it seems there should be an easier way.  Can I accomplish this strictly with a networking setup?  If so, how?
(Please feel free to use whatever IP scheme you need to illustrate your answer)
Thanks much!

A: Associating a port-group to a vSwitch does not necessarily give it upstream network access. The upstream device has to have a corresponding interface with a like configure IP/subnet for those devices to talk to.
Create an "internal only" port group. Give each virtual machine needing access to the uplink network and the internal network a second NIC that faces internal.
How it would look:
Router: 192.168.0.1/24
ESXi Host: 192.168.0.2/24
Public Server 1:
NIC1: Assign to existing "VM Network" port group. IP 192.168.0.11/24, Default Gateway 192.168.0.1
NIC2: Assign to "Internal Only" port group 172.16.0.11/24, No Default Gateway
Public Server 2:
NIC1: Assign to existing "VM Network" port group. IP 192.168.0.12/24, Default Gateway 192.168.0.1
NIC2: Assign to "Internal Only" port group 172.16.0.12/24, No Default Gateway
Public Server 3:
NIC1: Assign to existing "VM Network" port group. IP 192.168.0.13/24, Default Gateway 192.168.0.1
NIC2: Assign to "Internal Only" port group 172.16.0.13/24, No Default Gateway
Internal Only Server 1:
NIC1: Assign to "Internal Only" port group 172.16.0.21/24, No Default Gateway
Internal Only Server 2:
NIC1: Assign to "Internal Only" port group 172.16.0.22/24, No Default Gateway
Internal Only Server 3:
NIC1: Assign to "Internal Only" port group 172.16.0.23/24, No Default Gateway

A: *

*ESXi 5.1 and vSphere are synonomous. They are the same thing. I prefer to call it vSphere since that's what VMware calls it.

*Create a new vSwitch for the internal VM's. Do not bind this vSwitch to a physical NIC.

*Connect the internal VM's to this internal vSwitch.

*Add a new vNIC to each external VM and connect it to the "internal" vSwitch.

*Configure the internal vNIC appropriately on each VM so that they're all on the same internal subnet (whatever RFC1918 address range you choose to use).
Now each external VM is multihomed and will have a connection to both the external and the internal network and should be able to communicate on the internet as well as to the internal VM's.
Of course, this is just one of the possible ways to do this.

A: just add networks with specific vlan in the vswitch then add nics in said vlan pointing to specific network ... et voila!
if notice that the phisical interface is a trunk port will not ship between vlan only to specific vlan packets are tagged (segregation whithin the vswitch)
you can also in your case add phisical interface to specific networks  ( for example a vlan 10 with internet access then add a nic in the vm so that it connects to an internal vlan and add another phisical in that vlan for the internal network ( you can of course expand on that )
also vcenter/vsphere ==/== Esxi
ESXi is the OS the bare metal runs vcenter/vsphere is the management applications.


text:
Q: Remove rows with at least 1 value less than a certain limit in R I have a matrix, and I want to remove all rows that contain at least one element less than a value, 3 on this example. Sample data:
A=matrix(c(10,2,4,8,5,4,8,10,5),byrow=T,ncol=3)

#Remove rows that contain at least one value less than 3

final_matrix=matrix(c(8,5,4,8,10,5), byrow=T,ncol=3)

How to get to the final matrix from the initial matrix A? My real matrix contains thousands of rows tens of columns, this is a toy example. I tried A=A[A>3,] but I get an error "logical subscript too long"


text:
Q: TestNG, factory and parametrized Test description I just learned that I can nest TestNG factories. Yay! However I don't like that all test names are same. This is my example:
testng.xml:
<suite>
    <test name="TNGTST" >
        <classes>
            <class name="FactoryLevel1" />
        </classes>
    </test>
</suite>

FactoryLeve1.java:
import org.testng.annotations.Factory;
public class FactoryLevel1 {
    @Factory
    public Object[] createTest() {
        Object[] res = new Object[3];
        for (int i = 1; i <= 3; i++)
            res[i - 1] = new FactoryLevel2(i);
        return res;
    }
}

FactoryLeve2.java:
import org.testng.annotations.Factory;
public class FactoryLevel2 {
    int inst;
    public FactoryLevel2(int inst) {
        this.inst = inst;
    }
    @Factory
    public Object[] createTest() {
        Object[] res = new Object[10];
        for (int i = 1; i <= 10; i++)
            res[i - 1] = new TestClass(i * inst);
        return res;
    }
}

TestObj.java:
import org.testng.annotations.Test;
public class TestObj {
    int inst;
    public TestObj(int inst) {
        this.inst = inst;
    }
    @Test
    public void printMethod() {
        System.out.println("Instance: " + inst);
    }
}

My problem is that Intellij IDEA shows all tests with name TNGTST [printMethod()] and I guess Jenkins will show something similar same for all test (I don't know how does these tools obtain it). Can I somehow create my own name for tests in non-static way?

A: Have your test classes implement org.testng.ITest and override getName() to return what you want. I believe IDEA honors this (not 100% sure, try it).

A: Cedric Beust's solution is the correct one (implement org.testng.ITest).
the method is called getTestName though :
@Override
public String getTestName() {
    return "custom_" + i++;
}

IDEA 14 honors it :


text:
Q: Load an SWF file and close it in the same window I'm building an app where the user clicks on a button and loads an SWF file in the same window, then if he finishes, closes it with a closing button:

i want the user to be able to click on the orange closing button, and return to the first frame (the blue one),
i tried this:
orangeClosingButton.addEventListener(MouseEvent.CLICK, clickHandler);
 function clickHandler(event:MouseEvent):void {
  fscommand("quit");
 }

but this closes the whole App, i just want to close the gray SWF file, and return to the main App the blue one, any idea how can i achieve this?

A: To be able to completely stop and unload a loaded SWF, you need to invoke unloadAndStop() method on the Loader instance, that holds the loaded content. Like:
var outerSwf:Loader = new Loader;

// Load.
outerSwf.load(new URLRequest("outer.swf"));
addChild(outerSwf);

// ...
// Unload.
removeChild(outerSwf);
outerSwf.unloadAndStop();

Then, if you want to do it from inside of the loaded content. You can subscribe this method to button click of just call it.
function unloadThisSWF(e:Event = null):void
{
    // Obtain the reference to the Loader instance.
    // In AS3 root will always point to the compiled SWF
    // root, not to the topmost root attached to the Stage.
    var aLoader:Loader = root.parent as Loader;

    // Run it only if this SWF was actually loaded.
    if (aLoader)
    {
        // Detach it from display list if attached.
        if (aLoader.parent)
        {
            aLoader.parent.removeChild(aLoader);
        }

        // Invoke the unload.
        aLoader.unloadAndStop();
    }
}

A: Depends on how you load the inside SWF. Assuming this is ActionScript2 and this code is inside of the loaded movie (grey one) something like this might work:
orangeClosingButton.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:MouseEvent):void {
  // remove the event listener so the loaded movie can be garbage collected
  orangeClosingButton.removeEventListener(MouseEvent.CLICK, clickHandler);
  unloadMovie(this);
}

Not sure if you can unload the movie from the inside swf though, maybe this unloadMovie() has to be in the main SWF as well where you have loaded the movie.
if this is AS3 you should use removeChild(yourMovieClip) instead of unloadMovie


text:
Q: od --width=x option isn't working. My path seems to be correct. This is in my .bashrc file:
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

But when I run:
od –-width=10 image.ppm

I get the message "od: –width=10: No such file or directory"
Is there something wrong with my path?

A: It looks as if you pasted the --width option from something that improved the double-dash at the beginning of the option.  That should be two ASCII - (minus-sign) characters.
Pasting from your example command, the actual character is u+2013 rather than u+002d


text:
Q: Toolbar is moving under notification bar When I start my application, a few second after everything loads, the toolbar is appearing and everything moves a little up. I don't know why this is happening.

That's my layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".views.main.MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/drawer_toolbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <FrameLayout
        android:id="@+id/container_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/loader_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/loaderBackground"
        android:visibility="gone" />

</RelativeLayout>

On my phone with resolution 2340 x 1080 everything is working properly, but on phone with resolution 720 x 1440, it isn't working properly. I tried with other resolutions and it's not working still. I start thinking that the resolution isn't the reason for this bug. You can see on the screenshot above.
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorPrimary</item>
    </style>


text:
Q: ImportError: cannot import name 'Iterable' from 'collections' in Python Working in Python with Atom on a Mac.
Code:
from rubik.cube import Cube
from rubik_solver import utils

Full error:
Traceback (most recent call last):
  File "/Users/Audey/Desktop/solver.py", line 2, in <module>
    from rubik_solver import utils
  File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/rubik_solver/utils.py", line 4, in <module>
    from past.builtins import basestring
  File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/past/builtins/__init__.py", line 43, in <module>
    from past.builtins.noniterators import (filter, map, range, reduce, zip)
  File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/past/builtins/noniterators.py", line 24, in <module>
    from past.types import basestring
  File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/past/types/__init__.py", line 25, in <module>
    from .oldstr import oldstr
  File "/Users/Audey/Library/Python/3.10/lib/python/site-packages/past/types/oldstr.py", line 5, in <module>
    from collections import Iterable
ImportError: cannot import name 'Iterable' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py)

The from rubik_solver import utils is what is causing the error as when I remove it the error does not appear. I am not sure what is causing the error and hove checked there code and found it on other sources so am sure that it should work.
Any solves?

A: The Iterable abstract class was removed from collections in Python 3.10.  See the deprecation note in the 3.9 collections docs.  In the section Removed of the 3.10 docs, the item

*

*Remove deprecated aliases to Collections Abstract Base Classes from the collections module. (Contributed by Victor Stinner in bpo-37324.)

is what results in your error.
You can use Iterable from collections.abc instead, or use Python 3.9 if the problem is in a dependency that can't be updated.

A: As said in other answers, the issue is the deprecation of some aliases from collections.abc into collections from python 3.10.
If you can't modify the importations in your scripts because of a third-party import, as a temporary workaround you can do the aliases manually before importing the problematic third-party lib. See the example below for the importation of hyper library for example, which causes similar issues as yours.
import collections.abc
#hyper needs the four following aliases to be done manually.
collections.Iterable = collections.abc.Iterable
collections.Mapping = collections.abc.Mapping
collections.MutableSet = collections.abc.MutableSet
collections.MutableMapping = collections.abc.MutableMapping
#Now import hyper
import hyper

A: In python version 3.10 you should import Iterable from collections.abc instead:
from collections.abc import Iterable

or you can:
try:
    from collections.abc import Iterable
except ImportError:
    from collections import Iterable

A: You will have two files namely oldstr.py and misc.py
In misc.py:
change from collections import Mapping to from collections.abc import Mapping
and
In oldstr.py:
change from collections import Iterable to from collections.abc import Iterable
Simply... just add .abc after collections on import statement


text:
Q: How do I include a pipe | in my linux find -exec command? This isn't working.  Can this be done in find?  Or do I need to xargs?
find -name 'file_*' -follow -type f -exec zcat {} \| agrep -dEOE 'grep' \;

A: If you are looking for a simple alternative, this can be done using a loop:
for i in $(find -name 'file_*' -follow -type f); do
  zcat $i | agrep -dEOE 'grep'
done

or, more general and easy to understand form:
for i in $(YOUR_FIND_COMMAND); do
  YOUR_EXEC_COMMAND_AND_PIPES
done

and replace any {} by $i in YOUR_EXEC_COMMAND_AND_PIPES

A: I found that running a string shell command (sh -c) works best, for example:
find -name 'file_*' -follow -type f -exec bash -c "zcat \"{}\" | agrep -dEOE 'grep'" \;

A: the solution is easy: execute via sh
... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;

A: The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).
In your example you can either choose to use your top level shell to perform the piping like so:
find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'

In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.
This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.
If you for some reason would like to invoke agrep multiple times, you can do:
find . -name 'file_*' -follow -type f \
    -printf "zcat %p | agrep -dEOE 'grep'\n" | sh

This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed.  (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)
In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.
The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.

A: find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'

A: You can also pipe to a while loop that can do multiple actions on the file which find locates. So here is one for looking in jar archives for a given java class file in folder with a large distro of jar files
find /usr/lib/eclipse/plugins -type f -name \*.jar | while read jar; do echo $jar; jar tf $jar | fgrep IObservableList ; done

the key point being that the while loop contains multiple commands referencing the passed in file name separated by semicolon and these commands can include pipes. So in that example I echo the name of the matching file then list what is in the archive filtering for a given class name. The output looks like:
/usr/lib/eclipse/plugins/org.eclipse.core.contenttype.source_3.4.1.R35x_v20090826-0451.jar
/usr/lib/eclipse/plugins/org.eclipse.core.databinding.observable_1.2.0.M20090902-0800.jar
org/eclipse/core/databinding/observable/list/IObservableList.class
/usr/lib/eclipse/plugins/org.eclipse.search.source_3.5.1.r351_v20090708-0800.jar
/usr/lib/eclipse/plugins/org.eclipse.jdt.apt.core.source_3.3.202.R35x_v20091130-2300.jar
/usr/lib/eclipse/plugins/org.eclipse.cvs.source_1.0.400.v201002111343.jar
/usr/lib/eclipse/plugins/org.eclipse.help.appserver_3.1.400.v20090429_1800.jar
in my bash shell (xubuntu10.04/xfce) it really does make the matched classname bold as the fgrep highlights the matched string; this makes it really easy to scan down the list of hundreds of jar files that were searched and easily see any matches.
on windows you can do the same thing with:
for /R %j in (*.jar) do @echo %j & @jar tf %j | findstr IObservableList

note that in that on windows the command separator is '&' not ';' and that the '@' suppresses the echo of the command to give a tidy output just like the linux find output above; although findstr is not make the matched string bold so you have to look a bit closer at the output to see the matched class name. It turns out that the windows 'for' command knows quite a few tricks such as looping through text files...
enjoy

A: Here's what you should do:
find -name 'file_*' -follow -type f -exec sh -c 'zcat "$1" | agrep -dEOE "grep"' sh {} \;

I tried a couple of these answers and they didn't work for me. @flolo's answer doesn't work correctly if your filenames have special characters. According to this answer:

The find command executes the command directly. The command, including the filename argument, will not be processed by the shell or anything else that might modify the filename. It's very safe.

You lose that safety if you put the {} inside the sh command string.
There is a potential problem with @Rolf W. Rasmussen's answer. Yes, it handles special characters (as far as I know), but if the find output is too long, you won't be able to execute xargs -0 ...: there is a command line character limit set by the kernel and sometimes your shell. Coincidentally, every time I want to pipe commands from a find, I run into this limit.
But, they do bring up a valid point regarding the performance limitations. I'm not sure how to overcome that, though personally, I've never run into a situation where my suggestion is too slow.


text:
Q: enabling disabling button on checkbox check/uncheck wpf mvvm I have list of checkboxes on a window specifying some items to be ordered. I need to first disable the Order button when the windows loads and enable it after selecting/check  some items(checkboxes) and vice versa. I have bind the IsChecked property of the checkbox.
Edit Import from OP comment:-
I have only one checkbox in the ItemsControl. and I have bind the ItemsControl's ItemsSource to List. that way we can show multiple checkboxes as per the items in the List.
Here is the code:
<ItemsControl ItemsSource="{Binding FavoriteItems}" Margin="80,0">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Grid>
        <StackPanel>
          <Grid>
            <CheckBox IsChecked="{Binding IsHouseholdSelected}" Content="{Binding SubCategoryName}" Grid.ColumnSpan="1" FontFamily="Calibri" FontWeight="Bold" />
          </Grid>
        </StackPanel>
      </Grid>
    </DataTemplate>
  </ItemsControl.ItemTemplate>

A: Below is a sample code that could help you out.  Basically, the key here is I had the Items in the list implicitly notify its parent ViewModel's Command object to raise the CanExecuteChanged event every time the IsChecked property changes.  (Also, I'm using "DelegateCommand" here, which is just the same as "RelayCommand").
ViewModels:
    public class ViewModel : INotifyPropertyChanged
    {
        public DelegateCommand MyCommand { get; set; }

        private ObservableCollection<ItemViewModel> items = new ObservableCollection<ItemViewModel>();
        public ObservableCollection<Item> Items
        {
            get { return this.items; }
        }

        public ViewModel()
        {
            this.items.Add(new ItemViewModel(this) { IsChecked = false, Text = "Item 1" });
            this.items.Add(new ItemViewModel(this) { IsChecked = false, Text = "Item 2" });
            this.items.Add(new ItemViewModel(this) { IsChecked = false, Text = "Item 3" });

            this.MyCommand = new DelegateCommand(this.CanExecute, this.Execute);
        }

        public void Execute(object parameter)
        {
            MessageBox.Show("Executed");
        }

        public bool CanExecute(object parameter)
        {
            return (this.items.Count == this.items.Count((x) => x.IsChecked));
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        #endregion
    }

    public class ItemViewModel
    {
        private ViewModel parent;
        private bool isChecked;

        public string Text { get; set; }

        public bool IsChecked
        {
            get { return this.isChecked; }
            set
            {
                this.isChecked = value;

                if (this.parent.MyCommand != null)
                    this.parent.MyCommand.OnCanExecuteChanged(null);
            }
        }

        public Item(ViewModel parent)
        {
            this.parent = parent;
        }
    }

View:
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">

    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>

    <DockPanel>
        <Button DockPanel.Dock="Bottom" Command="{Binding MyCommand}">Test</Button>

        <ItemsControl ItemsSource="{Binding Items}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Text}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </DockPanel>

</Window>

A: Bind a command to the button and implement the CanExecute method to check the status of the checkboxes and either enable or disable the button and use the Execute method to invoke the functionality that you want on the button.
MVVM RelayCommand
CanExecute on MSDN
EDIT: Here is some source code of how to implement a RelayCommand. The RelayCommand class can be found at the first link provided above. I'm assuming that you know how to hook up the DataContext to the ViewModel implementation.
<StackPanel>
    <CheckBox Name="MyCheckBox" Content="Some CheckBox"
              IsChecked="{Binding MyCheckBoxChecked}"/>
    <Button Content="Click me" Command="{Binding MyCommand}"/>
</StackPanel>

public class OrderViewModel
{
    private RelayCommand MyRelayCommand;

    public OrderViewModel()
    {
        MyRelayCommand = new RelayCommand(Execute, CanExecute);
        MyCheckBoxChecked = false;
    }

    public RelayCommand MyCommand
    {
        get { return MyRelayCommand; }
    }

    public bool MyCheckBoxChecked { get; set; }

    private bool CanExecute(object o)
    {
         // Here I'm just checking the property we've bound to but you can put
         // anything in here that will return a bool, including a check of any/all
         // of the checkboxes you may need to check
         return MyCheckBoxChecked;
    }

    private void Execute(object o)
    {
        Console.WriteLine(@"Executing ...");
    }
}


text:
Q: Same table is extracted twice from a pdf by Camelot-py I am trying to extract tables from a multiple page PDF file using camelot-py v0.7.3.
So far it has been the best pdf reader tool for me. I just needed to read pdf line by line and detect table manually. I tried many other tools such as tabula, PyPDF2/4, pdfminer, etc. Some of them could not detect the text itself properly and some of them disturbed the word sequences or spacing between the columns.
But camelot-py gave me the data in the format which is best suited for my application.
In the process of extracting data from the pdf using camelot-py, it detects all tables' data almost very well except few errors:

*

*It is grouping multiple tables together in same 'TableList' element. But I am able separate these grouped tables. So no need to worry here.

*Last table from these grouped tables is repeated in a saparate 'TableList' element. This repeatition is the main concern for me.
The code used for above process is as below:
tables = camelot.read_pdf('test.pdf', pages='1-end', flavor='stream')
tables.export('foo.csv', f='csv', compress=False)

for table in tables:
    table_df = table.df
    # Code to parse data from tables in each element converted into datafram

Why camelot-py is repeating some tables? Is there any way to handle this repeatition?
More info:
Input PDF File:
I can't share the pdf files because of sensitive data. But here are some details which will give you good idea about its structure:
All pages contain only tables.
Page 1: Contains Table1 which contain customer's info. Table 2 to 4 with same structure
Page 2: Contains some rows from Table 4 and Table 5 to 7 with same structure as Table 2
Page 3: Table 8 to10 with same structure as Table 2
Output CSV files:
foo-page-1-table-1: Contain Table 1
foo-page-1-table-2: Contain last row (repeated) from Table 1 and Table 2 to 4
foo-page-2-table-1: Contain Table 7 (repeated with First row missing)
foo-page-2-table-2: Contain some end rows from Table 4 and Table 5 to 7
foo-page-3-table-1: Contain Table 10 (repeated fully)
foo-page-3-table-2: Contain Table 8 to 10


text:
Q: Graphic driver not supported in Windows 8 Few days back I installed Windows 8 Pro(32 bit) earlier it was Win7 (32bit). My Desktop configuration is the image I uploaded.
The problem is Win8 not detecting my Graphic / Video Card. I didn't purchase any graphic cards myself but I hope the graphic card is built in with AMD processors or Gigabyte Motherboard because it is working fine with Win XP, Win7.
I install Latest motherboard drivers of my Model (no effect), I installed the latest version of processors drivers of my Model (no effect). Also I tried with Legacy drivers from AMD (no effect).
Please check both images. Any help will be highly appreciated. Thank you.

I pasted dxdiag information here DxDiag Information.

------------------
System Information
------------------
Time of this report: 11/29/2012, 11:53:26
       Machine name: MUSIC_BARI
   Operating System: Windows 8 Pro 32-bit (6.2, Build 9200) (9200.win8_rtm.120725-1247)
           Language: English (Regional Setting: English)
System Manufacturer: Gigabyte Technology Co., Ltd.
       System Model: GA-MA74GMT-S2
               BIOS: Award Modular BIOS v6.00PG
          Processor: AMD Athlon(tm) II X2 250 Processor (2 CPUs), ~3.0GHz
             Memory: 6144MB RAM
Available OS Memory: 3326MB RAM
          Page File: 960MB used, 5565MB available
        Windows Dir: C:\Windows
    DirectX Version: DirectX 11
DX Setup Parameters: Not found
   User DPI Setting: 96 DPI (100 percent)
 System DPI Setting: 96 DPI (100 percent)
    DWM DPI Scaling: Disabled
     DxDiag Version: 6.02.9200.16384 32bit Unicode

---------------
Display Devices
---------------
          Card name: Microsoft Basic Display Adapter
       Manufacturer: (Standard display types)
          Chip type: ATI ATOMBIOS
           DAC type: (C) 1988-2005, ATI Technologies
        Device Type: Display-Only Device
         Device Key: Enum\PCI\VEN_1002&DEV_796E&SUBSYS_D0001458&REV_00
     Display Memory: 256 MB
   Dedicated Memory: 0 MB
      Shared Memory: 256 MB
       Current Mode: 1024 x 768 (32 bit) (64Hz)
       Monitor Name: Generic PnP Monitor
      Monitor Model: W1643
         Monitor Id: GSM3E88
        Native Mode: 1360 x 768(p) (60.015Hz)
        Output Type: Other
        Driver Name:
Driver File Version:  ()
     Driver Version: 6.2.9200.16384
        DDI Version: 11.1
     Feature Levels: 11.1,11.0,10.1,10.0,9.3,9.2,9.1
       Driver Model: WDDM 1.2
Graphics Preemption: DMA
 Compute Preemption: DMA
  Driver Attributes: Final Retail
   Driver Date/Size: , 0 bytes
        WHQL Logo'd: n/a
    WHQL Date Stamp: n/a
  Device Identifier: {D7B71AF4-43CC-11CF-B023-F003ADC2CB35}
          Vendor ID: 0x1414
          Device ID: 0x008C
          SubSys ID: 0x00000000
        Revision ID: 0x0000
 Driver Strong Name: display.inf:10809047d4324726:MSBDA:6.2.9200.16384:pci\cc_0300
     Rank Of Driver: 00FB2006
        Video Accel:
        DXVA2 Modes:

A: I had this problem as well. This is how is solved it: I was using a HP Pavillion notebook with AMD Radeon GPU.
PROBS:

*

*dxdiag showed display was working OK with all direct X Features enabled, BUT graphics adpter name was Microsoft Basic Display Adapter and only showed 256 MB graphics memory instead of the 2GB in my Radeon Graphics adapter.

*Device Manager showed display adapter 'working properly', but instead of 'AMD Radeon' as my adapter showed Microsoft Basic Display Adapter.

*GPU-Z AND CPU-Z were all showing Microsoft Basic Display Adapter as my display adaptor.

*The graphics drivers from HP.com dint work and graphics card was still not detected.

SOLUTION:

*

*I checked my notebook Specs from HP.com website and found that my notebook had AMD Radeon HD 8650M/8670M Dual GPU (1 GB DDR3 dedicated). This was the only way since device manager, dxdiag, system info, CPU-Z and GPU-Z were all showing Microsoft Basic Display Adapter as my adapter name!!

*I went to the amd site: http://support.amd.com/en-us/download , System: Notebook, Family: Radeon HD Series, Product: Radeon HD 8xxxM Series, OS: Windows 8

*Download Driver

*Install and finally worked.


text:
Q: How can I print a byte along with a string? I have a byte:
byte STX = 0x02;

Printing it as it is with printf returns 0x02 which is what I want:
System.out.printf("0x%02X", STX);

However, I want to concatenate it with strings like below or similar:
System.out.println("Found " +  STX + " at " + i);

But it returns the integer value. How can I therefore print a byte and concatenate it with a string?

A: Try this way:
System.out.println("Found " +  String.format("0x%02X", STX) + " at " + i);
or even better:
System.out.println(String.format("Found 0x%02X at %d", STX, i));
or even better:
System.out.printf("Found 0x%02X at %d%n", STX, i);

A: Use String.format:
System.out.println("Found " +  String.format("0x%02X", STX) + " at " + i);

A: Unfortunately this is effectively a copy of an existing answer, which was downvoted... but as your comment now indicates that you'd welcome such an option...
You can use printf to format your whole string:
System.out.printf("Found 0x%02X at %d%n", STX, i);

Here the 0x%02X is the part you already know; the %d is the format specifier for i; the %n is the platform-specific newline.
I find it clearer to use one style of formatting throughout a statement: either printf/String.format formatting or string concatenation, rather than a mixture of the two.
If you find yourself wanting the formatting without printing to the console, just use String.format instead:
String text = String.format("Found 0x%02X at %d", STX, i);

(That's assuming you don't want the line separator in that case.)
See the Formatter documentation for all the options in format strings.


text:
Q: convert list to vector when use for loop in R How can I convert  list to vector in R here?
a1 <- matrix(rcauchy(10*200, 0, 1), 200)

for (i in 1:150) {
  if (shapiro.test(a1[i,])$p.value >= 0.05) {
    print(t.test(a1[i,], alternative = "two.sided")$p.value)
  }
}

I use this code but I get only the first value
p <- NULL
for (i in 1:150) {
  p[i] <- if (shapiro.test(a1[i,])$p.value>=0.05) {
    (t.test(a1[i,], alternative = "two.sided")$p.value)
  }
}
p

A: To make the code run without errors, you just need to have an else statement for when the condition is false
p <- NULL
for (i in 1:150) {
  p[i] <- if (shapiro.test(a1[i, ])$p.value >= 0.05) {
    (t.test(a1[i, ], alternative = "two.sided")$p.value)
  } else {
    NA
  }
  print(i)
}
p

A: A apply loop solution.
a1 <- matrix(rcauchy(10*200, 0, 1), 200)

p <- apply(a1, 1, \(a){
  if(shapiro.test(a)$p.value >= 0.05)
    t.test(a)$p.value
  else NA_real_
})

Created on 2022-04-18 by the reprex package (v2.0.1)


text:
Q: Sencha Touch - Undefined mixin 'experimental' on compass compile When I try to compile my sass code with compass compile I get the following error :
error app.scss (Line 42 of /MyProject/touch/resources/themes/stylesheets/sencha-touch/base/src/_ProgressIndicator.scss: Undefined mixin 'experimental'.)
My sass code is pretty normal, I have :
@import 'sencha-touch/default';
@import 'sencha-touch/default/all';

/* Rest of my css below */

I'm using :
Sencha Touch 2.4 Compass 1.0.1 (Polaris) ruby 2.2.0dev Mac OSX Yosemite

A: Adding @import "compass/css3/shared"; to the project's app.scss resolves the error.  This import needs to be added before the sencha imports.
For subsequent errors I also had to add:
@import "compass/css3/box";
$experimental-support-for-pie:false;

Versions:
Sencha Touch: 2.4.1, Compass 1.0.1, Sass 3.4.9, Ruby 1.9.3
References:
http://hugogiraudel.com/2013/03/25/compass-extensions/,
http://compass-style.org/reference/compass/css3/box/,
Complete import to resolve the error:
@import "compass/css3/shared";
@import "compass/css3/box";
$experimental-support-for-pie: false;
@import 'sencha-touch/default';
@import 'sencha-touch/default/all';

<-- The rest of your sass -->


text:
Q: Validation of encrypted data I encrypt all private data of users before storing in database with help of gem 'attr_encrypted'. For example, I have 'email_addresses' table, which contains 'encrypted_email' column. This gem decrypt data when I call object.email or when I search by emails. But I have issues with validation of this column.
I have following validations for this and other tables:
validates_length_of :email, :within => 3..100
validates_numericality_of :post_code

I should decrypt data before validation somehow, but I don't know how to do this with help of built-in Rails tools. I don't want invent custom validations for this. Please, advise.

A: validations that doesn't need a db query run on the rails side so you can pass a method instead of a column to the validation methods
validates :decrypted_email, length: { within: 3..100 }

def decrypted_email
  # decrypt email here
end


text:
Q: $S_k(x+y)-S_k(x)-S_k(y)$ where $S_k$ is symmetric polynomial Let $S_k$ be the $k$-th elementary symmetric polynomial of $n$ variables. How can I rewrite $$S_k(x+y)-S_k(x)-S_k(y)$$ by just using $x,y,S_1,S_2,\cdots S_{k-1}$ where $x=(x_1,x_2,\cdots,x_n)$ and $y=(y_1,y_2,\cdots,y_n)$.
Example: Let $x=(x_1,x_2)$ and $y=(y_1,y_2)$
$$S_2(x+y)-S_2(x)-S_2(y)=(x_1+y_1)(x_2+y_2)-x_1x_2-y_1y_2$$
$$=x_1y_2+x_2y_1=(x_1+x_2)(y_1+y_2)-(x_1y_1+x_2y_2)$$
$$=S_1(x)S_1(y)-S_1(xy).$$
How can we generalize this for any $n$ and $k$?
I believe somebody found this before but my research area is far to symmetric polynomials. References are also accepted. Thanks.
Edit: (or addition:) It can be closed form or an algorithm.. Useful comments.

A: Express $S_k$ in power sums via the Newton formula. For power sums this is the binomial formula for each summand. Then express power sums again in elementary symmetric functions.
Added:
The expression $S_k(x+y)-S_k(x)-S_k(y)$ is still invariant under the diagonal action of the symmetric group $\mathfrak S(n)$ acting on $x$ and $y$ in the same way. So it can written as a polynomial in a basis for this diagonal representation. One has to determine such a basis.
By Corollary 2.17 of here the algebra of invariant polynomials of the diagonal action is the integral closure of the the algebra of 2-polarizations of the algebra of symmetric polynomials. By Example 2.18, in the case of the permutation group, the algebra of 2-polizations is already integrally closed.
However, the expression $S_2(x+y)-S_2(x)-S_2(y)$ is a 2-polarization.

A: Not quite an answer. The logarithmic derivative of the generating function trick (as described very well in Yakovlenko's notes would seem to give a reasonable approach to this (I am not quite up to working through it right this moment).

A: This is just a suggestion how to proceed in the case $k=3$, which is too long for a comment.
In case of degree $=$ number of variables $=3$ we have this formula:
\begin{align}
 & S_3(x+y+z)-S_3(x+y)-S_3(y+z)-S_3(z+y)+S_3(x)+S_3(y)+S_3(z) \\
=\;& S_1(x)S_1(y)S_1(z)-S_1(xy)S_1(z)-S_1(yz)S_1(x)-S_1(zx)S_1(y)+2S_1(xyz)
\end{align}
Specializing to $z=-\frac{x+y}{2}$ yields a formula for $S_3(x+y)-S_3(x)-S_3(y)$ in terms of $S_1$.

A: I will use the standard notation $e_k$ for the $k$-th elementary symmetric polynomial of $n$ variables, and just $e$ instead of $e_1$ for better readability.
For $k\le n$, denote the set of the "base polynomials" of degrees $\leqslant k$ that are writable in terms of $x,y,e_1,e_2,\cdots,e_{k-1}$, possibly including coordinate-wise products as in the OP, by $P_{k-1}$.
For a partition $k=\ell+m$, define, in somewhat sloppy notation, the symmetric polynomial
$$E_{(\ell,m)}:=\sum (x_1\cdots x_\ell y_{\ell+1}\cdots y_k +y_1\cdots y_\ell x_{\ell+1}\cdots x_k ).$$
So the sum is over all pairs of disjoint $\ell$- and $m$-tuples of indices. (If $\ell=m$, each monomial occurs twice, but we will count it only once.)
For instance, the following sum has $8$ monomials, and it can be checked that we can decompose it into polynomials of $ P_{3}$ as follows:
$$E_{(3,1)}=\sum (x_1x_2x_3y_4+y_1y_2y_3x_4)=\\ e_3(x)e(y)+e_3(y)e(x)-[e_2(x)+e_2(y)]e(xy) \\ +e(x)e(xxy)+e(y)e(yyx)-e(xxxy)-e(yyyx).$$ (BTW this splits of course into two non-symmetric identities, one which contains all terms featuring three instances of $x$ and one of $y$, and the other one switching $x\leftrightarrow y$.)
Now, taking $k=4$, it is easy to see that we have $$e_k(x+y)-e_k(x)-e_k(y)=E_{(3,1)}+E_{(2,2)}$$ but it seems to me that
$$E_{(2,2)}=\sum x_1x_2y_3y_4$$ can not be decomposed into polynomials of $ P_{3}$ . Or am I wrong?


text:
Q: restrict the size of video in a site We are using following code to display video in a site.

Video is displaying by covering entire monitor size.
If i click on menu_video.jpg image, it's displaying video with full size.
But I want to display the video for specific space. [width ="300" height="300" ]
Suggest me to find solution.

A: Try This

A: You should use video tag . try this:
<video width="400" height="400" controls>
  <source src="video file" type="video/mp4">
  <source src="video file" type="video/ogg">
</video>

A: Try this code istead
<video width="300" height="300" controls>
  <source src="http://www.youtube.com/embed/FEqXWwPFusI" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Source link
or try iframe

or refer this question for more


text:
Q: How to check the behavior of slope of the differential equation $y'(x) = \arctan[(2-y^2)(x^2+xy)]$? Given the Cauchy Problem,
$$ y'(x) = \arctan[(2-y^2)(x^2+xy)] $$ with initial conditions $y(0)=k$

I know that there are two horizontal asymptotes at $y=+\sqrt2$ and $y=-\sqrt2 $. Also, the $y'=0$ at $y=-x$. But I cannot understand how the slope increases or decreases between these asymptotes. The below-attached graph indicates when the slope increases (denoted as $+$) and the slope decreases (denoted as $-$). May I know how these signs are evaluated?


text:
Q: Cloud Database for Swift I've programmed in Objective-C for some time and used Parse as a back end. I was wondering if there is a backend to incorporate with a swift application as I build a new project.

A: You can still use Parse as your backend. They have updated their documentation and added the Swift equivalent of their example-codes etc.
Check this as example Just click on the Swift button on the bottom right side of a code-snippet and you will see the Swift-code.
Also you can use their Parse API in Swift too, without any problems. Just import the SDK into your project.


text:
Q: Understanding Python profile output I'm trying to use the Python profiler to speed up my code.  I've been able to identify the specific function where nearly all of the time is spent, but I can't figure out where in that function the time is being spent.
Below I have the profile output, which shows that "appendBallot" is the primary culprit and consumes nearly 116 seconds.  Further below, I have the code for "appendBallot".
I cannot figure out from the profile output, which part of "appendBallot" I need to optimize as the next highest time entry is less than a second.  I'm sure many of you could tell me just from my code, but I'd like to understand how to get that information from the profile output.  Any help would be greatly appreciated.
Profile output:
  ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       1    0.000    0.000  116.168  116.168 <string>:1(<module>)
       1    0.001    0.001  116.168  116.168 {execfile}
       1    0.003    0.003  116.167  116.167 foo.py:1(<module>)
       1    0.000    0.000  116.139  116.139 ballots.py:330(loadKnown)
       1    0.000    0.000  116.109  116.109 plugins.py:148(load)
       1    0.196    0.196  116.108  116.108 BltBallotLoader.py:37(loadFile)
  100000  114.937    0.001  115.912    0.001 ballots.py:133(appendBallot)
  100000    0.480    0.000    0.790    0.000 ballots.py:117(newBallot)
  316668    0.227    0.000    0.310    0.000 ballots.py:107(getNumCandidates)
417310/417273    0.111    0.000    0.111    0.000 {len}
  200510    0.071    0.000    0.071    0.000 {method 'append' of 'list' objects}
   99996    0.045    0.000    0.045    0.000 {method 'add' of 'set' objects}
  100000    0.042    0.000    0.042    0.000 {method 'has_key' of 'dict' objects}
       1    0.000    0.000    0.030    0.030 plugins.py:202(getLoaderPluginClasses)
       1    0.000    0.000    0.030    0.030 plugins.py:179(getPluginClasses)
       1    0.000    0.000    0.030    0.030 plugins.py:205(getLoaderPluginClass)
       3    0.016    0.005    0.029    0.010 {__import__}
       1    0.022    0.022    0.025    0.025 ballots.py:1(<module>)
       1    0.010    0.010    0.013    0.013 BltBallotLoader.py:1(<module>)
       7    0.000    0.000    0.003    0.000 re.py:227(_compile)

Code:
  def appendBallot(self, ballot, ballotID=None):
    "Append a ballot to this Ballots object."

    # String representation of ballot for determining whether ballot is unique
    ballotString = str(list(ballot))

    # Ballot as the appropriate array to conserve memory
    ballot = self.newBallot(ballot)

    # Assign a ballot ID if one has not been given
    if ballotID is None:
      ballotID = len(self.ballotIDs)
    assert(ballotID not in self.ballotIDs)
    self.ballotIDs.append(ballotID)

    # Check to see if we have seen this ballot before
    if self.uniqueBallotsLookup.has_key(ballotString):
      i = self.uniqueBallotsLookup[ballotString]
      self.uniqueBallotIDs[i].add(ballotID)
    else:
      i = len(self.uniqueBallots)
      self.uniqueBallotsLookup[ballotString] = i
      self.uniqueBallots.append(ballot)
      self.uniqueBallotIDs.append(set([ballotID]))
    self.ballotOrder.append(i)

A: Yeah I came across that same problem as well.
The only way I know to work around this is to wrap your large function into several smaller function calls. This will allow the profiler to take into account each of the smaller function calls.
Interesting enough, the process of doing this (for me, anyway) made it obvious where the inefficiencies were, so I didn't even have to run the profiler.

A: I've had a look at your code, and it looks like you make a lot of function calls and attribute lookups as part of your 'checking' or looking ahead before leaping. You also have a lot of code dedicated to track the same condition, i.e many bits of code looking at creating 'unique' IDs.
instead of trying to assign some kind of unique string to each ballot, couldn't you just
use the ballotID (an integer number?)
now you could have a dictionary (uniqueBallotIDs) mapping ballotID and the actual ballot object.
the process might be something like this:
def appendBallot(self, ballot, ballotID=None):
   if ballotID is None:
       ballotID = self._getuniqueid() # maybe just has a counter? up to you.
   # check to see if we have seen this ballot before.
   if not self._isunique(ballotID):
       # code for non-unique ballot ids.
   else:
       # code for unique ballot ids.

   self.ballotOrder.append(i)

You might be able to handle some of your worries about the dictionary missing a given key
by using a defaultdict (from the collections module). collection docs
Edit for completeness I will include a sample usage of the defaultdict:
>>> from collections import defaultdict

>>> ballotIDmap = defaultdict(list)
>>> ballotID, ballot = 1, object() # some nominal ballotID and object.
>>> # I will now try to save my ballotID.
>>> ballotIDmap[ballotID].append(ballot)
>>> ballotIDmap.items()
[(1, [<object object at 0x009BB950>])]

A: I'll support Fragsworth by saying that you'll want to split up your function into smaller ones.
Having said that, you are reading the output correctly: the tottime is the one to watch.
Now for where your slowdown is likely to be:
Since there seem to be 100000 calls to appendBallot, and there aren't any obvious loops, I'd suggest it is in your assert.  Because you are executing:
assert(ballotID not in self.ballotIDs)

This will actually act as a loop.  Thus, the first time you call this function, it will iterate through a (probably empty) array, and then assert if the value was found.  The 100000th time it will iterate through the entire array.
And there is actually a possible bug here: if a ballot is deleted, then the next ballot added would have the same id as the last added one (unless that were the one deleted).  I think you would be better off using a simple counter.  That way you can just increment it each time you add a ballot.  Alternatively, you could use a UUID to get unique ids.
Alternatively, if you are looking at some level of persistence, use an ORM, and get it to do the ID generation, and unique checking for you.

A: Profilers can be like that. The method I use is this. It gets right to the heart of the problem in no time.

A: I have used this decorator in my code, and it helped me with my pyparsing tuning work.

A: You have two problems in this little slice of code:
# Assign a ballot ID if one has not been given
if ballotID is None:
    ballotID = len(self.ballotIDs)
assert(ballotID not in self.ballotIDs)
self.ballotIDs.append(ballotID)

Firstly it appears that self.ballotIDs is a list, so the assert statement will cause quadratic behaviour. As you didn't give any documentation at all for your data structures, it's not possible to be prescriptive, but if the order of appearance doesn't matter, you could use a set instead of a list.
Secondly, the logic (in the absence of documentation on what a ballotID is all about, and what a not-None ballotID arg means) seems seriously bugged:
obj.appendBallot(ballota, 2) # self.ballotIDs -> [2]
obj.appendBallot(ballotb)    # self.ballotIDs -> [2, 1]
obj.appendBallot(ballotc)    # wants to add 2 but triggers assertion

Other comments:
Instead of adict.has_key(key), use key in adict -- it's faster and looks better.
You may like to consider reviewing your data structures ... they appear to be slightly baroque; there may be a fair bit of CPU time involved in building them.


text:
Q: Parsing a nested hierarchy in spirit qi - can't get the grammar right I'm in way over my head with spirit::qi and need some help. I'm trying to parse a phrase that is of the form:
( wheels=4 & chassis=metal & engine=( cylinders=8 & volume=6209 ) )

... into a nested structure:
class dict : public std::map<std::string, boost::variant<dict, std::string>>

... where car_dict["wheels"] returns "4", and car_dict["engine"] returns another dict, where engine_dict["cylinders"] returns "8".
Here is my grammar, I'm hoping someone that has plenty of experience in this stuff can just point out where I'm going wrong.
struct qi_car_grammar : qi::grammar<std::string::const_iterator, dict()>
{
    qi::rule<std::string::const_iterator, dict()> car_dict;
    qi::rule<std::string::const_iterator, std::string()> car_key;
    qi::rule<std::string::const_iterator, boost::variant<dict, std::string>()> car_variant_value;

    qi_car_grammar()
        : qi_car_grammar::base_type(car_dict)
    {
        // RULES
        car_key %= *(qi::lit(' ')) >> *(~qi::lit('='));

        car_variant_value %= car_dict | *(~qi::char_("&)"));

        car_dict = qi::lit('(')
            >> car_key >> qi::lit('=') >> car_variant_value
            >> *(qi::lit('&') >> car_key >> qi::lit('=') >> car_variant_value)
            >> qi::lit(')');
    }
}

Any help appreciated. Before anyone suggests it, no, I don't have much control over the structure that I am parsing into.

A: Mmm. I just did a general cleanup pass¹.
You were already pretty close.
You might just have been missing the boost/fusion/adapted/std_pair.hpp header, which is required in order to transform parsed tuples into std::pair<K,V> automagically.
Here's is the working sample (I spent the most time on creating the dict pretty printer...):
Live On Coliru
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <map>

namespace qi = boost::spirit::qi;

class dict : public std::map<std::string, boost::variant<dict, std::string>>
{
};

template <typename It = std::string::const_iterator, typename Skipper = qi::space_type>
struct qi_car_grammar : qi::grammar<It, dict(), Skipper>
{
    qi_car_grammar()
        : qi_car_grammar::base_type(car_dict)
    {
        // RULES
        car_key   = *~qi::char_("=");
        car_value = *~qi::char_("&)");

        car_variant_value = car_dict | car_value;

        car_dict = '(' >> (car_key >> '=' >> car_variant_value) % '&' >> ')';
    }

  private:
    qi::rule<It, dict(), Skipper> car_dict;
    qi::rule<It, std::string()> car_key, car_value;
    qi::rule<It, boost::variant<dict, std::string>(), Skipper> car_variant_value;
};

// for debug
static inline std::ostream& operator<<(std::ostream& os, dict const& d) {
    struct vis {
        using result_type = void;
        std::ostream& _os;
        std::string indent;

        void operator()(std::string const& s) const { _os << s; }
        void operator()(dict const& d) const {
            _os << "(\n";
            for (auto& entry: d) {
                _os << indent << "    " << entry.first << " = ";
                boost::apply_visitor(vis{_os, indent+"    "}, entry.second);
                _os << "\n";
            }
            _os << indent << ")\n";
        }
    } v { os, "" };

    v(d);
    return os;
}

int main()
{
    std::string const input = "( wheels=4 & chassis=metal & engine=( cylinders=8 & volume=6209 ) )";

    dict parsed;
    qi_car_grammar<> g;

    auto f = input.begin(), l = input.end();
    bool ok = qi::phrase_parse(f, l, g, qi::space, parsed);

    if (ok)
        std::cout << "Parsed: " << parsed << "\n";
    else
        std::cout << "Parsed failed\n";

    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}

Prints:
Parsed: (
    chassis = metal
    engine = (
        cylinders = 8
        volume = 6209
    )

    wheels = 4
)

¹ (as I always do when reading a code sample, it helps my understanding)


text:
Q: With webpack, can I put Node.js and browser code in the same file, but prevent the Node.js code making it to the browser? I have a file that I want to have both Node.js and browser code.
Node.js code should not be visible in the browser.
Can webpack exclude code from a file depending on the environment?
Kind of like C preprocessing directives. #if #else, etc.
I know that Webpack parses the code quite intensively which makes me think it can.
Constraints

*

*The Node.js code cannot make it to the browser because it might contain sensitive config options.

*I want the browser and Node code to be in the same file. I know that I could use the webpack.IgnorePlugin to ignore requires on a file basis, or put the shared code in the browser file and require that from the server (which I am doing now), but I want to know if its possible to have the code side by side in the same file.

EDIT: Here is an example of what I'm trying to do.
export class FooPlugin {

  $name = 'foo-plugin'

  register(app) {

    const app = koa()
    app.get('/foo', () => { this.send('foo') })
    app.set('SECRET STUFF!')
    app.start()
    this.shared()

  }

  shared(app) {

      // browser things - isomorphic react router routes, etc.

  }

  registerBrowser(app) {

      this.shared()

  }

}

// This is called in another file depending on the environment.

if (!isBrowser) {
  (new FooPlugin).register(app)
} else {
  (new FooPlugin).registerBrowser(app)
}

A: You can use the Define Plugin to set the NODE_ENV and gate your code that way:
var define  = new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production')}})

The DefinePlugin will replace instances of process.env.NODE_ENV in your code with the supplied string, so you will end up with something like if ('production' !== 'production') in the compiled code. When you do a production build, Webpack runs uglify with dead-code-elimination which will strip out these unreachable blocks. (See webpack howto: feature flags)
This is how React (and many other libraries) strip out development code before going to production.


text:
Q: Retrieve values from jQuery to C# Code I have a jQuery script like this:
var sList = "";
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? "1" : "0");
sList += (sList=="" ? sThisVal : "," + sThisVal);
});
console.log (sList);

But this script just writes sList values to console.
How can I retrieve sList values in C# code? and use it.

A: Alternatively, if you don't want to do a full postback, you could consider using the ASP.NET AJAX Server Callback mechanism.
This will allow you to send your sList to a server-side web service, do whatever server-side processing you want, and then return the JSON-encoded result to the client.

A: Add a hidden field:
<asp:HiddenField runat="server" ID="myList"/>

and write a JavaScript:
$("input[type=hidden][id$=myList]").val(sList);

and now you should get your sList on your server events, just see myList.Value from your C# code

A: you can simply add a hidden field to your asp.net page and set its value as a comma separated string using your JS function.
form the C# just get the data saved in the hidden field..


text:
Q: Break is not working properly after return true; The  return true; is not ending the current function loop!
This is so basic but I don't find why break is not working!
I try this piece of code:
function findKey($array, $keySearch) {
foreach ($array as $key => $item){
    echo "$key == $keySearch";
    if ("$key" == "$keySearch"){
        echo 'yes, it exists';
        return true;
    }
    else
    {
        if (is_array($item))
            findKey($item, $keySearch);
    }
}
return false;
}

The return true; never break as it let it go after the yes, it exists is echoed!
Solved
The code itself from an accepted solution here was wrong. It has been corrected. Also, below you will find the right answer.

A: You've jumped to a conclusion. In fact, your return true is assuredly ending the function immediately (including breaking out of the loop), but it only ends the current invocation of the function. Your solution is recursive, and has a bug in the else clause, whereby the result of a recursive call to findKey is completely ignored. As such, whatever happens inside that invocation has no effect.
You're seeing the echo from your outer function call.
I imagine that what you really intended to write was this:
function findKey($array, $keySearch)
{
   foreach ($array as $key => $item) {
      echo "$key == $keySearch";
      if ($key == $keySearch) {
         echo 'yes, it exists';
         return true;
      }
      else {
         if (is_array($item) && findKey($item, $keySearch))
            return true;
      }
   }

   return false;
}

I have made the same change to the original answer that you'd found.


text:
Q: Final Identifier is necessary, why? I try to write a program which convert string to integer.
But in defining method, it gets error in identifier, and tells it should be final.
"Illegal modifier for parameter stringtoInteger; only final is permitted"
does anybody know why it should be final?
public class StringtoInt {
    public static void main(String[] args) {
        public static void stringtoInteger(){

            int i = 24;
            String str = Integer.toString(i);

            int j = 23;
            String str2 = "" + j;

            int k = 22;
            String str3 = " " + k;

            System.out.println(str + "\t" + str2 + "\t" + str3);
            System.out.println(str + str2 + str3);

            System.out.println();

            System.out.println(i + "\t" + j + "\t" + k);
            System.out.println(i  + j  + k);
        }

    }
}

A: You shouldn't put a the method inside the main method.
Either drop the public static void stringtoInteger(){ method declaration, and put the code directly in main:
public class StringtoInt {
    public static void main(String[] args) {

        int i = 24;
        String str = Integer.toString(i);
        ...

or move stringtoInteger outside of main (and call it from main if you want it to execute)
public class StringtoInt {
    public static void main(String[] args) {
        stringtoInteger();
    }

    public static void stringtoInteger() {

        int i = 24;
        String str = Integer.toString(i);

        ...
    }
}

A: Use this code:
public class StringtoInt {
    public static void main(String[] args) {
        StringtoInt.stringtoInteger();
    }

    public static void stringtoInteger() {
        int i = 24;
        String str = Integer.toString(i);

        int j = 23;
        String str2 = "" + j;

        int k = 22;
        String str3 = " " + k;

        System.out.println(str + "\t" + str2 + "\t" + str3);
        System.out.println(str + str2 + str3);
        System.out.println(i + "\t" + j "\t" + k);
        System.out.println(i + j + k);
    }
}


text:
Q: How to scrape a new link with Scrapy I started using Scrapy recently, so I`m not that skilled with it, so this is really a newbie question.
I am scraping some random convention for practice, I have scraped the names and booth numbers, but I also want links from the companies, that are inside a new window, I`ve found and stored the link from anchor tags, but I do not know how to scrape those new links, any kind of help or direction will be lovely
import scrapy

class ConventionSpider(scrapy.Spider):
    name = 'convention'
    allowed_domains = ['events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']
    start_urls = ['https://events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']

    def parse(self, response):
        name = response.xpath('//*[@class="companyName"]')
        number = response.xpath('//*[@class="boothLabel"]')
        link = response.xpath('//*[@class="companyName"]')
        for row, row1, row2 in zip(name, number, link):
            company = row.xpath('.//*[@class="exhibitorName"]/text()').extract_first()
            booth_num = row1.xpath('.//*[@class="boothLabel aa-mapIt"]/text()').extract_first()
            url = row2.xpath('.//a/@href').extract_first()

            yield {'Company': company,'Booth Number': booth_num}

A: See this for reference https://github.com/NilanshBansal/Craigslist_Scrapy/blob/master/craigslist/spiders/jobs.py
import scrapy
from scrapy import Request

class ConventionSpider(scrapy.Spider):
name = 'convention'
# allowed_domains = ['events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']
start_urls = ['https://events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']

def parse(self, response):
    name = response.xpath('//*[@class="companyName"]')
    number = response.xpath('//*[@class="boothLabel"]')
    link = response.xpath('//*[@class="companyName"]')
    for row, row1, row2 in zip(name, number, link):
        company = row.xpath('.//*[@class="exhibitorName"]/text()').extract_first()
        booth_num = row1.xpath('.//*[@class="boothLabel aa-mapIt"]/text()').extract_first()
        url = row2.xpath('.//a/@href').extract_first()

        yield Request(url,callback=self.parse_page,meta={'Url':url,'Company': company,'Booth_Number': booth_num)

def parse_page(self,response):
    company = response.meta.get('Company')
    booth_num = response.meta.get('Booth Number')
    website = response.xpath('//a[@class="aa-BoothContactUrl"]/text()').extract_first()

    yield {'Company': company,'Booth Number': booth_num, 'Website': website}

Edit:
Comment the line allowed_domains to let the crawler work on other domains as well.
In reply to your code at https://stackoverflow.com/a/52792350

A: A much easier way of doing this would be to subclass the scrapy.spiders.CrawlSpider class instead and specify the rule attribute
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class ConventionSpider(CrawlSpider):
    name = 'convention'
    allowed_domains = ['events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']
    start_urls = ['https://events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']

    rules = (
    Rule(LinkExtractor(allow=('', ), # allow all links that match a given regex
        deny=('')), # deny all links that match given regex
        callback='parse_item', # function that gets called for each extracted link
        follow=True),
    )

    def parse_item(self, response):
        name = response.xpath('//*[@class="companyName"]')
        number = response.xpath('//*[@class="boothLabel"]')
        link = response.xpath('//*[@class="companyName"]')
        for row, row1, row2 in zip(name, number, link):
            company = row.xpath('.//*[@class="exhibitorName"]/text()').extract_first()
            booth_num = row1.xpath('.//*[@class="boothLabel aa-mapIt"]/text()').extract_first()
            # url = row2.xpath('.//a/@href').extract_first()
            # No need to parse links because we are using CrawlSpider

            yield {'Company': company,'Booth Number': booth_num}

Make sure you don't use parse as a callback though, since scrapy.spiders.CrawlSpider uses the parse method to implement its logic.

A: There's an indention problem of the class function parse_page in your code and you name it "parse" rather than "parse_page" by mistake. That may be the reason of why your code doesn't work properly. The code modified is shown below and that works pretty well for me:
import scrapy
from scrapy import Request

class ConventionSpider(scrapy.Spider):
    name = 'Convention'
    allowed_domains = ['events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']
    start_urls = ['https://events.jspargo.com/ASCB18/Public/Exhibitors.aspx?sortMenu=102003']

    def parse(self, response):
        name = response.xpath('//*[@class="companyName"]')
        number = response.xpath('//*[@class="boothLabel"]')
        link = response.xpath('//*[@class="companyName"]')
        for row, row1, row2 in zip(name, number, link):
            company = row.xpath('.//*[@class="exhibitorName"]/text()').extract_first(),
            booth_num = row1.xpath('.//*[@class="boothLabel aa-mapIt"]/text()').extract_first()

            next_page_url = row2.xpath('.//a/@href').extract_first()
            next_page_url = response.urljoin(next_page_url)
            yield Request(next_page_url, callback=self.parse_page, meta={'Company': company, 'Booth Number': booth_num}, dont_filter=True)

    def parse_page(self, response):
        company = response.meta.get('Company')
        booth_num = response.meta.get('Booth Number')
        website = response.xpath('//a[@class="aa-BoothContactUrl"]/text()').extract_first()
        yield {'Company': company, 'Booth Number': booth_num, 'Website': website}


text:
Q: How do you use NPM to get fontawesome pro css files I hope someone can help me here.
We recently purchased a font awesome pro license and would like to use it on many sub-domains, but can't add each one under the services tab on the font awesome site to allow the CDN access. So we decided to have the files in our project using NPM. But so far it seems like it only downloads the JS version of font awesome, which makes sense if the project was built as a javascript application, but it's not. We currently use css version, and were wondering if NPM has a font awesome pro css version we can reference.

A: $ npm i --save @fortawesome/fontawesome-pro-solid
$ npm i --save @fortawesome/fontawesome-pro-regular
$ npm i --save @fortawesome/fontawesome-pro-brands

Have you tried above...
you need to add npm config set "@fortawesome:registry" https://npm.fontawesome.com/TOKEN

A: After some research I found the answer on their site. This command downloads the pro css files.
$ npm install --save @fortawesome/fontawesome-pro-webfonts


text:
Q: What is the ultimate date at which the Platform App Builder Transition exam can be taken? DEV 401 is a dead end. Who knows how much time we have left for this transition to App Builder exam? It's not in the study guide.

A: I received an email from Salesforce, stating, among other things: "transition exams are available until March 30, 2018"

A: I'm pretty sure it's the end of 2016


text:
Q: how to read a csv and write it back exactly the same with pandas overcoming float imprecision I would like to read in a csv and write it back exactly the same as it was using pandas or similar
example csv
019-12-12 23:45:00,95480,12.41,-10.19,11.31851,2.1882

and when I go to write it back, due to floating point properties i might get something like
019-12-12 23:45:00,95480,12.410000009,-10.19,11.31851.000000002,2.1822

I've seen suggestions to use float_format but the format is different for each column and different across files I'm looping through.

A: I'm not sure what you're doing, but if you need pandas and want to re-save the file, you likely will want to change data somewhere. If so, I'd recommend using
df.set_option('precision', num_decimals)

as long as your decimals are reasonably close in precision, in the example given, 4 would allow for enough precision and remove any straggling floating point inaccuracy. Otherwise, you'll have to look for several zeros in a row and delete all decimal places after that.
If you don't need to change any data, I would go with an alternative solution: shutil
import shutil
shutil.copyfile(path_to_file, path_to_target_file)

This way, there's no mutation that can occur as it's just copying the raw contents.


text:
Q: Google analytics page per session is more than 1 for SPA I have built a SPA using Create React App. I have integrated google analytics and using google tag manager(tag) for sending events.
 window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'UA-xxxxxxxxxx');

While analyzing the events I have noticed that my application is only firing landing pageview event(Only on first-page user visit).
What I am not able to figure out is even though the application has fired pageview event only once how page/session > 1. Can someone please help me understand this mystery and how does Goggle analytics calculate page per session?

A: Pages Per Session

*

*Quick Description = Average number of pages viewed per session

*Calculation: PageViews / Sessions

*Referred to as = Pages Per Session

This shows you how many pages the average person views on your website per session… What we mean by sessions is essentially all of the actions performed during a person visiting your site.
A person may visit your site three times, the person is defined as a user and each visit (in its entirety) is called a session.
Sessions ::
A session is a collection of activities that all took place on your website within a time frame for a single user.
Pageviews ::
PageViews represent the number of times pages on your site have been visited/viewed.
If a user comes to your site and views 3 pages before leaving, this will increase total PageViews by 3.
Calculating Pages Per Session
This is a good engagement metric for businesses that want low bounce rates and high levels of engagement. A number, typically measured to a single decimal place, represents this metric.
For example, a website that has had 1,000 sessions and 3,500 PageViews, we would get the following:

3,500 / 1,000 = 3.5 Pages Per Session (PageViews Per Session)

Pages/Session Behavior for Single Page Application(SPA)
As per GA, Repeated views of a single page are counted which might be happening in your application.
You can find the data for pages per session by navigating to "Audience" > "Overview."
Pageviews aren't necessarily unique, as the same user can view the same page 5 times and log 5 pageviews. However, it's still a good indicator of the overall engagement. Just be sure to place any analysis within the context of how the metric is defined.

A: The answer to this can be found here: https://support.google.com/analytics/answer/2731565?hl=en.
For example, if a time based expiration is considered for a session, if someone opens a page, and let's say, reloads it for some reason, his session will now comprise of 2 page views, not 1.
The existence of such instances could be the reason why your SPA has 1.28 pages / session.


text:
Q: How To fetch records from MS ACESS databse table in asp .net using AJAX i want to fetch data from MS ACCESS database without reloading the asp .net web page..guys i don't know how to use AJAX in ASP .NET so please help me...thanks in advance...give me some idea

A: Thre are many solutions on this answer. Two of them you can think about is using

*

*UpdatePanel (i think this is the easing way, but not always the best choice)

*jQuery/AngularJS and a WCF or WebAPI2


text:
Q: Cremona 2.14.1 Why is $c_4$ and $c_6$ complex when they should be rational? In Cremona's online book Chapter 2, in order to calculate the lattice invariant we have:
$\tau=\omega_1/\omega_2$
Set $q=e^{2\pi i\tau}$
(2.14.1) $c_4 =(2\pi/\omega_2)^4(1+240 \sum_{n=1}^{\infty} n^3 q^n/(1-q^n))$
and $c_6 =(2\pi/\omega_2)^6(1-504 \sum_{n=1}^{\infty} n^5 q^n/(1-q^n))$
This is supposed to give us integer values for $c_4$ and $c_6$ that we can then use to calculate the discriminant of a modular elliptic curve. But whenever I calculate a few terms of the series with $\tau$ meeting the constraints laid out by Cremona in Chapter 2, it always gives me a complex exponent to $e$. The $i$ never goes away. The $q$ never gives up! How do we end up with the promised integer or rational values for $c_4$ and $c_6$?
Here is an example of what I am seeing:
Let $\omega_1=-3-.8i$
Let $\omega_2=-1+1.6i$
Then, $\tau=\omega_1/\omega_2$ and Cremona's conditions,
$\lvert\tau \rvert=1.64556>1$
$\lvert \Re(\tau) \rvert=.483146<.5$
$\Im(\tau)=1.57303>\sqrt3/2$
are satisfied by our choices.  Now instead of an infinite series let's limit it to $5$ terms only.  We can calculate $c_4$ only and see the issue.
Set $q=e^{2\pi i\tau}=e^{3.0357i}.000051$. At least that is what the calculator gave for $q$.
$c_4 =(2\pi/\omega_2)^4(1+240 \sum_{n=1}^{5} n^3 q^n/(1-q^n))=e^{-2.23309i}121.48$
If I take 10 terms I get the same result for $c_4$.  As you can see, it has an imaginary exponent that I can't get rid of no matter how many terms I use, and that prevents the expected result that Cremona states that $c_4$ will be approach a rational or an integer.
A more general way to ask the question is this:
Since the nome $q$ is complex, then taking one term or a hundred terms in the Lambert series always sums to a complex value, so how can it converge to a rational value? Is the problem the particular $q$ in the example? If so, then how can a $\tau$ that satisfies Cremona's conditions not work?


text:
Q: Scala Lift - Cloudbees 500 error, mongo record I have a perfectly fine, running version of my app both locally, and within a dedicated server environment.
I am now in the process of hosting the service through the cloud alone, but have run into an odd error that I would very much appreciate some help with.
The error in question results from a new record being created for this model:
    class Panel_Model private() extends MongoRecord[Panel_Model] with ObjectIdPk[Panel_Model] {

    def meta = Panel_Model

    object dbid extends LongField(this)
    object handle extends StringField(this, 50)
    object room extends StringField(this, 50)
    object user extends StringField(this, 50)
    object name extends StringField(this, 50)
    object element extends StringField(this, 50)

    object slide extends MongoJsonObjectListField(this, Panel_Model_Slide)

    object state extends JsonObjectField(this, Panel_Model_State) {
        def defaultValue = null.asInstanceOf[Panel_Model_State]
    }

    object time extends JsonObjectField(this, Panel_Model_Time) {
        def defaultValue = null.asInstanceOf[Panel_Model_Time]
    }

}

object Panel_Model extends Panel_Model with MongoMetaRecord[Panel_Model] {
    override def collectionName = "panels"
}

case class Panel_Model_Slide (

    handle: String,
    media: String,
    param: Map[String, String],
    content: String,
    view: String,
    index: Int,
    active: Int

) extends JsonObject[Panel_Model_Slide] {
     def meta = Panel_Model_Slide
}

object Panel_Model_Slide extends JsonObjectMeta[Panel_Model_Slide]

case class Panel_Model_State (

    ready: Int,
    active: Int,
    locked: Int,
    slide: Map[String, Int]

) extends JsonObject[Panel_Model_State] {
    def meta = Panel_Model_State
}

object Panel_Model_State extends JsonObjectMeta[Panel_Model_State]

case class Panel_Model_Time (

    created: Long

) extends JsonObject[Panel_Model_Time] {
    def meta = Panel_Model_Time
}

object Panel_Model_Time extends JsonObjectMeta[Panel_Model_Time]

And the actual call that produces the error, only within the cloudbees environment is this:
Panel_Model.createRecord.
dbid(dbid).
room(Room_Session.is).
user(User_Session.is).
name(fph.fileName).
handle(handle).
element(element).
state(Panel_Model_State(

    0, active, 0, Map(

    ("active" -> 1),
    ("total" -> 1)

)

)).
time(Panel_Model_Time(unix)).
save

Any help is very much appreciated, thanks in advance

A: you should take a look at the error in the log (bees app:tail, or the web console) to see what the actual error happening is.
bees app:tail -a yourAppId - and looking at the result when it is in the error state - that would help a lot.


text:
Q: unable to load CSV file in Postgresql I am new to PostgresSQL and i am trying to load a data of the following format:

1,57000000000A,A,EN,0:01,male,hahaha,"Address is address",1234567,Not Applicable,,
walk in and
scream,papa,00:20:54,02:17:41,ABC,00:20:54,02:17:41,musical,farm,,cody,9,bad
boy,,,,,X,,rest,,,musical is muscal,John Kotters ,,,2011-01-01

There are more than 10k records and some columns may have NULL data. When i try to do this:
COPY ane FROM 'C:/Program Files (x86)/PostgreSQL/8.4/csv-data/my-data.csv' WITH
DELIMITER ',';

I am getting the following error:ERROR: extra data after last expected column
SQL state: 22P04
I have checked the columns and they are ok. This means that no columns are left out.
Hope someone can help. Advance thanks.

A: It is supposed to be
 COPY ane FROM 'C:/Program Files (x86)/PostgreSQL/8.4/csv-data/my-data.csv' WITH
 DELIMITER ',' CSV;

It worked for me


text:
Q: Catch print output I'm using opencv and there is a call for video frame reading with VideoCapture and there is print statement automatically printing errors and information on console , and I want to catch these outputs and save to a file ..
VideoCapture is not returning this statements it's just directly printing
How do I do that ?

A: I dont know if its the best way to do this but it will work.
You can read in everything your program prints into the console by typing this:
Here we print print("test-test-test-test") into the console, like opencv does it, and with p.stdout.readline() you can read it in again.
import os
import sys
from subprocess import Popen, PIPE, STDOUT

script_path = os.path.join('name_of_your_program.py')

p = Popen([sys.executable, '-u', script_path],
          stdout=PIPE, stderr=STDOUT, bufsize=1)

while True:
    print("test-test-test-test")

    string = p.stdout.readline()
    print(string[0:3])

Output:
test-test-test-test
b'tes'
test-test-test-test
b"b'T"
test-test-test-test
b'tes'

(It reads in binary so you have to convert it to a string.)


text:
Q: binary insertion sort I've got a question that says use the binary insertion sort in which a binary search algorithm is used to determine the index to sort a list:
So, without thinking I tried implemented this for hours:
from binsert import binsert

def binary_insertion(List,L,R):
    """uses binary searching algorithm
    to determine the position for insertion"""

    for i in range(1,len(List)):
        position = binsert(List, i, L, R)
        for k in range(0, i-position):
            #note: the position must be atleast one
            #less than j otherwise this code won't
            #run, and it gives accuracy to statement:
            List[position-k] = List[position-k-1]
            #as the list bound is never exceeded

if __name__ == '__main__':

    List = [8, 9, 16, 17, 31, 34, 35, 39, 41, 45]
    Lcopy1 = List[:]
    Lcopy2 = List[:]

    binary_insertion(Lcopy1, 0, len(List)-1)
    print("The binary is: ", Lcopy1)

Where the binsert contains:
#!/usr/bin/python3

def binsert(List, search, L, R):
    """binary insertion determining algorithm"""
    List.sort()

    if L > R:
        #some code here

        ''' elif L == len(List):
            return L
        else R < 0:
            return L
        else:
            return L '''

        return L

    mid = (L+R)//2

    if List[mid] == search:
        return mid
    elif search < List[mid]:
        return binsert(List, search, L, mid-1)
    elif search > List[mid]:
        return binsert(List, search, mid+1, R)

if __name__ == '__main__':

    import random

    List =  [0, 9, 18, 25, 29, 34, 39, 40, 43, 49]
    print("The length of the list is: ", len(List))
    print("The list is: \n",List)
    Listnumber = binsert(List, 26, 0, len(List)-1)
    print("The item is to be inserted in: {}".format(Listnumber))

Now after I was done with these, I realized that This is a sorting algorithm but the binary search required input to be sorted, and I was trying to implement mutually exclusive things.
Either I've done a mistake in understanding and there's another explanation to what the question was saying, Or I just wasted my time.
So, I wanted to know what was the case.

A: You're basically doing two errors.
First of all the array you do binary insertion to must be sorted before insertion, but you're working on the entire input array when you're doing the binary insertion.
The second error which might show if you correct the first is that if you're working in-place you must take care not to destroy data. When inserting into the sorted portion of the array that portion will grow by one element and extend to the elemnt that is to be inserted.

A: Thanks to the sentences of skyking, I was able to solve this:
import random

def binsert(List, search, L, R):
    """binary insertion determining algorithm"""
    if L > R:
        #some code here
        return L

    mid = (L+R)//2

    if List[mid] == search:
        return mid
    elif search < List[mid]:
        return binsert(List, search, L, mid-1)
    elif search > List[mid]:
        return binsert(List, search, mid+1, R)

# binsert defn-> binsert(List, search, L, R)

def binsertion_sort(List):
    for i in range(1, len(List)):
        L = 0 #left index
        R = i-1
        position = binsert(List, List[i], L, R)

        curvalue = List[i]
        for k in range(i-position):
            List[i-k] = List[i-k-1]

        List[position] = curvalue

if __name__ == '__main__':
    import random
    List = random.sample(list(range(1, 1000)), 10)
    Lcopy1 = List[:]
    Lcopy2 = List[:]

    print("The copy is: ",Lcopy1)
    binsertion_sort(Lcopy1)
    print("The list is: ", Lcopy1)
    print("The rslt is: ", Lcopy1 == sorted(Lcopy2))