text:
Q: Cron configuration without SSH - Magento 1.9.2.4 I'm trying to setup the cronjobs execution as I recently noted issues with the order mails not being sent due to the latest updates of Magento with mail handling.
Specifically, I was trying to get the AOE Scheduler module working, which requires these configurations to be added on the crontab on the server:

My problem is that I have no SSH access. My hosting admin panel offers though a way to execute periodically some URL.
Is there a way to get the cronjobs working through PHP?

A: Calling http://example.com/cron.php via URL is now forbidden by default, but you can enable it.
Here are the relevant lines in .htaccess (read the comments):
###########################################
## Deny access to cron.php
    <Files cron.php>

############################################
## uncomment next lines to enable cron access with base HTTP authorization
## http://httpd.apache.org/docs/2.2/howto/auth.html
##
## Warning: .htpasswd file should be placed somewhere not accessible from the web.
## This is so that folks cannot download the password file.
## For example, if your documents are served out of /usr/local/apache/htdocs
## you might want to put the password file(s) in /usr/local/apache/.

        #AuthName "Cron auth"
        #AuthUserFile ../.htpasswd
        #AuthType basic
        #Require valid-user

############################################

        Order allow,deny
        Deny from all

    </Files>

So you should either make it password protected as described in the comments above, or add an IP whitelist to only allow access from localhost (or the IP which triggers your cronjob)
For example, to allow access from localhost (which should work for you), replace
Deny from all

in your .htaccess file with
Allow from 127.0.0.1

Regarding Aoe_Scheduler: it uses a different script, shell/scheduler.php which is only executable via shell and gets called from scheduler_cron.sh. You could create a wrapper PHP script like this:
<?php
exec('scheduler_cron.sh --mode default');

Save it as /cron_default.php
and set up http://example.com/cron_default.php as URL to be executed. Create multiple scripts if you need different commands, don't pass GET parameters to a shell command.
Also I recommend to add the same protection to these files that Magento applies to cron.php and follow the steps above.
To protect all PHP files that start with "cron", replace
<Files cron.php>
    ...
</Files>

with
<FilesMatch "^cron.*\.php$">
    ...
</FilesMatch>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Path drawing with d3? I'm trying to use d3 to generate path and set color by dataset. Color of path is set by "Req" and drawing path by set of point but i get some parsing problem when getting data back. My data format showed as below.
var feature = {"section":[
  {"ID": 1,"Req": 10,"Name": "Jame","point": [{"x": 1,"y": 1},{"x": 5,"y": 5},{"x": 20,"y": 30},{"x": 200,"y": 200}]},
  {"ID": 2,"Req": 20,"Name": "John","point": [{"x": 1,"y": 1},{"x": 7,"y": 10},{"x": 100,"y": 10},{"x": 20,"y": 200}]}
]};

In order to get coordinate of x and y in dataset,I have function of line generator as following by
var line = d3.svg.line()
     .interpolate("linear")
     .x(function(d) { d.point.forEach(function(a){ return a.x;});})
     .y(function(d) { d.point.forEach(function(a){ return a.y;});});

I set style color of path with value of "Req" in dataset.
canvas.selectAll("path")
    .data(feature.section)
    .enter()
    .append("path")
    .attr("d", line(feature.section))
    .attr("fill", "none")
    .style("stroke", function(d) {
       var returnColor;
       if (d.Req > 5){returnColor ="green";}
       else if (d.Req > 10){returnColor ="purple";}
       else if (d.Req > 15){returnColor ="red";}
       else{returnColor = "#ccc";}
       return returnColor;
    });

But I have no line showed on the screen.  The debugging console always showed Error: Problem parsing d="MNaN,NaNLNaN,NaNLNaN,NaNLNaN,NaNLNaN,NaNLNaN,NaN"
Did I miss something?
You also see my example of this code on http://jsfiddle.net/agadoo/RZQxV/

A: It looks like you're trying to draw several paths, one for each request ID. What you need in this case are nested selections.
To draw a path, you would pass an array to the .data() function and give x and y functions in your d3.svg.line() definition to extract the relevant datum from each element of that array. That is, the functions you specify there should return the x and y coordinates for exactly one point. So you would change them to be something like
.x(function(d) { return d.x; })

I've modified your jsfiddle here. Note that in this scenario you can't get the color for the lines in the same way that you did it anymore because that data is not available at that level. There're several ways to overcome this, the most straightforward is probably to reformat your data. The d3 array functions (in particular the d3.nest() functions) should be helpful here.
On a final note, your checks to set the color of the line won't work as you expect. d.Req > 5 will be true if d.Req > 10, so your second and third conditions will never be met as they are already covered by the first one.


text:
Q: Display aerial photographs interactively in R I have taken aerial photographs with a drone and stitched those together into a .geotiff file, using third party software. I would like to add this file as a layer to an interactive leaflet map, e.g. as produced by mapview. I can produce an interactive map, but this only shows data, e.g. digital elevation not the actual photograph.
.geotiff files aren't very freely available, so see this link for an example file from naturalearth: https://www.naturalearthdata.com/downloads/50m-raster-data/50m-cross-blend-hypso/
library(magrittr)

exmpl <- terra::rast(".\\HYP_50M_SR.tif") %>%
  raster::brick()

mapview::mapview(exmpl)

I am only interested in showing change over time as documented by repeated aerial photography and not interested in extracting data from the raster image. I have previously only worked with vector data, so please go easy on me if this is not a smart question. I like using mapview for it's simplicity, but base leaflet, tmap or any other interactive, R based solution would be fine by me. Thanks a lot!

A: I guess you ar looking for the mapview::viewRGB() function.
Please find below a little reprex.
Reprex
library(mapview)
library(magrittr)

exmpl <- terra::rast(".\\HYP_50M_SR.tif") %>%
  raster::brick()

plotRGB(exmpl)

mapview::viewRGB(exmpl, r = 1, g = 2, b = 3, quantiles = NULL)

Created on 2022-02-10 by the reprex package (v2.0.1)


text:
Q: ConvertPointFromView returning NAN I'm trying to fill my scene with some SKSpriteNode objects. However, inside other views I'm already using these objects as UIImageView's. So I have the normal coordinates and I'm trying to convert to GL coordinates.
I'm doing it like this:
SKSpriteNode *title = [SKSpriteNode spriteNodeWithImageNamed:@"labirinto_title"];
    CGPoint titlePoint = CGPointMake(238.0, 50.0); //coordinates already known.
    NSLog(@"X1: %f, Y1: %f", titlePoint.x, titlePoint.y);
    CGPoint titlePosition = [self convertPointFromView:titlePoint];
    NSLog(@"X: %f, Y: %f", titlePosition.x, titlePosition.y);
    title.position = titlePosition;
    NSLog(@"X: %f, Y: %f", titlePosition.x, titlePosition.y);

Then, the first NSLog is ok, however, the next two NSLogs are printing NAN for x and y values.
Anyone know what is going on here?

A: I guess self is an SKScene.  I suspect that self.view == nil (meaning no SKView is currently presenting self).  The documentation of convertPointFromView: says:

The scene must be presented in a view before calling this method.


text:
Q: Selenium WebDriver - Way to change firefox file save location Is there a way to change the location where firefox saves downloaded files using selenium webdriver?
Anyone have selenium web driver code to change the location where firefox saves the downloaded files?

A: if you know how to use Firefox profiles with custom preferences,
then the setting you are looking is  "browser.download.dir"
fProfile.setPreference("browser.download.dir", @your_dir);

have look at more Firefox download options and other configs @ http://kb.mozillazine.org/About:config_entries


text:
Q: How can I use LaTeX to build my website? Can I use LaTeX to specify cascading style sheet?
Can someone enlighten me something about using LaTeX with my website?
Basically to setup layout like how I do for documents, setting up fonts, spacing etc

A: I agree with what was already said: you won't get the flexibility of manually playing with css, jquery/ajax, etc. However, as far as structured/markup languages are concerned, you may find the following two projects interesting:

*

*AsciiDoc: I used it after having tried reST (though now I'm more and more versed into Markdown); it has html5/tex backend, and can be used for website management.

*plasTeX: I used it for creating a tutorial with html output; it is driven by Python and has support for a templates and themes.

However, note that in general stylesheet as well as layout are specified outside of the core document.

A: This is probably not exactly what you need, but I think it might make an interesting addition to the thread nonetheless. A few weeks ago, I stumbled across pdf2htmlEX, which can convert, as the name implies, pdf files to HTML, while maintaining the typography and layout pretty much intact.
I've tried it with some non-trivial LaTeX-generated pdfs of mine, and the results are truly impressive (they have very nice demos in their project page, too). On the other hand, the HTML markup it produces is heavy and not very editing-friendly. The point is that if you have some part of a site that you'd like to layout/typset with TeX, it is now possible to do so.

A: This is not a particularly good idea. While there are tools to convert LaTeX into HTML/CSS, they give a result that is nowhere near as flexible as you could get with HTML directly or other meta-languages.

A: If you like to use LaTeX equations in your web, you can use MathJax which is commonly used in Wikipedia, arxiv etc. (http://www.mathjax.org/)
You can also use Markdown to format your HTML files quickly if you'd like to create on-line documents. You can also find a collection of tools /web templates etc. for creating online articles here:(http://laplace.phas.ubc.ca/People/arman/sg/)

A: You could also look at Pandoc, which can be used as follows:
pandoc -r latex -w html -o outfile.html infile.tex

This will generate the HTML for you. You will have to specify your own stylesheets, however. Also, Pandoc only supports a subset of LaTeX.

A: LaTeX2HTML is a powerful TeX compiler to directly render a TeX document into HTML.
While installation of LaTeX2HTML involves several intricate steps, it is not impossible. Upon compilation, all necessary pages with the corresponding CSS is also created. Note, that the look of your document on the browser is only as good as you have developed it on TeX.
LaTeX2HTML is by far the best way to put your heavily loaded scientific and mathematical content on the web.


text:
Q: Run apache in default port I have ubuntu 11.04 and my apache was running on localhost but I tried to install varnish and have a ride on varnish . So I followed this tutorial and made changes. But after install I saw apache is not running on localhost. When I gave localhost:8008 it was okay. Now I removed varnish and made changes to the port  8008 to 80, but still apache is running on 8008 port.My default sites configuration is like this
<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride all
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

I just want to run apache in default port.
When I made the apche restart it showed an error like this
[warn] NameVirtualHost *:8008 has no VirtualHosts
httpd (pid 12174) already running

A: Ihis is the file you are looking for:
$ sudo vi /etc/apache2/ports.conf

In this file, change LISTEN 80

A: Somewhere in your Apache config is the line:
Listen 8008

That specifies the port Apache listens on.


text:
Q: Java multiprocessing to replicate Python implementation I've been asked to convert an application (relatively small one) from Python to Java since all the machines in adjacent branches have Java but not Python (and no .exe generator).
The gist of the application is a map that displays lines or polygons based on a variety of user chosen calculations. There is very minimal I/O in the program (at this state) and that which exists sits on a separate thread from the GUI. Currently the calculations are handled via multiprocessing, as there may be as many as 15 "packages" containing 10,000 calculations. Our systems have 32 cores (16 + 16 HTT) and the program was successfully implemented using a method similar to the first answer on this SO post. Essentially, each "package" is put into its own process and a Queue shares the results and the GUI updates.
My Java experience is all CLI based; I've messed around with some sample GUI's (making a button and what have you) but nothing nearly this complex. However, from the SO searching and Google results, it doesnt appear that multiprocessing would be the way to go. In fact, most answers say that multithreading is the way to go. Now, I believe this is where my Python-isms cause me a problem, as in Python the GIL prevents concurrent threads from executing (unless one starts using async implementations) and thus I switch to multiprocessing. I should note that the calculations require little overhead even when using 15 individual cores via the pool.map() method in Python; this implementation was chosen solely for concurrent CPU bound work.
Is my understanding of Python threading (and the terror that is the GIL) causing me unnecessary confusion in Java-land? Do Java threads run concurrently and there is no reason to say pull out 15 ProcessBuilders and run the JVM 15 times on a machine? I'm hoping not, thats a lot of resources!


text:
Q: Trying to repeat the same code for multiple dataframes I have the follwing code that takes a dataframe called dft1 and then produces a resulting dataframe called dfb1. I want to repeat the same code for multiple input dataframes such as dft1, dft2 all indexed by a number towards the end and then store the results using the same pattern i.e. dfb1, dfb2, ....
I have tried many methods such as using dapply or for loops but given the nature of the code inside I wasn't able to get the intended results.

#define the function for rolling

window <- 24
rolling_lm <-
  rollify(.f = function(R_excess, MKT_RF, SMB, HML) {
    lm(R_excess ~ MKT_RF + SMB + HML)
  }, window = window, unlist = FALSE)

#rolling over the variable

dfb1 <-
  dft1 %>%
  mutate(rolling_ff =
           rolling_lm(R_excess,
                      MKT_RF,
                      SMB,
                      HML)) %>%
  mutate(tidied = map(rolling_ff,
                      tidy,
                      conf.int = T)) %>%
  unnest(tidied) %>%
  slice(-1:-23) %>%
  select(date, term, estimate, conf.low, conf.high) %>%
  filter(term != "(Intercept)") %>%
  rename(beta = estimate, factor = term) %>%
  group_by(factor)

A: Add the command you want to apply to each dataframe in a function
apply_fun <- function(df) {
   df %>%
    mutate(rolling_ff =
         rolling_lm(R_excess,
                    MKT_RF,
                    SMB,
                    HML)) %>%
    mutate(tidied = map(rolling_ff,
                    tidy,
                    conf.int = T)) %>%
    unnest(tidied) %>%
    slice(-1:-23) %>%
    select(date, term, estimate, conf.low, conf.high) %>%
    filter(term != "(Intercept)") %>%
    rename(beta = estimate, factor = term) %>%
    group_by(factor)
}

Now apply the function to each dataframe and store the results in a list
n <- 10
out <- setNames(lapply(mget(paste0("dft", 1:n)), apply_fun), paste0("dfb", 1:n))

Assuming you have input dataframes like dft1, dft2...this will output a list of dataframes which you can now access doing out[['dfb1']], out[['dfb2']] and so on. Change the value of n based on number of dft dataframes you have.
If the data is already present in a list we can avoid mget by doing
setNames(lapply(result, apply_fun), paste0("dfb", 1:n))


text:
Q: How can I save jenkins output to file Is anyone able to provide a way to save the jenkins output to a file that can be uploaded to s3 using shell commands and without the post-build plugin?

A: You can use the Curl command to get the console output to a text file and then upload the file to your nexus, in the below example ,in place of last build you can specify the specific build number for which you want the console output.

curl -L http://path-for-jenkins-JOB/lastBuild/consoleText > consoleText.txt


text:
Q: Directives not working in ionic 3 Directive example in ionic 3, method used previously are not working.
Already tried the way in which directives where implemented in ionic 2.
import {Directive} from 'angular2/core';

@Directive({
   selector: 'test',
   template: './test.html'
)}
export class MyDirective { }

import {MyDirective } from './test'

@Page({
   templateUrl: '../page.html',
   directives: [MyDirective ],
})

A: This can be achieved with the following:
ComponentA, parent component
acomponent.ts
import {Component} from '@angular/core';

@Component({
    selector: 'component-a',
    templateUrl: 'acomponent.html'
})
export class ComponentA { }

acomponent.html

Component A

  <component-b></component-b>

bcomponent.ts
import {Component} from '@angular/core';

@Component({
    selector: 'component-b',
    templateUrl: 'bcomponent.html'
})
export class ComponentB { }

bcomponent.html

Component B

app.module.ts
import { ComponentA } from 'pathto/acomponent';
import { ComponentB } from 'pathto/bcomponent';
//other imports here too

@NgModule({
  declarations: [
    ComponentA,
    ComponentB,
    //other declarations
  ],
  imports: [//your imports],
  bootstrap: [IonicApp],
  entryComponents: [
    ComponentA,
    ComponentB,
    //other entryComponents
  ],
  providers: [//your providers]
})
export class AppModule { }

When you navigate to ComponentA it will then inject ComponentB onto the selector <component-b></component-b>
Hopefully this helps


text:
Q: Magento 1.9 and nginx - ssl redirect loop I have a magento 1.9.2.4 installation on nginx server.When I enable SSL for frontend and for backend and now I have this error when I try to access any page in the site: The page isn't redirecting properly.
My db core_config_data is look like in the image:

A: It's better to give a full steps , how to change Magento URL
Check Current Status :
select * from core_config_data where path like '%base%url%';
Update URL :
update core_config_data set value = 'https://domainname/' where path = 'web/unsecure/base_url';
update core_config_data set value = 'https://domainname/' where path = 'web/secure/base_url';
In WebServer :
Please do not close 80 port untill you ensure that no http request is present
another solution add 301 redirect
server {
      listen         80;
      server_name    XXXX.com;
      return         301 https://$server_name$request_uri;
}

Clean Cache :
Disable all cache
Flush Redis if you are using Redis or clean file cache


text:
Q: axios.get not loading correct the first time, but works on refresh I have tried everything for this to load on the first load. I even added the .finally as a desperate measure. I tried async await, but not sure I did that correctly. This is the version that works, but I have to refresh the page as it doesn't load proper the first time. I need this to be vanilla javascript.
axios.get(`https://api.github.com/repos/${orgEl}/${repoEl}/contents/Transactions/${projectJ}/${fundJ}/${poolJ}`)
      .then(response => {
        const data = response.data;
        console.log('data', data);
        for (let j in data) {
          budgetI[j] = data[j].name.replace(/\s/g, '-'); //* over here is the 'budgetI' variable
          axios.get(`https://api.github.com/repos/${orgEl}/${repoEl}/contents/Transactions/${projectJ}/${fundJ}/${poolJ}/${budgetI[j]}`)
          .then(response => {
            const data = response.data;
            for (let m in data) {
              axios.get(data[m].download_url)
              .then(response => {
                const data = response.data;
                bi.push(data);  //* over here is the 'bi' variable
              })
              .catch(error => console.error(error)).finally(() => {
                console.log("first load");
            });
            }
          })
          .catch(error => console.error(error)).finally(() => {
            console.log("mid load");
        });
          }
      })
      .catch(error => console.error(error))
      .finally(() => {
        console.log("final load");
    });

axios.get(`https://pool.pm/wallet/${walletEl}`)
      .then(response => {
        for (let i in bi) {
          y = bi[i].budget.replace(/\s/g, '-')   //* bi value comes from axios.get above
          for (let j in budgetI) {    //* budgetI value comes from axios.get above
            if ( y == budgetI[j]) {
              totals[y] = totals[y] + (parseInt(bi[i].ada));
              totals.outgoing = totals.outgoing + (parseInt(bi[i].ada));
            }
          }
        };

This last axio.get uses the 'budgetI' and 'bi' variables from the top axios.get
As I type this I realize that maybe I should promise.all the first axios.get and the last axios.get . I will try that, but will upload this anyway. Hope someone can show me an easy way of improving this code.

A: Without knowing anything else about your program's, or those GitHub repos', structure, I'd break this down into two async functions:
async function downloadFromDownloadURLs(url) {
  console.log(`==> ${url}`);
  const { data } = await axios.get(url);
  const downloadedData = [];
  for (let key in data) {
    let downloadUrl = data[key].download_url;
    console.log(`--> ${url}`);
    const downloadResponse = await axios.get(downloadUrl);
    downloadedData.push(downloadResponse.data);
  }
  return downloadedData;
}

async function loadData(orgEl, repoEl, projectJ, fundJ, poolJ) {
  let prefixUrl = `https://api.github.com/repos/${orgEl}/${repoEl}/contents/Transactions/${projectJ}/${fundJ}/${poolJ}`;
  const { data } = await axios.get(prefixUrl);
  const allDownloadedData = [];
  for (let dataKey in data) {
    const budget = data[dataKey].name.replace(/\s/g, "-");
    const url = `${prefixUrl}/${budget}`;
    const budgetData = await downloadFromDownloadURLs(url);
    allDownloadedData.push([budget, budgetData]);
  }
  return allDownloadedData;
}


text:
Q: javascript cant get string from textbox i am trying to get date string from Textbox ASP.NET control but with no success.
my code is:
function countdown() {
    now = new Date();
    var biddate = $("#InitiateDate1").val();
    kickoff = Date.parse(biddate);
    diff = kickoff - now;...

A: it's $('<%=InitiateDate1.ClientID%>').val();

A: just try
function countdown() {
    now = new Date();
    var biddate = document.getElementById('<%=InitiateDate1.ClientID%>').value
    kickoff = Date.parse(biddate);


text:
Q: ON DUPLICATE KEY UPDATE every column except I am using mysql through a socket, and I am updating 4000 records therefore I need to mass INSERT / UPDATE them to reduce network lag. The problem is that I have a column datetime_inserted that I want to set as NOW() when a record is first inserted, but never be replaced when it already exists, therefore REPLACE is not an option and I want to update the record, so IGNORE won't work.
I don't really understand the whole ON DUPLICATE KEY UPDATE but I want every column (40 or so) to update EXCEPT for datetime_inserted
How can I do this?

A: INSERT INTO the_table (col1,col2,...,datetime_inserted) VALUES(value1,value2,...,NOW())
ON DUPLICATE KEY UPDATE SET col1=VALUES(col1), col2=VALUES(col2), ... #skip the datetime_inserted for the updates


text:
Q: Splitting polygon with line using ArcPy? In looking at Buffering with physical barrier using ArcGIS for Desktop?, it occurred to me that I am not sure how one would go about using geoprocessing tools in ArcGIS to split a polygon with a line programatically.
Manually, you would use the Cut Polygons tool or the Split Polygons tool on the Topology toolbar, but how would you accomplish the same task using modelbuilder or python groprocessing scripting tools?
Right off the bat I think of all of the tools in the Analysis toobox like Union, Identity, etc, but those are all Polygon-Polygon tools, NOT Polygon-Line tools.  Even the Split tool is Polygon-Polygon.
Any ideas?

A: Using ET Geowizard you can access the code for the Split Polygons with Polylines tool:

Here is the link to the script.
Alternatively, you can use ArcObjects to do this:
Cut Polygon Snippet
You may also use the one side buffer method described here.

A: If you want to go outside of ArcGIS then use geom.splitpolysbylines.
Personally i have never use it in a programme but i think you can access this commondline with python, please see the help for more details.

A: After the fact, I ended up creating my own ModelBuilder tool.  I had forgot about this question and posted my solution to another similar question.  For completeness, this is a repost of the answer:

I thought there must be a way to do this, so I created my what I
  believe to be a pretty good solution. I have posted it on the ArcGIS
  Resources site in the Community->Technical->Analysis &
  Geoprocessing->Analysis->Gallery.
The tool is called Split Polygons With Lines and requires an ArcInfo
  license because of some of the tools used within the model.
  Essentially what I did was create the minimum bounding box for the
  polygons and extend the lines to them. So using some ModelBuilder
  voodoo, I was able to turn the linework into polygons, which then I
  used Identity to split the original polys.
Please test it out and see if it works for you. In my (limited) tests
  it preserved attributes of the original polygons, and split only the
  existing polygons.

A: if you haven't some high accuracy issues , you would buffer the line with the minimum distance for eg (0.002 i think that should be superior than the accuracy of you feature class) , then apply a erase tool to polygon  by the buffered line.

A: Updated arcpy code to split polygons in horizontal or vertical direction using percent values
'''-------------------------------------------------------------------------------------------
 Tool Name:   Polygon Bisector in percent parts
 Source Name: polygonbisector.py and splitPolygonsWithLines
 Version:     ArcGIS 10.0
 Author:      ESRI, Inc.
 Required Arguments:
              Input Features (Feature Layer)
              Output Feature Class (Feature Class)
 Optional Arguments:
              Axis (X|Y)
              Group Field(s) (Field)
              Acceptable Error Percent (Double)

 Description: Computes a line that bisects, or divides in Commulative Percent value, a polygon area along a line
              of constant latitude or longitude. each successive input polygon's area will be
              on either side of the bisecting line.
https://www.arcgis.com/home/item.html?id=9aadb577ccb74f0e88b13a0e3643ca4d
Credits (Attribution)
Esri, Inc. dflater@esri.com

http://www.arcgis.com/home/item.html?id=cd6b2d45df654245b7806a896670a431
Split Polygons using Line features
Shapefile by daltongis
Credits (Attribution)
GIS.StackExchange.com

updated by : Sham Davande, GIS Analyst - sham.davande@gmail.com
-------------------------------------------------------------------------------------------'''

# Import system modules
import arcpy
from arcpy import env
import os
import sys
import math
import time
arcpy.env.overwriteOutput = True

# Change input polygon feature class name and path here
split_poly = "D:\\temp\\polygon2.shp"

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#   Split percent   Commulative Percent value for python code
#   3.7         3.7
#   25.5            29.2
#   20.8            50.0
#   10.5            60.5
#   31.5            92.0
#   8.0

# its cumulative percent values to split polygon with N number percent parts
list = ["3.7","29.2","50.0","60.5","92.0"]

# Set local variables
out_folder_path = "C:\\"
out_name = "temp71"
# Set workspace
env.workspace = "C:\\temp71"

# Execute CreateFolder
arcpy.CreateFolder_management(out_folder_path, out_name)

# Set local variables
out_folder = "C:\\temp71"
out_name = "NewGdb.gdb"
out_name2 = "C:\\temp71\\NewGdb.gdb"
geometry_type = "POLYLINE"
template = ""
has_m = "DISABLED"
has_z = "DISABLED"

# Execute CreateFileGDB
arcpy.CreateFileGDB_management(out_folder, out_name)

percent_lines = "C:\\temp71\\NewGdb.gdb\\line1"
line2 = "C:\\temp71\\NewGdb.gdb\\line2"
line3 = "C:\\temp71\\NewGdb.gdb\\line3"
allLines = "C:\\temp71\\NewGdb.gdb\\all_lines"
outFeatureClass1 = "polygon"
outFeatureClass2 = "C:\\temp71\\NewGdb.gdb\\polygon"
expression = ""

#############################################
# No hard coded input files path mentioned in the code below here after
# and don't want interfere somebodies C:\Temp folder, so C:\temp71 folder automatically created by code below.
#############################################

file_prj1 = os.path.splitext(split_poly)[0]
file_prj2 = str(file_prj1 + ".prj")
out_coordinate_system = str(file_prj2)

# Execute CreateFeatureclass
arcpy.CreateFeatureclass_management(out_name2,"all_lines", "POLYLINE", "", "DISABLED", "DISABLED", out_coordinate_system)
# Execute FeatureClassToFeatureClass
arcpy.FeatureClassToFeatureClass_conversion(split_poly, out_name2,
                                            outFeatureClass1, expression)

for i in list:
    if i > 0:
        percent_area = float(i)

        ith_part = 100/percent_area

        print "Generating a polyline to split a polygon into two horizontal parts of", percent_area, "% and",100-percent_area, "% areas"
        print ith_part, "ith part of polygon"

        schemaType = "NO_TEST"
        fieldMappings = ""
        subtype = ""

        # Main function, all functions run in GravityModel
        def PolygonBisector(in_features, out_fc, axis="x", groupfields=[], error=0.001):
        # Error if sufficient license is not available
            if arcpy.ProductInfo().lower() not in ['arcinfo']:
                arcpy.AddError("An ArcInfo/Advanced license is required.")
                sys.exit()

            # Set geoprocessing environments
            arcpy.env.overwriteOutput = True
            arcpy.env.qualifiedFieldNames = False

            shapefield = arcpy.Describe(in_features).shapeFieldName
            rounder = GetRounder(in_features)

        # If group fields are specified, dissolve by them
            if groupfields:
                in_features = arcpy.management.Dissolve(in_features, "in_memory/grouped", groupfields)
            else:
                groupfields = [arcpy.Describe(in_features).OIDFieldName]
            fields = [shapefield] + groupfields

        # Create output feature class and set up cursor
            icur = irow = scur = None
            arcpy.management.CreateFeatureclass(os.path.dirname(out_fc), os.path.basename(out_fc), "POLYLINE", "", "", "", arcpy.Describe(in_features).spatialReference)
            arcpy.management.AddField(out_fc, "Group_", "TEXT", "", "", "", "Group: {0}".format(", ".join(groupfields)))
            icur = arcpy.InsertCursor(out_fc)
            scur = arcpy.SearchCursor(in_features, "", "", ";".join(fields))
            count = int(arcpy.management.GetCount(in_features).getOutput(0))
            arcpy.SetProgressor("step", "Processing polygons...", 0, count, 1)
            bigi = 1

            # Begin processing
            try:
                for row in scur:
                    minx = miny = float("inf")
                    maxx = maxy = float("-inf")
                    totalarea = 0
                    feat = row.getValue(shapefield)
                    totalarea = row.getValue(shapefield).area
                    group = []
                    for field in groupfields:
                        group.append(str(row.getValue(field)))
                    partnum = 0
                    # Get the min and max X and Y
                    for part in feat:
                        for point in feat.getPart(partnum):
                            if point:
                                minx = point.X if point.X < minx else minx
                                miny = point.Y if point.Y < miny else miny
                                maxx = point.X if point.X > maxx else maxx
                                maxy = point.Y if point.Y > maxy else maxy
                        partnum += 1

                    # Process the polygon
                    # Some variables
                    conditionmet = False
                    difference = 0
                    lastdifference = float("inf")
                    differences = {}
                    itys = {}
                    i = 1
                    strike = 0

                    # The starting bisector (half the distance from min to max)
                    if axis == "x":
                        ity = (miny + maxy)/2.0
                    else:
                        ity = (minx + maxx)/2.0

                    while not conditionmet:
                        # Construct a line through the middle
                        if axis == "x":
                            line = MakeBisector(minx, maxx, ity, in_features, axis)
                        else:
                            line = MakeBisector(miny, maxy, ity, in_features, axis)
                        # The FeatureToPolygon function does not except a geometry object, so make a temporary feature class
                        templine = arcpy.management.CopyFeatures(line, "in_memory/templine")
                        temppoly = arcpy.management.CopyFeatures(feat, "in_memory/temppoly")
                        # Intersect then Feature To Polygon
                        bisected = arcpy.management.FeatureToPolygon([temppoly, templine], "in_memory/bisected")
                        clip = arcpy.analysis.Clip(bisected, in_features, "in_memory/clip")

                        # Group bisected polygons according to above or below the bisector
                        arcpy.management.AddField(clip, "FLAG", "SHORT")
                        ucur = arcpy.UpdateCursor(clip, "", "")
                        flag = 0
                        try:
                            for urow in ucur:
                                ufeat = urow.getValue(arcpy.Describe(clip).shapeFieldName)
                                partnum = 0
                                for upart in ufeat:
                                    for upoint in ufeat.getPart(partnum):
                                        if upoint:
                                            if axis == "x":
                                                if round(upoint.Y, rounder) > round(ity, rounder):
                                                    flag = 1
                                                    break
                                                elif round(upoint.Y, rounder) < round(ity, rounder):
                                                    flag = -1
                                                    break
                                            else:
                                                if round(upoint.X, rounder) > round(ity, rounder):
                                                    flag = 1
                                                    break
                                                elif round(upoint.X, rounder) < round(ity, rounder):
                                                    flag = -1
                                                    break
                                    partnum += 1
                                urow.setValue("FLAG", flag)
                                ucur.updateRow(urow)
                        except:
                            raise
                        finally:
                            if ucur:
                                del ucur

                        # Check if the areas are halved
                        dissolve = arcpy.management.Dissolve(clip, "in_memory/dissolve", "FLAG")
                        scur2 = arcpy.SearchCursor(dissolve)
                        try:
                            for row2 in scur2:
                                firstarea = row2.getValue(arcpy.Describe(dissolve).shapeFieldName).area
                                firstflag = row2.getValue("FLAG")
                                break
                        except:
                            raise
                        finally:
                            if scur2:
                                del scur2

                        difference = abs(firstarea - (totalarea/ith_part))
                        differences[i] = difference
                        itys[i] = ity
                        print round(100*(difference/(totalarea/ith_part)),5)
                        #arcpy.AddWarning(round(100*(difference/(totalarea/ith_part)),5))
                        # Stop if tolerance is achieved
                        if (difference/(totalarea/ith_part))*100 <= error:
                            conditionmet = True
                            break
                        # Moving the line in the wrong direction? due to coordinate system origins or over-compensation
                        if difference > lastdifference:
                            firstflag = firstflag*-1.0
                        # If we're not improving
                        if abs(difference) > min(differences.values()):
                            strike+=1
                        # Or if the same values keep appearing
                        if differences.values().count(difference) > 3 or strike >=3:
                            arcpy.AddWarning("Tolerance could not be achieved. Output will be the closest possible.")
                            # Reconstruct the best line
                            if axis == "x":
                                line = MakeBisector(minx, maxx, itys[min(differences,key = lambda a: differences.get(a))], in_features, axis)
                            else:
                                line = MakeBisector(miny, maxy, itys[min(differences,key = lambda a: differences.get(a))], in_features, axis)
                            break
                        # Otherwise move the bisector so that the areas will be more evenly split
                        else:
                            if firstflag == 1:
                                if axis == "x":
                                    ity = ((ity-miny)/((totalarea/ith_part)/firstarea)) + miny
                                else:
                                    ity = ((ity-minx)/((totalarea/ith_part)/firstarea)) + minx
                            elif firstflag == -1:
                                if axis == "x":
                                    ity = ((ity-miny)*math.sqrt((totalarea/ith_part)/firstarea)) + miny
                                else:
                                    ity = ((ity-minx)*math.sqrt((totalarea/ith_part)/firstarea)) + minx
                            lastdifference = difference
                        i +=1
                    irow = icur.newRow()
                    irow.setValue(arcpy.Describe(out_fc).shapeFieldName, line)
                    irow.setValue("Group_", ", ".join(group))
                    icur.insertRow(irow)
                    arcpy.SetProgressorPosition()
                    arcpy.AddMessage("{0}/{1}".format(bigi, count))
                    bigi +=1

            except:
                if arcpy.Exists(out_fc):
                    arcpy.management.Delete(out_fc)
                raise
            finally:
                if scur:
                    del scur
                    if icur:
                        del icur
                if irow:
                    del irow
                for data in ["in_memory/grouped", temppoly, templine, clip, bisected, dissolve]:
                    if data:
                        try:
                            arcpy.management.Delete(data)
                        except:
                            ""

        def MakeBisector(min,max,constant, templatefc, axis):
            if axis == "x":
                array = arcpy.Array()
                array.add(arcpy.Point(min, constant))
                array.add(arcpy.Point(max, constant))
            else:
                array = arcpy.Array()
                array.add(arcpy.Point(constant, min))
                array.add(arcpy.Point(constant, max))
            line = arcpy.Polyline(array, arcpy.Describe(templatefc).spatialReference)
            return line

        def GetRounder(in_features):
            try:
                unit = arcpy.Describe(in_features).spatialReference.linearUnitName.lower()
            except:
                unit = "dd"
            if unit.find("foot") > -1:
                rounder = 1
            elif unit.find("kilo") > -1:
                rounder = 3
            elif unit.find("meter") > -1:
                rounder = 1
            elif unit.find("mile") > -1:
                rounder = 3
            elif unit.find("dd") > -1:
                rounder = 5
            else:
                rounder = 3
            return rounder

        # Run the script
        if __name__ == '__main__':
            # Get Parameters
            in_features = str(outFeatureClass2)
            out_fc = percent_lines
            axis = arcpy.GetParameterAsText(2).lower() or "x"
            groupfields = arcpy.GetParameterAsText(3).split(";") if arcpy.GetParameterAsText(3) else []
            error = float(arcpy.GetParameter(4)) if arcpy.GetParameter(4) else 0.001
            out_data = line2
            # Run the main script
            PolygonBisector(in_features, out_fc, axis, groupfields, error)
            arcpy.Copy_management(out_fc, out_data)
            # Use Append tool to move features into single dataset
            arcpy.Append_management(out_data, allLines, schemaType, fieldMappings, subtype)
            print "again generating a polyline to split same polygon"
            print ""

        else:
            print "Error"

print "finished"
print ""
print "Splitting polygon using multiple lines generated for a percent area values provided by you..."
def splitPolygonsWithLines(Poly, Lines, LinesQuery="", outPoly=""):
    inputPoly=Poly
    inputLines=Lines
    query=LinesQuery

    inputPolyName=os.path.basename(inputPoly)
    inputLinesName=os.path.basename(inputLines)

    parDir=os.path.abspath(inputPoly+"\..")
    if outPoly=="":
        outputPolyName=os.path.splitext(inputPolyName)[0]+u"_Split"+os.path.splitext(inputPolyName)[1]
        outputPoly=os.path.join(parDir,outputPolyName)
    else:
        outputPolyName=os.path.basename(outPoly)
        outputPoly=outPoly

    sr=arcpy.Describe(inputPoly).spatialReference
    fieldNameIgnore=["SHAPE_Area", "SHAPE_Length"]
    fieldTypeIgnore=["OID", "Geometry"]

    #############################################################################################################################
    arcpy.CreateFeatureclass_management (parDir, outputPolyName, "POLYGON", "", "", "", sr)

    arcpy.AddField_management(outputPoly, "OLD_OID", "LONG")
    for field in arcpy.ListFields(inputPoly):
        if (field.type not in fieldTypeIgnore and field.name not in fieldNameIgnore):
            arcpy.AddField_management (outputPoly, field.name, field.type)

    arcpy.MakeFeatureLayer_management(inputLines,inputLinesName+"Layer",query)
    arcpy.MakeFeatureLayer_management(inputPoly,inputPolyName+"Layer")

    arcpy.SelectLayerByLocation_management(inputPolyName+"Layer","INTERSECT",inputLinesName+"Layer","","NEW_SELECTION")
    arcpy.SelectLayerByAttribute_management(inputPolyName+"Layer", "SWITCH_SELECTION")

    fieldmappings = arcpy.FieldMappings()
    for field in arcpy.ListFields(inputPoly):
        if (field.type not in fieldTypeIgnore and field.name not in fieldNameIgnore):
            fm=arcpy.FieldMap()
            fm.addInputField(outputPoly, field.name)
            fm.addInputField(inputPolyName+"Layer", field.name)

            fm_name = fm.outputField
            fm_name.name = field.name
            fm.outputField = fm_name

            fieldmappings.addFieldMap (fm)

    fm=arcpy.FieldMap()
    fm.addInputField(outputPoly, "OLD_OID")
    fm.addInputField(inputPolyName+"Layer", "OBJECTID")

    fm_name = fm.outputField
    fm_name.name = "OLD_OID"
    fm.outputField = fm_name

    fieldmappings.addFieldMap (fm)

    arcpy.Append_management(inputPolyName+"Layer", outputPoly, "NO_TEST", fieldmappings)

    polySelect=arcpy.SelectLayerByLocation_management(inputPolyName+"Layer","INTERSECT",inputLinesName+"Layer","","NEW_SELECTION")
    lineSelect=arcpy.SelectLayerByLocation_management(inputLinesName+"Layer","INTERSECT",inputPolyName+"Layer","","NEW_SELECTION")
    #############################################################################################################################

    fields=[f.name for f in arcpy.ListFields(inputPoly) if (f.type not in fieldTypeIgnore and f.name not in fieldNameIgnore)]
    fields.append("SHAPE@")
    totalFeatures=int(arcpy.GetCount_management(polySelect).getOutput(0))

    count=0
    timePrev=time.time()
    with arcpy.da.SearchCursor(polySelect,["OID@"]+fields) as curInput:
        for rowInput in curInput:
            linesTemp=arcpy.SelectLayerByLocation_management(lineSelect,"INTERSECT",rowInput[-1],"","NEW_SELECTION")
            geometry=arcpy.CopyFeatures_management(linesTemp,arcpy.Geometry())
            geometry.append(rowInput[-1].boundary())
            arcpy.FeatureToPolygon_management (geometry, "in_memory\polygons_init")
            arcpy.Clip_analysis ("in_memory\polygons_init", rowInput[-1], "in_memory\polygons_clip")
            with arcpy.da.SearchCursor("in_memory\polygons_clip","SHAPE@") as curPoly:
                newGeom=[]
                for rowP in curPoly:
                    if not rowP[0].disjoint(rowInput[-1]):
                        newGeom.append(rowP[0])
            arcpy.Delete_management("in_memory")

            with arcpy.da.InsertCursor(outputPoly, ["OLD_OID"]+fields) as insCur:
                for geom in newGeom:
                    insertFeature=[r for r in rowInput[:-1]]
                    insertFeature.append(geom)
                    insCur.insertRow(insertFeature)
            count+=1
            if int(time.time()-timePrev)%5==0 and int(time.time()-timePrev)>0:
                timePrev=time.time()
                arcpy.AddMessage("\r{0}% done, {1} features processed".format(int(count*100/totalFeatures),int(count)))

def main():
    arcpy.env.overwriteOutput = True
    arcpy.env.XYTolerance = "0.1 Meters"

    inputPoly = arcpy.GetParameterAsText(0) # required
    inputLines = arcpy.GetParameterAsText(1) # required
    linesQuery = arcpy.GetParameterAsText(2) # optional
    outPoly = arcpy.GetParameterAsText(3) # optional

    if inputPoly=="":
        inputPoly=outFeatureClass2
    if arcpy.Exists(inputPoly):
        arcpy.AddMessage("Input polygons: "+inputPoly)
    else:
        arcpy.AddError("Input polygons layer %s is invalid" % (inputPoly))

    if inputLines=="":
        inputLines=allLines
    if arcpy.Exists(inputLines):
        arcpy.AddMessage("Input lines: "+inputPoly)
    else:
        arcpy.AddError("Input lines layer %s is invalid" % (inputLines))

    if linesQuery=="":
        arcpy.AddMessage("Performing without query")

    if outPoly == "":
        arcpy.AddMessage("Output will be created at the same location as input polygons layer is.")

    splitPolygonsWithLines(inputPoly, inputLines, linesQuery, outPoly)

if __name__ == "__main__":
    main()
print ""
print "Done"


text:
Q: MySQL 5.7 - how to get id for a max value and group by query? I work on MySQL 5.7, I want to get the ID and TITLE of the last article for each category. For example I have the following table 'Article':
| ID | TITLE   | DATE       | FK_CATEGORY |
| 1  | title 1 | 2016-10-05 |      1      |
| 2  | title 2 | 2017-10-02 |      1      |
| 3  | title 3 | 2015-10-10 |      2      |
| 4  | title 4 | 2017-04-20 |      2      |
| 5  | title 5 | 2017-04-12 |      3      |

For this example I expect the result to be:
| 2  | title 2 | 2017-10-02 |      1      |
| 4  | title 4 | 2017-04-20 |      2      |
| 5  | title 5 | 2017-04-12 |      3      |

I have tryed this request but it does not work :
SELECT id, title, MAX(date), fk_category
FROM article
GROUP BY fk_category
ORDER BY date DESC

What query do I have to use ?
PS: I do not want to disable ONLY_FULL_GROUP_BY SQL mode

A: Even if you were to disable MySQL's ONLY_FULL_GROUP_BY mode, and your current query were to run, it might not yield the correct results.  Also, you would not be able to port the query to most other databases.  A better approach is to use a subquery which finds the most recent date for each category.  Then, join article to this subquery to get the result set you want.
    SELECT t1.*
    FROM article t1
    INNER JOIN
    (
        SELECT FK_CATEGORY, MAX(DATE) AS MAX_DATE
        FROM article
        GROUP BY FK_CATEGORY
    ) t2
        ON t1.FK_CATEGORY = t2.FK_CATEGORY AND
           t1.DATE        = t2.MAX_DATE
    ORDER BY date DESC

A: The only way is to join the table back, something like:
select a.id, a.date, a.title, a.fk_category
from article a
join
(
SELECT id, MAX(date) as date, fk_category
FROM article
GROUP BY fk_category
) x using (id, date, fk_category)
ORDER BY a.date DESC;


text:
Q: How can I dynamically change the XML structure of a string in SQL I need a SQL script that will to pull an XML string from the DB [varchar(max)], inspect it, and update it if it fits a specific situation.
Imagine that my xml is in the following format:
<root>
  <level1>
    <level2>
      <level3 />
      <level3 />
    </level2>
  </level1>
  <level1>
    <level2>
      <level3>
        <level4>
          <level5>
            <level6 here="now is the time for XYZ">
              <options>
                <option this="that" />
                <option me="you" />
              </options>
            </level6>
          </level5>
        </level4>
      </level3>
    </level2>
  </level1>
  <level1>
    <level2>
      <level3>
        <level4>
          <level5>
            <level6 here="this one is not of interest">
              <options>
                <option this="that" />
                <option me="you" />
              </options>
            </level6>
          </level5>
        </level4>
      </level3>
    </level2>
  </level1>
  <level1>
    <level2>
      <level3>
        <level4>
          <level5>
            <level6 here="now is the time for ABC">
              <options>
                <option this="that" />
                <option me="you" />
                <option here="now" />
              </options>
            </level6>
          </level5>
        </level4>
      </level3>
    </level2>
  </level1>
</root>

So, what I want to do is to update all elements whose name is "level6" and which have an attribute called "here" whose value begins with "now is the time".  So, that should match just two elements above.
But, that's not the only selection criteria.  The list of options must not contain <option here="now" />.  So, that should leave us with just one element to update.
<level6 here="now is the time for XYZ">
    <options>
        <option this="that" />
        <option me="you" />
    </options>
 </level6>

To that element, I then want to add the missing <option here="now" />, so that becomes:
<level6 here="now is the time for XYZ">
    <options>
        <option this="that" />
        <option me="you" />
        <option here="now" />
    </options>
 </level6>

So, the end result should be:
 <root>
  <level1>
    <level2>
      <level3 />
      <level3 />
    </level2>
  </level1>
  <level1>
    <level2>
      <level3>
        <level4>
          <level5>
            <level6 here="now is the time for XYZ">
              <options>
                <option this="that" />
                <option me="you" />
                <option here="now" />      // <- this one new
              </options>
            </level6>
          </level5>
        </level4>
      </level3>
    </level2>
  </level1>
  <level1>
    <level2>
      <level3>
        <level4>
          <level5>
            <level6 here="this one is not of interest">
              <options>
                <option this="that" />
                <option me="you" />
              </options>
            </level6>
          </level5>
        </level4>
      </level3>
    </level2>
  </level1>
  <level1>
    <level2>
      <level3>
        <level4>
          <level5>
            <level6 here="now is the time for ABC">
              <options>
                <option this="that" />
                <option me="you" />
                <option here="now" />
              </options>
            </level6>
          </level5>
        </level4>
      </level3>
    </level2>
  </level1>
</root>

Assume that I can read the data out of the DB into a string, and that I know how to update the DB, so it's really how to manipulate the xml string in SQL (SQL Server).

A: You can use XML DML (data modification) with the .modify function to change the XML.
SET @xml.modify('
  insert <option here="now" />
  as last into
  ( /root/level1/level2/level3/level4/level5/level6
     [substring(@here, 1, 15) = "now is the time"]
     /options [not(/option[@here = "now"])]
   )[1]');

This works as follows:

*

*insert <option here="now" /> this is the value we are inserting

*as last into it goes after other child nodes of the selected one

*/root/level1/level2/level3/level4/level5/level6 this gets us that level6 node

*[substring(@here, 1, 15) = "now is the time"] predicates the node to have a here attribute starting with that value. You must modify the length parameter to match the value you are comparing. There is no LIKE in XQuery

*/options [not(/option[@here = "now"])] we look for an options node which has no option child which in turn has a here="now" attribute

*[1] the first such node

If you need to modify multiple nodes within a single XML document, you need to run this in loop
DECLARE @i int = 20; --max nodes

WHILE @xml.exist('
  /root/level1/level2/level3/level4/level5/level6
     [substring(@here, 1, 15) = "now is the time"]
     /options [not(option[@here = "now"])]
   ') = 1
BEGIN

    SET @xml.modify('
      insert <option here="now" /> as last into
      ( /root/level1/level2/level3/level4/level5/level6
         [substring(@here, 1, 15) = "now is the time"]
         /options [not(option[@here = "now"])]
       )[1]');

    SET @i -= 1;
    IF @i = 0
        BREAK;
END;

You can also do this for a whole table
DECLARE @i int = 20; --max nodes

WHILE EXISTS (SELECT 1
    FROM YourTable
    WHERE XmlColumn.exist('
      /root/level1/level2/level3/level4/level5/level6
         [substring(@here, 1, 15) = "now is the time"]
         /options [not(option[@here = "now"])]
       ') = 1)
BEGIN

    UPDATE t
    SET XmlColumn.modify('
      insert <option here="now" /> as last into
      ( /root/level1/level2/level3/level4/level5/level6
         [substring(@here, 1, 15) = "now is the time"]
         /options [not(option[@here = "now"])]
       )[1]')
    FROM YourTable t
    WHERE XmlColumn.exist('
      /root/level1/level2/level3/level4/level5/level6
         [substring(@here, 1, 15) = "now is the time"]
         /options [not(option[@here = "now"])]
       ') = 1;

    SET @i -= 1;
    IF @i = 0
        BREAK;
END;

For very large datasets it may be faster to rebuild the whole XML using XQuery, with the extra node added using Constructed XML.
db<>fiddle


text:
Q: Need to get custom checkbox columns to work in KoGrid I am trying to display a KoGrid that contains some basic show data. The grid has an embedded checkbox that tells whether or not the show is a movie, and another embedded checkbox that tells whether or not the show is a cartoon. The Javascript for this grid, in a file called testgrid.js,  is provided below:
var theList = [
               { isMovie: false, isCartoon: true, name: "Johnny Quest" },
               { isMovie: true, isCartoon: true, name: "Heavy Metal" },
               { isMovie: true, isCartoon: false, name: "Star Wars Rogue One" },
               { isMovie: false, isCartoon: false, name: "The Invaders" },
               { isMovie: true, isCartoon: false, name: "Star Trek: The Voyage Home" },
               { isMovie: false, isCartoon: true, name: "Space Ghost" },
               { isMovie: false, isCartoon: false, name: "Star Trek Classic" },
               { isMovie: false, isCartoon: false, name: "Lost In Space" },
               { isMovie: false, isCartoon: true, name: "Bugs Bunny/Road Runner Hour" },
           ];

var showTitles = [
              {field: 'isMovie',displayName: 'Movie',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: theData.isMovie' />"},
              {field: 'isCartoon',displayName: 'Cartoon',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: theData.isCartoon' />"},
              {field: 'name',displayName: 'Show Name',width: '78%'},
          ];

var TestModel = function() {
  var self = this;

  self.theData = ko.observableArray(theList);
  self.selectShow = ko.observableArray([]);

  self.instantiateSelf = function() {
       ko.applyBindings(theModel);
   }

  self.listOptions = {
      afterSelectionChange: function () { alert("Show Selected: "+selectShow()[0]); },
      data: self.theData,
      selectedItems: self.selectShow,
      displaySelectionCheckbox: false,
      multiSelect: false,
      columnDefs: showTitles
  }
}
var theModel = new TestModel();

The HTML that I am using is provided below:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
   <title>Grid Test</title>
   <link href="lstyles.css" rel="stylesheet" type="text/css">
   <link href="KoGrid.css" rel="stylesheet" type="text/css">

The grid does not display. What displays looks like a part of a grid display but nothing appears.
I did some troubleshooting. I have discovered that the problem is n the "data-bind" statements in the cellTemplate definition that I provide for the checkboxes in the showTitles object in testgrid.js. If I remove these statements, the grid displays, but I cannot check or uncheck the checkboxes, and I cannot get the state of the checkboxes.
Is there some way to get these checkboxes to work properly in a kogrid? How do I get one to bind to the boolean that they are assigned to?
Someone please advise.
For completeness, below is the stylesheet, called lstyles.css:
#lstStyle {
   border: 4px solid #0055AA;
   width: 100%;
   height: 400px;
   float: left;
}

.grpcheck {
   position:relative;
   top: 10px;
   left: 10px;
}

Checkbox problems, continued
Thanks to donMateo, I made some changes that allowed me to display the grid. Once I was able to get it displayed, I began clicking on the checkboxes to see if they would work. They do not -- or, rather, they do not work the way I was hoping they would.
Problem 1:
The first thing I noticed was that the checkbox states do not reflect the data they are bound to. Regardless of the value of isMovie and isCartoon, the checkboxes for each show appear unchecked. For example: Johnny Quest has isCartoon set to "true". The list shows that box as unchecked. Star Wars Rogue One has isMovie set to true. Its isMovie box is unchecked. Figure 1 shows what I am seeing.
NOTE: The image embedding on this site is not working. Even linking the images seems to be broken. I am providing straight HTTP links to my site hoping they will be sufficient to illustrate.
I changed my selection code so that it calls a function that displays an alert box showing the values of the show name, the isMovie value, and the isCartoon value. Selecting Johnny Quest, I see that the isMovie and isCartoon values are correct. So my first problem is: why aren't the checkboxes reflecting the values of their data?
Problem 2:
Another problem I found was that when I click on a checkbox, it doesn't appear to retain the change I make. Figure 2 shows what happens when I click on Johnny Quest's isMovie checkbox. Note that the checkbox is checked, but the alert box still shows the isMovie value as false. Note please that the alert is shown after the checkbox changes state.
When I click on the Alert Box's "OK" button, note in Figure 3 how the checkbox goes back to an "unchecked" state. In fact, the only reason we see the checked box in Figure 2 is because of the delay caused by the alert box! I know this because as an experiment I temporarily removed the alert box, refreshed the browser, and clicked on the Movie checkbox for Johnny Quest. There was a brief indication of the checkbox being pressed, then the checkbox went back to being unchecked. So my second problem is: why doesn't the checkbox display the appropriate change when checked or unchecked?
Problem 3:
The third and most disturbing thing I discovered is that there apparently is a change of state for the checkboxes -- but it doesn't show that change and (worse) it doesn't cause the changes one would expect. This can be demonstrated by causing a redisplay of the data in the grid, in my case by sorting the data.
When I start up the grid, the order in which the shows are displayed is the order shown in Figure 1. If I click on the "Show Name" column, the sorted list looks like Figure 4.
I then click on the Johnny Quest movie checkbox, get the alert box, click Ok. Figure 5 shows how the checkbox is still unchanged.
Now when I hit the "Show Name" column again, in order to do a reverse sort, note what happens to all the movie checkboxes in Figure 6!
The same thing happens to the cartoon checkboxes. Click on one, click Ok on the alert box, then do a resort. All cartoon checkboxes will be checked.
To uncheck them, just click on a checked box, note the incorrect status shown in the alert box, click on Ok, then resort. All the boxes will be unchecked.
So my third problem is: what is the link between the checkboxes in the different rows? More important: how do I sever this link???
Summary:
The KoGrod is really screwed up when it comes to putting controls in custom columns. For checkboxes: the data shown by a checkbox is not in sync with the individual data setting that is is supposedly bound to. Attempting to change the checked status of the chekbox does not work, and changing one checkbox cuses all of them to change -- but you do not see that change until you redraw the grid (using sorting or, possibly, scrolling or paging).
This leads to a question: is the cell template intended to just be a display template for a grid? Is the koGrid even capable of properly handling custom columns that contain controls? If so, how? Of not, then where can I find a grid control that can?
Someone please advise.
The current testgrid.js is provided below. No other files have been changed.
var theList = [
               { isMovie: false, isCartoon: true, name: "Johnny Quest" },
               { isMovie: true, isCartoon: true, name: "Heavy Metal" },
               { isMovie: true, isCartoon: false, name: "Star Wars Rogue One" },
               { isMovie: false, isCartoon: false, name: "The Invaders" },
               { isMovie: true, isCartoon: false, name: "Star Trek: The Voyage Home" },
               { isMovie: false, isCartoon: true, name: "Space Ghost" },
               { isMovie: false, isCartoon: false, name: "Star Trek Classic" },
               { isMovie: false, isCartoon: false, name: "Lost In Space" },
               { isMovie: false, isCartoon: true, name: "Bugs Bunny/Road Runner Hour" },
           ];

var showTitles = [
              {field: 'isMovie',displayName: 'Movie',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: $data.isMovie' />"},
              {field: 'isCartoon',displayName: 'Cartoon',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: $data.isCartoon' />"},
              {field: 'name',displayName: 'Show Name',width: '78%'},
          ];

var TestModel = function() {
   var self = this;

   self.theData = ko.observableArray(theList);
   self.selectShow = ko.observableArray([]);

   self.instantiateSelf = function() {
        ko.applyBindings(theModel);
   }

   self.displaySelect = function() {
      alert("Show Selected: "+self.selectShow()[0].name+" Movie: "+self.selectShow()[0].isMovie+" Cartoon: "+self.selectShow()[0].isCartoon);
   }

   self.listOptions = {
        afterSelectionChange: function () { self.displaySelect(); },
        data: self.theData,
        selectedItems: self.selectShow,
        displaySelectionCheckbox: false,
        multiSelect: false,
        columnDefs: showTitles
   }
}
var theModel = new TestModel();

A: here is your "repaired" code:
var theList = [
           { isMovie: false, isCartoon: true, name: "Johnny Quest" },
           { isMovie: true, isCartoon: true, name: "Heavy Metal" },
           { isMovie: true, isCartoon: false, name: "Star Wars Rogue One" },
           { isMovie: false, isCartoon: false, name: "The Invaders" },
           { isMovie: true, isCartoon: false, name: "Star Trek: The Voyage Home" },
           { isMovie: false, isCartoon: true, name: "Space Ghost" },
           { isMovie: false, isCartoon: false, name: "Star Trek Classic" },
           { isMovie: false, isCartoon: false, name: "Lost In Space" },
           { isMovie: false, isCartoon: true, name: "Bugs Bunny/Road Runner Hour" },
       ];
var showTitles = [
          {field: 'isMovie',displayName: 'Movie',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: $data.isMovie' />"},
          {field: 'isCartoon',displayName: 'Cartoon',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: $data.isCartoon' />"},
          {field: 'name',displayName: 'Show Name',width: '78%'},
      ];
var showTitles = [
          {field: 'isMovie',displayName: 'Movie',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: $data.isMovie' />"},
          {field: 'isCartoon',displayName: 'Cartoon',width: '10%',cellTemplate: "<input type='checkbox' class='grpcheck' data-bind='checked: $data.isCartoon' />"},
          {field: 'name',displayName: 'Show Name',width: '78%'},
      ];
var TestModel = function() {
var self = this;

self.theData = ko.observableArray(theList);
self.selectShow = ko.observableArray([]);

self.instantiateSelf = function() {
   ko.applyBindings(theModel);
}

self.listOptions = {
  afterSelectionChange: function () { alert("Show Selected: "+self.selectShow()[0].name); },
  data: self.theData,
  selectedItems: self.selectShow,
  displaySelectionCheckbox: false,
  multiSelect: false,
  columnDefs: showTitles
}
}

The problem was "theData" which was undefined property of record. Had to change it to $data.
And in select handler add self. in alert.


text:
Q: Basel problem, but with cosines I found a formula in a book
$ \sum_{n=1}^{\infty} \frac{(\cos (\pi n s) - \cos (\pi n s'))^2}{n^2} = \frac{\pi^2}{2} |s-s'|$
but no explanation of where it came from. I checked that it holds true numerically. I wondered whether this series has a name and where could I find more information about it. It looks like some variant of the Basel problem, but other than that I'm clueless. Thanks!

A: Upon expanding the square, the numerator comes down to
$$(\cos(\pi ns)-\cos(\pi ns'))^2=\cos^2(\pi ns)+\cos^2(\pi ns')-2\cos(\pi ns)\cos(\pi ns')$$
Using trigonometric identities, this further reduces down to
$$=\frac12\cos(2\pi ns)+\frac12\cos(2\pi ns')+1-\cos(\pi n(s+s'))-\cos(\pi n(s-s'))$$
We may then apply the Clausen function to deduce that (refer to formula 7)
$$\sum_{n=1}^\infty\frac{\frac12\cos(2\pi ns)+\frac12\cos(2\pi ns')+1-\cos(\pi n(s+s'))-\cos(\pi n(s-s'))}{n^2}\\=\frac12\operatorname C_2(2\pi s)+\frac12\operatorname C_2(2\pi s')+\frac{\pi^2}6-\operatorname C_2(\pi(s+s'))-\operatorname C_2(\pi(s-s'))\\=\pi^2\left(\frac1{12}-\frac12s+\frac12s^2+\frac1{12}-\frac12s'+\frac12s'^2+\frac16-\frac16+\frac12(s+s')-\frac14(s+s')^2-\frac16+\frac12(s-s')-\frac14(s-s')^2\right)\\=\frac{\pi^2}2\left(s-s'\right)$$
assuming that $0\le s\le1$ and $0\le s'\le1$.


text:
Q: First-order nonlinear non-homogeneous ODE with multiple functions I have an equation of the form
$$A(x) = f(y_1, y_2)y_1' + g(y_1, y_2)y_2'$$
where $A(x)$ is an arbitrary function of $x$; $y_i\equiv y_i(x)$ are arbitrary functions of $x$; and $f$ and $g$ are functions of $y_i$.
I am confident that this is a first order differential equation since the maximum derivative of $x$ is to the first order. Also, I believe that this is non-linear since the derivatives of $y_i$ are multiplied by functions of $y_i$. Finally I believe that it is non-homogeneous since there is a function of $x$ involved.
The aim of what I am trying to do is solve this for $y_1$ since $y_2$ is known (although can still be considered arbitrary for my particular case)
I would be grateful for the following help:

*

*Have I classified the differential equation correctly? (and if not why not)

*How do you solve this differential equation?

*How do you create an expression to evaluate $y_1(x)$


text:
Q: Spring Boot Cache Redis + Jackson. Serialize value as JSON. Cannot read - no session Using spring boot latest with jpa + caching. For caching used Redis.
pom looks like this:
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

I'm storing a history record in cache, which has the next structure:
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@Entity
@Table(name = "entity1")
@ToString
public class Entity1 implements Serializable {

    @Id
    @Builder.Default
    private String id = UUID.randomUUID().toString();

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "parentId")
    @Builder.Default
    private List<Entity1Entry> history = new ArrayList<>();

    @Temporal(TemporalType.TIMESTAMP)
    @Builder.Default
    private Date created = new Date();

    @Temporal(TemporalType.TIMESTAMP)
    @Builder.Default
    private Date updated = new Date();
}

Decided to try if I could change things from Serializable to JSON and got stuck at that.
My config:
@Configuration
public class RedisConfig {

        @Bean
    public CacheManager redisCacheManager(@Value("${spring.cache.ttl}") Integer ttl,
                                          RedisConnectionFactory redisConnectionFactory) {
        RedisCacheManager cacheManager =  RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(redisConnectionFactory)
                .cacheDefaults(
                        RedisCacheConfiguration.defaultCacheConfig()
                                .entryTtl(Duration.ofDays(ttl))
//                                .serializeValuesWith(getJsonSerializer())
                                .disableCachingNullValues()
                )
                .transactionAware()
                .build();
        return cacheManager;

    }
    @Bean
    public RedisCacheConfiguration defaultCacheConfig() {
        return RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
//                .serializeValuesWith(getJsonSerializer())
                .entryTtl(Duration.ofDays(7))
                ;
    }

    private RedisSerializationContext.SerializationPair getJsonSerializer() {
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = genericJackson2JsonRedisSerializer();
        return RedisSerializationContext.SerializationPair.fromSerializer(jsonRedisSerializer);
    }

    private GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer() {
        ObjectMapper objectMapper = objectMapper();
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }

    private ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        objectMapper.registerModule(new Hibernate5Module());
        return objectMapper;
    }
}

Ignore the commented out parts to be commented out - it been a 3 hour fight so far, so I'm trying everything.
The problem I'm getting is that I can't read the record from @Cacheable, always failing with a Could not read JSON: No session when trying to read the Entity1 with its list entity.
Any ideas?


text:
Q: Do the relations in a group carry forward to a subgroup? If $G=\langle\, S\,|\,R\, \rangle$ is a finitely presented group and $H=\langle\, S'\,|\,R'\,\rangle$ is a group with generating set $S'\subseteq G$ then does that make $H$ a subgroup of $G$?
Also, If $H$ is a subgroup of $G$ then do the generators of $H$ satisfy the relations of $G$ as well? Let me give an example :
Let $G=\langle\, s_i:1\leq i\leq 4\,|\, s_i^2=1 \text{ for all }i \text{ and } (s_1s_2)^2=(s_1s_4)^2=(s_2s_3)^2=(s_3s_4)^2=1\rangle$
Let $H=\langle\, a,b\,|\,ab^{-1}a^{-1}b^{-1}=1\,\rangle$ where $a=s_3s_1$ and $b=s_4s_2$.

*

*Is $H$ a subgroup of $G$ above?

*If so, can we say $ab=s_3s_1s_4s_2=s_3s_4s_1s_2=s_4s_3s_2s_1=s_4s_2s_3s_1=ba$. This means that $H$ should also have the relation $aba^{-1}b^{-1}=1$? This seems wrong to me.

Could someone please clarify what is wrong?
Thank you.

A: When forming the group $H=\langle S'|R'\rangle$, you only consider $S'$ as a set. In particular, you forget that $S'$ is a subset of a group, and thus that there are some operations you can do with its elements. So $H$ has no reason in general to be a subset of $G$.
So in your example, when you consider the group $H=\langle a,b |ab^{-1}a^{-1}b^{-1}\rangle $, you don't actually care about who $a$ and $b$ are, so $H$ has no relation with $G$.
On the other hand, if $H$ is really a subgroup of $G$, then any relation that holds in $G$ will of course still hold in $H$.

A: There are two notions of relations in groups: one is defining relations, and other is called laws that group can satisfy.
Every group $G$ can be written in form $F(X)/N$, where $F(X)$ is a free group on $X$ — some generating set for $G$, and $N$ is the kernel of surjection $\pi: F(X) \to G$. Defining relations $R$ for given $\pi$ is some subset of $N$ such that $N$ is the minimal normal subgroup of $F(X)$ containing $R$, called the normal closure of $R$ in $F(X)$ They are not determined uniquely: from $R$ you can produce $R'$ changing one of its elements to its inverse or multiplying one by another. Their normal closures, of course, will be same.
Laws in group $G$ (more generally, in some class of groups) are different thing: they are words in (infinite) alphabet (alternatively, elements of free group with countable number of generators) with the property that for every homomorphism to $G$ (to every group in class respectively) they fall into its kernel. Typical examples are

*

*$[x, y] := x^{-1}y^{-1}xy$: group satisfying this law is abelian

*$[xy, z][yz, x][zx, y]$: this law holds in every group (i. e. reduced word corresponding to it is empty)

*$[[x, y], z][[y, z], x][[z, x], y]$: this law holds in groups with abelian commutator subgroup

As it follows from definition, if a law holds in $G$, then it holds in every factorgroup and subgroup of $G$. Somewhat less trivial result is that if a law
holds in $G$ and $H$, then in holds in $G \times H$. Conversely, Birkhoff theorem states that every collection of groups closed under passing to subgroups, factors and products is defined by some set of laws.
You can look at two groups: one is $\langle x, y \, | \, x^2, y^2 \rangle$, the infinite dihedral group, and second is $\langle x, y \, | \, g^2 = 1 \,$for every$\, g \rangle$, which is isomorphic to $\mathbb Z / 2 \times \mathbb Z / 2$. Contemplating a bit on this may help.


text:
Q: Why can I not import Tensorflow.contrib I get an error of No module named 'tensorflow.python.saved Hi I just installed Tensorflow on my Mac and I want to use tf.contrib.slim but when I use it I get this
import tensorflow as tf

slim = tf.contrib.slim

Error:

File
  "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow_estimator/python/estimator/export/export_lib.py", line 25, in
      from tensorflow.python.saved_model.model_utils import build_all_signature_defs ModuleNotFoundError: No module named
  'tensorflow.python.saved_model.model_utils'

I don't know what to do, please help me
I use Tensorflow.13.1 and python 3.7

A: If the following command doesn't work
pip3 install tensorflow==1.14.0

then we can try the following command
pip3 install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.14.0-py3-none-any.whl

A: For anyone who is trying some old codes from github with Tensorflow 1.x.x versions while having Tensorflow 2.0.x please note that tf.contrib no longer exist in Tensorflow 2.0.x and it's modules were moved.
Please google the name of the module without the tf.contrib part to know it's new location and thus migrating your code accordingly by correcting the import statement.
Hope this helped!

A: I solved this by below method.
  pip uninstall tensorflow_estimator
  pip install tensorflow_estimator

the reference is : https://github.com/tensorflow/tensorflow/issues/27079

A: Currently the default install of tensorflow is 2.x while your code is for 1.x.
The contrib module has been removed from tf 2.x. Check the warnings:
"The TensorFlow contrib module will not be included in TensorFlow 2.0"
Uninstall tensorflow and then install the 1.x version with
pip install tensorflow==1.15

A: first unistall tensorflow
pip uninstall tensorflow

then install 1.13.2 version
pip install tensorflow==1.13.2

it works.. had the same issue.. but installing tensorflow 1.13.2 solved it!
the newer version of tensorflow doesn't have

A: tf.contrib has moved out of TF starting TF 2.0 alpha.
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

A: As suggested in the Migration Guide from TensorFlow 1.x to TensorFlow 2 page, install TF-Slim, available on Google-research Github page and then use
import tf_slim as slim

instead of tf.contrib.layers

A: first:
pip install --upgrade tf_slim

then:
import tf_slim as slim

A: I solved this using following steps:
First i do check current version of my tf
using
import tensorflow
print(tensorflow.__version__)

2.5.0

Then contrib is part of older version of tensorflow as it removed from 2.X.
so we need to use tf version 1.X
that will be done using following snippet
%tensorflow_version 1.x
import tensorflow
print(tensorflow.__version__)

and you will get output
**TensorFlow 1.x selected.
1.15.2**

now you can use
from tensorflow.contrib import seq2seq
from tensorflow.contrib.rnn import DropoutWrapper

A: Editing the code may be a bit tedious but if you are willing to make the effort - just add this in all tensorflow links
compat.v1

so tf.assign -> tf.compat.v1.assign
etc

A: Contrib has been taken from tensorflow in 2.x version we have to switch to an older version.
If you are using in collab you can directly switch from 2.x version to 1.x with this command
%tensorflow_version 1.x
Doing this solved the problem.
Apart from collab you can just uninstall your current version and install 1.15.2 with the following commands.
pip uninstall tensorflow
pip install tensorflow==1.15.2

A: As mentioned in the answers, tensorflow.contrib is not supported in tensorflow 2. I fixed the problem with creating an environment in conda with its python version set to 3.7 and setting tensorflow version to 1.14. You may face a one or two bugs related to package compatibility but eventually it'll work.

A: In GoogleColab try:
%tensorflow_version 1.x
and
!pip install q keras==2.0.5
then restart run time.

A: I think majority of solution is suggesting to downgrade tensorflow version. At first place why does TF 2 does not support WALS factorization?One blog suggest its because official recommendataion is NCF Matrix Factorization in tensorflow 2.0 using WALS Method.

A: Starting from tensorflow 13.1 there's no contrib. You can use without it slim = tf.slim or you can install pip install tensorflow==1.13 and use it

A: for running it on python3 I used pip3 to install
pip3 install tensorflow

This worked for me


text:
Q: Permutation and combinations using chairs? After reading and watching a lot about permutation, combination and variation i still don't understand them fully. So i have two questions:

*

*How many ways are there to position 5 people on 10 chairs?

*How many wars are there to position 10 people on 5 chairs?

Please include solving so i can learn from it.

A:
How many ways are there to position $5$ people on $10$ chairs?

We have 10 chairs and $5$ people to be seated. So the answer is ${ 10 \choose 5}$ to select which chairs people will be seated on. If the order matters, you will need to multiply that by $5!$ which is the number of ways that people can be arranged among themselves.
$$ \binom{10}{5} \times 5! = 252 \times 120 = 30240$$
Here $\binom{n}{k}$ is the binomial coefficient which denotes the number of ways to choose $k$ objects from a collection of $n$ distinct objects.
The number $\binom{n}{k} \times k!$ is also denoted as $^nP_k$.

How many wars are there to position $10$ people on $5$ chairs?

We have $5$ empty slots where people could be seated __ __ __ __ __ For the first one, any of the $10$ people could seat, then $9$ people are left to be seated on the second chair, the third now has $8$ choices, leaving $7$ choices for the fourth chair, and finally $6$ for the fifth chair.
By the fundamental principle of counting, there are a total of $10*9*8*7*6 = 30240$ different seating arrangements.

A: *

*First man has $10$ choises, then second one $9$ and so on... we get $10\cdot 9\cdot 8\cdot 7 \cdot 6$ ways to arrange $5$ people if we have $10$ chairs.

*We first choose $5$ people among $10$ which are going to be sited, this we can do on ${10\choose 5}$ ways, then we arrange this 5 people on $5!$ ways. So we have $${10\choose 5}\cdot 5!$$
ways $10$ people to be sited.


text:
Q: Unsupported major.minor version 52.0, java 7 I have an web app, with spring,thymeleaf,hibernate and java 7. My pom have the following added dependencies:
   <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.transaction</groupId>
            <artifactId>jboss-transaction-api_1.1_spec</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.2.11.Final</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>4.0</version>
        </dependency>

My persistence.xml is the following:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="unidadPersistencia" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
         <class>es.xunta.amtega.vp301b.entity.SolicitudTelematica</class>
         <class>es.xunta.amtega.vp301b.entity.ProcedimientoAsociado</class>
         <class>es.xunta.amtega.vp301b.entity.DocumentacionAdjunta</class>
         <class>es.xunta.amtega.vp301b.entity.BandejaSalida</class>
         <class>es.xunta.amtega.vp301b.entity.SolicitudCampamentos</class>
         <class>es.xunta.amtega.vp301b.entity.SolicitudCampamentosResultas</class>
         <class>es.xunta.amtega.vp301b.entity.SolicitudCampamentosUrgencia</class>
         <properties>
            <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/><!-- QUE DRIVER USA -->
            <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://10.199.247.82:1433;databaseName=AvanteDXXS_Pruebas"/>
            <property name="javax.persistence.jdbc.user" value="******"/>
            <property name="javax.persistence.jdbc.password" value="*******"/>
         </properties>
    </persistence-unit>
</persistence>

And when i run the jboss server i obtain the error java.lang.UnsupportedClassVersionError: org/hibernate/jpa/HibernatePersistenceProvider : Unsupported major.minor version 52.0 but if i change the hibernate.entitymanager version to a previous one, i obtain PersistenceProvider not found 'org.hibernate.jpa.HibernatePersistenceProvider'


text:
Q: URL query (get parameters like ?id=5) redirecting with mod_rewrite in htaccess My current htaccess looks like
DirectoryIndex welcome.do index.jsp default.php index.wml homepage.php default.htm default.html index.php index.php4 index.php3 index.htm index.html index.shtml default_new_vhost.html

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

RedirectPermanent /content.asp?AUID=01 /content/
...

The redirecting doesn't work (I only get the 404 page of Wordpress). The reason are the get parameters in the URL. I tried the answers posted here. E.g.
RewriteCond %{REQUEST_URI} ^/content.asp$
RewriteCond %{QUERY_STRING} ^AUID=01$
RewriteRule ^.*$ http://www.yourdomain.com/content? [L,R=301]

Either I get a 500 error or I come to the 404 page of Wordpress. What is the correct way doing this? Than I have many entries in the form
RedirectPermanent /content.asp?pCategory=&pCountry=1&AUID=01 /content/

which is wrong, but I look for an efficient way putting this in the htaccess. Can I use something like this instead?
RewriteCond %{REQUEST_URI} ^/content.asp$
RewriteCond %{QUERY_STRING} ^pCategory=([0-9]+)&pCountry=([0-6]+)$
RewriteRule ^.*$ http://www.yourdomain.com/content? [L,R=301]

A: You simply do this (from my site)
rewriteCond %{QUERY_STRING} ^id=([0-9]+)$
rewriterule ^news_details.asp$ news/index.php?old_id=%1

Replace ^id with any param and simply user %1, %2 to access them in the rewrite, yours would be
rewriteCond %{QUERY_STRING} ^pCategory=([0-9]+)&pCountry=([0-6]+)$
rewriteRule ^content.asp$ /content/?category=%1&country=%2

A: I ended up with the following solution:
DirecotryIndex welcome.do index.jsp ...

RewriteCond %{REQUEST_URI} ^/content.asp$
RewriteCond %{QUERY_STRING} ^AUID=01$ [OR]
RewriteCond %{QUERY_STRING} ^pCategory=&pCountry=1&AUID=01$ [OR]
RewriteCond %{QUERY_STRING} ^pCategory=&pCountry=8&AUID=01$
RewriteRule ^.*$ /content? [L,R=301]

RedirectPermanent /italiano/index.asp /it/

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

The problem was that I placed my code after the Wordpress code instead before. It is also possible to use umlauts if you change the encoding of htaccess to UTF-8 without BOM. You also can redirect to URLs with GET parameters without problems.