text:
Q: Show/Hide input fields based on double radio button selection Is there a possible way that I can target two radio buttons at the same time?
I have two sets of radio buttons, where I want to hide input fields based on the combo selection.
I want to be able to select the Team radio button and the Remote Session button and hide/show inputs fields
Here are the images:
Correct:

Correct:

Wrong:

Here is the code:

$(document).ready(function () {
 $('input[name=requestType]').click(function() {
  if(this.value == 'Team')
  {
   $(".total").show();
   $(".teamname").show();
   $(".one").show();
   $(".two").show();
   $(".three").show();
   $(".four").show();
   $(".five").show();
  }
  else
  {
   $(".teams").hide();
  }
 });

<form id="form">

   Request Type:
    <input id="singleUser" type="radio" name="requestType" value="Single User" checked>Single User
  <input id="teamSelection" type="radio" name="requestType" value="Team">Team

   Session Type:
    <input id="liveSession" type="radio" name="sessionType" value="Live Session" checked>Live Session
  <input id="remoteSession" type="radio" name="sessionType" value="Remote Session">Remote Session

   Requester Name:
    <input class="form-control" name="requesterName" type="text" id="requesterName" data-minlength="2" data-error="Please enter a valid name." placeholder="Ex: Jane Doe" required/>

   Team Name:
    <input class="form-control" name="teamName" type="text" id="teamName" data-minlength="2" data-error="Please enter a valid team name." placeholder="Ex: PortalHelp Team" required/>

     Number of Attendees:
        <select class="form-control" id="totalUsers">
          <option value="Five" selected>5</option>
          <option value="Six">6</option>
          <option value="Seven">7</option>
          <option value="Eight">8</option>
          <option value="Nine">9</option>
          <option value="Ten">10</option>
        </select>

        Names of Attendees:
        <input class="form-control" name="oneUser" type="text" id="oneUser" data-minlength="2" data-error="Please enter a valid name." placeholder="Ex: John Smith" required/>

        <input class="form-control" name="twoUsers" type="text" id="twoUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="threeUsers" type="text" id="threeUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="fourUsers" type="text" id="fourUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="fiveUsers" type="text" id="fiveUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="sixUsers" type="text" id="sixUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="sevenUsers" type="text" id="sevenUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="eightUsers" type="text" id="eightUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="nineUsers" type="text" id="nineUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="tenUsers" type="text" id="tenUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <button type="button" name="singlebutton" class="btn btn-success" id="submit">Submit</button>
          <button type="reset" name="cancelbutton" class="btn btn-warning" id="cancel" onclick="window.location.href='/TrainingResourceCenter/O365Training/Pages/Training.aspx'">Cancel</button>

</form>

A: Use function onclick #remoteSession then check if Team is checked if yes hide/show whatever you want...

$(document).ready(function () {
 $('input[name=requestType]').click(function() {
  if(this.value == 'Team')
  {
   $(".total").show();
   $(".teamname").show();
   $(".one").show();
   $(".two").show();
   $(".three").show();
   $(".four").show();
   $(".five").show();
  }
  else
  {
   $(".teams").hide();

  }
 });
  $('input[name=sessionType]').click(function() {

  if($('input[name=requestType]:checked').val()=='Team' && $('input[name=sessionType]:checked').val()=='Remote Session')
  {
   $(".teams").hide();
    $(".teamname").show();

  }
else
$('input[name=requestType]').click();
  });
   });

<form id="form">

   Request Type:
    <input id="singleUser" type="radio" name="requestType" value="Single User" checked>Single User
  <input id="teamSelection" type="radio" name="requestType" value="Team">Team

   Session Type:
    <input id="liveSession" type="radio" name="sessionType" value="Live Session" checked>Live Session
  <input id="remoteSession" type="radio" name="sessionType" value="Remote Session">Remote Session

   Requester Name:
    <input class="form-control" name="requesterName" type="text" id="requesterName" data-minlength="2" data-error="Please enter a valid name." placeholder="Ex: Jane Doe" required/>

   Team Name:
    <input class="form-control" name="teamName" type="text" id="teamName" data-minlength="2" data-error="Please enter a valid team name." placeholder="Ex: PortalHelp Team" required/>

     Number of Attendees:
        <select class="form-control" id="totalUsers">
          <option value="Five" selected>5</option>
          <option value="Six">6</option>
          <option value="Seven">7</option>
          <option value="Eight">8</option>
          <option value="Nine">9</option>
          <option value="Ten">10</option>
        </select>

        Names of Attendees:
        <input class="form-control" name="oneUser" type="text" id="oneUser" data-minlength="2" data-error="Please enter a valid name." placeholder="Ex: John Smith" required/>

        <input class="form-control" name="twoUsers" type="text" id="twoUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="threeUsers" type="text" id="threeUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="fourUsers" type="text" id="fourUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="fiveUsers" type="text" id="fiveUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="sixUsers" type="text" id="sixUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="sevenUsers" type="text" id="sevenUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="eightUsers" type="text" id="eightUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="nineUsers" type="text" id="nineUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <input class="form-control" name="tenUsers" type="text" id="tenUsers" data-minlength="2" data-error="Please enter a valid name." required/>

          <button type="button" name="singlebutton" class="btn btn-success" id="submit">Submit</button>
          <button type="reset" name="cancelbutton" class="btn btn-warning" id="cancel" onclick="window.location.href='/TrainingResourceCenter/O365Training/Pages/Training.aspx'">Cancel</button>

</form>
 Run code snippet


text:
Q: Índice Full Text para Banco de dados voltado para Ecommerce! Li várias postagens aqui no SOPT sobre criação de índices a qual me tirou inúmeras duvidas que tinha, mas a minha principal é sobre FULL TEXT!
Em um banco de dados que é exclusivamente voltado para ecommerce, onde existem inserts, updates e deletes o tempo todo. Eu tenho que frequentemente estar recriando estes índices ou mysql faz isso automaticamente?

A: O MySQL não recria os índices FULLTEXT automaticamente.
Deleções de registros que possuem colunas com índice deste tipo são gravadas em tabelas auxiliares, utilizadas como filtro para retornar os resultados das consultas sem as deleções. Como vantagem, as deleções são rápidas e performáticas. Porém, a desvantagem é que o tamanho do índice não é imediatamente reduzido após a deleção dos registros. Para remover as entradas de índices FULLTEXT e melhorar a performance das consultas, é necessário fazer o rebuild do índice, conforme instruções abaixo.
Para recriar um índice FULLTEXT você precisa habilitar innodb_optimize_fulltext_only e rodar OPTIMIZE TABLE:
mysql> set GLOBAL innodb_optimize_fulltext_only=ON;
Query OK, 0 rows affected (0.01 sec)

mysql> OPTIMIZE TABLE opening_lines;
+--------------------+----------+----------+----------+
| Table              | Op       | Msg_type | Msg_text |
+--------------------+----------+----------+----------+
| test.opening_lines | optimize | status   | OK       |
+--------------------+----------+----------+----------+
1 row in set (0.01 sec)

Maiores detalhes podem ser vistos na documentação.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WildFly: HTTP method POST is not supported by this URL I'm developing a Java EE web application running on WildFly 18, and Angular on the front end. All the HTTP calls from Angular to Wildfly are POSTs. The application works fine, but once a month, when I start it, I cannot use it because Wildfly rejects the request saying that the HTTP method POST is not supported by this URL (see error below on browser console). Just to make sure is not Angular, I made the POST call from a Java program, and got the same error.
The solution is to close everything and restart, sometimes more than once. Why does this happen and how to fix this? The big problem is that this may happen in production.

visualcode/rest/getbropr:1 Failed to load resource: the server
responded with a status of 405 (Method Not Allowed) main.js:1127
HttpErrorResponse error:
"Error HTTP method POST is not
supported by this URL" headers: HttpHeaders
{normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message:
"Http failure response for
http://localhost:4400/visualcode/rest/getbropr: 405 Method Not
Allowed" name: "HttpErrorResponse" ok: false status: 405 statusText:
"Method Not Allowed" url:
"http://localhost:4400/visualcode/rest/getbropr"

UPDATE
This happened to me in two different machines with identical Wildfly configuration, so it must be something on how JAX-RS or any other related component is set up.
UPDATE 2
I got the error and this is the server log:
11:46:17,306 DEBUG [io.undertow.request] (default I/O-12) Matched prefix path /visualcode for path /visualcode/rest/getbropr
11:46:17,306 DEBUG [io.undertow.request.security] (default task-1) Attempting to authenticate /visualcode/rest/getbropr, authentication required: false
11:46:17,306 DEBUG [io.undertow.request.security] (default task-1) Authentication outcome was NOT_ATTEMPTED with method io.undertow.security.impl.CachedAuthenticatedSessionMechanism@2d8f2c0a for /visualcode/rest/getbropr
11:46:17,306 DEBUG [io.undertow.request.security] (default task-1) Authentication result was ATTEMPTED for /visualcode/rest/getbropr
11:46:17,307 INFO  [io.undertow.request.dump] (default task-1)
----------------------------REQUEST---------------------------
               URI=/visualcode/rest/getbropr
 characterEncoding=null
     contentLength=2
       contentType=[application/json]
            cookie=_ga=GA1.1.1378850711.1587329434
            header=accept=application/json, text/plain, */*
            header=accept-language=en-US,en;q=0.9,es;q=0.8
            header=accept-encoding=gzip, deflate, br
            header=sec-fetch-mode=cors
            header=origin=http://localhost:4400
            header=user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
            header=sec-fetch-dest=empty
            header=connection=close
            header=sec-fetch-site=same-origin
            header=cookie=_ga=GA1.1.1378850711.1587329434
            header=content-type=application/json
            header=content-length=2
            header=referer=http://localhost:4400/login
            header=host=localhost:8080
            locale=[en_US, en, es]
            method=POST
          protocol=HTTP/1.1
       queryString=
        remoteAddr=/127.0.0.1:51323
        remoteHost=kubernetes.docker.internal
            scheme=http
              host=localhost:8080
        serverPort=8080
          isSecure=false
--------------------------RESPONSE--------------------------
     contentLength=104
       contentType=text/html;charset=UTF-8
            header=Connection=close
            header=Content-Type=text/html;charset=UTF-8
            header=Content-Length=104
            header=Date=Thu, 09 Jul 2020 15:46:17 GMT
            status=405

==============================================================

And this is the code that (sometimes) fails:
@Path("/")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public class LoginService {

    @Inject
    private SomeBean bean;

    @Context
    private HttpServletRequest httpRequest;

    @POST
    @Path("/getbropr")
    public Response getBrowserProperties() {
          // process response
    }

A: At the moment I did not find any similar issue in his issue tracker.  I have also not had a similar problem with wildfly 17 and 19.
So, the first Thing I suggest you check to solve the problem is to carry out the following checks and collect certain information to help:

*

*first check the wildfly logs and change them in trace or debug mode

*Second verify that you are not going through a balancer, reverse proxy, firewall or any intermediary that may be the issuer of the response that you are seeing in the client

*Log the call made including (url, headers, http method, parameters and body) and the same data of the received answer, or try if it is possible to reproduce the call with a visual tool like postman or by command line with a command like curl.

With these tests, you can first determine the true origin of the service response.  sometimes bad configurations in balancers, networks, etc. can cause that the calls do not arrive at the destination and the one that answers is another service.
It is useful to check the headers that are included, since traces are sometimes found. Or the format or message in the body of the response, which can be another indication to determine the origin.
If we have confirmed that the origin is the service, it is convenient for us to review the traces from the moment it began to fail backwards.
There may be clues to a fault or a mishandled exception when a fault occurs internally.  For example if we are using Resteasy (jax-rs) with wildfly (which is quite common), an exception thrown wrong when there is an internal error (database not available, internal services unreachable, etc.) or an exception mapper is wrong... it can cause an incorrect message and error code to be printed which would be a distraction to solve the real problem (it would not be something very common that happens but it is a point to keep in mind and reviewing the logs can help here).
if after analyzing the response, confirming its origin, analyzing the traces and exceptions, your problem persists ... I suggest you provide greater detail of your application in this thread (for example, java version, libs, implement direct with servlet or resteasy?, authentication?, etc) ... any information you can provide such as the trace or a small demo with similar characteristics that can be used to reproduce the problem will be welcome to help you solve the problem.
Update:
Knowing that you are running the service locally, I ask you to configure Wildfly to print the call and its parameters in your logs.
Wildfly uses undertow as engine so please add a filter to your undertow configuration to log your request. Add to your standalone.xml -> subsystem "undertow" the following configuration:
<subsystem xmlns = "urn:jboss:domain: undertow: 3.0">
         <server name = "default-server">
             <host name = "default-host" alias = "localhost">
...
                 <filter-ref name = "request-logger" />
             </host>
         </server>
         <filters>
...
             <filter name = "request-logger" module = "io.undertow.core"
               class-name = "io.undertow.server.handlers.RequestDumpingHandler" />
         </filters>
     </subsystem>

Alternatively, you can change your xml configuration with jboss-cli.sh with this script:

$WILDFLY_HOME/bin/jboss-cli.sh --connect --file=script.cli

script.cli file:
batch
/subsystem=undertow/configuration=filter/custom-filter=request-logging-filter:add(class-name=io.undertow.server.handlers.RequestDumpingHandler, module=io.undertow.core)
/subsystem=undertow/server=default-server/host=default-host/filter-ref=request-logging-filter:add
run-batch

Any call that reaches undertow through the open port should log the data received in your logs and that will help to know if the call reaches the wildfly and be able to trace the problem. Debug logs will also be welcome later if the call actually reaches wildfly.
On the other hand, have you tested if the problem persists in Wildfly 20? Updating the wildfly between 18-20 is relatively simple.
Update 2:
The request looks good, so I suggest you check the startup logs. Seems to be a race condition at start, Wildfly runs many tasks simultaneously to get started ASAP.
Typically, when you have duplicate configuration files in classpath or startup codes, it can lead to unexpected behavior, so comparing logs is helpful. Check that you only have a web.xml and file descriptors in your .war file.
Hope I can helps


text:
Q: I want to change the position of the launcher items
Possible Duplicate:
Is there an easy way to rearrange the icons in Unity launcher?

I have added a quicklist launcher to Unity, it sits at the bottom of the list, I want to change that to another position easily with minimal effort / programs.

ie: I want to move firefox from being the 2nd item in the list to the first position bellow the dash button.
How can I do that?

A: Left-click and hold your application icon for couple of seconds then move it over the launcher to desired place.

A: Drag the firefox icon some out of the launcher until a white bar appears where the icon has been. THen continue to drag the firefox icon up. The white bar will show the new position of the launcher icon. Then drop the icon into its new position.
Edit: I run 11.10, unity 3D:
$ more /etc/issue
Ubuntu 11.10 \n \l

$ unity --version
unity 4.24.0

And it looks like this:


text:
Q: Unable to remove legends from seaborn subplots created by iteration and create one, overarching legend I have a data set that looks similar to the below, but is much longer:
   Sample Name Treatment Replicate  Time Congener  Concentration (ng/L)
0     Blank-1     Blank         1     0   PbTx-1                     0
1      Ctrl-1      Ctrl         1     0   PbTx-1                  8800
2      Ctrl-2      Ctrl         2     0   PbTx-1                  7500
3      Ctrl-3      Ctrl         3     0   PbTx-1                  9100
4     10ppm-1     10ppm         1     0   PbTx-1                  9800

I am attempting to create a group (array?) of subplots that shows each time period in a different plot, comparing each treatment, with each congener represented, that has a single legend for the entire plot with 4 columns below the "treatment" x-label.
This link goes to the almost perfect graph, except all the legends are visible
This is the code I used to generate the nearly perfect graph, but with visible legends:
#Setting the variables outside of the actual arguments to improve readability
first_dimension = "Treatment"
second_dimension = "Concentration (ng/L)"
third_dimension = "Congener"

#Setting the y-axis limit for toxin
ylim_toxin = td['Concentration (ng/L)'].max() * 1.05

#This gets the total number of subplots
num_plots = len(treatments)
fig, axes = plt.subplots(ncols = num_plots, sharey=True, sharex=True, figsize = (5*num_plots,5))

#Removes the space between the plots, so they share an X and are lined up nicely by time the sample was taken
fig.subplots_adjust(hspace=0, wspace=0)

#Set overarching title based on previously input project name
fig.suptitle(f'{pdate}', fontweight='bold')
fig.supxlabel(f'Treatment')

#Create a bar plot of the data using seaborn, looping through the treatments list and each axis using count
count = 0
for ax in axes:
    axes[count].set_title(f"T = {treatments[count]}")
    treat = treatments[count]
    tdtreat = td.loc[td['Time'] == treat]
    sns.barplot(
                x = first_dimension ,
                y = second_dimension ,
                hue = third_dimension ,
                data = tdtreat ,
                capsize = 0.05 ,
                errwidth = '1' ,
                errcolor = '0' ,
                edgecolor="0" ,
                errorbar = 'sd',
                ax = ax)
    count = count + 1

ax.set(xlabel=None)
ax.set(ylabel=None)

#Setting a y-label with supylabel created a y label that was far to the left, simply labelling the first y-axis
axes[0].set_ylabel("Concentration (ng/L)", fontsize = 12)

I managed to get the following graph, with the one legend moved to the bottom and stretched out perfectly into four columns, but the other legends are still visible:
Graph with one legend in correct location
I have attempted setting the legend equal to False to remove all legends, then add one back in, but it says " 'Rectangle' object has no property 'legend'":
sns.barplot(x = first_dimension ,
            y = second_dimension ,
            hue = third_dimension ,
            data = tdtreat ,
            capsize = 0.05 ,
            errwidth = '1' ,
            errcolor = '0' ,
            edgecolor="0" ,
            errorbar = 'sd',
            ax = ax,
            legend = False)

I have attempted adding "ax.legend_.set_visible(False)", but I get the error "'NoneType' object has no attribute 'set_visible'":
count = 0
for ax in axes:
    axes[count].set_title(f"T = {treatments[count]}")
    ax.legend_.set_visible(False)
    treat = treatments[count]
    tdtreat = td.loc[td['Time'] == treat]
    sns.barplot(x = first_dimension ,
                y = second_dimension ,
                hue = third_dimension ,
                data = tdtreat ,
                capsize = 0.05 ,
                errwidth = '1' ,
                errcolor = '0' ,
                edgecolor="0" ,
                errorbar = 'sd',
                ax = ax)
    count = count + 1

ax.set(xlabel=None)
ax.set(ylabel=None)

I have tried updating the seaborn package, along with all other packages in the anaconda terminal, yet it still produces these errors.
As mentioned in this prior question on how to remove matplotlib legends, I attempted "ax.get_legend().remove()" and yet  I got "'NoneType' object has no attribute 'remove'" as an error.
This question addressed the none type, "You have a variable that is equal to None and you're attempting to access an attribute of it called 'something'."
I'm not sure why the axis would be "None" when the axis appears to be there..
Thank you very much.


text:
Q: Call Child Method from Parent with react-native I know that this is a pretty common question but some answers I found on the internet are deprecated.
How do you call a method of a Child Component from the Parent Component in 2020?
My actual code is something like this but it's not working
Child:
export default class CustomComp extends React.Component{
  exampleMethod = () => {
    console.log('pressed');
  };

  render(){
    return (
      ...
    );
  }
}

Parent:
export default class App extends React.Component{
  child = CustomComp;
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={this.child.exampleMethod} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}

A: You can follow in this example. Here I used React.createRef and pass the ref into child and then I called this.child.current.getAlert
import React, {useRef} from "react";

export default class MyParent extends React.Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
  }

  onClick = () => {
    this.child.current.getAlert('Mr. Kamal');
  };

  render() {
    return (

        <Child ref={this.child} />
        <button onClick={this.onClick}>Click</button>

    );
  }
}

class Child extends React.Component {
    getAlert(name) {
        alert(`Hi ${name}`);
    }

    render() {
        return
Hello
;
    }
}

A: You have to call the function as a callback function.
onPress={() => this.child.exampleMethod()}

Plus, I think child = CustomComp has no effect since ref={child => {this.child = child}} is NOT affected by child = CustomComp.
So, your Parent js file should be as follows.
export default class App extends React.Component{
  render(){
    return (
      <View style={styles.container}>
        <Button title="Press" onPress={() => this.child.exampleMethod()} />
        <CustomComp ref={child => {this.child = child}} {...this.props} />
      </View>
    );
  }
}


text:
Q: How can I evaluate this surface integral Find the value of Surface Integral $ \displaystyle \int \int yzdxdy + xzdydz + xydxdz$ Where the surface is the outer side of the surface formed by the cylinder $x^2 + y^2 =4 $ and the plane $x = 0 , y= 0 ,z = 0$ and  $z=  2$
Now I would like to solve this surface integral with the help of Gauss Divergence theorem, but firstly I want the surface integral in the form $\int F.n ds$
so that I can calculate $\nabla. F$
Can anyone tell me how should I solve this integral ?
Thank you .

A: This is a surface integral of the second kind. A surface integral of the form
$$\iint_R Pdydz + Qdxdz + Rdxdy$$
$$= \iint_S (Pcos\alpha + Qcos\beta + Rcos\gamma)dS$$
Where
$$cos\alpha = \frac{A}{\sqrt{A^2 + B^2 + C^2}}$$
$$cos\beta = \frac{B}{\sqrt{A^2 + B^2 + C^2}}$$
$$cos\gamma = \frac{C}{\sqrt{A^2 + B^2 + C^2}}$$
Where
$$A = \frac{\partial{(y, z)}}{\partial{(u, v)}}$$
$$B = \frac{\partial{(z, x)}}{\partial{(u, v)}}$$
$$C = \frac{\partial{(x, y)}}{\partial{(u, v)}}$$
Based on these formulae we use the following parameter for the cylinder
$$x = 2cos\theta $$
$$y = 2sin\theta $$
$$z = z$$
Using the above formulae we have
$$\sqrt{A^2 + B^2 + C^2} = 2$$
Where
$$A = 2cos\theta$$
$$B = 2sin\theta $$
$$C = 0$$
Substitute x, y, z into the integral we have
$$I = \iint_S (2zsin\theta cos\theta + 2zcos\theta sin \theta)dS$$
Using the change of variables from x, y, z to $\theta$ and z, J factor is 2.
$$= \int_0^{2}\int_0^{\frac{\pi}{2}} 4z sin \theta cos \theta d\theta dz= 4$$


text:
Q: Check in Spring AOP if method is called by another annotated method I use in my Spring boot project aspect that is fired on every public method in annotated class:
@Aspect
@Component
public class DeletedAwareAspect {
    @Before("@within(com.example.DeleteAware)")
    public void aroundExecution(JoinPoint pjp) throws Throwable {
        //... some logic before
    }

    @After("@within(com.example.DeleteAware)")
    public void cleanUp(JoinPoint pjp) throws Throwable {
       //... some logic after
    }
}

Usage of that aspect is below:
@DeleteAware
@Service
public class MyService {
    public void foo() {}
}

@DeleteAware
@Service
public class MyAnotherService {
    @Autowired
    private MyService service;

    public void anotherFoo() {}

    public void VERY_IMPORTANT_METHOD() {
        service.foo();
    }
}

MyService.foo() and MyAnotherService.anotherFoo() works as expected. But here is the problem - if method wrapped by aspect is called by another aspected method (like VERY_IMPORTANT_METHOD()), I dont want to fire aspect twice, but only once.
How to check from Aspect whether method is called inside another aspected method?

A: Like I said, if you would switch to native AspectJ you could use percflow() aspect instantiation and/or cflow() pointcuts, but I will not explain that here in detail because you are looking for a Spring AOP solution. Like R.G said, it is actually quite simple: Use a thread-local counter for the aspect nesting level and only do something (e.g. deleting something in the after advice) if the counter is zero.
@Aspect
@Component
public class DeletedAwareAspect {
  private ThreadLocal<Integer> nestingLevel = ThreadLocal.withInitial(() -> 0);

  @Before("@within(com.example.DeleteAware)")
  public void aroundExecution(JoinPoint pjp) {
    int level = nestingLevel.get() + 1;
    nestingLevel.set(level);
    System.out.println("BEFORE " + pjp + " -> " + level);
  }

  @After("@within(com.example.DeleteAware)")
  public void cleanUp(JoinPoint pjp) {
    int level = nestingLevel.get() - 1;
    nestingLevel.set(level);
    System.out.println("AFTER " + pjp + " -> " + level);
    if (level == 0)
      System.out.println("Deleting something");
  }
}


text:
Q: Vaadin CheckBox object becomes null I have this Vaadin object:
CheckBox mycb = new CheckBox("caption");

Later on the value of this checkbox is updated from the database like this:
mycb.setValue(dbvalue);

dbvalue is actually NULL in the database. mycb was not null before this line, and is null after this line. Shouldn't its value remain the same, only mycb.getValue() returning null?
Furthermore, trying to avoid a NullPointerException with short-circuit evaluation:
if (mycb != null && mycb.getValue() == true)
...

That produces a NullPointerException anyway. Is this normal behavior or there is something I'm doing wrong?

A: You said yourself mycb doesn't actually become null. That's great.
if (mycb != null && mycb.getValue() == true)

This throws a NullPointerException because Java tries to cast the result of mycb.getValue() to a boolean. But because mycb.getValue() returns null, it throws a NullPointerException.
Change it to:
if (mycb.getValue() != null && mycb.getValue() == true)

Or something similar


text:
Q: Using GitHub as a code repository for tutorial project I`m planning a project, and was wondering if it would be a good idea to use GitHub as a code repository for the project.
The project is just me creating a single application step by step. In fact, it is more like me learning how to do it, and documenting my process, and letting other people tag along.
So step 1 could be setting up the project, step 2 how to organize the files, step 2 connecting to the database, step 3 how to do the UI etc. (btw. this is not how the project is set up)
The documentation would consist of a website with articles for each step and along with each step I want to enable the visitor to download/view the code for the project to the point where we are in the process.
I don`t know how top use GitHub, but I was planning on learning it as well. Would GitHub be a good way to share the code for a project like this?
Is there a way in GitHub to take snapshots, like step 1, step 2, etc., or would it be better to use branches or forks for this?
A nice feature would be the ability to correct the entire chain of steps if I find a typo in step one.
Does anyone know of an existing GitHub project that is set up in a similar way?

A: You could use GitHub, provided you push also tags for each significant steps.
(as explained in "How do I use github tags to create downloads for my project?")
That way, you can provide download links for each of those tags, even for the readers who don't have Git installed.
See "All of your downloads. One big button."


text:
Q: Bootstrap columns not working with width adjustment I want to display two input areas next to each other with one taking less space than the other. This is what I have now but somehow it won't work.

            Reihentitel
            <input type="text" class="form-control" id="inputReihentitel" input>

            Bandaufführung
            <input type="text" class="form-control" id="inputBandaufführung" input>

When I just use the .col class it splits the two div tags evenly across the screen. With for example the .col-xs-8 and .col-xs-4 it is displayed one below the other.
Now I put the input-group into an other div which has the .col class but it is the same as before.

          Reihentitel
          <input type="text" class="form-control" id="inputReihentitel" input>

          Bandaufführung
          <input type="text" class="form-control" id="inputBandaufführung" input>

A: When you read the documentation you will see that the smallest columns don't need any prefixes anymore. This is because this is the default width and you don't need any prefixes for a default.
In other words: col-xs-4 becomes just col-4 (since it is 4-width on all sizes, not only xs)
My advice from the comments to not mix column-classes with other classes is still something I highly recommend. It is too easy to just overwrite column styling and have the layout break if you do it otherwise.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

          Reihentitel
          <input type="text" class="form-control" id="inputReihentitel" input>

          Bandaufführung
          <input type="text" class="form-control" id="inputBandaufführung" input>


text:
Q: upload jar in artifactory I am new to artifactory, I need to upload new version of jar in the repository, here are the steps I am following:
login to artifactory--> deploy tab--> choose file--> upload--> the target repository I am seeing are

*

*plugins-releases-local

*libs-releases-local

*libs-snapshots-local

*plugins-snapshots-local

*ext-releases-local

*ext-snapshots-local

I uploaded my new jar in number 2 (libs-releases-local),
it shows that it is in virtual repository repo and lib-releases,
but older version of same jar has virtual repository repo, remote-repos, libs-releases, plugins-releases, libs-snapshots, plugins-snapshots
I am not sure how do I do the same with my new versioned jar,
also when I search for jar by name for older version it appears in folder repo1-cache while for new version it appears in libs-releases-local
can anyone help me in this would be great.

A: The older version came from repo1. That's why it appears in repo1-cache, remote-repos, etc.
You have uploaded your version to a local repository (btw, ext-release-local seems like a better fit for this kind of artifact), that's why it appears on only on subset the virtual repositories.
Either way, if you want to use this artifact as a dependency in your build you should configure your build tool to use libs-releases, which contain both libs-releases-local and repo1-cache.


text:
Q: When any button click form will auto submit even the button is a different function All the button in the form, submit the form automatically, but I need other button function.
Code here:
     <html lang="en">
     <title>NTF Catering Service</title>
     <meta charset="utf-8">
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">              </script>
       <script src="js/js.1.js" type="text/javascript"></script>
    </head>
   <body>
       <form action="create.php" method="post">

         <select multiple="multiple" class="options" id="textarea">
         <option value="item1">Item 1</option>
         <option value="item2">Item 2</option>
         <option value="item3">Item 3</option>
         <option value="item4">Item 4</option>
          <option value="item5">Item 5</option>
        </select>

    <button id="copy">Copy</button>
    <button id="remove">Remove</button>

     <select id="textarea2" multiple class="remove">

<input type="submit" name="submit" />
</form>
    </select>
     </html>

A: If you mean that all  the Buttons submit your form then add the following to the  elements: type="button"
<button type="button" id="copy">Copy</button>
<button type="button" id="remove">Remove</button>

This should ensure only the  will submit the form
Then control these via your jquery code:
    $('#copy').on('click', function(e){ ///do stuff here });
    $('#remove').on('click', function(e){ ///do stuff here });

or add onclick to the buttons:
<button onclick="someCopyfunction();" type="button" id="copy">Copy</button>
<button onclick="someRemovefunction();"  type="button" id="remove">Remove</button>

etc

A: Since you tagged jQuery and Javascript you can also use:
$('input[name="submit"]').click(function(event){
  event.preventDefault();
  //Do other stuff here
});

A: By default <button> tags are submit button , to make them just button use
<button type="button">copy</button>
<button type="button">Remove</button>

Check this what's the standard behavior when < button > tag click? will it submit the form?
Note Always specify the type attribute for a <button> element. Different browsers use different default types for the  element.
Use <input> to create buttons in an HTML form.

A: Now you are write input button inside <select> tag.
 <select id="textarea2" multiple class="remove">

   <input type="submit" name="submit" />
   </form>
    </select>

To
</select>
 <input type="submit" name="submit" />
 </form>

Also
If you don't want to submit your button
Change
<input type="submit" name="submit" />

TO
<input type="button" name="submit" onclick='yourFunction()' />

A: Try these one if it may work for you
<form action="">
  <textarea value="text here..." type="submit" method="post"></textarea>
</form>


text:
Q: How to access (or switch between) tray icons with shortcut in windows? How to access (or switch between) tray icons with defined shortcuts in windows? I have many running programs which I cannot reach with alt-tab because they are not in taskbar - they are in tray. How do you reach those applications without a mouse? I heard of some tricky keys combination (like ctrl+esc esc tab tab tab and then find application with arrow keys), but it's ridiculous to use such long keys combination for such simple task. Is there any utility to manage switching like TaskSwitchXP for alt+tab? Or maybe TaskSwitchXP has possibility to access applications in tray?

A: Use Windows + B to access tray icons in Windows 7. To access Hidden tray icons press Enter after it. Use Arrow keys to nevigate between icons. Used a lot in Windows 7, But I have to check it for Windows XP

A: 4t Tray Minimizer Free can do this and more.

*

*various ways to minimize any application to the system tray;

*ability to hide any application without showing tray icon;

*the customized hotkeys for minimizing, restoring, maximizing and
  launching applications;

*ability to customize the minimizing behavior of your favorite
  application;

*quick hiding/showing the whole system tray.

You can download it here. A free version as well as a paid version ($19.95) is available.

As for the key combination, it's Ctrl + Esc, then Tab 3 times to get to the tray. But I don't think you can switch between the apps in the tray like this, it only highlights time.


text:
Q: Como posso fazer um laço para inserir dados em uma tabela no meu formulário para depois enviar para meu banco? //Parte do Formulário ao qual quero aplicar o laço

            Curso
            <input name="cursolivre" id="cursolivre" class="form-control" type="text" value="">

            Segmento
            <select class="form-control" name="segmento" id="segmento">
              <option value="Administrativo">Administrivo</option>
              <option value = "Tecnologico">Tecnológico</option>
              <option value="Tecnico">Técnico</option>
              <option Value="Livre">Livre</option>
            </select>

            Inicio
            <input name="iniciol" id="iniciol" class="form-control" type="date" value="">

            Termino
            <input name="termino" id="termino" class="form-control" type="date" value="">

            Carga Horário
            <input name="cargahorario" id="cargahorario" class="form-control" type="number" value="">

        <button class="btn btn-default btn-adicionar-curso-livre" onclick="inserirTabela()" type="button">  Nova Atividade</button>

                  Curso
                  Segmento
                  Inicio
                  Termino
                  Carga Horário

//Código de inserção
function inserirTabela(){
  var curso = document.form1.cursolivre.value;
  var segmento = document.form1.segmento.value;
  var inicio = document.form1.iniciol.value;
  var termino = document.form1.termino.value;
  var cargahorario = document.form1.cargahorario.value;

  document.getElementById("dado1").innerHTML = curso;
  document.getElementById("dado2").innerHTML = segmento;
  document.getElementById("dado3").innerHTML = inicio;
  document.getElementById("dado4").innerHTML = termino;
  document.getElementById("dado5").innerHTML = cargahorario;
}

Quando eu clicar em nova atividade, preciso inserir ela em uma nova linha abaixo da primeira atividade, guardar em um array para poder enviar para meu banco.

A: Allan, basicamente o que você precisa é trabalhar com um objeto javascript.
Chamarei esse objeto de atividade.
Classe model
function atividade() {
    this.curso: undefined,
    this.segmento: undefined,
    this.inicio: undefined,
    this.termino: undefined,
    this.cargahorario: undefined
}

Eu inicializo as propriedades do objeto com undefined, por uma preferencia minha, mas você pode iniciar com null, ``, da forma que você entender que lhe é mais conveniente de acordo com o escopo de seu projeto.
Evento clique do botão nova atividade
Bem, agora que temos o objeto, no evento de clique do botão nova atividade, você deve mapear o objeto atividade com os valores do formulário.
var novaAtividade = new atividade();

novaAtividade.curso = document.form1.cursolivre.value;
novaAtividade.segmento = document.form1.segmento.value;
novaAtividade.inicio = document.form1.iniciol.value;
novaAtividade.termino = document.form1.termino.value;
novaAtividade.cargahorario = document.form1.cargahorario.value;

atividades.push(novaAividade);

A variável atividades, é um array que deve ser criado em um escopo global do arquivo que controla a tela com o seu formulário, sua declaração deve ser feito da seguinte forma:
var atividades = [];

[] diz que a variável atividade recebera um array vazio, desta forma o método push() se torna possível de ser executado.
push() fará a inclusão do objeto novaAtividade no final do array.
Desta forma o usuário pode incluir quantias atividades quiser. Para esta resposta vou assumir a abordagem de percorrer o array atividades, e ir ao server para cada registro. Para a abordagem de persistir o array, já tem que ser no server, mas imagino que a ideia em php, seja a mesma que farei com JS.
Persistir
Como nao conheço, a sua função, irei apenas descrever idaAoServer(atividade), para identificar o momento de persistir a entidade.
Basicamente, no botão que terá o evento de salvar os dados digitados pelo usuário, você deve incluir o seguinte bloco:
for (atividade in atividades){
    idaAoServer(atividade);
}

Referencias
Objetos com construtor em javascript
Método push
for in objects javascript


text:
Q: I want to convert CSV to JSON file using python import csv
import json

# defining the function to convert CSV file to JSON file
def convjson(cleanedhm, js):
    # creating a dictionary
    mydata = {}

    # reading the data from CSV file
    with open(cleanedhm, encoding='utf-8') as csvfile:
        csvRead = csv.DictReader(csvfile)

        # Converting rows into dictionary and adding it to data
        for rows in csvRead:
            mykey = rows['hmid']
            mydata[mykey] = rows

            # dumping the data
    with open('cleanedhm', encoding='utf-8') as jsonfile:
        jsonfile.write(json.dumps(mydata, indent=4))

    # filenames

cleanedhm = r'mydatalist.csv'
js = r'mydatalist.json'

# Calling the convjson function
convjson(cleanedhm, js)

A: Pandas is a really great tool, and in this case it does what you need in two very easy lines!
import pandas as pd

csv = pd.read_csv (r'Path where the CSV file is saved\File Name.csv')
csv.to_json (r'Path where the new JSON file will be stored\New File Name.json')

A: process your file with pandas as a DataFrame and then export with the to_json() method


text:
Q: Is there some way to circumvent sluggish Android Studio editor after debugging? Every time I make debugging in a system written in Kotlin (I think the same thing should happen in Java) inside Android Studio the editor becomes extremely slow, even after stop running the code, forcing myself to write in another editor and after use copy & paste.
The longer it passes, it seems that Android Studio's IDE slowly recovers its agility. It's insane.
Since Android Studio's support is not very responsive, I appeal to someone who also goes through this situation and has found some practical solution different from restarting Android Studio again and again.
In any case, I've posted on the Android Studio Issue Tracker, something that has always been useless.
PS: I always use the most updated stable version from Android Studio.


text:
Q: How to properly pass data to fragment using external AsyncTask and Interface callback I had this setup working when I just had an activity but now when im trying to use it in a fragment Im a little bit confused,  Im not sure if i need to implement the interface and override the methods in the fragment or leave it in the activity and somehow pass the data to fragment from activity.
Interface
    public interface TaskListener{
    void onTaskFinish(String m);
}

AsyncTask
public class MyAsyncTask extends AsyncTask<Void, Void, Integer>{
private TaskListener taskListener;
Activity activity;
int type;
String gid;
int result = -1;
String gameName;

public DatabaseOperations(int type, Activity activity, String gid){
    this.type = type;
    this.activity = activity;
    this.gid = gid;
}

@Override
protected Integer doInBackground(Void... params){
    if(type == 1){
        gameName = getGameName(gid);
        result = 1;
    }
    if(type ==2){
        //other database function
        result = 2;
    }
    return result;
}

@Override
protected void onPostExecute(Integer result){
    if(result == 1){
        taskListener.onTaskFinish(gameName);
    }
    if(result ==2){
        //other return
    }

    super.onPostExecute(s);
}

public String getGameName(String gameId){
    //insert database function here
}

}

A: Inside AsyncTask:
public TaskListener delegate = null;

.......

@Override
    protected void onPostExecute(String result) {
        progressDialog.dismiss();

        delegate.onTaskFinish(result);

    }

Inside Fragment:
    public class YourFragment implements TaskListener
    {

    .......

    //execute as per your requirement
    MyAsyncTask myAsyncTask = new MyAsyncTask (type, activity, gid);
         myAsyncTask.delegate = (AsyncResponse) this;
         myAsyncTask.execute();

    ......

    //implement method

     @Override
        public void onTaskFinish(String output) {
            parseResult(output);
        }

}

A: There's no hard guideline on this, but generally, I believe that it is more common (and safer) to have the Activity communicate with your 'service' (AsyncTask), and then communicate the result to the Fragment.
To communicate with the fragment, you can either implement interfaces in the Activity and the Fragment that define how they communicate, or you can employ a message bus.
Also, be aware that despite being in the API and being shown in lots of examples, AsyncTask has some non-obvious, non-trivial issues, and I personally recommend staying away from them completely. Without you doing a lot of work on your own, your AsyncTask is not going to be synchronized with the Activity lifecycle. For instance, what happens if the user rotates the device or navigates to a different activity while your AsyncTask is still in it's doInBackground method?
I personally prefer using RxJava to handle background tasks, but there are other solutions to this problem as well.


text:
Q: Receiving keyError: 'deletionTime' on the User resource object I unexpectedly am receiving a keyError when I try to access 'deletionTime' on the User resource object after successfully retrieving a user object from a Users.get call.
I tried printing all the keys of the returned user by executing print(user.keys()).  'deletionTime' is not listed, but it is shown in the documentation, https://developers.google.com/admin-sdk/directory/v1/reference/users
user_service = build('admin', 'directory_v1', credentials=d_creds)
user = user_service.users().get(userKey=userkey).execute()

if not user:
   print('user not found')
else:
   UserObj.fullName = user['name']['fullName']
   UserObj.lastLoginTime = user['lastLoginTime']
   UserObj.creationTime = user['creationTime']
   UserObj.deletionTime = user['deletionTime']
   UserObj.suspended = user['suspended']

Expected: ability to retrieve the deletionTime of a user
Actual: KeyError: 'deletionTime'

A: It's possible that the deletionTime does not exist if the user account was not actually deleted. Can you confirm the user was actually deleted?
If this is the case, you may just want to use Python's get method to try and retrieve the value safely 1. get() will allow you to set a default value if the key-value pair is not in the user dictionary.


text:
Q: Django UserCreationForm add request.user.pk ? Hi i need add request user pk to UserCreationForm. I try many times, but with out results. In my dashboard i have user owner and i have user seller.
One model for all 3 types user. So Owner can create another user with role=seller, but for this i need add parent field with param=request.user.pk  to seller
Custom UserModel
from django.db import models
from django.contrib.auth.models import AbstractUser

USER = 0
OWNER = 1
SELLER = 2
user_type_choice = (
    (USER, 'User'),
    (OWNER, 'Owner'),
    (SELLER, 'Seller'),
)

class User(AbstractUser):
    role = models.CharField(max_length=100, choices=user_type_choice, default=USER)
    idn = models.CharField(max_length=10, blank=True, default=None, null=True)
    mobile = models.CharField(max_length=15, blank=True, default=None, null=True)
    parent = models.ForeignKey('self', null=True, blank=True)
    tariff = models.IntegerField(default=None, null=True, blank=True)

    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

forms.py
class SellerRegisterForm(UserCreationForm):

email = forms.EmailField(required=True)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)

class Meta:
    model = User
    fields = ('username', 'email', 'password1', 'password2') """try add and remove 'parent' here in felds """

def save(self, commit=True):
    user = super(SellerRegisterForm, self).save(commit=False)
    user.email = self.cleaned_data['email']
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.role = ROLE_SELLER
    # try add user.parent = self.request.user.pk
    # but it does not work

    if commit:
        user.save()

    return user

views.py
def register_seller(request):
if request.method == 'POST':
    form = SellerRegisterForm(request.POST)     # create form object
    if form.is_valid():
        #try add new_form = form.save(commit=False)
        # new_form.parent = request.user.pk
        # new_form.save() but it not working

        form.save()
        return HttpResponseRedirect('/accounts/login')

else:
    form = SellerRegisterForm()
return render(request, 'register_owner.html', {'form': form})

A: You need to pass the user object through the form's __init__ method.
class SellerRegisterForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(SellerRegisterForm, self).__init__(*args, **kwargs)

and in your view:
form = SellerRegisterForm(request.POST, user=request.user)

Then simply use self.user anywhere in your form class.


text:
Q: Can I represent a "git rebase" as a series of cherry-picks? It seems that "git rebase" has additional fallback logic to deal with merge failures:
Falling back to patching base and 3-way merge...

What is it doing there, and how would I need to invoke my cherry-picks to get the same behavior?
Probably the right solution is to just not attempt to represent a rebase as a series of cherry-picks, but it would be nice if this were possible, since I can then deal with both rebases and arbitrary collections of changes using the same flow.

A: Most git rebase commands actually do run git cherry-pick.
The fallback you're seeing occurs from the one form of git rebase that, for historical reasons, doesn't use git cherry-pick.  That one form is used when you invoke a non-interactive git-rebase and don't use any of the options that make it use new-and-improved rebase-invoking method.
The old form usually produces the same effect.  It consists of using git format-patch to turn each commit into a patch, and then using git am --3way to apply all the formatted patches.  The --3way option tells git am that, if the patch cannot be applied blindly, it should use the index lines in each formatted patch to achieve part of what git cherry-pick would have done automatically.
If you want rebase to use git cherry-pick directly, you may:

*

*supply the -k option, or

*supply the -m option, or

*supply a -s strategy option, or

*supply a -X extended-option option, or

*use interactive rebase (-i or --interactive), or

*use the --autosquash option, or

*use the -p or (Git 2.18+) -r option.


text:
Q: Jquery each interation problem I got this random position script. But it works only on the first image... What I'm doing wrong?
var randnumsX = [1,2,3,4,5,6,7,8];
var randnumsY = [1,2,3,4,5,6];

$('#obra img').each(function(i,el) {

    m = Math.floor(Math.random()*randnumsX.length);
    randnumsX = randnumsX.splice(m,1);
    posx = Math.floor(m * 50);

    n = Math.floor(Math.random()*randnumsY.length);
    randnumsY = randnumsY.splice(n,1);
    posy = Math.floor(n * 50);

    $(el).css({position:'absolute', left: posx + 155, top: posy});
    $(el).fadeIn('slow');

});

A: splice returns the removed element not the array with the element removed.

A: If you are accessing the div then you won't need # sign
$('div img').each(function(i,el) {

m = Math.floor(Math.random()*randnumsX.length);
randnumsX = randnumsX.splice(m,1);
posx = Math.floor(m * 50);

n = Math.floor(Math.random()*randnumsY.length);
randnumsY = randnumsY.splice(n,1);
posy = Math.floor(n * 50);

$(el).css({position:'absolute', left: posx + 155, top: posy});
$(el).fadeIn('slow');

});


text:
Q: Formal regular expression for a language over a,b,c such that a is never adjacent to b I am trying to write a regex query for a language with letters a,b,c such that a is never adjacent to b.
Can it be done by using only the alternation (plus), concatenation and repetition (multiplication) operators?
L = w belongs to {a,b,c}* such that a is never adjacent to b

A: (Lets see if I recall enough formal language theory.)
Such a regular expression could be built with help of a DFA like this:
A = aA + cC + F      // only a or c can follow a
B = bB + cC + F      // only b or c can follow b
C = cC + aA + bB + F // any char can follow c

Where A, B and C are states representing the state when a, b and c respectively was the previous character. Since any character can follow c we can make C our start state. F being the final end state (end of string).
This DFA can be converted to a regular expression like this:
A = a*(cC+F) // eliminate recursion
B = b*(cC+F) // eliminate recursion

C = cC + aA + bB + F
  = cC + aa*(cC+F) + bb*(cC+F) + F       // substitute A and B
  = (c + aa*c + bb*c)C + aa*F + bb*F + F // regroup
  = (c + aa*c + bb*c)*(aa*F + bb*F + F)  // eliminate recursion
  = (c + aa*c + bb*c)*(aa* + bb* + e)F   // regroup

So the expression would be:
(c + aa*c + bb*c)*(aa* + bb* + e) // e being the empty/null string

Or in informal regex format:
(c|a+c|b+c)*(a+|b+)?

Which can be shortened to:
(a+c|b*c)*(a*|b*)


text:
Q: Tomcat context path issue I deployed application in tomcat under webapps/testing1 folder.
http://localhost:8080/testing1/index.html
This html page has anchor tag with href as "/login"
When I click on anchor, it takes to localhost:8080/login instead of localhost:8080/testing1/login
I did not do any change in tomcat conf xmls. How can I make all paths starts with slash would goto application context?
Suggestions would be appreciated.

A: By declaring a link href="/login" you make that an absolute link on your host. If you want login inside your app you'd have to prepend the context path (request.getContextPath ()) or use relative links ( href="login" )

A: If you deployed context successfully in Tomcat and it is Start up successfully. Then the Application access directly the web.xml from the WEB-INF folder.
It access the servlet using the <url-pattern> and <servlet-class> to identify the servlet.
If you are worrying about accessing HTML files from the servlet you can access them directly from the context path.
i.e
if file present at CONTEXT/html/file1.html you can access it as html/file1.html
if file present at CONTEXT/file2.html you can access it as file2.html

A: You have to specify the . prefix to the href value.
<a href="./login"> so that the URL will be localhost:8080/testing1/login


text:
Q: How to validate a RadioGroup as a required field? I'm making an app and I have a register actvity to register a user using firebase. Everything works fine, but I'm not understanding how to validate the RadioGroup as a gender for male and female. When I click Sign Up values were saved to database even if the Radio Button is not checked.
Here what I have:

        first_name = (EditText) findViewById(R.id.first_name);
        last_name = (EditText) findViewById(R.id.last_name);
        register_email = (EditText) findViewById(R.id.register_email);
        register_password = (EditText) findViewById(R.id.register_password);
        confirm_password = (EditText) findViewById(R.id.confirm_password);
        male = (RadioButton) findViewById(R.id.checkBox);
        female = (RadioButton) findViewById(R.id.checkBox2);
        gender = (RadioGroup) findViewById(R.id.gender);
        login_to_account = (TextView) findViewById(R.id.login_to_account);
        signUp = (Button) findViewById(R.id.signup_button);
        pd = new ProgressDialog(this);

        login_to_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent GoToLoginActivity = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(GoToLoginActivity);
                finish();
            }
        });

        gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mGenderOptions = gender.findViewById(checkedId);

                switch (checkedId) {
                    case R.id.checkBox:
                        strGender = mGenderOptions.getText().toString();
                        break;
                    case R.id.checkBox2:
                        strGender = mGenderOptions.getText().toString();
                        break;

                    default:
                }
            }
        });

        signUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String firstName = first_name.getText().toString();
                String lastName = last_name.getText().toString();
                String email = register_email.getText().toString();
                String password = register_password.getText().toString();
                String confirmPassword = confirm_password.getText().toString();
                validateRegisteringFields(firstName, lastName, email, password, confirmPassword, strGender);
                registerUser(firstName, lastName, email, password, strGender);
            }
        });

    }

    private void registerUser(final String firstName, final String lastName, final String email ,final String password, final String strGender) {
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FirebaseUser firebaseUser = mAuth.getCurrentUser();
                            assert firebaseUser != null;
                            String userId = firebaseUser.getUid();

                            reference = FirebaseDatabase.getInstance().getReference("Users").child(userId);

                            HashMap<String, String> hashMap = new HashMap<>();
                            hashMap.put("id", userId);
                            hashMap.put("firstName", firstName);
                            hashMap.put("lastName", lastName);
                            hashMap.put("gender", strGender);

                            reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Intent registerActivityIntent = new Intent(RegisterActivity.this, MainActivity.class);
                                        registerActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(registerActivityIntent);
                                        finish();
                                    }
                                }
                            });
                        } else {
                            Toast.makeText(RegisterActivity.this, "User already exists", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void validateRegisteringFields(final String firstName, final String lastName,
                                           final String email ,final String password,
                                           final String confirmPassword, final String strGender) {
        if (TextUtils.isEmpty(firstName) || TextUtils.isEmpty(lastName) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(strGender)) {
            Toast.makeText(RegisterActivity.this, "All fields are required", Toast.LENGTH_SHORT).show();
        } else if (password.length() < 6) {
            Toast.makeText(RegisterActivity.this, "Password must be at least 6 characters", Toast.LENGTH_SHORT).show();
        } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(RegisterActivity.this, "Please enter a valid email address", Toast.LENGTH_SHORT).show();
        } else if (!confirmPassword.equals(password)) {
            Toast.makeText(RegisterActivity.this, "Passwords doesn't match", Toast.LENGTH_SHORT).show();
        }
    }

Any help is appreciated!

A: It's wrong to validate like this.
switch (checkedId) {
            case R.id.checkBox:
                strGender = mGenderOptions.getText().toString();
                break;
            case R.id.checkBox2:
                strGender = mGenderOptions.getText().toString();
                break;

            default:
        }

because it will give you always true, this read the text string from your radio butto.
To solve it, use radioButton.isChecked(); it returns true if the radio is checked otherwise false.
Okay, just check inside your method validateRegisteringFields()
if (!female.isChecked() && !male.isChecked()){
            Toast.makeText(RegisterActivity.this, "Please select your gender", Toast.LENGTH_SHORT).show();
        }


text:
Q: How do I access an object in a decorator in RactiveJS I am using Pikaday date picker as a decorator in RactiveJS and want to access the api of the datepicker outside of the decorator, but adding it to the return object doesn't seem to work. Can someone point me in the right direction please.
http://jsbin.com/lefiyume/1/edit?html,js

A: Decorators are designed to be reusable bridges between Ractive and external libraries - so rather than having a startdate decorator and an enddate decorator, it's better to have a single pikaday decorator.
The decorator function is then responsible for managing its own state and interacting with the Ractive instance. If you find yourself trying to get a reference to objects created by the decorator (i.e. the Pikaday instance) it's generally a red flag.
Here's one way you could do it: http://jsbin.com/susev/5/edit?html,js,output
In this example, we're passing a keypath to both instances of the decorator. When the pikadayDecorator function is called with each <input> node, it gets called with two arguments - the node, and the keypath. (You can have additional arguments - just comma-separate them.)
The decorator can then set up two-way binding - it observes the given keypath (e.g. startdate or enddate) and calls the Pikaday instance's setDate() method when it changes. We also use the onSelect() method to update Ractive's model when the selected date changes - this means that we can use the date elsewhere in our template, or even outside the Ractive instance:
ractive.observe('startdate', function (newDate) {
  // This may have been as a result of a `ractive.set()`, or
  // because the user interacted with the datepicker
  console.log('startdate changed to', newDate);
});

(Note that Pikaday will automatically convert strings like '2015-01-01' to date objects.)
There's more information on creating decorators on the docs.

A: You need to call setDate inside the saleEndDecorator function.
http://jsbin.com/lefiyume/7/edit


text:
Q: Already read posts I am working right now on a forum and I'm almost done, but now I came to a point where it kinda got difficult.
You're probably familiar with the phpBB forum. There's this cool feature which flags posts as read and unread.
I found here a similar thread about this, but I didn't really get the solution.
If I save the time when the user logs in and mark all posts which have been created in the past, it might work. But now, what's next? The user read an unread post and I want to mark it as "read" but the other posts should still stay flagged as "unread" until he reads them. I kinda have to store this data, don't I?
And I've actually been also thinking about saving that data in cookies. How about that?

A: You should have a table with a many-to-many reltaionship:
marked_as_read
--------+--------
user_id | post_id
--------+--------

Remove any posts older than (say) 30 days, to keep the table under hysterical size.
In your PHP code, mark any posts not present in this table AND are younger than 30 days as not read. When an answer is read, place it here.
When a post is edited/updated, remove it from all users in this table.

A: Plain and simple: store it in a database. One table with a user_id column and a post_id/thread_id column, which you keep updating when somebody reads a post or updates a post/thread. Yes, that's a lot of data, but it's not really so much that it'd make any problems for a database.


text:
Q: Appimage vs. Flatpak vs Snap apps number I was wondering which one of those package managers contain the biggest selection of apps.
Honestly speaking this fragmentation is confusing and frustrating. Instead of uniting behind one package manager and then create it really good now we have three, fighting between each other.
I am personally leaning towards Appimage, but the selection of apps available seems more limited.
According to the tags usage, there were 34 questions tagged with flatpak, 49 with snap and 0 with appimage, even though this one is the oldest one. So I guess snap should be the most popular.

A: As someone who works on Snapcraft, I can tell you as developers we're not 'fighting' with eachother. That's entirely user-developed human-nature tribalism at work. The fact is each has advantages over the others, and there isn't a one-size fits all.
To answer your question about popularity..
At the time of writing there are 733 flatpaks in flathub. Around 4442 snaps in the Snap Store. There's 969 AppImages listed on AppImage Hub.
There may be more flatpaks in external self-hosted repositories, so this number may not fully represent the number of flatpaks available. However, flathub is the more popular way to distribute flatpaks. There may also be flatpaks lurking in download folders which users can side-load.
The number of snaps may not be accurate either because the data only covers the public snap store. Canonical run a private snap store offering for device manufacturers. So there are more snaps there. As with flatpak there are snaps available to download on various download pages, but this is less common, because the snap developers encourage distribution via the Snap Store.
Appimages are designed to be self hosted, so there's not a central 'store' which provides numbers. There are a ton of appimages which only reside on the download page of a product, or in a github repository release area.


text:
Q: On :hover opacity 0.0 on other level in css I'm trying to make a double rollover link.
When rolling over 'foto'; I'd like to make 'fotografie' appear and 'grafisch' disappear (same thing: when rolling over grafisch, 'foto' to disappear). I've found that it'd be easiest with opactiy, but I can't seem to figure out the code.
Any help highly appreciated.
HTML

foto

fotografie

grafisch

grafisch ontwerp

CSS
.masterplan .fotografie {color: #ff6666;}
.masterplan .fotografie .fotografieh { display: none; }
.masterplan .fotografie:hover .foto { display: none; }
.masterplan .fotografie:hover .fotografieh { display: inline;}
.masterplan .grafischontwerp {color: #33cccc; }
.masterplan .grafischontwerp .grafischontwerph { display: none; }
.masterplan .grafischontwerp:hover .grafisch { display: none; }
.masterplan .grafischontwerp:hover .grafischontwerph { display: inline;}

A: Seeing no easy answer using just CSS, I'd like to suggest adding simple few lines of jQuery:
$(document).ready(function() {

    $(".foto").hover( function() { // Assign 'hover' action to all elements with 'foto' class
        $(".grafisch").toggle(); // 'toggle' display on 'hover' event trigger for all elements with 'grafisch' class
    });
    $(".grafisch").hover( function() {
        $(".foto").toggle();
    });
    /* insert other jQuery code, if any */
    ...
});

I hope that helps, IF you're using jQuery.

EDIT:
Michael, I suspected that you may not be familiar with JavaScript/jQuery. There are tons of examples and tutorials on the web you can easily find. Also, be sure to search StackOverflow as well.
If you expect to continue to work with html and css at all, I'd suggest learning at least the basic concept behind JavaScript and jQuery, which is one of the most widely used JavaScript framework/libraries.
To get you started, check out the following links:

*

*Setting up jQuery

*How jQuery Works
Notice that I also added some comments to the code I wrote earlier. Let me know if you have any other questions on this topic.

Check out this demo --> DEMO


text:
Q: When does analytic in the operator norm imply analytic in the trace class norm? Consider $U$ a nice compact region in $\mathbb{C}$ with boundary $\Gamma$. Let $S_1$ b the ideal of trace class operators on a separable complex Hilbert space $H$. We will let $\|\cdot \|$ be the operator norm and $\|\cdot \|_1$ be the trace norm. Suppose $W:U\to S_1$ is complex analytic in the operator norm. Under what conditions is $W(\lambda)$ analytic in the $\| \cdot \|_1$ norm? I have proved that the following are equivalent when $W(\lambda)$ is operator analytic:

*

*$W(\lambda)$ is continuous in the operator norm

*for a fixed $M$, we have $\|W(\lambda)\|_1 <M$ for each $\lambda \in \Gamma$

*tr $W(\lambda)B$ is analytic for each bounded operator $B$.

*$W(\lambda)$ is analytic in the $\|\cdot\|_1$ norm.

I can provide some ideas for these proofs if that's be helpful.
This leads us to Question 1: What if we know that tr $W(\lambda)$ is analytic? Is there a nice way to compare tr $W(\lambda)$ with tr $W(\lambda)B$? I would love an inequality like
$$ |\text{tr }AB| \leq\|B\||\text{tr }A|  $$
for $A \in S_1$ and $B$ bounded. Although it would probably be greedy to expect this in general.
Also, I'm willing to impose even stronger assumptions on $W$ if necessary. One very strong constraint is to assume that $W$ has a rank bound along $\Gamma$, I.E. for a fixed $N$ we have rank $W(\lambda)<N$ for each $\lambda \in \Gamma$. This actually guarantees analyticity as
$$\|W(\lambda)\|_1 \leq N\sup_{\lambda \in \Gamma} \|W(\lambda)\|$$
Attempting to weaken this condition, we arrive at Question 2: What happens if $W(\lambda)$ is finite rank for each $\lambda$, but has no rank bound? I suspect that finite rank and analytic actually implies rank bounded, but I do not know.
Edit 1
Here's a fun idea to that might help prove finite rank implies rank bounded. The set
$$
S_n = \{\lambda : W(\lambda) \text{ has rank at most}n\}
$$
is closed (continuity of $W$ tells us singular values are continuous). So Baire Category theorem tells us that some $S_n$ is dense somewhere. So in some open set, $W$ is rank bounded. So can I use an analytic extension in the trace norm to do something? This looks like the proofs of the open mapping theorem and whatnot...
Edit 2
Here's another fact that may be helpful. Consider a sequence of complex analytic functions $f_n:U\to \mathbb{C}$. Suppose they converge pointwise to an analytic function $f$. Then $f$ is analytic on an open dense neighborhood of $U$. This is potentially helpful because for any orthonormal basis $\phi_i$,
$$
\text{tr} W(\lambda) B = \sum_{i=1}^\infty \langle W(\lambda)B\phi_i,\phi_i\rangle
$$
And because $W(\lambda)B$ is analytic in the operator norm, so will the each inner product be analytic.
I am fairly familiar with Gohberg's work on trace class operators. Unfortunately, despite all of the great theorems on bounds for singular values, knowing that tr $W(\lambda)$ is analytic gives no information about the singular values.


text:
Q: I want to use one controller and html.erb files for my dynamic table. How I will do it in Ruby On Rails? I stored all the tablename I've created to Menu table. And every time I add the table in Menu, it will automatically create a link under Menu list
see below.

I want each table in Menu to have a Listing, New, Edit, and Delete.
see below.

I have a controller prj_menus_controller, I will just pass the id of the table from Menu table.
here is the code for index and new in my controller.
Class PrjMenusController < ApplicationController

  def index
    @prj_menus = Menu.find(params[:id]).tablename.singularize.classify.constantize.all
  end

  def new
    @prj_menu = Menu.find(params[:id]).tablename.singularize.classify.constantize.new
  end

  def create
    @prj_menu = Menu.find(params[:id]).tablename.singularize.classify.constantize.new(prj_menu_params)

    if @prj_menu.save
      redirect_to :action => 'index'
    else
      render :new
    end
  end

private
  def prj_menu_params
    params.require("HERE IS MY PROBLEM").permit(:name)
  end
end

and in my
new.html.erb
<%= simple_form_for (@prj_menu),:url => prj_menus_path, :method => :post do |f| %>
    <%= f.input :name %>
    <%= f.submit 'Save', class: 'btn btn-primary' %>
    <%= link_to "Cancel", :back, {:class=>"btn btn-default"} %>
<% end %>

I can get the list in my index.html.erb, it is working. My problem is that I don't know how to get all params when I click the submit in new.html.erb. I got this hash
{"sample1_table"=>{"name"=>"test 6"}, "commit"=>"Save","controller"=>"prj_menus", "action"=>"create"}

It is correct but I don't know what to put in my controller. I tried this params.require(["#{@prj_menu}"]).permit(:name), it creates new record but params[:name] does not save.
I am still a noob to Ruby On Rails and I don't know what to search for this.

A: I think you are mostly confused on what parameter whitelisting does and how parameters are passed from the form to the controller.
I does not really matter if the name of the form hash matches the name of the database table. It just does in most cases since that makes the most sense. It's simply representative of the REST interface of your app.
Let's say you have a action which creates Pets:
POST /pets
And in our form we have a bunch of inputs like so:
<input name="pet[name]">

Rails will map create a params[:pet] hash { name: 'Spot' }. But we want to save the pets as an Animal.
class PetsController < ApplicationController

  def new
    @pet = Animal.new()
  end

  def create
    @pet = Animal.new(pet_params)
    if @pet.save
    # ...
  end
  def pet_params
    params.require(:pet).permit(:name)
  end
end

Animal does not care what the params key is, it just gets a hash. But we also need to tell simple_form what parameter key we want to use since it looks at the model_name attribute.
simple_form_for(@pet, as: :pet)

Gives us pet[name] instead of animal[name].
I don't get why you are so adamant about making things so difficult for yourself though unless you are creating a database administration tool in the vein of PHP_MyAdmin. And even that case you don't even want to be altering the schema of the app database at runtime.
You are going to run into huge problems when it comes to creating effective queries for getting all the menus.


text:
Q: How to derive the Asymptotic series of sums related to Euler's Summatory Function? I need techniques to solve the density of $T$, a subset of $\mathbb{Q}$ in form of an albegraic expression with relatively prime numerator and denominator values. The best way of doing this is by deriving an asymptotic series of sums related to Euler's Summatory Function.
Many are familiar with Euler's Totient Function or $\phi(n)$; however, the function has an alternate form
$$\phi(n)=\left|\left\{\left.\frac{m}{n}\in[0,1]\right|\gcd{\left(m,n\right)}=1\right\}\right|$$
where $m,n\in\mathbb{Z}$
Similarly, Euler's Summatory Function or $\Phi(t)$ can be defined as
$$\Phi(t)=\sum_{0<n<t}\left|\left\{\left.\frac{m}{n}\in[0,1]\right|\gcd{\left(m,n\right)}=1\right\}\right|$$
which has an asymptotic series of
$$ \frac{3}{\pi^2}t^2+O\left(t\left(\log t\right)^{2/3}\left(\log \log t\right)^{4/3}\right)$$
In general, I want to find the asymptotic series of sums that contain the subset of $\left\{\left.\frac{m}{n}\in[0,1]\right|\gcd{\left(m,n\right)}=1\right\}$. This helps me derive an approximation. The sums are in the form
$$\sum_{0<D(n)<t}\left|\left\{\left.\frac{N(m)}{D(n)}\in[0,1]\right|\gcd{\left(N(m),D(n)\right)}=1\right\}\right|$$
Where $N$ and $D$ are functions that allow the set inside the sum to be a subset of $\left\{\left.\frac{m}{n}\in[0,1]\right|\gcd{\left(m,n\right)}=1\right\}$.
I was unable to mathematically derive the asymtotic series for sums with specific functions of $N$ and $D$. Instead I found approximations using Computer Programming. Unfortunately most approximations were inaccurate and for those that were, I could not solve certain variables.
For example, in equation
$$\sum_{0<D_1 n+ D_0<t}\left|\left\{\left.\frac{N_1m+N_0}{D_1n+D_0}\in[0,1]\right|\gcd{\left(N_1 m +N_0, D_1 n +D_0\right)}=1\right\}\right|\approx A\Phi(t)\approx \frac{3A}{\pi^2}t^2 $$
I am unable to determine $A$ in terms of integers $N_0, N_1, D_0$ and $D_1$.
In equation
$$\sum_{0<D_c n^c+D_0<t}\left|\left\{\left.\frac{{N_p}m^p+N_0}{D_{c}n^c+D_0}\in[0,1]\right| \gcd{\left({N_p}m^p+{N_0},D_{c}n^c+D_0\right)}=1\right\}\right|\approx \frac{R}{t^{(p-1)/p} t^{(c-1)/c}}\Phi(t)$$
I am unable to solve $R$ in terms of integers $D_c,D_0,N_p,$ and $N_0$. Morover, the approximation is poor since the relative error is less than $.01$.
And in equation
$$\sum_{0<{\left(D_1\right)}^{n}+D_0<t}\left|\left\{\left.\frac{N_1m+N_0}{{\left(D_1 \right)}^{n}+D_0}\in[0,1]\right|\gcd{\left(N_1 m+N_0, \left(D_1\right)^{n}+D_0\right)}=1\right\}\right|$$
I am unable to find an approximation
Questions
In conclusion:
How does one mathematically derive the asymptotic series of the sums listed above?
Are there better approximations that can be used?
Are there research papers on this subject? I have searched but found nothing. The closest I've got is the Totient function being related to factor rings

A: For a Dirichlet character $\chi$ let
$$F_\chi(s) = \sum_{n=1}^\infty n^{-s} (\sum_{m \le n}\chi(m)), \qquad L(s,\chi) = \sum_{n=1}^\infty n^{-s} \chi(n),\qquad G_\chi(s) = \frac{F_\chi(s)}{L(s,\chi)}$$
Then if $\gcd(a,b)=1$
$$H(s) =\frac{1}{\phi(a)}\sum_{\chi \bmod a} \overline{\chi(b)} G_\chi(s) = \sum_{n=1}^\infty c_n n^{-s}, \qquad c_n = \sum_{m \le n, m \equiv b \bmod a, \gcd(n,m)=1} 1$$
You'll obtain that
$$\sum_{n \le x} c_n = \frac{1}{2i\pi} \int_{3-i\infty}^{3+i\infty} H(s) \frac{x^s}{s}ds \sim \text{Res}(H(s) \frac{x^s}{s},2) \\= \frac{1}{\phi(a)}\sum_{\chi \bmod a} \overline{\chi(b)}\frac{x^2}{2 L(2,\chi)} \text{Res}(F_\chi(s) ,2) =\frac{1}{\phi(a)} \overline{\chi_0(b)}\frac{x^2}{2 L(2,\chi_0)} \text{Res}(F_{\chi_0}(s) ,2)= \frac{x^2}{2a \zeta(2)}\prod_{p | a} (1-p^{-2}) $$
(where $\text{Res}$ is the residue of a meromorphic function and $\chi_0(m) = 1_{\gcd(m,a)=1}$ is the trivial character so that $L(s,\chi_0) = \zeta(s)\prod\limits_{p | a} (1-p^{-s})$ and $F_{\chi_0}(s) \sim \sum\limits_{n=1}^\infty n^{-s} \frac{n\phi(a)}{a}$)
Following the same lines, if $gcd(d,e)=1$ you should get
$$\sum_{n \le x, n \equiv e \bmod d} c_n \sim \frac{x^2}{2a \phi(d) \zeta(2)}\prod_{p | a} (1-p^{-2})$$


text:
Q: How to convert MS Word to PDF in the web browser I've seen others ask this but I think my requirement is the most strict yet:
I need to programmatically convert MS Word .DOC (Office 2003 or earlier) or .DOCX (Office 2007 or later) files into PDF files. This needs to happen on an ad-hoc basis over time - not once, not with a set of files sitting on my desktop right now.
My platform runs in the cloud, so I have no server on which to run one of the many server-side conversion tools out there and I cannot write a VB or C# or Java application in which to make this happen. For instance, I cannot use Aspose.words or Libre Office since I have no computer on which to install them or an app that uses them.
I am thinking I need a client-side, web browser-based solution, JavaScript for instance. Is there such a library? From the other questions I see have been asked here over the last couple of years, I think the answer is no, but I thought I'd better check to be sure.
Thanks!

A: The Docmosis Cloud service can do doc/docx -> pdf from JavaScript.  You can have a doc/docx converted (rendered) by posting a https request with a JSON payload.  Please note I work for the company that created Docmosis.
I hope that helps.


text:
Q: Is it possible to force a WebControl to render as a  instead of a ? How can I force the WebControl to render as a <div>? Currently, it renders as a <span> and our UI guy prefers it be a <div>. To accommodate him, I'd like to see if this is possible and if so, how it's possible.

A: You can override the RenderBeginTag method of WebControl:
public override void RenderBeginTag(HtmlTextWriter writer)
{
    writer.RenderBeginTag("div");
}

There's also a RenderEndTag that you can override, which might not be necessary in this case:
public override void RenderEndTag(HtmlTextWriter writer)
{
    writer.RenderBeginTag();
}

A: Yes, it is definitely possible. Asp.net gives you full control over the output rendered.
Take a look at Control Adapters
The asp.net team has released many adapters for CSS friendly rendering for controls like Menu, TreeView, and FormView. Take a look at CSS friend control adapters
You can always build your own to customize the rendering as needed by your UI guy.

A: Probably better to override TagKey like so:
protected override HtmlTextWriterTag TagKey => HtmlTextWriterTag.Div;
Then any attributes the WebControl would render continue to be placed on opening tag.


text:
Q: Creating 'n' number of variables, where 'n' is an input from the user I am beginner in C language.
Just wanted to know if there's a way of creating 'n' number of variables, where 'n' is an input from the user. Is it possible to decide the number of variables to be created during runtime.

A:
Is it possible to decide the number of variables to be created during runtime.

If we are talking about creating more or less variables depending on user input, that would mean something like this:
   int n;
   int result = scanf("%d", &n);
   // TODO: Check result value.

   int var0, var1, var2, ... varn;

This is not possible. Each variable you want to use, must de defined in your code at compile time.
If you think about "number of variables" in the way of "room for a number of values" then we can do something for you.
In C99 a feature called "Variable Length Arrays" (VLA) was introduced. (In C11 it was made optional)
This feature allows you to define a local array variable with a non-constant number of elements:
   int n;
   int result = scanf("%d", &n);
   // TODO: Check result value; check n for allowed range to fit into stack

   int values[n];

The memory for this array is released when you leave the function where you defined it.
Or in all C standards you can use a pointer to a dynamically allocated memory:
   int n;
   int result = scanf("%d", &n);
   // TODO: Check result value.

   int *values = malloc(n * sizeof(*values));
   // TODO: Check for NULL value.

You can use this memory also after leaving the function where you allocate it. And you must free it later if you don't need it anymore.
In both versions you can access the values via array notation: value[index].


text:
Q: Modifying elements of an iframe with local source with Chrome extension I'm working away at a Chrome extension right now, but I'm running into permission/security issues. I have a local HTML template file which I am inserting into a floating iframe on certain web pages. I have certain information retrieved from AJAX / cookies which I want to insert into the template. When I do this, I am met with an error:
Some relevant code:
$(this).after('

');
$('iframe').contents().find('#description').html(data.description);

The second line throws the error:
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement'
Blocked a frame with origin "http://ugradcalendar.uwaterloo.ca" from accessing a frame with origin "chrome-extension://kdjcjbijngfephllebpnahpodnbcnhlo".
The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "chrome-extension". Protocols must match.

I think I have my manifest set up properly, but am not entirely sure:
...
"web_accessible_resources": ["loading.gif", "hoverwindow.html"],
"content_scripts": [
{
  "matches": ["http://ugradcalendar.uwaterloo.ca/*"],
  "css": ["extension-styling.css"],
  "js": ["jquery-1.11.3.js","js.cookie.js","script.js"],
  "all_frames": true
}
],
"permissions": [
  "activeTab",
  "cookies",
  "http://uwflow.com/",
  "https://uwflow.com/",
  "http://ugradcalendar.uwaterloo.ca/",
  "https://ugradcalendar.uwaterloo.ca/"
]

A: So, a couple days later and I found a solution that works for me. I didn't end up having any success with iframe for this.
Since my template was a local file, I learned I could simply $.load() the template into an absolute-position div and save myself the headache of postMessage errors and other iframe quirks.
For reference, in case anybody runs into a similar problem with trying to use local html in an iframe, the way I did this:
$('body').after('

');
$('#flowframe').load(chrome.extension.getURL("hoverwindow.html"));

Then I am able to directly modify elements of hoverwindow.html on the same domain without issues.


text:
Q: How to implement ontology in chatbots? I am trying to develop a chatbot that needs to have a basic ontology embedded in it. I'm having trouble thinking of an approach to solve these kinds of problem.
For example,
User Input: Who is Barack Obama?
Answer: Barack Obama is a politician of the USA.

User Input: What is his age?
Answer: 57 years.

What should I do to let the system know his in the second question refers to Barack Obama in the first question? Thanks.


text:
Q: Waiting for a button click during the execution of a function in Pyside I have multiple buttons. When I click one of them, I call a function that iterates over rows of a table (say, changes the background colour of the row). During the execution of this function, in the middle of the iteration, I'd like to "pause" and wait for another button to be clicked in order to resume the execution of the function. During this "pause" I'd like all other buttons (that is, the ones I'm not waiting to be clicked) to be disabled or ignored.
I've looked into QTimer and QThread, but I think that I'm unnecessarily over-complicating things. Looking for suggestions...

A: First of all you need to call QtGui.qApp.processEvents() method at the end or beginning of the iteration in order to make the gui responsive during the execution of the loop. Then you need to maintain a list of rows (say, self.allRows), in each iteration pop one row from the list change the background color and append it to a second list (say, self.doneRows). Also declare a boolean variable as False (say, self.pause = False) inside __init__ and add a check statement at the beginning of the loop, if the self.pause is True, break the loop. Then you need to add a slot to update the value of self.pause to True.
def pause_execution(self):
    self.pause = True
    # loop through all the buttons to make them disabled excluding the pause and resume buttons
    for btn in self.buttons:
        btn.setEnabled(False)
    QtGui.qApp.processEvents()

Connect Pause button's clicked signal to this slot. Now the loop will be broken and self.allRows contains only the rows with no background color changed yet. Create another slot to resume the loop again. This time the loop will change the background color of only remaining rows.
def resume(self):
    self.stop = False
    # loop through all the buttons that were disabled, to make them enabled (if you need to)
    for btn in self.buttons:
        btn.setEnabled(True)
    QtGui.qApp.processEvents()
    # call the method which contains the background color changing loop.

A: I think you are looking for this to execute on each method depending on the mouse button click:
myWidget.setDisabled(true)

Then, you could find all the children of the main window or the root widget whatever that is, this way:
widgets = form.findChildren(QtGui.QWidget)

Then, you could connect your push button click to the desired method as follows:
button.clicked.connect(setDisableWidgets)

So, here is a simple example:
import sys
from PySide.QtCore import *
from PySide.QtGui import *

g_disable = true
g_mainWidget = ...

def setDisableWidgets():
    ''' This will get more exciting when you have other widgets, too,  for sure '''
    widgets = mainWidget.findChildren(QtGui.QWidget)

    for widget in widgets:
        # filter out push button though based objectName for instance
        widget.setDisabled(disable)

    # Toggle for the next run
    disable = not disable

app = QApplication(sys.argv)
button = QPushButton("Click me")
button.clicked.connect(setDisableWidgets)
button.show()
app.exec_()

In your QThread run, you could extend the code that runs that function the way that, for instance is checks against the disable variable after processing each row or even small units if you wish and if that is false, it runs QThread.sleep(100) or so, and then wakes up for a check against disable. If it is false, then it continues the execution, otherwise sleeps back.
Here is the pseudo code:
class MyThread (QThread):
    def run():
        isEnd = false
        while not isEnd:
            while disable:
                self.msleep(200)
            # Process next row
            # if we are done, isEnd = true


text:
Q: OutputProjectionWrapper vs fully connected layer on top of RNN I'm reading the 14th chapter of Hands-On Machine Learning with Scikit-Learn and TensorFlow. It says:

Although using an OutputProjectionWrapper is the simplest solution to reduce the dimensionality of the RNN's output sequences down to just one value per time step (per instance), it is not the most efficient. There is a trickier but more efficient solution: you can reshape the RNN outputs, then apply a single fully connected layer with the appropriate output size. [...] This can provide a significant speed boost since there is just one fully connected layer instead of one per time step.

This makes no sense to me. In case of OutputProjectionWrapper we need to perform 2 operations per time step:

*

*Calculate new hidden state based on previous hidden state and input.

*Calculate output by applying dense layer to calculated hidden state.

Of course, when we use plain BasicRNNCell + dense layer on top, we need to do only one operation on each time step (the first one), but then we need to pipe each output tensor through our dense layer. So we need to perform the very same amount of operations in the both cases.
Also, I can't understand the following part:

This can provide a significant speed boost since there is just one fully connected layer instead of one per time step.

Don't we have only one fully connected layer in both cases? As far as I understand OutputProjectionWrapper uses the same shared layer on each time step. I don't even know how it can create different layer for every time step because OutputProjectionWrapper has no information about the amount of time steps we will be using.
I will be very grateful if someone can explain the difference between these approaches.
UPD Here is pseudocode for the question. Am I missing something?
# 2 time steps, x1 and x2 - inputs, h1 and h2 - hidden states, y1 and y2 - outputs.

# OutputProjectionWrapper
h1 = calc_hidden(x1, 0)
y1 = dense(h1)
h2 = calc_hidden(x2, h1)
y2 = dense(h2)

# BasicRNNCell + dense layer on top of all time steps
h1 = calc_hidden(x1, 0)
y1 = h1
h2 = calc_hidden(x2, h1)
y2 = h2

y1 = dense(y1)
y2 = dense(y2)

UPD 2 I've created two small code snippets (one with OutputProjectionWrapper and another with BasicRNNCell and tf.layers.dense on top) - both created 14 variables with the same shape. So there is definitely no memory differences between these approaches.

A: My guess is applying 1 layer to a tensor of shape (x, n) is faster than applying same layer to a tensor of shape (x) n times due to matrix multiplication optmizations.

A: This webpage has a detailed explanation to your very question.
https://www.oreilly.com/library/view/neural-networks-and/9781492037354/ch04.html
Here is an excerpt from the above page. Hope this helps.
Although using an OutputProjectionWrapper is the simplest solution to reduce the dimensionality of the RNN's output sequences down to just one value per time step (per instance), it is not the most efficient. There is a trickier but more efficient solution: you can reshape the RNN outputs from [batch_size, n_steps, n_neurons] to [batch_size * n_steps, n_neurons], then apply a single fully connected layer with the appropriate output size (in our case just 1), which will result in an output tensor of shape [batch_size * n_steps, n_outputs], and then reshape this tensor to [batch_size, n_steps, n_outputs]. These operations are represented in Figure 4-10.


text:
Q: How do I bind child entity detail fields to text boxes? My RadGridView is bound to child records via the parent entity's navigation property. Users can edit records in the grid. Now I'd like to also allow editing of child records outside of the grid. After selecting a record in the grid you could edit it using text boxes. I can't seem to find the right binding statement for each text box. My working child grid XAML looks something like this:
<telerik:RadGridView Name="childGrid" ItemsSource="{Binding ChildEntitiesNav, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" AutoGenerateColumns="False">
     <telerik:RadGridView.Columns>
          <telerik:GridViewDataColumn DataMemberBinding="{Binding ChildFieldOne}" Header="Child Field One"/>
          <telerik:GridViewDataColumn DataMemberBinding="{Binding ChildFieldTwo}" Header="Child Field Two" />

I've added text boxes corresponding to each grid column but I can't get any data to appear. I've tried these text box binding statements:
Text="{Binding Path=ChildEntitiesNav.ChildFieldOne}
and Text="{Binding Path=ChildFieldOne}
I'm using WPF and Entity Framework database first. What is the correct binding statement for editing child detail entities via a parent navigation property?
Thanks in advance.
ANSWER: Andrey's response led me to the solution. I simply needed to bind my text boxes to the grid's SelectedItem (rather than binding to the child entity). I added the grid name as the DataContext to my text box:
<TextBox Name="ChildFieldTextBox" Text="{Binding Path=ChildFieldName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" DataContext="{Binding ElementName=childGrid, Path=SelectedItem, Mode=TwoWay}"  />

These links helped:
Here and here.

A: Here is an article which may help you. It describes how to bind a control to a property of DataGrid's selected item.
Or you can to add SelectedChildEntityNav property to your ViewModel. The RadGridView declaration will look like this:
<telerik:RadGridView Name="childGrid" IsSynchronizedWithCurrentItem="True" AutoGenerateColumns="False"
ItemsSource="{Binding ChildEntitiesNav, Mode=TwoWay}"
SelectedItem="{Binding SelectedChildEntityNav, Mode=TwoWay}">

After that you're able to bind the textboxes to SelectedChildEntityNav's properties.