text:
Q: I can use simplexml_load_file on an URL but if I save it, it won't load If I load a file using simplexml_load_file($URL), the file loads without a problem.
However, when I try to load it from local, using:
simplexml_load_file(Storage::get('public/XML/myfile.xml'))

I get the error:

simplexml_load_file(): I/O warning : failed to load external entity

The file exists, as the Storage::exists() method returns true and if I write in the Artisan tinker console, Storage::get('public/XML/myfile.xml'), the file will be returned.
I am saving my file using:
Storage::put('public/XML/myfile.xml', file_get_contents($URL));

A: simplexml_load_file() interprets an XML file (either a file on your disk or a URL) into an object.
But in your case you want interpret the content of the file => string of XML into an object for that you can use simplexml_load_string
simplexml_load_string(Storage::get('public/XML/myfile.xml'));


text:
Q: Magento 1.9.3 Command Line Not Available I have a quick question regarding the command line tool seen in Magento 2. I've been using it and it's amazing cool.
However now I'm working on an older version of Magento 1.9.3 and I see there isn't a command line tool. Am I wrong, or is there one? I can't seem to figure it out. I do see however a folder called /shell in my default directory that allows some basic reindexing commands. Is the command line tool a new feature for Magento 2 only?

A: You seem to be talking about the php bin/magento CLI tool.
This is something that is wonderful and indeed there is one for M1 - however its not built in and you need to add it to your server. Its called Mage Tools (what we call it around the office)
install link::
https://github.com/netz98/n98-magerun
Is that the answer you were looking for?

redpajama_set_name: RedPajamaStackExchange


text:
Q: SharePoint 2010 Playground Site I'm a seasoned developer and CMS consumer, but I've never used SharePoint specifically. Is there a website where I can quickly create and manage a SharePoint site, without installing the entire stack myself?
For example, if I wanted to learn Wordpress, I would create an account at wordpress.com. This would allow me to create sites, manage sites, create and publish content, change the look and feel, etc. with no installation or infrastructure required from my end. I'm looking for something roughly equivalent in SharePoint, even if it's limited in the scope of what I can do with it.
Edit: Trials are great. But ideally, I want something unlimited/free.

A: You could use http://www.cloudshare.com/ where you could spin up an entire environment and have complete access to the back end.  It looks like there is a trial period so you could check it out without paying.
I have not used this environment so I can not give you personal experience, but if you want developer level access for learning this seems like a great way to go.

A: I use the IW VM, Office 365, hosted sites from Rackspace and FPWeb.net, but by far the quickest way to get an environment you can play with is to use one of these pre-built, hosted in the cloud VM's from Cloudshare:
http://www.cloudshare.com/Products/CloudShare-ProPlus/solution-showcase.aspx
The permalinks in the Solution Showcase are different from the 14 day trial. Each link on that page provisions a complete SharePoint Environment for free with registration. The limitation is that the enviornment loses its state after 48 hours, but you can provision a new one the next time you want to expiriment. The first link on the page is a copy of the IW VM from Microsoft, but it's already warmed up and waiting with Visual Studio installed and configured. I use it to expiriment with all the time even though I have a paid account with them and SharePoint VM's spun up on my desktop.

A: I'd agree with Christophe on this. I think you really need to sit down and work out exactly what it is you want to do.
Wordpress and SharePoint have different business models and you will be extremely hard pushed to find anywhere providing the full features for free; these hosts have to recoup their licensing costs and are businesses trying to make a profit.
The best approach I can suggest if you want to dip your toe in at low cost is to install SharePoint Foundation. You can do this on a 64-bit Windows 7 machine for DEV purposes or properly on a Server OS. The install process is not that onerous and you will get a better understanding of the architecture of the product. You will also have something that is available to you whether you are connected to the internet or not.
Beyond that, you will have to take up one of the hosted solutions such as Cloudshare or invest in the infrastructure yourself to have your own instance.
If you are really serious about progressing with SharePoint, you will have to incur some costs somewhere whether it be a hosted service or getting an MSDN subscription. As above, you need to work out what it is you want to do.

A: You can use SharePoint Online and Office 365 trial to access SharePoint's limited feature and see how it turns up for you. With SharePoint Online you can create sites to:

*

*manage and share important documents (My Sites)

*keep teams in sync and manage important projects (Team Sites)

*stay up to date with company information and news (Intranet Sites)

*share documents securely with partners and customers (Extranet Sites)

*market your business using a simple public-facing website

A: If you don't mind downloading a VHD then Microsoft provides a 2010 Information Worker Demonstration and Evaluation Virtual Machine. The nice thing about it is that it's already preloaded with sample content and user accounts.

A: As far as I know, you won't find for SharePoint the equivalent of Wordpress.com. By the way, note that Wordpress.com allows you to use Wordpress, not really to learn it. It comes with strict limitations, and only the basic features are free.
If you are ok with Foundation and only want to play with the user side (SharePoint UI and SharePoint Designer), you can find a hosting provider for less than $10/month. MSS would be more expensive.
If you are looking at this from the developer side, your best bet is certainly to install it yourself on your local machine.

A: You can also try Office 365 Preview which includes Sharepoint (2013) Online.
From the FAQ:
..the Preview will expire approximately 60 days after the next version of Office becomes available in your market. As the date approaches, you will receive notifications in the Office applications alerting you to the pending expiration.
When the Preview ends, all data in the Preview account will be deleted, including email and calendar data, web sites, and uploaded documents

A: Yes, I agree with Christophe, if you want only SharePoint Designer and SharePoint UI, please just find SharePoint Foundation 2010 hosting. Hmmm, this is the provider I know that support SharePoint 2010 hosting with affordable rate, please visit asphostportal.com. Fpweb is good, but you need to spend more money. Good luck


text:
Q: What is the hotkey for the spell next to the right click spell? How do I activate it?
Here's a picture of what I'm talking about.
http://i.snag.gy/ODKx1.jpg

A: That spell overrides your current right-click spell by using TAB (default bindings).
You unfortunately will need to TAB between those two spells to use them.
If that proves too slow for you, you'll have to bind it to another key. Notice you already have it bound to 5.
The answer to this question covers the keybinding issue.

A: You can also click to the spell menu (not the spell tree) and aim with your mouse to the spell that you want to key-assign, then press one of the function buttons (by those I mean any of them: F1, F2, F3, F4, F5, and so on...).
So when you want to use (e.g.) you assign a fireball spell, which was assigned to F1, you press that and there you have it.


text:
Q: How to define smooth random initial conditions consistent with boundary conditions for this 1+2D PDE? I wrote a fully working code to numerically solve a non-linear variation of the classic 1+2D waves equation.  Here's a stripped down version of it (classic waves equation), with static initial conditions (initial velocities are all 0):
Clear["Global`*"]

size = 30;
tmax = 20;

equDiff = D[phi[t,x,y],t,t] - D[phi[t,x,y],x,x] - D[phi[t,x,y],y,y]) == 0;

bones = Table[{x,y,RandomReal[{-1,1}]}, {x,-size,size,2}, {y,-size,size,2}];
flesh = Interpolation[Flatten[bones, 1], Method -> "Spline"];

Phi0[t_, x_, y_] := flesh[x,y] (* Random function of X and Y only. *)

boundariesCond = {
   phi[t,-size,y] == Phi0[t,-size,y],
   phi[t,size,y] == Phi0[t,size,y],
   phi[t,x,-size] == Phi0[t,x,-size],
   phi[t,x,size] == Phi0[t,x,size]
   };

initialCond = {phi[0,x,y] == Phi0[0,x,y], (D[phi[t,x,y],t]/.t -> 0) == D[Phi0[t,x,y],t]/.t -> 0};

fieldSolution = NDSolve[
   Flatten@{equDiff, initialCond, boundariesCond}, phi,
   {t,0,tmax}, {x,-size,size}, {y,-size,size},
   Method -> {"MethodOfLines","SpatialDiscretization" -> {"TensorProductGrid","MaxPoints" -> 50,"MinPoints" -> 50,"DifferenceOrder" -> 2}}
   ];

Manipulate[
 Plot3D[
  Evaluate[phi[t,x,y]/.fieldSolution/.t -> time],
  {x,-10,10}, {y,-10,10},
  PlotPoints -> ControlActive[20, 60],
  PlotRange -> {{-10,10}, {-10,10}, {-3,3}},
  Axes -> True,
  Mesh -> True,
  MeshFunctions -> {(#3&)},
  MeshStyle -> GrayLevel[0.25],
  ColorFunction -> "Rainbow",
  ImageSize -> 500,
  Method -> {"RotationControl" -> "Globe"},
  SphericalRegion -> True
  ],
 {time, 0, tmax, 0.1,ImageSize -> Large,Appearance -> {"Labeled", "Closed"},AppearanceElements -> {"InputField", "Slider"}},
 ControlPlacement -> Bottom
 ]

This code is working pretty well on my system.
My problem is to define smooth (and derivable) random initial conditions for both the initial field and its initial time derivative (or "velocities"), that would be consistent with the boundary conditions.  Currently, the code above is using only static initial conditions, so all initial velocities are 0.  This isn't very "natural" to me.  So how would you define smooth and derivable random initial conditions for this system, that would be compatible with this kind of boundary conditions?
All the code should remain the same (unless you notice some mistakes or problems), except the bones and flesh functions that would need to change, so Phi0[t_, x_, y_] := flesh[x,y] would be replaced by Phi0[t_, x_, y_] := someNewRandomFunction[t,x,y].


text:
Q: WordPress, Laravel, and NGINX I"m trying to get the configuration for NGINX to work with WordPress being the default such as domain.com and the Laravel app being domain.com/app.
I'm not opposed to it being a sub-domain, but I wanted to try this first.  I'm not sure which is easier / better.
The directories are:
WP - /var/www/wordpress
L5 - /var/www/laravel
server {
        client_max_body_size 10M;
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/wordpress;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.nginx-debian.html;

        server_name somename;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                log_not_found off;
                access_log off;
                allow all;
        }

        location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
                expires max;
                log_not_found off;
        }

        location / {
                try_files $uri $uri/ /index.php$is_args$args;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

        location /app/ {
                alias /var/www/laravel/public;

                try_files $uri $uri/ /app//app/index.php?$query_string;

                location ~ /app/.+\.php$ {
                        include snippets/fastcgi-php.conf;
                        fastcgi_pass unix:/run/php/php7.0-fpm.sock;

                }

        }

        location ~ /\.ht {
                deny all;
        }

}

A: I cannot confirm that this will work as I do not know Laravel. Two PHP apps without a common root will need two PHP locations (which you have). However, the location /app/ statement needs to use the ^~ modifier to stop the wrong PHP location from being selected. See this document for details.
location ^~ /app/ {
    alias /var/www/laravel/public/;

    if (!-e $request_filename) { rewrite ^ /app/index.php last; }

    location ~ \.php$ {
        if (!-f $request_filename) { return 404; }

        include snippets/fastcgi-php.conf;

        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

I see your question includes a fix for the alias/try_files bug - but I prefer the the if block solution above.


text:
Q: What is the difference between "is subject to" and "is subjected to"? I found the following sentence on the U.S. Customs and Border Protection website:

All persons, baggage, and other merchandise arriving in or leaving the
  United States are subject to inspection and search by CBP officers.

I would like to know whether changing "subject" to "subjected" will change the meaning of the sentence.

A: When you are subject to inspection, you may undergo inspection.
When you are subjected to inspection, you do undergo inspection.


text:
Q: Index method not accepting parameters in ASP.NET Core MVC with Entity Framework I am working on a webpage where I have to filter results using value from the select menu's selected option when the user clicks on filter button by sending a get parameter to the index method.

A:
refId is never passed into the Index method

In your code, we can find that you specify asp-for="@Model.FirstOrDefault().RefereeId" for your <select> tag, if you check the source code of this dropdown in browser, you would find name attribute value is RefereeId (not refId) as below. So it would pass something like RefereeId=168 through querystring to your action, and parameter refId of your action would always be 0, which cause the issue.

To fix it, you can try to rename your action parameter to RefereeId, like below.
public async Task<IActionResult> Index(int RefereeId)
{
    //code logic here

Or modify view page code to set name of <select> tag with "refId".
<select name="refId" asp-items="@ViewBag.PersonId"></select>

A: If you don't have a custom route defined, the default routing in asp.net core uses id.
Replace the refId parameter to id.
public async Task<IActionResult> Index(int id)
{
    // ...

    if (id != 0) //always remains 0
    {
        games = games.Where(g => g.RefereeId == id);
    }

    // ...
}


text:
Q: IB CP WebAPI Gateway certificate change I am trying to replace the default certificate for Interactive Brokers Client Portal WebAPI Gateway application. I am trying to install and configure the software on Windows 10 (20H2, build: 19042.685)
Here are the steps I followed:

*

*Installed Java 8 Update 271

*Downloaded the latest Gateway software, from here.

*Unzipped the file to $HOME\Documents\clientportal.gw

*Created the jks file using the following command:

keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore2.jks -storepass password -validity 360 -keysize 2048

*Provided the details: CN=localhost, OU=home, O=home, L=riga, ST=riga, C=lv

*Then exported the cer file using the following command:

keytool -export -alias selfsigned -file mydomain2.cer -keystore keystore.jks

*Imported the cer file into following Local Machine certificate stores:
7.1 Trusted Root Certification store
7.2 Trusted Publishers store
7.3 Personal store

*Ran the command as per the vendor: bin\run.bat root\conf.yaml
Unfortunately I still get the certificate error:
Your connection is not private
Attackers might be trying to steal your information from localhost (for example, passwords, messages, or credit cards). Learn more
NET::ERR_CERT_AUTHORITY_INVALID
Any suggestions?
Thanks!


text:
Q: Can't View what inside directory but can view file inside of that directory I have directory and file in it
$HOME/tmp/file.txt

I want to make it so that I can't visualize contents inside of tmp but I can visualize contexts inside file.txt
So I make this part
cd $HOME
cd tmp
bash: cd: tmp: Permission denied
ls tmp
ls: cannot open directory 'tmp': Permission denied

Now I can't view what's inside of tmp directory (as I wanted)
But I want to access what inside of file.txt, so when I type
 cat $HOME/tmp/file.txt
it must show me what's inside of file.txt and not something like this:
cat: /home/user/tmp/file.txt: Permission denied

A: You need to understand how directory permissions work.
read(r): Allows listing the names of entries in the directory but not entry metadata or contents.
write(w): Allows adding, removing, or moving entries
execute(x): Allows accessing and modifying the entry contents and metadata. In short the permission to search the directory.
So, an execute(x) only directory permission would be sufficient for your use case and let you achieve what you want. As for cd you need r+x or for ls you need the r permission.


text:
Q: whats a good ios charting library/framework Has anyone got any recommendations for a charting library/framework for ios. I need to be able to create bar, pie, line trend, scatter charts from an internal database/warehouse onto an iPad. I've read some mixed reports about core-plot.

A: We've used this in the past
http://code.google.com/p/core-plot/
and found it to be the most reliable!

A: iOS chart libraries
1.Core Plot : https://github.com/core-plot/core-plot
Core Plot is a plotting framework for OS X and iOS. It provides 2D visualisation of data, and is tightly integrated with Apple technologies like Core Animation, Core Data, and Cocoa Bindings.
Advantage:
Core Plot is a free, open source charting library available under the New BSD License.
Example Graphs :
https://github.com/core-plot/core-plot/wiki/Example-Graphs#wiki-dropplot-example-app
2.Shinobi Charts : http://www.shinobicontrols.com/ios/shinobicharts
Shinobi Controls released their new charting library, Shinobi Charts. This is a paid library but with a free 30 day trial available. It features several chart types, from Pie and Donut to Bar and Column and Area charts.Shinobi comes packaged with a comprehensive set of apple style documentation.
Advantage:
In terms of the smoothness of the interaction with the charts, Shinobi has a clear advantage. Pan and zoom have momentum and smoothly move to the new range requested. The performance of the Shinobi interaction is also markedly better than Core Plot, especially when there are a lot of labels visible on the chart.
Shinobi is very lightweight and perfect.
Price plans :
http://www.shinobicontrols.com/ios/shinobicharts/price-plans
3.KeepEdge  : http://www.keepedge.com/products/iphone_charting/
The KeepEdge iPhone Charting Library for iPhone Objective-C is a paid library with a free trial available. It features a wide range of chart types, ranging from a standard line chart to Stock High Low charts and 3D Clustered Bar charts. KeepEdge does include a TimeSeries chart, with a date/time axis.
Price plans :
http://www.keepedge.com/purchase/#pIphoneChart
4.JBChartView : https://github.com/Jawbone/JBChartView
Jawbone's iOS-based charting library for both line and bar graphs. It is easy to set-up, and highly customizable.
Features :

*

*Drop-in UIView subclass supported across all devices.

*Lie and bar graph support.

*Simple to use protocols modeled after a UITableView.

*Highly customizable.

*Expand & collapse animation support.

Disadvantage :

*

*Requires iOS 7 or later.

*Requires Automatic Reference Counting (ARC)
After a bit of googling , i have found that Core-plot is one of most flexible libraries and free of cost . But if we can afford paid one ShinobiControls is worth of buying , it provides  iOS software and Android components to ease the development of native, cross platform mobile apps.
Update
5. SwiftCharts : https://github.com/i-schuetz/SwiftCharts
This is a new charts library for iOS, written in Swift. It's free, open source, said to be easy to use and highly customizable. Video.
6. SciChart : https://www.scichart.com/ios-charts
This is a new chart library for iOS, written in Objective-C and supporting Swift as well. It's paid, but very powerful for streaming charts and realtime updates. Video.

A: Coreplot is good for an open source option, but struggles with large data sets.
We've developed a suite of speedy iOS controls. We're launching charts soon, there's free trials, if you're interested?
http://www.shinobicontrols.com/

A: Just released a new CocoaPod called CHRadarGraph.  It's a circular bar graph that allows dense amount of data to be viewed in a smaller space.
Take a look!


text:
Q: MUI V5, how to minify class names in production build How is possible to there is no option to minify the prod class names? It is a a big step back. Please say me that I am not right.
In Material v4 can be achieved with 3 simple rules:

*

*Only one theme provider is used (No theme nesting)

*The style sheet has a name that starts with Mui (all Material-UI components).

*The disableGlobal option of the class name generator is false (the default).

In v5.5 in my experiment I don`t use any custom styles, just default provided from MUI components.
"react": "^18.0.0",
"react-dom": "^18.0.0",
"@emotion/react": "^11.8.1",
"@mui/material": "^5.5.2"

import { ThemeProvider, createTheme } from '@mui/material/styles'

<ThemeProvider theme={theme}>
    <CssBaseline />
    <Component {...this.props} />
</ThemeProvider>

import { Paper, Grid, Typography, Box } from '@mui/material'

<Grid container component={'main'}>
    <Grid item xs={false} sm={4} md={8} />
    <Grid item xs={12} sm={8} md={4} component={Paper} elevation={6} square>
        <Typography component={'h1'} variant={'h4'} align={'center'}>
            <Box fontWeight={'fontWeightLight'} m={1}>
                {'MY ACCOUNT'}
            </Box>
        </Typography>
    </Grid>
</Grid>

In production build I expect to be something like this:
jss1 jss2 jss3 jss4 jss5 jss6 and etc...

but the result is:
MuiGrid-root MuiGrid-container css-1d3bbye

MuiGrid-root MuiGrid-item MuiGrid-grid-sm-4 MuiGrid-grid-md-8 css-18mwvdj

A: I think i found it
https://v5-0-6.mui.com/guides/classname-generator/
Converts from
<button
  class="MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root css-1ujsas3"
>
  Button
</button>

to
<button
  class="foo-bar-MuiButton-root foo-bar-MuiButton-text foo-bar-MuiButton-textPrimary foo-bar-MuiButton-sizeMedium foo-bar-MuiButton-textSizeMedium foo-bar-MuiButtonBase-root css-1ujsas3"
>
  Button
</button>

I have just tried it with latest MUIv5 and works great.


text:
Q: Redshift Join on multiple conditions but return only where one condition doesn't match I have two tables, the first has ID's and Numbers. The ID's and numbers can potentially be listed more than once.
My second table has rows (100 million) with the ID and Numbers again (as well as other data.) I need to search that table for any ID that has a Number not in the list of Numbers from the result table.
I am having trouble with a join that returns any records from table 2 that match the first qualifier, but not the second.
DROP TABLE IF EXISTS `myTable`;

CREATE TABLE `myTable` (
  `id` mediumint(8) unsigned NOT NULL auto_increment,
  `ID` varchar(255),
  `Numbers` mediumint default NULL,
  PRIMARY KEY (`id`)
) AUTO_INCREMENT=1;

INSERT INTO `myTable` (`ID`,`Numbers`)
VALUES
  ("CRQ44MPX1SZ",1890),
  ("UHO21QQY3TW",4370),
  ("JTQ62CBP6ER",1825),
  ("RFD95MLC2MI",5014),
  ("URZ04HGG2YQ",2859),
 ("CRQ44MPX1SZ",1891),
  ("UHO21QQY3TW",4371),
  ("JTQ62CBP6ER",1826),
  ("RFD95MLC2MI",5015),
  ("URZ04HGG2YQ",2860),
 ("CRQ44MPX1SZ",1892),
  ("UHO21QQY3TW",4372),
  ("JTQ62CBP6ER",1827),
  ("RFD95MLC2MI",5016),
  ("URZ04HGG2YQ",2861);

DROP TABLE IF EXISTS `myTable2`;

CREATE TABLE `myTable2` (
  `id` mediumint(8) unsigned NOT NULL auto_increment,
  `ID` varchar(255),
  `Numbers` mediumint default NULL,
  PRIMARY KEY (`id`)
) AUTO_INCREMENT=1;

INSERT INTO `myTable2` (`ID`,`Numbers`)
VALUES
  ("CRQ44MPX1SZ",1870),
  ("UHO21QQY3TW",4350),
  ("JTQ62CBP6ER",1825),
  ("RFD95MLC2MI",5014),
  ("URZ04HGG2YQ",2859),
 ("CRQ44MPX1SZ",1891),
  ("UHO21QQY3TW",4371),
  ("JTQ62CBP6ER",1826),
  ("RFD95MLC2MI",5015),
  ("URZ04HGG2YQ",2860),
 ("CRQ44MPX1SZ",1882),
  ("UHO21QQY3TW",4372),
  ("JTQ62CBP6ER",1827),
  ("RFD95MLC2MI",5016),
  ("URZ04HGG2YQ",2861);

SELECT mytable1.ID, listagg(distinct mytable2.Numbers, ',') as unauth_list, count(mytable2.Numbers) as unauth_count
FROM mytable1
LEFT JOIN mytable2 on mytable1.id = mytable2.id
WHERE (mytable1.id = mytable2.id)
AND (mytable1.Numbers <> mytable2.Numbers)
GROUP BY mytable1.id

Expected output:
("CRQ44MPX1SZ", "1870,1882", 2)
("UHO21QQY3TW", "4350", 1)

A: Steve.  You are close.  You need to reverse your tables in the FROM clause (or use RIGHT JOIN) and add a JOIN ON clause.  The WHERE clause will now be bases on seeing NULL in Numbers for table1.  With your data setup try this:
SELECT mytable2.ID, listagg(distinct mytable2.Numbers::text, ',') as unauth_list, count(mytable2.Numbers) as unauth_count
FROM mytable2
LEFT JOIN mytable1 on mytable1.id = mytable2.id
and mytable1.numbers = mytable2.numbers
Where mytable1.Numbers is null
GROUP BY mytable2.id;

See fiddle - http://sqlfiddle.com/#!15/44b5e/4
Produces results:
id  unauth_list unauth_count
CRQ44MPX1SZ 1870,1882   2
UHO21QQY3TW 4350    1

SF wants me to repeat your data set up so
CREATE TABLE myTable1 (
  ID varchar(255),
  Numbers int default NULL
) ;

INSERT INTO myTable1 (ID,Numbers)
VALUES
  ('CRQ44MPX1SZ',1890),
  ('UHO21QQY3TW',4370),
  ('JTQ62CBP6ER',1825),
  ('RFD95MLC2MI',5014),
  ('URZ04HGG2YQ',2859),
 ('CRQ44MPX1SZ',1891),
  ('UHO21QQY3TW',4371),
  ('JTQ62CBP6ER',1826),
  ('RFD95MLC2MI',5015),
  ('URZ04HGG2YQ',2860),
 ('CRQ44MPX1SZ',1892),
  ('UHO21QQY3TW',4372),
  ('JTQ62CBP6ER',1827),
  ('RFD95MLC2MI',5016),
  ('URZ04HGG2YQ',2861);

CREATE TABLE myTable2 (
  ID varchar(255),
  Numbers int default NULL
) ;

INSERT INTO myTable2 (ID,Numbers)
VALUES
  ('CRQ44MPX1SZ',1870),
  ('UHO21QQY3TW',4350),
  ('JTQ62CBP6ER',1825),
  ('RFD95MLC2MI',5014),
  ('URZ04HGG2YQ',2859),
 ('CRQ44MPX1SZ',1891),
  ('UHO21QQY3TW',4371),
  ('JTQ62CBP6ER',1826),
  ('RFD95MLC2MI',5015),
  ('URZ04HGG2YQ',2860),
 ('CRQ44MPX1SZ',1882),
  ('UHO21QQY3TW',4372),
  ('JTQ62CBP6ER',1827),
  ('RFD95MLC2MI',5016),
  ('URZ04HGG2YQ',2861);


text:
Q: How to pause and resume fadeIn() from opacity? I'm trying to resume a fadeIn() from the opacity where it paused.
I have two draggables. If the one is dropped (I called it draggable_purple), a purple div starts to fade in. Only to a specific opacity. When the opacity has been reached, another div appears (lightblue) with a message to drop the yellow-draggable. After the yellow-draggable has been dropped, I want the purple div to proceed the fadeIn.
It might sound a bit far fetched and excuse me for my code, I tried to narrow it down to the only elements that matter in this case.
In the JsFiddle you'll find my solution, but it doesn't work. My question to you is; How would you solve this and why isn't my own solution working. Thank you for your time in advance.
JsFiddle
jQuery
$("#draggable_purple").draggable({
    revert: true
});

$("#draggable_yellow").draggable({
    revert: true
});

$("#orange").droppable({
    drop: function(event, ui) {
        if (ui.draggable.is('#draggable_purple')) {
            $(this).parent().find('#purple').fadeTo(1500, 0.5, onhold);

            $(this).droppable('destroy');
        }
    }
});

function onhold() {
    $(this).parent().find('#lightblue').show();
}

$('#lightblue').droppable({
    accept: '#draggable_yellow',
    drop: function(event, ui) {
        $(this).hide('fast'); $('#purple').css('opacity', 0.5).fadeIn(1500, 1.5);
    }
});

HTML

 Drop the yellow div,
            to continue the fadeIn

 start purple fadeIn

 resume fadeIn

A: Good solid pause/resume is surprisingly tricky but - good news - there's a jQuery plugin to help you.

A: You're using .fadeIn in the yellow method instead of .fadeTo (I'm not sure why you have 1.5 either .. I think 1 will do).

A: Change this:
$('#purple').css('opacity', 0.5).fadeIn(1500, 1.5);

To this:
$('#purple').fadeTo(1500, 1);

Here's the updated fiddle

Another thing, this line:

$(this).parent().find('#purple').fadeTo(1500, 0.5, onhold);

Is pointless. You have the id, it's unique, there is no need for parent and find:
$('#purple').fadeTo(1500, 0.5, onhold);


text:
Q: How compiled language like Go performs without dynamic load compared to interpreted languages? I switched to Go from interpreted languages like javascript, php, python.
After using some CMS frameworks for web app like qor then i realized it loads all the resources at runtime like: backend and frontend even when user only access to the frontend.
All backend/admin resources will be loaded like: routing, SetupDashboard, templates ... after i ran go run main.go
All the memory will be allocated for those wasted resources?
Is it good for performance comparing to interpreted language while it loads needed resources with dynamic load (which Go don't have)?
def doSomething(name):
    name = "package." + name
    mod = __import__(name, fromlist=[''])
    mod.doSomething()

Or how compiled language like Go with its GC have it's way to handle the allocated memory while not in use?


text:
Q: JQuery POST showing as empty array in PHP script In a JS file I am performing this function:
$(function() {
    $(".button").click(function() {

        //get the button's ID (which is equal to its row's report_id)
        var emergency = this.id;
        var button = this.attributes['name'].value;
        var dataString = 'reportid=' + emergency;

        alert(dataString);
        if (button == "clockin") {
            $.ajax({
                type: "POST",
                url: "/employeetimeclock.php",
                data: dataString,
                success: function() {
                    window.location = "/employeetimeclock.php";
                }
            });
        } else if (button == "closereport") {
            var r = confirm("Are you sure you want to close this report?\nThis action CANNOT be undone!");
            if (r == true) {
                $.ajax({
                    type: "POST",
                    url: "/closeemergencyreport.php",
                    data: dataString,
                    success: function() {
                        alert("Report Successfully Closed!");
                        window.location = "/closeemergencyreport.php";
                    },
                    error: function() {
                        alert("An error has occured, the report was not closed");
                    }
                });
            } else {
                alert("Report was not closed.");
            }
        }
    });
});

For the else if (to closeemergencyreport.php) the code in that php script is as follows:
<?php

require_once("models/config.php");
require_once("models/header.php");
require_once("models/dbconnect.php");

$reportid = $_POST['reportid'];

var_dump($_POST);

$sql = "UPDATE emergency_report SET report_closed = '1' WHERE report_id IN ( $reportid )";
//execute and test if succesful
$result = mysql_query($sql) or die(mysql_error());
if($result){
} else{
}
?>

I've done this same exact thing on 3 other pages and it works flawlessly however this is giving me trouble where on that php script the VAR_DUMP is saying it's returning an empty array. I've been reading and rereading the code for about an hour and a half now so I think i'm burnt out and need to have an outside view. Ive been all over the site and no one has had a solution that worked for me.
I know it's posting because fire bug is showing this on the form's page that the javascript is run on:
http://i.imgur.com/hItdVU1.png (sorry cant post images yet)


text:
Q: How to fetch nodes and all their children in Spring Data Neo4j I have this Neo4j Node class:
@Node
@Data
@AllArgsConstructor
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    private Long parentId;

    @Relationship(type = "PARENT_OF", direction = Relationship.Direction.OUTGOING)
    private List<Person> children;

    public Person addChild(Person person) {
        person.setParentId(this.id);
        this.children.add(person);
        return this;
    }

}

I would like to build a query to use with the Spring Data @Query annotation, in order to fetch a list of genealogical trees, where the roots have null parentId. For each root I also would like to fetch their children, for each child their own children, etc.
The best I could come up with, so far, is the following:
public interface PersonRepository extends Neo4jRepository<Person, Long> {

    @Query("""
        MATCH (person:Person)
        WHERE person.parentId IS NULL
        OPTIONAL MATCH (person)-[parentOf:PARENT_OF]->(children)
        RETURN person, collect(parentOf), collect(children)
        SKIP 0
        LIMIT 10
    """)
    List<Person> findAllGenealogicalTrees();
}

but it doesn't seem to do what I'm looking for, as it seems to only fetch the children of the roots, but not the children of the children.
Is something wrong with my query?
EDIT:
Tried the suggested query:
MATCH path=(person)-[parentOf:PARENT_OF*]->(child)
WHERE person.parentId IS NULL
      AND NOT (child)-[:PARENT_OF]->()
RETURN path

but the resulting list seems to be the following:
Person(id=0, parentId=null, children=[Person(id=1, parentId=0, children=[Person(id=3, parentId=1, children=[])])])
Person(id=1, parentId=0, children=[Person(id=3, parentId=1, children=[])])
Person(id=3, parentId=1, children=[])

I was expecting the first record only, since parentId should be null. How come is it returning two other records that have a not null parentId?

A: To get all the paths, you can use a variable-length pattern
MATCH path=(person)-[parentOf:PARENT_OF*]->(child)
WHERE person.parentId IS NULL
      AND NOT (child)-[:PARENT_OF]->()
RETURN path

A: I think we can agree that the first query by its nature does only one hop because you explicitly say with (person)-[parentOf:PARENT_OF]->(children) that you only want to find the direct children.
The suggestion @Graphileon gave goes into the right direction but from its return part only provides an unordered set of nodes and relationships.
Spring Data Neo4j can only assume that all Persons have the same importance and thus returns a collection of all Persons.
What I would suggest is to stay with the path-based approach but modifying the return statement in a way that Spring Data Neo4j and you agree on ;)
MATCH path=(person)-[:PARENT_OF*]->(child:Person)
WHERE person.parentId IS NULL
RETURN person, collect(nodes(path)), collect(relationships(path))

Reference: https://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#custom-queries.for-relationships.long-paths
Another approach could also be that you are using the so-called derived finder methods in your repository:
List<Person> findAllByParentIdIsNull();

Or if you want to have it pageable (don't forget some ordering because the data could get returned randomly otherwise):
Page<Person> findAllByParentIdIsNull(Pageable pageable);

This creates the internal query generator which will do an explorative search (non-path based queries) over the data with multiple cascading queries.
There are (in general) a few things to keep in mind when making the decision:

*

*The path-based approach could really ramp up the memory usage in the database if you have a lot of hops and branches which leads to relative slow response times. I assume that won't be a problem for your domain above but this is always something I would keep an eye on.

*In both cases (path-based or cascading queries) you will end up with three buckets of data: The root node, all relationships and all related nodes. The mapping will take some time because Spring Data Neo4j would have to match every returned relationship with the right related node for each relationship it wants to map. There is nothing wrong with this but the result of having a cyclic mapped domain.


text:
Q: Identify parentheses in lambda expression with ExpressionVisitor in C# I have a library that converts a lambda expression to an odata filter string using the ExpressionVisitor class.
For example, the expression o => o.Teste == null && !(o.Date != DateTime.Now) turns into $filter=Teste eq null and not(Date ne xx/xx/xx)
It works fine. The problem is when I have to group parts of the condition with parentheses (). The parentheses are ignored and it just writes the condition without it.
For example, the expression (o => o.Name != null && o.Name == "Joe") || !(o.Date != DateTime.Now) turns into $filter=Name ne null and Name eq 'Joe' or not(Date ne xx/xx/xx)
What's weird is that the ExpessionVisitor doesn't seem to identify the parentheses, it has a NodeType for not !(expression) but it doesn't have for (expression).
I've been searching for this on Google for two days and I can't seem to find an answer.
Thanks in advance for the Help.

A: The node type for not isn't for !(expression) it's just for !expression - the parentheses aren't part of it.
Parentheses are necessary in source code to indicate the precedence you want. They're not necessary in expression trees because the precedence is inherent in the tree.
If you don't mind sometimes having extra parentheses, you could just make your string conversion always include them. So every time you have an OR or and AND expression with operand expressions x and y, just turn that into (x || y) or (x && y), unconditionally including those parentheses. It may not look pretty, but it will always give you the right precedence.


text:
Q: How can I fix this pytorch error on Windows? (ModuleNotFoundError: No module named 'torch') Edit: You might want to skip to the end of the question first, I've followed some advice in comments / answers and the current error is different from the original (appears to be related to numpy possibly).
This error ModuleNotFoundError: No module named 'torch' shows up in tons of threads, I've been trying solutions all day. I'll go through my troubleshooting steps one by one, using the solutions suggested in threads.
System info:
Windows 10

First thing I did was follow the instructions on Pytorch, installed Anaconda and did this using the correct settings for my machine (Note: I tried Python v3.7 before trying v3.8 in these screenshots, none of the solutions worked with that either):

As you can see, that should be good to go, according to the instructions.
So I go into the python terminal and try to import pytorch, like so:

ModuleNotFoundError: No module named 'torch' Great, so what now? Well I paste the error into Google and begin my 4 hour wild goose chase.
First result, stack overflow answer: No module named "Torch"
 Let's try the selected answer, it requires some version-related syntax so lets check my python version:

Alright so as directed by the answer:

Try to install PyTorch using pip:
First create a conda environment using:
conda create -n env_pytorch python=3.6

Ok:

Activate the environment using:
source activate env_pytorch

That doesnt work, but if we activate using the instructions given by the prompt, we can do so:

Now install PyTorch using pip:
pip install torchvision --user ( this will install both torch and torchvision)

Hmmm.. well that went up in flames, so the following...

Now go to python shell and import using the command:
import torch
import torchvision

...doesn't do anything new, same error as before.
Well, to the next thread, on PyTorch GitHub: https://github.com/pytorch/pytorch/issues/4827
They're trying to use Jupyter, so I tried this, is was another long process like the above that went up in flames, and I really dont want to need to use Jupyter anyway, so we'll skip this one.
Another Pytorch GitHub thread: https://github.com/pytorch/pytorch/issues/12004

@edtky Could you please give me the output of the following commands
  in CMD?
where conda.exe
  where pip.exe
  where python.exe

Sure I'll give it a shot:

@edtky Looks like you have two Python environments. Please try
  importing torch in Anaconda Prompt.

Oh well, I already did that. No bueno.
Another thread: https://discuss.pytorch.org/t/modulenotfounderror-no-module-named-torch/7309 suggests:

In that case you've probably forgotten to activate the environment
  where pytorch is installed. It can also be the library missing in your
  PYTHONPATH variable.

Well I did activate the environment as shown above, but I dont know anything about a PYTHONPTH variable, seems like the PyTorch setup guide wouldve mentioned if I needed to manually do that, I have no clue how to do it and you aren't explaining, so lets look for other answers.
Someone made a whole article to give us this little gym of advice: https://medium.com/@valeryyakovlev/anaconda-no-module-named-torch-ead10946de66

Another beginner error I encountered when started to use pytorch in
  anaconda environment
      import torch ModuleNotFoundError: No module named 'torch' the proper way to install pytorch to anaconda is following
      conda install -c pytorch pytorch It's not enough to simply run "conda install pytorch" — the package won't be found. So first
  activate your conda profile with "source activate {your_profile}" and
  then run the command conda install -c...

Ok thats new info, let's try that command again now that our env is activated:

Ok that's a lot of green, let's try now...

Well we can't win 'em all, so lets go onto the next thread: https://forums.fast.ai/t/modulenotfounderror-no-module-named-torch-windows-10/12438/2

I had also faced the similar problem , I just installed torch and torchvision using pip and it worked …

Ok! Let's try:

Oh well, another solution up in flames..

I ran into a similar issue with Windows 10. In the end I could only get torch installed with Miniconda.

Alrighty, lets try it!

Alright, cool, moment of truth:

Awesome! You just read through 25 minutes of me re-producing all my attempts to solve this problem, and it doesnt even include the hour I spend down a rabbit hole trying to use Jupyter, which failed equally as miserably. I think it's time to post the question to StackOverflow!
Edit 1:
An answer points out that one of my logs was an error python 3.8 isn't compatible with pytorch, good point I'll fix that. After unintalling 3.8 and installing 3.7:

And no luck! Remember I actually mentioned in my first paragraph that while I was trying 3.8 in these screenshots, the first time around I did all of this with 3.7
Edit 2:
I forgot to install after activating the environment in the previous edit. Once I fixed that, there's a new error:

A: Pytorch requires 3.5 <= python < 3.8. Setup an environment with:
conda create -n pytorch python=3.7
conda activate pytorch
conda install pytorch

You should also make sure that you launch the installed python interpreter from this environment (YourAnacondaInstallDirectory\envs\pytorch\python.exe) from the activated conda environment! The later is important because conda will export certain environment variables (have a look at this for a related issue caused by missing envionment variables).

A: Use This Let me Know if it will Work!
pip install https://download.pytorch.org/whl/cpu/torch-1.0.1-cp37-cp37m-win_amd64.whl

A: If you would like to install it with plain pip rather than conda:
As you know, Pytorch 1.5.1 requires 3.5 <= python < 3.8.  Use Python 3.7 or slightly earlier.
Do NOT try to install with simple pip install torch. Instead, as you say, go to https://pytorch.org/, in the colorful grid, click on pip, copy the command, open a command prompt as an administrator (right-click and select "Run as Administrator") then paste the command, which should look something like:
pip install torch===1.5.1 torchvision===0.6.1 -f https://download.pytorch.org/whl/torch_stable.html
Then, edit the command to replace pip with the full path to your version of pip, e.g.:
"C:\Program Files\Python37\Scripts\pip.exe" pip install torch===1.5.1 torchvision===0.6.1 -f https://download.pytorch.org/whl/torch_stable.html
(You don't need to edit the command as long as Python 3.7 is in your path.)


text:
Q: Can ADFS SSO work with delegated authentication? currently we have ADFS SSO setup in our org and I would like prevent our users to login to Salesforce using the general login.salesforce.com link but we do not want to check the "Prevent login from https://login.salesforce.com" because if our ADFS goes down even us (Admin) unable to login. So we just want our users to use the mydomain url to login as SSO but not Admin and I found it can be done by setting up delegated authentication.
So will this still work with ADFS SSO? What will be the sequence? If i have this delegated authentication setup, the user tried to login through https://login.salesforce.com and our webservice will simply return false? So they will need to use mydomain url? If they use mydomain url to login then it will bypass delegated authentication?
Thanks

A: Delegated authentication is very rarely the right thing to do. I suggest you enable MyDomain, so that the login page for your org is unique, and then leave the SSO off for system administrators, so that they can still login in case your ADFS is down.
I hope it helps.

A: @user2074703 You can leverage frontdoor to accomplish what you want. By clicking "Prevent login from https://login.salesforce.com", this does not prevent admins obtaining a Salesforce Session Id via an API call such as SOAP API login(). From there you can use the SessionId to go through the frontdoor to login if your ADFS IdP is down.

A: Yes, it is a recommended practice... Please read the link below.
https://help.salesforce.com/articleView?id=000329322&type=1&mode=1


text:
Q: How to optimise MongoDB search with indexing? These documents are in my MongoDB collection:
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe85"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page1/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe86"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page2/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe87"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test2",
  "page" : "page3/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}

I need to filter and get some documents like these:
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe85"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page1/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}
{
  "_id" : ObjectId("57f5e1b5c7739d9805edfe86"),
  "date" : ISODate("2016-10-01T00:00:00.000Z"),
  "query" : "test1",
  "page" : "page2/runway/ready-to-wear/ss17/2016/10/christian-dior/",
  "clicks" : 17.0,
  "impressions" : 161.0,
  "ctr" : 0.10559006211180125,
  "position" : 8.503105590062113
}

I created an index using query field and ran db.query using aggregate() method like this:
{
     "aggregate" : "Mycollection Name" ,
     "pipeline" : [
         { "$match" : { "$text" : { "$search" : "\"test1\""}}},
         { "$match" : { "date" : { "$gte" : { "$date" : "2016-10-  01T00:00:00.000Z"} ,"$lte" : { "$date" : "2016-10-01T00:00:00.000Z"}}}},
         { "$group" : { "_id" : "$page" , "clicks" : { "$sum" : "$clicks"} ,  "impressions" : { "$sum" : "$impressions"} , "ctr" : { "$avg" : "$ctr"} ,  "position" : { "$avg" : "$position"}}} ,
         { "$sort" : { "clicks" : -1}}
      ]
}

This query is working but it is not return exactly search.
How can I optimize this query?


text:
Q: Can I get Mercurial to point out loudly that there are files I forgot to "hg add"? For example:
HG: Enter commit message.  Lines beginning with 'HG:' are removed.
HG: Leave message empty to abort commit.
HG: --
HG: user: romkyns
HG: branch 'default'
HG: UNTRACKED FILE: NewFile.xaml
HG: UNTRACKED FILE: NewFile.xaml.cs
HG: changed MainWindow.xaml.cs
HG: changed Settings.cs

Obviously adding those untracked files would still be optional, but hopefully this will significantly reduce the number of times I push commits with missing files.
Is there some easy way to achieve this?

A: Not easily, but you can indeed do it with a bit of work.
When you run hg commit without a given message, Mercurial will choose an editor to use based on a few things, mainly the HGEDITOR environement variable and the ui.editor configuration setting from your hgrc.
If you point this to a script that will generate the commit message your want before running your editor of choice, you would get the expected result. The Mercurial wiki has an article about making this work but it will only work on Mac/Linux unless you have bash (or some other Unix shell) running on Windows. If you know batch scripting or Powershell it should be too hard however.


text:
Q: Telling mutable objects Is there a method that tells if an object is mutable, similar to mutable? in the following? If not, what is the best way to implement it?
"abcde".mutable? # => true
0.mutable? # => false

To answer mu is too short and dbenhur's question, I do not like the syntax of enumerated.inject(initial){...} or enumerated.each_with_object(initial){...}. I wanted a method that reverses the receiver and the argument, and I wanted it to be available to a wide variety of classes; so that I have:
initial.my_new_method(enumerated){...}

0.my_new_method(1..10){|sum, i| sum + i} # => 55
"a".my_new_method(b: 3, c: 4){|s, (k, v)| s + k.to_s * v} # => "abbbcccc"

This will make the return a modified version of the receiver, and is conceptually more natural. And with my_new_method, I wanted it to be non destructive. When the receiver is mutable, I further wanted to define a destructive version
initial.my_new_method!(enumerated){...}

"a".my_new_method!(b: 3, c: 4){|s, (k, v)| s << k.to_s * v} # => "abbbcccc"

So to detect whether the receiver is mutable or not is necessary. It does not matter if it is frozen. If I use the destructive version of the method with a frozen object, it will simply raise an error. Nothing wrong with that.

A: AFAIK all (unfrozen) objects are mutable, except nil, true, false and all integers and symbols.

A: You can call .frozen? on an object to see if that instance of an object is immutable:
1.9.3p194 :001 > a = Array.new
 => []
1.9.3p194 :002 > a.frozen?
 => false
1.9.3p194 :003 > a.freeze
 => []
1.9.3p194 :004 > a.frozen?
 => true

After calling .freeze no other changes will be allowed on that instance of an Object, a RuntimeError will be thrown if anyone attempts to change a frozen object.
EDIT:
As check mentions below in the comments 0.frozen? will correctly return false because 0 is an instance of the Fixnum class.

A: There are two properties that can make an object immutable in ruby
1) the object may be frozen with Object#freeze, in which case your immutability check is Object#frozen?
2) The object may be an immediate value. There's no built-in method I know of to tell that an object is immediate, so one must rely on a side-effect of the immediate nature.  Immediate values are not permitted to have singleton-classes defined on them, so I might try the following as a proxy:
class Object
  def immediate_value?
    class <<self; end
    return false
  rescue TypeError
    return true
  end

  def mutable?
    !(frozen? || immediate_value?)
  end
end

While this is probably a pretty reliable detector (I don't know of another mechanism that prevents opening the singleton class of an object), it does have the unfortunate side-effect of creating a singleton class for each object so queried.

A: I came up with this
class Object
  def mutable?; !!(dup rescue false) end
end


text:
Q: TS2345 error, but the arguments should be ok? So i have this error:
TS2345: Argument of type '(bounds: any, fill: any, stroke: any, strokewidth: any) => mxShape' is not assignable to parameter of type 'new (...args: any) => mxShape'.
Type '(bounds: any, fill: any, stroke: any, strokewidth: any) => mxShape' provides no match for the signature 'new (...args: any): mxShape'.

In my understanding, new (...args: any): mxShape should be sufficient for the given, but Typescript says, its not fitting for it. Why?
This how my MxHeaderShape is built:
     function MxHeaderFooterShape(bounds, fill, stroke, strokewidth) : mxShape{
        let val = mxShape.call(this);
        this.bounds = bounds;
        this.fill = fill;
        this.stroke = stroke;
        this.strokewidth = (strokewidth != null) ? strokewidth : 1;
        return val;
    }

A: It seems that you want to create a MxHeaderFooterShape class that extends mxShape.
Assuming you are using typed-mxgraph, you can use this way of doing
import mx from './mxgraph'; // mxGraphExportObject returned by the mxgraph factory function
import type { mxRectangle } from 'mxgraph';

class CustomMxShape extends mx.mxShape {

  constructor(bounds: mxRectangle, fill: string, stroke: string, strokewidth?: number) {
    super(bounds, fill, stroke, strokewidth);
  }

}

You can also check this demo: https://github.com/typed-mxgraph/typed-mxgraph-example-bundled-with-webpack/blob/7f0bf757aedb12cec84d86b4c4e4cbcb0f7a8147/src/app/custom-shapes.ts


text:
Q: How to generate $2\times 2$ matrix with integer entries and both eigenvalues inside unit disk I am looking for a method to generate $2\times 2$ matrices whose all elements are integers and whose both eigenvalues lie inside the unit disk.
I realise that I could do so via similar matrices, i.e. take  matrix $A$ to be a diagonal one, and then the matrix $B=P^{-1}AP$ will have the same eigenvalues. My question is - how do I ensure that the elements of the matrix $B$ are integers?
EDIT:
What I am interested in ultimately is the asymptotic stability of the discrete time linear systems of the type $x(k+1)= Ax(k)$, where $x(k)$ is the state of the system at time step $k$. Asymptotic stability of such a system is equivalent to $A$ having all its eigenvalues inside open unit disk, which is equivalent to the existence of positive definite solution $P > 0$ to the discrete Lyapunov equation $A^TPA-P = -Z$ for some $Z$ positive definite. Hence, what I am actually looking for is a solution $P$ of the above equation with integer or rational elements, and thought initially that $A$ with integer elements might be a way to get there.

A: The sum of the eigenvalues is $\operatorname{tr} A$ and their product is $\det A$, and these expressions are of course also integers. Then we conclude $|\det A|\le1$ and $|\operatorname{tr} A|\le 2$ (assuming you consider the closed unit disk). For example, the simplest case $\det A=\operatorname{tr} A= 0$ leads to $A=\begin{pmatrix}a&b\\c&-a\end{pmatrix}$ with $a^2=-bc$; this can be rewritten as $A=\begin{pmatrix}uvd&-u^2d\\v^2d&-uvd\end{pmatrix}$ with $u,v,d\in\mathbb Z$. The other cases lead to similar Diophantine conditions.
This may look confusing, but now we can exploit your idea of similarity. However, $A$ is similar to a diagonal matrix only over $\mathbb C$. You better restrict your $P$ matrices to elements of $SL(2,\mathbb Z)$. This at least allows you to achieve things like e.g. $|c|\le |a|$.

A: Since your matrix is real, the eigenvalues are real or come in complex conjugate pairs. The real part of the pair is half the trace, and since it must lie strictly within the unit circle, your matrix must have zero trace (similarly, the average of the eigenvalues must be in the unit circle if both are). If both eigenvalues are within the unit circle, then their product is also, so $\det A < 1$. Since the determinant is an integer, then $\det A = 0$. A zero-trace, zero-determinant matrix is highly constrained (and probably trivial for your application), but I will parameterize them anyways. It must be of the form
$$ \begin{bmatrix} a&b\\c&-a\end{bmatrix}$$
The condition $\det A = 0$ is equivalent to $a^2+bc = 0$.
So choose a random integer $a$, compute factorizations of $a^2$, then choose $b$ and $c$ of opposite sign from possible factorizations.


text:
Q: How to find best match with sklearn pipeline in Python I've got a Pipeline setup using a TfidfVectorizer and TruncatedSVD. I train the models with sklearn and calculate the distance between two vectors using the cosine similarity. Here's my code:
def create_scikit_corpus(leaf_names=None):

    vectorizer = TfidfVectorizer(
        tokenizer=Tokenizer(),
        stop_words='english',
        use_idf=True,
        smooth_idf=True
    )

    svd_model = TruncatedSVD(n_components=300,
                             algorithm='randomized',
                             n_iterations=10,
                             random_state=42)
    svd_transformer = Pipeline([('tfidf', vectorizer),
                                ('svd', svd_model)])

    svd_matrix = svd_transformer.fit_transform(leaf_names)

    logging.info("Models created")

    test = "This is a test search query."
    query_vector = svd_transformer.transform(test)
    distance_matrix = pairwise_distances(query_vector, svd_matrix, metric='cosine')

    return svd_transformer, svd_matrix

The thing is that I'm not sure what to do once I have the distance_matrix variable. I guess I'm kinda confused on exactly what that is.
I'm trying to find which document matches best with my query. Thanks for a push in the right direction!

A: Once you have the distance_matrix computed, you can find the closest singular vector according to the cosine similarity... And that might be the reason you are confused: what does this singular vector represent?
The problem is that this answer is not straightforward, the singular vector is usually not a document in your corpus.
If what you want is the best match as in "the document from your corpus that is the most similar to this one", there is something simpler to do: pick the closest document according to cosine similarity. You do not need SVD for this approach.


text:
Q: Find $c$ such that $cy^3(1-y)^8$ for $0 \leq y \leq 1$ is a PDF I have a function
$$f(y) = \left\{\begin{array}{cc} cy^3(1-y)^8 & 0 \leq y \leq 1 \\
                                    0 & \text{ Otherwise.}\end{array}\right. .$$
I want to figure out what value of $c$ makes this function a legal probability
density function.
I'd imagine that we start out by setting
$$1 = \int_0^1 cy^3(1-y)^8 dy$$
$$\implies 1 = c \int_0^1 y^3(1-y)^8 dy.$$
However, the degrees seems to make this integral somewhat hard. I tried plugging
this into Wolfram, but I couldn't seem to get any meaningful information as to
how to calculate that. Any suggestions?

A: Hint. One may recall the Euler beta integral (or here),
$$
\int_0^1 y^{a-1}(1-y)^{b-1} dy=\frac{\Gamma(a)\cdot \Gamma(b)}{\Gamma(a+b)}
$$ giving
$$
\int_0^1 y^3(1-y)^8 dy=\frac{\Gamma(4)\cdot \Gamma(9)}{\Gamma(13)}=\frac{1}{1980}.
$$

A: You can always expand $(1-y)^8$ with the binomial theorem and integrate term by term. Somewhat more elegant is to substitute $u=1-y$.


text:
Q: Fine tuning the agsm bibliography style, and adding links Lovely day. I am quite new to LaTeX but picking things up fast. One area which is confusing me greatly is getting my bibliography to work just how I like it.
I have settled on the agsm style and the natbib citation management issue, but there are still some issues.

*

*The volume number of a journal is set in bold. (blue in pic)
I want it to just be plain (un-bolded).

*The journal titles have apostrophes around them. (red in pic)
I want to get rid of the apostrophes.
This image added highlights these problems.

Lastly, for the electronic copy, I would like it so the journal identifiers (DOIs) are highlighted blue, so you can click on them and it takes you to the website of the journal article. (green in pic)
Help on any / all of the above would be greatly appreciated. I have searched online for about 8 hours and finally need to ask the lords of TeX.
Edit: This is my bibliography code so far I forgot to add:
\documentclass[11pt,a4paper]{report}
\usepackage[numbers]{natbib}
\renewcommand\harvardyearleft{\unskip, }
\renewcommand\harvardyearright[1]{.}
\bibliographystyle{agsm}
\usepackage{hyperref}
\begin{document}
\cite{ref1}
\bibliography{bibFile}
\end{document}

Note - that \renewcommand I found from this forum; it gets rid of brackets around the year field which I didn't want.

A: Find the file agsm.bst and make a copy, say, myagsm.bst. Next, open the new file in a text editor of your choice and search for the following line:
{ volume embolden field.or.null

(It's on l. 357 in my copy of the file.) Change this line to
{ volume field.or.null

i.e., tell BibTeX not to render the volume number in bold.
Third, look for the line
    { format.title quote "title" output.check }

inside the function named article. (It's on l. 698 in my copy of the file.) Change it to
    { format.title "title" output.check }

i.e., tell BibTeX not to place (single) quotes around the title. Finally, save the new file, update the TeX filename database if necesssary (say, by running texhash if you use TeXLive or MacTeX), and start using the new bibliography style by issuing the command
\bibliographystyle{myagsm}

from now on.
I should note that this is all extremely hack-ish. What you really ought to do is to run the utility program makebst, which will pose lots and lots of questions on just how you want to set up your custom .bst file. This utility will then create a brand-new bibliography style file that is based on the answers you provided. To run this utility, at a command prompt type latex makebst and follow the prompts.
An important additional advantage of using the makebst utility is that it will let you set up exactly what you think should happen with the contents of a field called doi. This is something you simply can't do by hacking the file agsm.bst -- short of a complete rewrite of the entire file, of course -- because the agsm bibliography style is quite old and doesn't even recognize the contents of a field named doi.


text:
Q: How to programatically generate Bearer Token using Azure AD when Multifactor Authentication is enabled I am following the example https://github.com/Azure-Samples/active-directory-dotnet-native-headless to authenticate a user against Azure AD in which the user sends his user credentials (uname,pwd) to acquire a bearer access Token(grant_type set to password). This token will be sent in the Authorization header to the internal Rest API. The REST API uses the token to get the details of the user using ClaimPrincipal and to authorize the user against AD Security group using Graph-API.
Now the problem is, we have Multi factor authentication (MFA) enabled, in this case how shall I able to generate the Token using Azure Oath APIs and get the above program to work.


text:
Q: Induced Sequence of a SES of Sheaves I have a question about a step in the proof of Prop. 5.2.15 in Liu's "Algebraic Geometry" (page 184):

We have the short exact sequence $0 \to \mathcal{F''} \overset{\alpha}{\rightarrow} \mathcal{F} \overset{\beta}{\rightarrow} \mathcal{F'} \to 0$.
If $s \in \mathcal{F'}(X)$  and $\{U_i\}_i$ is a covering of $X$, why there exist $t_i \in \mathcal{F}(U_i)$ such that $s|_{U_i} = \beta(U_i)(t_i)$?
Or more precisely I know that a ses as above induce ses of stalks in each $x \in X$:
$0 \to \mathcal{F_x''} \overset{\alpha}{\rightarrow} \mathcal{F_x} \overset{\beta}{\rightarrow} \mathcal{F_x'} \to 0$, and also a ses of global section: $0 \to \mathcal{F''}(X) \overset{\alpha}{\rightarrow} \mathcal{F}(X) \overset{\beta}{\rightarrow} \mathcal{F'}(X) \to 0$.
But I'm not sure if it induces also following ses for every open $U_i$:
$0 \to \mathcal{F''}(U_i) \overset{\alpha}{\rightarrow} \mathcal{F}(U_i) \overset{\beta}{\rightarrow} \mathcal{F'}(U_i) \to 0$
wich was obviously required above to find the $t_i$'s.

A: Liu does not asserts that for any cover $U_i$ there are such sections, but that there exist such cover. Indeed, by definition a sequence of sheaves is exact iff it is exact at every stalk. Now, if $s \in F'(X)$, by exactness at each stalk,for all $x \in X$ there is $t_x$ with $\beta_x(t_x) = s_x$, i.e there is an open $U_x \ni x$, a section $t \in F(U_x)$ with $\beta(t_U)_x = s_x$ : taking the set of all $U_x$ for $x \in X$ give you the cover you were looking for.
Edit : A short exact of sheaves does not induces a short exact of global sections, this is precisely why cohomology is made for ! As an example, let us take the exponential sequence $0 \to \Bbb Z \to \mathcal O \to \mathcal O^* \to 0$ on $X = \Bbb C^*$.Notice that  $\text{id}_{\Bbb C^*}$ is a global section of $\mathcal O^*$ but there is no function $g$, with $e^g = id$ (i.e there is no global logarithm on $\Bbb C^*$).


text:
Q: Format of JPanel I have set of code that seems somewhat messy. I was wondering how to tidy it up
JPanel inventory = new JPanel();
    JPanel options = new JPanel();
    JPanel planet = new JPanel();
    JPanel mainPanel = new JPanel();
    JFrame mainFrame = new JFrame("Inventory");
    inventTitle = new JLabel("Inventory");
    inventMoney = new JLabel("   - " + money);
    optTitle = new JLabel("Options");
    opt1Label = new JLabel("Mine Ice -1 P, +100 M");
    opt2Label = new JLabel("Heat Planet -500 M, +10T");
    opt3Label = new JLabel("BLANK");
    opt4Label = new JLabel("BLANK");
    opt5Label = new JLabel("BLANK");
    opt6Label = new JLabel("BLANK");
    opt7Label = new JLabel("BLANK");
    opt8Label = new JLabel("BLANK");
    opt9Label = new JLabel("BLANK");
    JButton opt1 = new JButton("1");
    JButton opt2 = new JButton("2");
    JButton opt3 = new JButton("3");
    JButton opt4 = new JButton("4");
    JButton opt5 = new JButton("5");
    JButton opt6 = new JButton("6");
    JButton opt7 = new JButton("7");
    JButton opt8 = new JButton("8");
    JButton opt9 = new JButton("9");

    mainPanel.setLayout(null);
    mainPanel.add(inventory);
    mainPanel.add(options);
    mainPanel.add(planet);
    mainPanel.setOpaque(true);
    mainPanel.setBackground(Color.WHITE);

    inventory.setLayout(new BoxLayout(inventory, 1));
    inventory.add(inventTitle);
    inventory.setOpaque(true);
    inventory.setBackground(Color.RED);
    inventory.setBounds(0, 0, 360, 400);
    inventory.add(inventMoney);

I saw somewhere a way of setting it like a method.

A: You can use a for loop instead of writing the same statements multiple times.
JLabel optLabel[] = new JLabel[9];
JButton opt[] = new JButton[9];

for (int i = 0; i < 9 ; i++) {
   optLabel[i] = new JLabel ("BLANK");
   opt[i] =  new JButton (Integer.valueOf (i + 1).toString());
}


text:
Q: How to fetch apk itself from the google play store using PHP script? Hey guys i have this project which needs to download APK file directly from google play store to the PC using an PHP script. I have looked into the python script which is very old and doesn't work now. I see sites like apkpure.com and apk-dl are doing it.
I have used google play link scraper Link to scrape the application details from google play store. But i can't figure out a way to get the application itself from google play.
Can anyone guide me in a right direction for this?
Really appreciate it guys.
Thanks.
The link scraper that i use only fetch the application information not the application itself. I also looked into chrome extensions like some of you suggested but they don't hold the answer that i require. Please suggest something else.


text:
Q: Average number of tries to get an X number of unique elements Assuming that we have the following loot table
Type     Chance Number of unique elements
common   30.00%  21
Uncommon 30.00%  27
Rare     20.00%  32
Ultra    15.00%  14
Epic     5.00%   10

How can I calculate the average number of tries to get X unique elements regardless from their rarity, with x starting from 1 to all elements (tries to get 1 element, tries to get 2 etc...). I have tried the formula here but that works only for calculating the number of tries for all elements. Ideally I want to plug the formula in excel so I can use it for different games.
P.s. I am not a math student, just a gamer!


text:
Q: Nginx Configuration - Upstream - Backup Server I'm having a with my upstream, i'd like to know what's wrong with my nginx configuration:
upstream backends {
server 127.0.0.1:80;
server 188.200.200.200 backup;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html index.php;

    server_name localhost;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
        proxy_read_timeout 150;
        proxy_pass http://backends;
        proxy_set_header Host $host;
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
 }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_read_timeout 150;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_buffer_size 128k;
            fastcgi_buffers 4 256k;
            fastcgi_busy_buffers_size 256k;

    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
            deny all;
    }

 location ~* \.      (jpg|jpeg|gif|png|css|js|ico|xml|woff|ttf|otf|svg|woff2|eot)$ {
     access_log        off;
     log_not_found     off;
     expires           30d;
 }

It gives this message in the log:
connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000"
Someone can help me?
Thanks in advance

A: It seems that you are requesting a .php file, which is served by the second location block. In this block nginx tries to connect to 127.0.0.1:9000 as per the fastcgi_pass 127.0.0.1:9000;-directive. But there seems to be no FastCGI-daemon running at this address.
The same may happen if you request / and have none of the index files from the index-directive present. The last entry (index.php) also activates the second location.


text:
Q: How can we define the infinite sum of $1$ and $-1$? $1-1+1-1+1-1+1-1+1-1......$
it seems first that this is equal to $0$
but we re-arrange this sum
$1+(1-1)+(1-1)..... $
so the sum is $1$
In this case,
do we say that this sum is undefined?

A: Yes, we say the series is divergent, and its sum is undefined. But to answer the question in the title:

How can we define the infinite sum of 1 and -1?

There are various definitions of generalized sums that apply to divergent series. The most important methods that apply to this series are listed here: Wikipedia:Summation of Grandi's series. Briefly, the Cesàro sum, Abel sum, and Borel sum of the series is $\frac12$.

A: Clearly  for each $n \in \mathbb N$,
$$U_n=(-1)^n$$
Now observe that
$U_{2n}=(-1)^{2n}=1$ and
$U_{2n+1}=(-1)^{2n+1}=-1$ .
So $$U_n= \begin{cases}
 ~~~1&  ; n \text{ is  even}\\
 -1& ; n \text{ is  odd}
\end{cases}$$
Then $\displaystyle \lim_{n \to \infty}U_n \neq 0$  $\Rightarrow \sum U_n$ diverges.


text:
Q: Combining generic MVP pattern with abstract factory pattern Is there some way to solve my code below? I'm kinda stuck.
How can I use a factory to create generic presenters, is it even possible without a non generic base class?
public abstract class Presenter<T>
{}

public SomePresenter : Presenter<ISomeVew>
{}

public SomeOtherPresenter : Presenter<ISomeOtherView>
{}

public class Factory()
{

  public ??? CreatePresneter(int runTimeValue)
  {
    if (runTimeValue == 1)
      return new SomePresenter()
    else
      return new SomeOtherPresenter()
  }

}

A: Many times generic base classes need non-generic bases, so write
public abstract class Presenter
{}

public abstract class PresenterOf<T> : Presenter
{}

and use PresenterOf for your presenters.
Then CreatePresenter can return Presenter.  Obviously, this only helps if ISomeView and ISomeOtherView have a base class that Presenter can work on.
If these views and presenters don't have commonality in the interface, then using one factory to make them all might not make sense.


text:
Q: How to add image using GridView? I have a problem I would like to display images using GridView, but it is not working. Images are upluded already
Here is a code
<asp:Gridview id="zbozi" runat="server"  AutoGenerateColumns="False" OnRowCommand="zbozi_RowCommand1" OnSelectedIndexChanged="zbozi_SelectedIndexChanged">
    <Columns>
        <asp:BoundField DataField="id_pocitace" HeaderText="ID" />
         <asp:BoundField DataField="nazev" HeaderText="Název" />
             <asp:BoundField DataField="cena" HeaderText="Cena" />

               HERE I WOULD LIKE TO PUT IMAGES

              <asp:BoundField DataField="popis" HeaderText="Popis" />

    </Columns>
</asp:Gridview>

This is Cs
public partial class online : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["idecko"] == null)
        {
            Response.Redirect("login.aspx");

        }
        uziv.Text = Convert.ToString(Session["uziv"]);
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["logins"].ConnectionString);
        conn.Open();

        SqlCommand sqlDa = new SqlCommand("select * from pocitace", conn);
        var rdr = sqlDa.ExecuteReader();
        zbozi.DataSource = rdr;
        zbozi.DataBind();

Image of visual studio, folders etc.. for understanding the situation:

A: To show image in GridView, you need to create a column with "ImageField".
<asp:GridView runat="server" ID="testGridView" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:ImageField DataImageUrlField="Image" HeaderText="Image"></asp:ImageField>
    </Columns>
</asp:GridView>

Then access the image path in the database directly and bind the data from database like:
string constr = @"connection string";
con.Open();
da = new SqlDataAdapter("select * from TestTable", con);
ds = new DataSet();
da.Fill(ds);
testGridView.DataSource = ds;
testGridView.DataBind();

A: dont upload binary or like this in sql just upload the path and get the path
add this column
<asp:ImageField DataImageUrlField="image_Path" HeaderText="Image"></asp:ImageField>
and set column name İmage_Path nvarchar in sql


text:
Q: How to cycle through rainbow color Combination Java I have found some other similar questions but they do not really answer my question.
Currently I'm making a game and I want this object on the screen to cycle through the rainbow colours.
This class has a method called tick and render; each of these is run every game tick. I didnt even bother running the example below as i dont know how to approach this question.
Color c;
int r=0,g=0,b=0;
boolean ascending = true;

public void tick(){
    while(ascending) {
            if(r <= 255)
                r++;
            else
                break;
            if(g <= 255)
                g++;
            else
                break;
            if(b <= 255)
                b++;
            else
                break;
        }
}

A:
I want this object on the screen to cycle through the rainbow colours.

*

*Create an ArrayList of Color objects to represent the colors of the rainbow.

*Create a Swing Timer for the animation.

*Each timer the Timer fires you get the Color object at index 0 from the ArrayList at set the color of your component.

*Then remove the Color object at index 0.

*When the ArrayList is empty, you stop the Timer.
See: Timer doesn't stop. Trying to do clicks for n steps for a basic example that updates the time for 10 seconds and then stops.


text:
Q: Unity 3d Photon как при старте активировать другую модель для первого игрока? Unity 3d Photon как при старте активировать другую модель для первого игрока?
Нужно чтобы первый входящий игрок имел особую модель, но по какой-то причине второй игрок тоже активирует эту же модель.
public class SpawnPlayers : MonoBehaviour
{
    public GameObject[] players;
    public GameObject player1;
    public GameObject player2;
    public GameObject player3;
    public GameObject player4;
    public GameObject player5;
    public GameObject monster1;
    public int x = 0;

    public void Start()
    {
        if (players.Length == 0)
        {
            Vector3 playerPosition = new Vector3(-7.75f, 1.1f, -3f);
            PhotonNetwork.Instantiate(monster1.name, playerPosition, Quaternion.identity);
        }
        else
        {
            x = PlayerPrefs.GetInt("x", x);
            if (x == 1)
            {
                Vector3 playerPosition = new Vector3(-7.75f, 1.1f, -3f);
                PhotonNetwork.Instantiate(player1.name, playerPosition, Quaternion.identity);
            }
            else
            if (x == 2)
            {
                Vector3 playerPosition = new Vector3(-7.75f, 1.1f, -3f);
                PhotonNetwork.Instantiate(player2.name, playerPosition, Quaternion.identity);
            }
            else
            if (x == 3)
            {
                Vector3 playerPosition = new Vector3(-7.75f, 1.1f, -3f);
                PhotonNetwork.Instantiate(player3.name, playerPosition, Quaternion.identity);
            }
            else
            if (x == 4)
            {
                Vector3 playerPosition = new Vector3(-7.75f, 1.1f, -3f);
                PhotonNetwork.Instantiate(player4.name, playerPosition, Quaternion.identity);
            }
            else
            if (x == 5)
            {
                Vector3 playerPosition = new Vector3(-7.75f, 1.1f, -3f);
                PhotonNetwork.Instantiate(player5.name, playerPosition, Quaternion.identity);
            }
        }
    }

    public void Update()
    {
        players = GameObject.FindGameObjectsWithTag("Player");
    }
}


text:
Q: How to get authors in links? I am trying to get the names Pucheu_M, Romero_C, Bellini_M and Aguilar_J in
http://arxiv.org/find/gr-qc/1/au:+Pucheu_M/0/1/0/all/0/1
http://arxiv.org/find/gr-qc/1/au:+Romero_C/0/1/0/all/0/1
http://arxiv.org/find/gr-qc/1/au:+Bellini_M/0/1/0/all/0/1
http://arxiv.org/find/gr-qc/1/au:+Aguilar_J/0/1/0/all/0/1

This is what I tried:
/"au:+"([^/]+)/?$

See regex101 demo.
However no result is found. Can this be fixed?

A: Your regex must be like below.

*

*Escape the + symbol.

*Use a different php delimiter.

*Put / and $ inside a group delimited by |. Because think your input won't contain an end of the line immediately next to / symbol.

*Finally get the string you want from group index 1.

Regex:
'~/au:\+([^/]+)(?:/|$)~'

DEMO


text:
Q: noob javascript recursion I'm a sys admin trying to learn javascript as a first language. One of the text I am studying has this code example in the chapter on recursion.
(variables changed for simplicity)
function fruit(n) {
    return n > 1 ? fruit(n - 1) + "apples" : "bananas";
}

I understand the ternary operator aspect of the function, the same thing could be written as this:
function fruit(n) {
    if n > 1
      return fruit(n - 1) + "apples";
    else
      return "bananas";
}

when I call the function I get the following result
console.log(fruit(3));

bananas apples apples

I don't understand how the first value is bananas (would that not mean the conditional 3 > 1 would be false)? What is going on in terms of how this code is executed to come up with that result?
Not sure if this site is noob friendly but thanks in advance for any help.

A: When figuring out recursion, it's best to start with the base case. In this case, your base case is fruit(1) - I hope it's clear that this returns bananas.
Now consider fruit(2) - this will return fruit(1) + "apples", and we already know fruit(1) is bananas, so this means bananas apples.
Extend this case further - fruit(3) is basically fruit(2) + "apples", and you already know what fruit(2) is... you end up with "bananas apples" + "apples", giving you your result.

A: I have tested your code like follows:
<script>
function fruit(n) {
    console.log("Called with " + n);
    if (n > 1) {
      return fruit(n - 1) + "apples ";
    } else {
      console.log("Called with " + n + " returning bananas.");
      return "bananas ";
    }
}
console.log(fruit(3));
</script>

My output:
Called with 3
Called with 2
Called with 1
Called with 1 returning bananas.
bananas apples apples

The line return fruit(n - 1) + "apples "; means you concatenate a string: "bananas" + "apple" + "apple".
Looking on every step:
fruit(3):
- calling fruit(2)
- - calling fruit(1)
- - get return "bananas" // string consinst of "bananas" only here
- get return "apple" // string = "bananas" + "apple"
get return "apple" // string = "bananas" + "apple" + "apple"

EDIT:
If you want to have bananas at the end.
Change
return fruit(n - 1) + "apples ";

to
return "apples " + fruit(n - 1);

A: This happens because recursion continues as follows:
function fruit(n) {
if n > 1
  return fruit(n - 1) + "apples";
else
  return "bananas";
}

In the example you gave (listed above) you check to see if n > 1. In this case n = 3 so the answer is yes. So what do we do? We execute fruit(2).
Is 2 greater than 1? yes, so what do we do? We execute fruit(1).
Is 1 > 1? No, so we write Bananas.
Then recursion sort of back-tracks, writing the apples and apples as it returns to finish the previous methods.
VISUAL EXAMPLE:
Since we know that the function will return "bananas" only when n <= 1
function fruit(3) will return SOMETHING and then write "apples"
  fruit(3) = fruit(2) apples
  fruit(2) = fruit(1) apples
  fruit(1) = banana

so you see, therefore substituting [fruit(2)] and (fruit(1)):
fruit(3) = [fruit(1) apples] apples
fruit(3) = [(banana) apples] apples

A: If you trace your code, it will be clearer what is going on.
You can think of recursion as layers, and each call goes deeper and deeper in. When these calls resolve, they resolve in the reverse order, with the latest recursion resolving first, then coming outwards to the outward layer.
If you wanted to print the latest recursion at the end you should change
return fruit(n-1) + "apples"

to
return "apples"+ fruit(n-1)

A: try to create a binary tree structure in a paper you will start to understand,
Firstly 3 is given which will be true so it will return
fruit(2)+"apple"
continue this until you reach the else part and then start to go up in the binary tree and you will get the output,
always try to think how a computer would process it


text:
Q: Python crash on class instance call I am using pyqtgraph for real-time data plotting. Unfortunately, the library does not support time series real-time plotting, so I went googling and found someone that had written specific classes for that (you can find it here). I used these classes once with no problem at all, but now python instantly crashes upon call of the 'TimeSeriesPlot()' class. I tried to delete all .pyc files in the python folder and all subfolders, but that did not change anything, neither did a repair of the python install. Any ideas as to what causes the problem and how to solve it? Has anyone been confronted to that sort of problem?
My configuration is:

*

*Windows 7 Home Edition Blockquote

*Python 2.7.5

*Pyside 1.1.2 with QT 4.8

*PyQtGraph 0.9.7

Here is the content of the file I have been trying to execute:
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

class TimeSeriesPlotViewBox(pg.ViewBox):
    def __init__(self, timeSeriesPlot, *args, **kwds):
       pg.ViewBox.__init__(self, *args, **kwds)
       self.timeSeriesPlot = timeSeriesPlot

   def mouseClickEvent(self, ev):
      if ev.button() == QtCore.Qt.RightButton:

         self.timeSeriesPlot.xFrom = None
         self.timeSeriesPlot.xTo = None
         self.timeSeriesPlot.updateView()

         self.enableAutoRange(pg.ViewBox.XAxis,1.0)
         self.enableAutoRange(pg.ViewBox.YAxis,1.0)

   def mouseDoubleClickEvent(self, ev):
      if ev.button() == QtCore.Qt.LeftButton:

         xFrom = 0
         if not self.timeSeriesPlot.xFrom is None and self.timeSeriesPlot.xFrom < 0:
            xFrom = self.timeSeriesPlot.xFrom
         else:
            xFrom = -len(self.timeSeriesPlot.timedata)
         self.timeSeriesPlot.xFrom = int(round(xFrom / 2.0))

         self.timeSeriesPlot.updateView()
         self.enableAutoRange(pg.ViewBox.XAxis,1.0)
         self.enableAutoRange(pg.ViewBox.YAxis,1.0)

   def mouseDragEvent(self, ev):
      if ev.button() == QtCore.Qt.RightButton:
         ev.ignore()
      else:
         pg.ViewBox.mouseDragEvent(self, ev)

class TimeSeriesPlot(pg.QtCore.QObject):

   def __init__(self, tsTitle, parent = None):
      pg.QtCore.QObject.__init__(self, parent)

      self.vb =TimeSeriesPlotViewBox(self)

      self.plt = pg.PlotWidget(viewBox=self.vb, title = tsTitle)
      self.vb.sigRangeChangedManually.connect(self.zoom)

      #time axis
      self.timedata = []

      #val data
      self.valdata = []
      self.curveVal = pg.PlotDataItem([])
      self.plt.addItem(self.curveVal)

      self.xFrom = -50
      self.xTo = None

   def zoom(self):
       xlimits,ylimits = self.vb.viewRange()

       import bisect
       self.xFrom = bisect.bisect_left(self.timedata,xlimits[0])
       self.xTo = bisect.bisect_right(self.timedata,xlimits[1])

       self.vb.disableAutoRange(pg.ViewBox.XAxis)
       self.vb.disableAutoRange(pg.ViewBox.YAxis)

       self.updateView()

   def show(self):
       self.plt.show()

   def updateModel(self,newdata):
       time = float(newdata["time"])
       val = float(newdata["val"])

       self.timedata.append(time)
       self.valdata.append(val)

   def updateView(self):
       useAA = True
       viewSlice = None
       maxElementCnt = 500.0
       if self.xFrom is None and self.xTo is None:
          elementCnt = len(self.timedata)
          step = max(int(round(elementCnt / maxElementCnt)),1)
          viewSlice = slice(-elementCnt,None,step)
       elif self.xFrom < 0:
          elementCnt = -self.xFrom
          step = max(int(round(elementCnt / maxElementCnt)),1)
          viewSlice = slice(-elementCnt,None,step)
       else:
          elementCnt = self.xTo - self.xFrom
          step = max(int(round(elementCnt / maxElementCnt)),1)
          viewSlice = slice(self.xFrom,self.xTo,step)

       useAA = True
       self.curveVal.setData(x=self.timedata[viewSlice],y=self.valdata[viewSlice],clear=True,antialias=useAA)
####################################
TimeSeriesPlot('plot')

A: The first error message I see when I run this code is:
QWidget: Must construct a QApplication before a QPaintDevice

This is true for all Qt applications; you must create a QApplication instance before anything else. After this is fixed, the script still crashes with a segmentation fault, probably because the TimeSeriesPlot instance is being deleted immediately (since it is not assigned to any variable). Even after that is fixed, the script exits immediately (because there is nothing else to do). I replaced the last line in your example with the following code to get the expected result:
app = pg.QtGui.QApplication([])
tsp = TimeSeriesPlot('plot')
tsp.show()
app.exec_()


text:
Q: Bower Loading devDependencies in Production? Short Version
My project requires angular-leaflet, and angular-leaflet has a long list of devDependencies, including jQuery 2. I don't want jQuery 2--I want jQuery 1.x. How can I get bower to ignore the devDependencies of angular-leaflet and let me use jQuery 1?
Long Version
I am using bower 1.2.8. Here is a minimal bower.json that reproduces the problem for me:
{
  "name": "bower-test",
  "dependencies": {
    "jquery": "1.x",
    "angular": "1.2.x",
    "angular-leaflet": "0.7.x"
  }
}

Running bower install results in the following error:
Unable to find a suitable version for jquery, please choose one:
    1) jquery#1.x which resolved to 1.11.0 and has bower-test as dependants
    2) jquery#2.1.0 which resolved to 2.1.0 and has angular-leaflet#0.7.5 as dependants
    3) jquery#>= 1.9.0 which resolved to 2.1.0 and has bootstrap#3.0.3 as dependants

At the very least, I expected bower install --production to ignore devDependencies in angular-leaflet. But here's the result (identical to above):
Unable to find a suitable version for jquery, please choose one:
    1) jquery#1.x which resolved to 1.11.0 and has bower-test as dependants
    2) jquery#2.1.0 which resolved to 2.1.0 and has angular-leaflet#0.7.5 as dependants
    3) jquery#>= 1.9.0 which resolved to 2.1.0 and has bootstrap#3.0.3 as dependants

Why is bower not ignoring the devDependencies of angular-leaflet? Is there a way to make it do so?

A: I think the solution you are looking for is the resolutions section of bower.json though
as to why devDependencies of your dependencies are even being analyzed is not clear to me.
{
  "name": "bower-test",
  "dependencies": {
    "jquery": "1.x",
    "angular": "1.2.x",
    "angular-leaflet": "0.7.x"
  },
  "resolutions": {
    "jquery": "1.x"
  }
}

Perhaps this is a slight difference from npm in that doing bower install xyz includes devDependencies unless the -p or --production parameter is specified, but even if it is specified it doesn't seem to get passed on to dependencies -- perhaps this is a bug.
UPDATE: The problem seems to be related to this particular package/setup using angular-leaflet. Other components do not have this issue. For example,  bower install webmaker-analytics just fetches webmaker-analytics, not qunit even though it was listed in this package's devDependencies.


text:
Q: derivative of $y=\sqrt{10^{5-x}}=u^{1/2}$ $y=\sqrt{10^{5-x}}=u^{1/2}$
$y\;'=\dfrac{1}{2}u^{-1/2}\times u\;'=\dfrac{1}{2}(10^{5-x})^{-1/2}=\dfrac{1}{2\sqrt{10^{5-x}}}\times 10^{5-x}\ln10(-1)$
$=\dfrac{10^{5-x}\ln10(-1)}{2\sqrt{10^{5-x}}}$
However the correct answer is: $-\dfrac{10^{.5(5-x)}}{2}\ln(10)$
what am I doing wrong?

A: $$\displaystyle\frac{10^{5-x}\ln(10)(-1)}{2\sqrt{10^{5-x}}} = -\frac{\sqrt{10^{5-x}}\ln(10)}{2} = -\frac{10^{.5(5-x)}}{2}\ln10$$
You didn't had any problems, you just didn't complete the simplification of the fraction.

A: Write $y=10^{(5-x)/2}$ and recall $(b^{x})'=b^{x}\ln b$
Then the chain rule implies (with $u=(5-x)/2$ and $u'=-1/2$) that
$$y'=\frac{-\ln 10}{2}10^{(5-x)/2}.$$


text:
Q: Phantom tests after switching from unittest.TestCase to tf.test.TestCase The following code:
class BoxListOpsTest(unittest.TestCase):
    """Tests for common bounding box operations."""

    def test_area(self):
        corners = tf.constant([[0.0, 0.0, 10.0, 20.0], [1.0, 2.0, 3.0, 4.0]])
        exp_output = [200.0, 4.0]
        boxes = box_list.BoxList(corners)
        areas = box_list_ops.area(boxes)

        with tf.Session() as sess:
            areas_output = sess.run(areas)
            np.testing.assert_allclose(areas_output, exp_output)

if __name__ == '__main__':
    unittest.main()

Is interpreted as a test case with a single test:
.
----------------------------------------------------------------------
Ran 1 test in 0.471s

OK

However, switching to tf.test.TestCase:
class BoxListOpsTest(tf.test.TestCase):
    """Tests for common bounding box operations."""

    def test_area(self):
        corners = tf.constant([[0.0, 0.0, 10.0, 20.0], [1.0, 2.0, 3.0, 4.0]])
        exp_output = [200.0, 4.0]
        boxes = box_list.BoxList(corners)
        areas = box_list_ops.area(boxes)
        # with self.session() as sess:
        with tf.Session() as sess:
            areas_output = sess.run(areas)
            np.testing.assert_allclose(areas_output, exp_output)

if __name__ == '__main__':
    tf.test.main()

introduces some second test, which is skipped:
.s
----------------------------------------------------------------------
Ran 2 tests in 0.524s

OK (skipped=1)

What is the origin of the second test and should I worry about it?
I am using TensorFlow 1.13.

A: It's the tf.test.TestCase.test_session method. Due to the unlucky naming, unittest considers test_session method to be a test and adds it to the test suite. To prevent running test_session as a test, Tensorflow has to skip it internally, so it results in a "skipped" test:
def test_session(self,
                 graph=None,
                 config=None,
                 use_gpu=False,
                 force_gpu=False):
    if self.id().endswith(".test_session"):
        self.skipTest("Not a test.")

Verify the skipped test is the test_session by running your test with a --verbose flag. You should see an output similar to this:
...
test_session (BoxListOpsTest)
Use cached_session instead. (deprecated) ... skipped 'Not a test.'

Although the test_session is deprecated since 1.11 and should be replaced with cached_session (related commit), as of now, it's not scheduled for removal in 2.0 yet. In order to get rid of it, you can apply custom filter on collected tests.
unittest
You can define a custom load_tests function:
test_cases = (BoxListOpsTest, )

def load_tests(loader, tests, pattern):
    suite = unittest.TestSuite()
    for test_class in test_cases:
        tests = loader.loadTestsFromTestCase(test_class)
        filtered_tests = [t for t in tests if not t.id().endswith('.test_session')]
        suite.addTests(filtered_tests)
    return suite

pytest
Add a custom pytest_collection_modifyitems hook in your conftest.py:
def pytest_collection_modifyitems(session, config, items):
    items[:] = [item for item in items if item.name != 'test_session']


text:
Q: Tkinter drawing on canvas is delayed I am new to tkinter and trying to make a basic drawing app. However, when I move my cursor around, it will sometimes suddenly stop drawing, and then only show the finished line several seconds later. This is shown here.
https://www.youtube.com/edit?video_referrer=watch&video_id=_g8n55V6qPQ
Is this lag? My laptop runs fine otherwise, and it can even 'lag' on the first go (i.e. before there are any other objects on the canvas). If it is just lag, what sort of workarounds do I have in making my python drawing app?
This is my code:
from tkinter import *
root = Tk()
root.title("Note Taking")

can_width = 800
can_height = 800
canvas = Canvas(root, width=can_width, height=can_height, bg='white')
canvas.pack(padx=20, pady=20)

class g():
    points = []
    user_line = None
    drawing = False
    t = 0

def leftClick(event):
    g.points = []
    g.user_line = None
    g.drawing = True
    g.points.append(event.x)
    g.points.append(event.y)

def leftMove(event):
    # Print out an increasing number: t, so I can see it in the output
    print(g.t)
    g.t+=1

    if g.drawing:
        g.points.append(event.x)
        g.points.append(event.y)
        if g.user_line == None:
            g.user_line = canvas.create_line(g.points, width=4, smooth=1)
        else:
            canvas.coords(g.user_line, g.points)

def leftRelease(event):
    g.points = []
    g.user_line = None

canvas.bind('<Button-1>', leftClick)
canvas.bind('<B1-Motion>', leftMove)
canvas.bind('<ButtonRelease-1>', leftRelease)

root.mainloop()


text:
Q: How to get response from server using curl in php i am using CURL to get data from server. The way it works is like the following:

*

*A device send data to routing application which is found on server.

*To get the data from the routing application, clients must ask with GET method specifying server address, port and parameter.

*once a client is connected, the application start sending data on every new packet arrived from the device to connected clients. see below picture

now lets see my code that i run to get the response:
<?php
   $curl = curl_init('http://192.168.1.4/online?user=dneb');
   curl_setopt($curl, CURLOPT_PORT, 1818);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
   $result = curl_exec($curl);
   curl_close($curl);
   echo $result;

With this CURL request i can get the response data from routing application. But the routing application will never stop sending data to connected clients, so i will get the result only if i close the routing application, and it will echo every data as one. Now my question is how can i echo each data without closing the connection or the connection closed by the routing application? i.e When data received, display the data without any conditions. You can suggest any other options to forward this data to another server using TCP. Thanks!

A: a http connection that never close? don't think php's curl bindings are suitable for that. but you could use the socket api,
$sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_set_block($sock);
socket_connect($sock,"192.168.1.4",1818);
$data=implode("\r\n",array(
'GET /online?user=dneb HTTP/1.0',
'Host: 192.168.1.4',
'User-Agent: PHP/'.PHP_VERSION,
'Accept: */*'
))."\r\n\r\n";
socket_write($sock,$data);
while(false!==($read_last=socket_read($sock,1))){
   // do whatever
    echo $read_last;
}
var_dump("socket_read returned false, probably means the connection was closed.",
"socket_last_error: ",
socket_last_error($sock),
"socket_strerror: ",
socket_strerror(socket_last_error($sock))
);
socket_close($sock);

or maybe even http fopen,
$fp=fopen("http://192.168.1.4:1818/online?user=dneb","rb");
stream_set_blocking($fp,1);
while(false!==($read_last=fread($fp,1))){
// do whatever
    echo $read_last;
}
var_dump("fread returned false, probably means the connection was closed, last error: ",error_get_last());
fclose($fp);

(idk if fopen can use other ports than 80. also this won't work if you have allow_url_fopen disabled in php.ini)