text:
Q: polynomial and integer roots I'm doing some homework for a computer science class. It's been so long since I've done math, I have a question that assumes math knowledge that confuses me.
Given:
Whether a diophantine polynomial in a single variable has integer roots.
With the given question I need to determine if that question is solvable using computers. I know how to do that, but I don't the math required to answer this question.
So I understand "Whether a .... polynomial in a single variable has integer ...?"
My question:

*

*What does diophantine mean

*What is an integer root

*How do you determine if a diophantine polynomial in a single variable has integer roots?

The math behind this question is assumed to be known, once I know the answers to those three questions (really just the last one) I can answer my homework.
Note: it may or may not be obvious that this is computable, since I don't know enough about the math to say, I will say a lot of things that seem computable are not unless their input and output are acceptable to a finite precision.

A: There are various definitions of Diophantine equation, not all equivalent. But one standard definition goes as follows. Let $P(x_1,x_2,\dots,x_k)$ be a polynomial with integer coefficients. A solution of the Diophantine equation $P(x_1,x_2,\dots,x_k)=0$ is a $k$-tuple $(x_1,x_2,\dots,x_k)$ of integers that satisfies the equation.  An equation is Diophantine partly because of its shape, but much more because of the kinds of solutions we are looking for.
General Diophantine equations can be exceedingly difficult. However, in principle one variable equation are simple. We have a polynomial $P(x)$ with integer coefficients. Let
$$P(x)=a_0x^n+a_1x^{n-1}+a_2x^{n-2}+\cdots +a_n.$$
Without loss of generality we may assume that the constant term $a_n$ is not equal to $0$. It is straightforward to show that any integer solution of the equation $P(x)=0$ must divide the constant term $a_n$.
So there is a simple (in principle!) algorithm for finding all the integer solutions of $P(x)=0$:
(i) Find all the divisors (positive and negative) of the constant term and then
(ii) Find out, by substitution, which ones of these divisors "work."
As you know, factorization of large numbers can be computationally difficult. However, there certainly is an algorithm for factoring.
Remark: There is a very famous related problem, called Hilbert's 10th Problem. Hilbert asked for a general algorithm that would, for any polynomial $P$ with integer coefficients, and possibly many variables, determine whether the equation $P=0$ has integer solutions. After earlier progress by a number of people, Matijasevich showed that there is no general algorithm of the type that Hilbert asked for. But as we noted in our answer to your question, there certainly is an algorithm that works for polynomials in one variable.
Diophantus himself in his Arithmetica looked mainly for rational solutions. Often, a problem is called Diophantine if we are interested in solutions that are somehow fairly closely related to the integers.
Note that (at least to people in Logic) the famous Fermat equation $x^n+y^n=z^n$ is not a Diophantine equation, since the exponents are also variable. Such equations are sometimes called exponential Diophantine, or, more casually, Diophantine.
A simple example: Consider the equation $3x^4-12x^3-x^2+4x=0$. We want to find all integer solutions of this equation. First rewrite our equation as
$x(3x^3-12x^2-x+4)=0$. This has the obvious solution $x=0$. Any other solutions must be solutions of the equation
$$3x^3-12x^2-x+4=0.$$
By the result mentioned in the main post, any integer solution of this equation must divide the constant term $4$. The divisors of $4$ are $\pm 1$, $\pm 2$, and $\pm 4$. Substitute these values in turn for $x$. We find that $x=4$ is a root, but none of the others are. So we have found all the integer solutions of our original equation: they are $x=0$ and $x=4$.

A: A Diophantine equation is one where the variables are required to take integer values.  A root of a polynomial is a value of the variable(s) that gives the polynomial the value $0$.


text:
Q: swagger return `Whitelabel Error Page` for url `../swagger-ui.html` I followed this link: a Chinese introduction article, according to it, I only need to add the dependencies in pom.xml. (./v2/api-docs has been always working.)
It used to work, but today it breaks.
my swagger dependencies in pom.xml file
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

I am using spring boot 2.3.3, and swagger 2.9.2 .

A: in SwaggerConfig.java,
add below codes:
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

    ...

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决静态资源无法访问
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

A: With newer versions of spring boot, this can be achieved with a property:
spring.resources.static-locations=classpath:/static/,classpath:/static/vendor/,classpath:/static/custom/

Also, make sure you configure SpringSecurity class to accept requests to this resources
@Override
public void configure(WebSecurity web)
{
    web.ignoring()
            .antMatchers( "/static/**","/resources/**", "/js/**", "/css/**", "/images/**");

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Perforce version in puppet Im trying to automate deployment of perforce (p4 & p4v) using puppet. For this I have created a perforce resource
perforce { 'p4' :
    version => '>= 15.1',
    ensure  => 'present',
}

The problem I have is how to determine installed version. Perforce sort all tar balls in release order .../R15.1/... but running p4 -V yields a version number that looks more like date and build no , e.g. 2016.2.345671
Is there a way that I can get the release installed?

A: I'm not really sure what you're asking since it sounds like you already know about p4 -V, but will try to answer the implied question of "what do all the pieces of the version string mean"...
"2016.2" is the same as "r16.2" -- releases are named according to the year of release, and there have historically been two major releases most years so the version numbers tend to be of the form YEAR.1 and YEAR.2.
The number at the end of the version string in the binary is basically the patch level (it correlates with changes in the release notes).
Here's an example of using a regex to deconstruct a Perforce version string:
https://swarm.workshop.perforce.com/files/guest/sam_stafford/scripts/itest.pl#401


text:
Q: os.environ.setdefault('DJANGO_SETTINGS_MODULE') doesn't work I'm trying to run a standalone script that uses the Django models for accessing the database.
The script is very simple, see below:
import sys
from manager.models import Playlist
from manager.utils import clean_up_playlist, add_record_to_playlist

def main(playlist_id, username):
    playlist = Playlist.objects.get(playlists=playlist_id)
    # the script does other stuff

if __name__ == "__main__":
    playlist_id = sys.argv[1]
    username = sys.argv[2]
    import os
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SpotifyPlaylistManager.settings')
    import django
    django.setup()
    main(playlist_id, username)

The script is in the top folder of the Django folder
SpotifyPlaylistManager/
|-SpotifyPlaylistManager/
  |-settings.py
|-venv
|-manage.py
|-my_script.py

For some reason, if I try to run it with the command below I got the error
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

The actual command I need to launch
source /home/nicola/PycharmProjects/SpotifyPlaylistManager/venv/bin/activate && python /home/nicola/PycharmProjects/SpotifyPlaylistManager/scheduler.py 6tIMeXF1Q9bB7KDywBhG2P nicoc && deactivate

I can't find the issue

A: Moving the Django include inside the main worked
if __name__ == "__main__":
    playlist_id = sys.argv[1]
    username = sys.argv[2]
    import os
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SpotifyPlaylistManager.settings')
    import django
    django.setup()
    from manager.models import Playlist
    from manager.utils import clean_up_playlist, add_record_to_playlist

    main(playlist_id, username)


text:
Q: capybara find and save text value from a page i am in the process of writing a Capybara Automation suite. one thing that i am trying to do is extract a value between the td tags from the html source
CB/AE9999XX/A001

i.e. find and extract the value CB/AE9999XX/A001 then save it into a variable to use later on.
i hope you can help
thanks

A: saved_text = find("td.table-column-data").text

Will get the text from the element - obviously the selector passed needs to select a unique element, which will depend on the surrounding html

A: You can use the below mentioned way to extract and save the value in a variable:
extractedValue = find('.table-column-data').text

This will fetch the text "CB/AE9999XX/A001" and store it in the variable "extractedValue".
Apart from this, you can also extract the text using jquery as shown below:
extractedValue = page.evaluate_script("$('.table-column-data').text()")

Hope this helps :)


text:
Q: Ocultar e mostrar div utilizando href Gostaria de saber como ocultar e mostrar div utilizando href?
Por exemplo, tenho um Titulo chamado "Filtro" ao clica no botão ao lado dele, quero que mostre os elementos que estão dentro dele e ao clicar novamente quero que oculte os elementos.

      Filtros

A: Pode criar uma função do JavaScript:

Você deve chamar a função dentro do Título: onclick="myFunction()"

A: Seu href vai ficar da seguinte maneira:

Agora você precisa ter a função que faz a mágica :
Primeiro você verifica o estado atual ( caso seja do seu interesse se não pode apenas ocultar ou mostrar diretamente ) e armazena em uma variável.
function ocultarMostrarFiltros(){
    var visivel = document.getElementsByClassName("example").style.display;
    var element = document.getElementsByClassName("example");
    if(visivel == 'none'){
        element.style.display = 'block';
    }else{
        element.style.display = 'none';
    }
}

Se quiser deixar com um tom mais agradável você pode usar o jQuery com a função hide() e show() ou simplesmente trabalhar com transition no seu css.
Espero ter ajudado! até a próxima.


text:
Q: What does the overlap between momentum eigenstates mean? I am studying quantum mechanics right now, and I learned that momentum eigenstates are plane waves, that is
$$
\langle x \vert p\rangle = e^{ipx}
$$
and
$$
\langle p' \vert p\rangle = \int_{-\infty}^{\infty} e^{i(p-p')x}dx = \delta(p-p')
$$
This makes sense when thinking about Fourier transforms, but I'm confused how to think of this integral. If I were to think of this integral as $\sum e^{i(p-p')x}\Delta x$, then I would end up with a bunch of imaginary components in the sum, and I don't see how that ends up being a delta function.

A: First the quantity $\langle x|p\rangle$ is the probability amplitude that when the particle has the momentum $p$, its position is $x$.
Now coming to the main concern
I'll use the short hand, so I'll suppress the notation a bit and not write $\hbar$ and $k$ for $p$ that just different from the scalar factor.
The delta function is the sampling function since it samples the value of the function at one point
$$\int \delta(k-k')f(k')dx=f(k)$$
$$f(x)=\frac{1}{\sqrt{2\pi}}\int e^{-ikp}f(k)dk$$
and its inverse
$$f(k')=\frac{1}{\sqrt{2\pi}}\int e^{ikk'}f(x)dx$$
feeding one into other
$$f(k')=\int \left(\frac{1}{2\pi}\int dx e^{ik(k'-k)}\right)f(k)dk$$
Comparing it with the first
$$\frac{1}{2\pi}\int dx e^{ix(k'-k)}=\delta (k'-k)$$

If you want to work with sum then you need to take the limit in the end so you end up with integral.

A: $\delta(p-p')$ is often called delta function, but actually it is not function at all. It is a so-called distribution, it does not have values, but it has integrals with functions, these integrals may be functions or distributions. The "delta function" distribution is defined by its behaviour under integration sign:
$$
\int_{-\infty}^{+\infty} \delta(p-p')f(p)dp = f(p').
$$
for any continuous function $f(p)$.
It turns out there are many ways to express this distribution, for example
$$
I(p,p') = \frac{1}{2\pi}\int_{-\infty}^{+\infty} e^{i(p-p')x}dx
$$
is one of them. Don't agonize over imaginary numbers in the integrand, all of them (except one) can be paired with complex conjugated counter part and their imaginary parts cancel each other:
$$
e^{i(p-p')x} + e^{-i(p-p')x} = 2\cos(px-p'x)
$$
The exception is the central contribution due to $e^{i~(p-p')0}$ which is equal to 1.

A: The mathematical version of the theory is more complicated (you would have to study functional analysis), but there is a very nice explanation in the book Numerical and Analytical Methods for Scientists and Engineers, Using Mathematica. The argument is given in chapter 2 section 2.3.4 on generalized Fourier integrals.

*

*The issue is that the integral $\int_{-\infty}^{\infty} e^{-ikx}dk$ is not convergent, but we still want to use it, make sense of it, and say it's equal to $2\pi\delta(x)$.

*We write the integral as a symmetric limit $\lim_{\Delta k\to\infty}\int_{-\Delta k}^{\Delta k} e^{-ikx}dk=\lim_{\Delta k\to\infty}2\sin(\Delta k x)/x$. Note that this limit "does not exist" in the introductory calculus sense, which is why we have to call this a generalized Fourier integral.

*We want to see if we can make sense of this, so we look at how it acts on a function if we take an inner product: $\lim_{\Delta k\to\infty}\int_{-L}^{L} f(x)2\sin(\Delta k x)/x dx$. (Here there's another mathematical crime of changing the order of the limit vs the integral. The integration is from $-L$ to $L$ because we assume $f$ is zero outside some region around the origin). Change variables to $y=\Delta k x$ to get $\lim_{\Delta k\to\infty}\int_{-L\Delta k}^{L\Delta k} f(y/\Delta k)2\sin(y)/y dy$.

*This integral is convergent, so we should be able to take the limit to get $\int_{-\infty}^{\infty} f(0)2\sin(y)/y dy=2\pi f(0)$.

*Conclude that $\int_{-\infty}^{\infty} e^{-ikx}dk=2\pi\delta(x)$.

This argument shows where the factor of $2\pi$ comes from, and also gives some extra parameters $L$ and $\Delta k$ to play around with.
Also note that I usually prefer to work with the normalization $\langle x \vert p\rangle = \frac{1}{\sqrt{2\pi}}e^{ipx}$, but this is just personal preference of how you go about bookkeeping your $2\pi$'s.

A: < x | p > is the scalar-product of 2 vectors. The resulting scalars can be complex in QM: z = x + i . y = exp(i.alpha), with alpha being the angle of the z-vector with the positive x-axis. The wave function PSI in QM is like a vector containing complex components. Unfortunately, the wave function is sometimes called a probability amplitude. The wave function squared gives a probability density function and an integral of this function gives a probability.


text:
Q: IntelliJ Idea sbt managed source file I am using sbt-buildinfo plugin that generates Scala source from my build definitions, allowing me to reference project name, version, etc. from my Scala code.
It does this by generating a file BuiltInfo.scala with the following contents:
package hello

case object BuildInfo {
  val name = "helloworld"
  val version = "0.1-SNAPSHOT"
  val scalaVersion = "2.10.3"
  val sbtVersion = "0.13.2"
}

in
target/scala-2.10/src_managed/main/sbt-buildinfo/BuildInfo.scala.
Everything compiles and I can reference those vals.
However, IntelliJ Idea doesn't recognize BuildInfo.scala as a managed source file, so that it would stop showing me errors. Any idea how to do that?
Thanks!

A: Grega, are you working in a Play Framework project? Or do you have any SBT sub-projects? I don't have a complete answer, but may have a lead.
This same problem shows up in my IDEA projects when using sbt-buildinfo and sbt-scalaxb. Frustratingly, it has worked intermittently—usually after lots of tinkering around, but inexplicably stops.
I wound up digging a bit deeper (and eventually issued bug report SCL-7182 to JetBrains), and noticed the root cause was having a sub-project. When present, IDEA doesn't correctly identify src_managed for the root project, but does for the sub-project.
A work-around, for now, is to manually add the correct src_managed directory to your project's sources using the Project Structure dialog.
For reference, I'm running version 0.38.437 of the Scala plugin on IntelliJ IDEA 13.1.3.


text:
Q: Wordpress as cms for different page content per country Which plugin to use?
I use wordpress as a CMS and was wondering which plugin I could use make 1 page with dynamic content for different selected country/per domain/URL?
(I would like to have many versions of the same site where, some pages have common page content while other pages have different page content)

A: I would recommend http://wordpress.org/extend/plugins/sitepress-multilingual-cms/

A: Try qTranslate
http://www.qianqin.de/qtranslate/
used it successfully to provide translations (with different content) on the same page.

A: Agree strongly with the previous poster who suggested WPML (WordPress Multilingual) plugin.
It's a very sophisticated extension to WordPress and provides a number of different ways of implementing multilingual capabilities. It is easy to set-up but you do need to think carefully about how you configure it.
There isn't a problem with its configuration procedures, but do read through all the settings and think about the implications of the different options.


text:
Q: When redirecting printf to UART, output lines have a stair-stepped appearance I am just starting with STM32 microcontrollers, and I am redirecting the output of printf to UART. For some strange reason, the displayed terminal keeps adding extra spaces that are not present in the code. I can't seem to find the cause for this.
Here is a screenshot of the displayed output; note the stair-stepped appearance as each printf statement is wrapped to a new line that is more deeply indented than the previous one:

Here is the code that I am using for redirecting printf:
int _write(int file, char *ptr, int len)
{
    HAL_USART_Transmit(&husart3, (uint8_t*)ptr, len, HAL_MAX_DELAY);
    return len;
}

I am invoking this code as follows:
printf("program starting...\n");
int counter = 0;
while(1)
{
    printf("counter = %d\n", counter);
    counter++;
    HAL_Delay(1000);
}

What could be causing this strange wrapping behavior, and how can I fix it?

A: Your terminal - like most terminals - interprets \n and \r like an old type writer:

*

*\n moves the roller by one line

*\r moves the carriage to the left of the paper

The output shows that only the roller was moved but the carriage did not return to the left most position.
Two options:

*

*Output \r\n instead of just \n

*Configure your terminal such that \n is sufficient to move to the next line and return to the left most position.


text:
Q: In Java, classes with a run() method are not allowed as argument to new Thread() If I make a new Java class as follows:
class A
{
   public void run() {
       // do something
   }
}

And then I do this:
new Thread(new A()).start()

Then I expect it to run the run() method.  But it does not.
Why can't we pass any object having the run method as an argument to new Thread()?
Why can't java just allow any class with a run() method to run?  Would there be a problem to have java implement threads in this way?

A: Java doesn't use structural typing.

A: Because that's what a language with duck typing (like JavaScript for example) would do. Java is not such a language. Two classes having the same methods are unrelated. What is important is the inhertiance relationship between their classes.
Since the Thread constructor accepts a Runnable as argument, only instances of classes which implements the Runnable interface can be passed as argument.

A: Make class A implement the Runnable interface.  Then it will work.
The compiler needs to assure type safety, and by providing the Runnable interface you guarantee that.

A: A Thread wants to invoke a routine, and in java it's defined as run(). The only way to do that is if it knows the passed object has a run() method. The object oriented approach to this problem is defining an interface which forces the presence of a run() method.

A: Short answer: Because Java doesn't work that way.
Long answer: Thread has several constructors, one of which takes an instance of a class implementing the Runnable interface as a parameter.  If a class doesn't implement this interface, it cannot be used.
An interface is a guarantee of structure.  A class implementing Runnable is guaranteed to implement a method with the signature public void run() which raises no checked Exceptions and returns nothing.  Without the interface, this becomes more difficult to a) check and b) enforce

A: Because Thread requires Runnable instance (object implementing Runnable), not something that has a run() method.
This feature is called duck typing and is implemented e.g. in Groovy.

A: It looks like the same interface, of course, because you have "run()" in it.  But that's not how Java works.  Thread needs an object that implements the Runnable interface.  That means the Java compiler can piece together the code ahead of time because it knows where it will find the run() method.  The interface points to it, in a matter of speaking.  When you implement that interface, you're "filling the slot" that the thread constructor has already been set to point at.  The interface knits things together, lining things up so that everything matches up.  A computer language could be defined that allows what you are asking for, but then there would have to be all sorts of analysis to find things, and then further checks to detect when the contract was broken -- it would be highly inefficient and error prone.  Interfaces make it easier for both the Java compiler and the Java programmer.


text:
Q: Localizable User Controls If I have a form that is localized and has User Controls that are localized, how I can I view the form and the controls in the language specified in the VS Properties?
Right now when I change the language, all my controls that are not part a user control adjust appropriately, but my user controls do not.

A: You have to localize each user control individually when designing it in the designer. Then you can set the property Localizable on the user control to true and choose your language. Unfortunately the surrounding Form does not escalate these two properties to its user controls when the Form is designed. That is a problem, but only at design time. At runtime however it will work and your user controls should show the correctly localized values.

A: Just to make sure: has the user control Localizable=true? It should probably not define a language for its own, to make it use the language set on the parent.


text:
Q: Is there any tool to generate Watin page objects from a given web page? WatiN looks nice, but generating page objects by hand seems very tedious.
Is there any browser plugin or other tool that would allow me to click a few elements (form fields, divs, etc) and export the source of a page object for these elements? It looks like an obvious addition to the framework.
Thanks,
Adrian

A: Have a look at this blogpost.
http://slmoloch.blogspot.com/2009/12/design-of-selenium-tests-for-aspnet.html
It discusses a mixture of the xpather tool and T4 templates to autogenerate pageobjects. Its also a nice series on how to setup a selenium environment for .Net, most of the things are also applicable for Watin tests.

A: I've been curious about Page Object generation as well.  However, instead of having to load a browser and click around like a recorder, I was thinking of discovering the pages and controls through reflection of the web app dll.
I have not heard of a tool that does this, but I'm just putting this out there in case you wanted to spend a little bit of time to discover and generate the code exactly they way you want.
Hope this helps.

A: How about the WatiN Test Recorder?
http://watintestrecord.sourceforge.net/


text:
Q: iPhone CameraOverlay view 20px gap I have an app that uses the iPhone camera and puts an overlay over the camera. However it all works fine and i have managed to rotate the UIView to landscape but their is a 20px gap at the top of the view although i have set the positioning to (0,0,480,320).
starContainerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 480.0, 320.0)]     autorelease];
 UIImageView *overlayViewNew = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,480.0,320.0)];
 UIImage *OverlayImage = [[UIImage imageNamed:@"overlay.png"] autorelease];
 overlayViewNew.image = OverlayImage;
 [starContainerView addSubview:overlayViewNew];

So as you can see above I have set the UIView and set the UIIMageView and assigned a UIImage to that UIImageview and then added it to a subview of the view.
Here is the code I use to rotate the View.
- (void) accelerometer:(UIAccelerometer *)accelerometer
   didAccelerate:(UIAcceleration *)acceleration {
     if (fabsf(acceleration.x) > -1.0) {
       CGAffineTransform landscapeTransform =     CGAffineTransformMakeRotation(degreesToRadian(90));
       landscapeTransform = CGAffineTransformTranslate (landscapeTransform, +80.0, +100.0);
       [self.starContainerView setTransform:landscapeTransform];
     }
   }

I just cant seem to get it to fill that gap! Can i also say that no rocket science was involved whilst developing this but I still cant find the answer.

A: A 20px gap might have something to do with the status bar not being hidden properly. Make sure you have this in your info.plist:
<key>UIStatusBarHidden</key>
<true />

A: If was down to the following code. I played about with the figures below and this worked.
CGAffineTransform landscapeTransform =     CGAffineTransformMakeRotation(degreesToRadian(90));
  landscapeTransform = CGAffineTransformTranslate (landscapeTransform, +80.0, +80.0);


text:
Q: How to access variable from aspx to .jsx I am currently trying to migrate AngularJS Code in ASPX to React.
I would like to pass some variables of aspx to .jsx files which it can be used by react component.
Mainpage.aspx contains some variables which needs to be passed to Client.jsx(which is in React).
I am trying to access this variable noSessionText from .aspx file to .jsx and i am failing to achieve it.
aspx code
<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolderMiddlePanel" runat="Server">
  var noSessionText = '<%= Resources.WebPageResource.SessionSharing_NoSessions_Text %>';
      var HeaderName = '<%= Resources.WebPageResource.SessionSharing_Header_Name %>';

</asp:Content>

jsx code
class Client extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            activeSessions: {},
            headerUserSession: props.HeaderName
        };
    }
    renderSessionDetails() {
        console.log("inside rendersessiondetails");
        console.log("headerusersession from aspx->react" + this.state.HeaderName);
    }

    render() {

        return (

SESSIONCLIENT IN REACT

                {this.renderSessionDetails()}

            );
    }
}
ReactDOM.render(
    <Client />,
    document.getElementById('SessionClient_root')
);

Is there any way which i could achieve this.
Thanks in advance for help.

A: You can register a client side script block Create javaScript variable in code behind of asp.net
This will enable you to declare javascript variables that the jsx could access.

A: changes in my .aspx file

 let noSessionText = '<%= Resources.WebPageResource.SessionSharing_NoSessions_Text %>';
 let HeaderName = '<%= Resources.WebPageResource.SessionSharing_Header_Name %>';

.jsx file
to access the above variables just use the variable name
alert(noSessionText);
Steps to be considered:
1. add the variables in tag with type let. var should not be used.
2. by adding it in script tag it will be globally available.
3. from other js files you can easily access the variables which are defined globally in other js files.


text:
Q: Solving a system of two equations of cube integers using ParallelTable Well, I have the following problem: I need to solve the following system of equations:
$$
\begin{cases}
n=a^3+b^3+c^3\\
\\
n=d^3+k^3+f^3
\end{cases}\tag1
$$
Where:

*

*$n\ne a\ne b\ne c\ne d\ne k\ne f$;

*$1\le a<n,1\le b<n,1\le c<n,1\le d<n,1\le k<n,1\le f<n$;

*$n\in\mathbb{N}^+,a\in\mathbb{N}^+,b\in\mathbb{N}^+,c\in\mathbb{N}^+,d\in\mathbb{N}^+,k\in\mathbb{N}^+,f\in\mathbb{N}^+$
And I want to search for solutions using the following range: $2\le n\le1000^3$.
I thought of the following code:
ParallelTable[{n,Solve[{n==a^3+b^3+c^3,n==d^3+k^3+f^3,
1<=a<n&&1<=b<n&&1<=c<n&&1<=d<n&&1<=k<n&&1<=f<n&&a!=b!=c!=d!=k!=f},
{a,b,c,d,k,f},Integers]},{n,2,1000^3}]

Question: is there a faster way to let Mathematica evaluate this?

EDIT:
After seeing the answer that was posted by @kglr, I wondered can I use that technique to solve the same problem by using more variables:
$$
\begin{cases}
n=a^3+b^3+c^3\\
\\
n=d^3+k^3+f^3\\
\\
n=g^3+h^3+m^3\\
\\
n=a^3+k^3+m^3\\
\\
n=g^3+k^3+c^3\\
\\
n=a^3+d^3+g^3\\
\\
n=b^3+k^3+h^3\\
\\
n=c^3+f^3+m^3
\end{cases}\tag2
$$
All the conditions are the same, so they all can not be equal to each other and needs to be an integer bigger than zero.

A: SeedRandom[1]
While[Length[pr] < 2,
  pr = Select[FreeQ @ 0] @ PowersRepresentations[RandomInteger[{2, 10^6}], 3, 3]]; //
     AbsoluteTiming // First

5.8*10^-6

 {{a, b, c}, {d, k, f}, n} = Join[pr[[;;2]], {Total[pr[[1]]^3]}]

{{2, 3, 16}, {3, 9, 15}, 4131}

Total[pr^3, {2}]

{4131, 4131}

If you want the 6 numbers all distinct:
SeedRandom[1]
While[Length[Union @@ pr] < 6,
    pr = Select[FreeQ@0]@
      PowersRepresentations[RandomInteger[{2, 10^6}], 3, 3]]; //
  AbsoluteTiming // First

 0.0000275

pr

 {{5, 53, 88}, {12, 29, 93}, {15, 74, 75}}

Total[pr[[1]]^3]

830474


text:
Q: JavaScript "normalize event object" This program taken from a book Pro JavaScript Techniques is used to create hover-like functionality for an Element.
I don`t understand what the author means when he says, in the comments, Normalize the Event object.
Can you tell me
a) why is this necessary, explaining what would happen if it wasn`t normalized
b) how does the code provide achieve the effect
Thank you.
var div = document.getElementsByTagName('div')[0];

div.onmouseover = div.onmouseout = function(e) {

//Normalize the Event object
e = e || window.event;

//Toggle the background colover of the <div>
this.style.background = (e.type == 'mouseover') ? '#EEE' : '#FFF';

};

A: It's referring to window.event, IE's non-standard version of the event object.  If it weren't normalized, it would break in at least one browser.
What the code does is set e to itself (essentially a no-op), if the parameter is truthy (the event parameter is properly set).  If not (in IE), it sets it to window.event.


text:
Q: How can I use a Google Apps Script to add multiple Google Docs to a Google Drive folder? I have a list of Google Document URLs (about 700 of them) and need to add them to a Google Folder so that they are all in one space because currently they are owned by hundreds of different users.
I've seen a few postings on how to do the inverse of this: Generate a list of URLs from the contents of a folder. This has been helpful, but it seems this task is much more difficult.
This is what I've tried, and it doesn't seem to be working:
var doc = DocumentApp.openById('1sQGds0kyeO66ZiMiJlsKkHPcqjySPy5q0dWShc2irts'),
docFile = DriveApp.getFileById( doc.getId() );
DriveApp.getFolderById('0B7yp85g7j5ZHbVlEUmNGX2w0M1k').addFile( docFile );
DriveApp.getRootFolder().removeFile(docFile);

A: it doesn't error check and may timeout... but it is a start.
You would add the fileIds in Column A.

function makeCopyFromId() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 700;   // Last row to process.
  var dataRange = sheet.getRange(startRow, 1, numRows, 5)
  var data = dataRange.getValues();
  var destFolder = DriveApp.getFolderById("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
  for (i in data) {
    var row = data[i];
    var ssId = row[0];
    Logger.log(ssId);   // check the log to see if they all complete-

     var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(ssId).makeCopy("",destFolder))  //copies each file.
  }}


text:
Q: Magento\Customer\Model\Customer::__construct() must be an instance of Magento\Framework\Model\Context I have create a module and its working fine when compilation is disabled. Its getting below error when after compilation run.

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to Magento\Customer\Model\Customer::__construct() must be an instance of Magento\Framework\Model\Context, instance of Magento\Framework\ObjectManager\ObjectManager given,

<?php

namespace Supravat\Customer\Helper;

class Customer extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $customerRepositoryInterface;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
    )
    {
        ...........
        parent::__construct($context);
        $this->customerRepositoryInterface = $customerRepositoryInterface;
    }

    public function getCustomerById() {
        $customer_id  = 1; // 1 is the magento customer id
        $customer = $this->customerRepositoryInterface->getById($customer_id);
        var_dump($customer->getData());
    }
}

Note: Compilation is generates code and dependency injection configuration successfully.

A: The \Magento\Customer\Api\CustomerRepositoryInterface not injected properly. It should be as shown below:

Injection patter is wrong.You should inject class as parameter of
  __construct().

<?php

namespace Supravat\Customer\Helper;

class Customer extends \Magento\Framework\App\Helper\AbstractHelper
{
  protected $customerRepositoryInterface;

  public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
)
{
    ...........
    parent::__construct($context);
    $this->customerRepositoryInterface=$customerRepositoryInterface;

}

public function getCustomerById() {
    $customer_id  = 1; // 1 is the magento customer id
    $customer = $this->customerRepositoryInterface->getById($customer_id);
    var_dump($customer->getData());
}
}

A: Tested on 2.1.6 and 2.1.8 works just fine. I injected the helper into a footer copyright plugin for proof of concept.
File Structure
app/code/Supravat/
└── Customer
    ├── Helper
    │   └── Customer.php
    ├── Plugin
    │   └── Magento
    │       └── Theme
    │           └── Block
    │               └── Html
    │                   └── Footer.php
    ├── etc
    │   ├── di.xml
    │   └── module.xml
    └── registration.php

registration.php
<?php
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Supravat_Customer',
        __DIR__
    );

module.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Supravat_Customer" setup_version="0.0.1"/>
</config>

di.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Theme\Block\Html\Footer">
        <plugin name="supravat_customer_magento_theme_block_html_footer" type="Supravat\Customer\Plugin\Magento\Theme\Block\Html\Footer"/>
    </type>
</config>

Customer.php
<?php

namespace Supravat\Customer\Helper;

class Customer extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $customerRepositoryInterface;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
    ) {
        parent::__construct($context);
        $this->customerRepositoryInterface = $customerRepositoryInterface;
    }

    public function getCustomerById($customerId)
    {
        $customer = $this->customerRepositoryInterface->getById($customerId);
        return var_export($customer->__toArray(), true);
    }
}

Footer.php
<?php

namespace Supravat\Customer\Plugin\Magento\Theme\Block\Html;

use Supravat\Customer\Helper\Customer as Helper;

class Footer
{
    protected $helper;
    public function __construct(Helper $helper)
    {
        $this->helper = $helper;
    }

    public function afterGetCopyright(
        \Magento\Theme\Block\Html\Footer $subject,
        $result
    ) {
        return $this->helper->getCustomerById(1);
    }
}

Once all files are in place:
./bin/magento --clear-static-content module:enable Supravat_Customer
./bin/magento setup:upgrade
./bin/magento setup:di:compile

Refresh the home page and you should see the customer's information in the footer.
This is obviously just a proof of concept, there isn't any good reason why you'd want the customer's information dumped in the footer copyright, but it shows you that it works out of the box.


text:
Q: Why is there an error when I run an exe file compiled from a python file in MATLAB? I wanted to use pyradiomics to extract radiomic features from medical images in MATLAB, so I tried to transfer my FeatureExtraction file to an exe file, then call it in MATLAB. I used pyinstaller -F -w FeatureExtraction.py in command line, then I got an exe file FeatureExtraction.exe. But when I called the exe file in MATLAB, there was an error : pykwalify.errors.CoreError: <CoreError: error code 3: Provided source_file do not exists on disk :C:\Users\ADMINI~1\AppData\Local\Temp\_MEI318322\radiomics\schemas\paramSchema.yaml: Path: '/'>
I tried to run the FeatureExtraction.py in Pycharm, there was no error. I could get the result I wanted. Then I uninstalled and reinstalled some packages use in the file, there was still no error. But when I called the exe file compiled from the python file in MATLAB, there was still that error:
pykwalify.errors.CoreError: <CoreError: error code 3: Provided source_file do not exists on disk :C:\Users\ADMINI~1\AppData\Local\Temp\_MEI318322\radiomics\schemas\paramSchema.yaml: Path: '/'>


text:
Q: Django3, custom 404 page redirects to 500 when Debug=False because Django cannot find exception parameter When Debug = True django returns a Page not found (404) page which is totally fine
But when I change Debug = False django return a Server Error (500) and the server shows these requests made:
[30/Jul/2022 12:29:44] "GET /__reload__/events/ HTTP/1.1" 500 145
[30/Jul/2022 12:29:44] "GET /__reload__/events/ HTTP/1.1" 500 145
[30/Jul/2022 12:29:44] "GET /sdfs HTTP/1.1" 500 145
[30/Jul/2022 12:29:45] "GET /favicon.ico HTTP/1.1" 302 0

myproject main urls.py
from django.conf.urls import handler404
handler404 = 'myproject.views.custom_page_not_found'

please note here that hander404 is not found by django
handler404 not found
my views.py
def custom_page_not_found(request, exception, template_name="errors/404.html"):
    return render(request, template_name, status=404)

Please not here django cannot find the exception parameter
exception parameter not found
In previous community questions i could not find any question that points to the exception parameter not found issue.  Please note that i am not using django templates {% %} in my 404.html file
I think when django does not find the exception parameter it returns server error 500.

A: you don't need to import this handler from django.conf.urls import handler404.
you should simply to define variable in url:
handler404 = 'myproject.views.custom_page_not_found'

as function of view (is better) you can made this:
def custom_page_not_found(request, *args, template_name="errors/404.html", **kargs):
    return render(request, template_name, status=404)


text:
Q: Magento 1.7 doesn't return token key I installed magento 1.7 and test for rest api according to this link.
http://www.aschroder.com/2012/04/introduction-to-the-magento-rest-apis-with-oauth-in-version-1-7/
When I request to this
http://demo.io/oauth/authorize?oauth_token=mbmuatb1a9704p94pfpqy48i2uv8s2vg
It redirect to home page and return nothing.
If anyone know, help me plz. Thanks for your time.

A: I will shoot in the dark here, but most probably you have the flag Auto-redirect to Base URL set to Yes under System->Configuration->Web->Url Options. and when you are calling the authorize url, the Base url you are using is not the same as the base url set in the backend.
Check if you are missing the www or something similar.


text:
Q: Display Image According to its equivalent letter using hashtable im having a hard time  how to display image according to its equivalent letter
as my current code wont work with array
Hashtable<String, Integer> images = new Hashtable<String, Integer>();
    images.put("A"+"a",R.drawable.a);
    images.put("B"+"b",R.drawable.b);
    images.put("C",R.drawable.c);
    images.put("D",R.drawable.d);
    images.put("E",R.drawable.e);
    images.put("F",R.drawable.f);
    images.put("G",R.drawable.g);
    images.put("H",R.drawable.h);
    images.put("I",R.drawable.i);
    images.put("J",R.drawable.j);
    images.put("K",R.drawable.k);
    images.put("L",R.drawable.l);
    images.put("M",R.drawable.m);
    images.put("N",R.drawable.n);
    images.put("O",R.drawable.o);
    images.put("P",R.drawable.p);
    images.put("Q",R.drawable.q);
    images.put("R",R.drawable.r);
    images.put("S",R.drawable.s);
    images.put("T",R.drawable.t);
    images.put("U",R.drawable.u);
    images.put("V",R.drawable.v);
    images.put("W",R.drawable.w);
    images.put("X",R.drawable.x);
    images.put("Y",R.drawable.y);
    images.put("Z",R.drawable.z);

        //String [] search = {"A"+"a","B"+"b"};    <<< this wont work
        String search = "A"+"a";
        if(images.containsKey(search)){

            ImageView image = (ImageView)findViewById(R.id.imageView1);
            image.setImageResource(images.get(search));
        }

if i do it manually, i only get "a" or "A" as a result,
how about if i enter letter "b" or "B", what proper code will i use this time?
because i think if i continue that method, i think my code will be awkward
*edit
what i want to do now is that this code will do a one character search, then this character will search to the
res/drawable folder to its equivalent image...
but my problem is that how to search with the other letters...
 as the code i post above... my current code only works with "a" or "A" letter
...any suggestion will be fine to improve my application

A: you may try:
 Collection<String> search = new HashSet<String>{
{add("Aa");
add("Bb");}
};

        if(images.keySet().containsAll(search)){
...


text:
Q: Hide div on responsive screens I want to hide the facebook like box with CSS.
I used this:
.fb-like-iframe.fb_iframe_widget {
    display: none !important;
}

but this works but only for big displays and it's still showing on mobile.
When I resize the webpage on desktop and make it smaller in width, there is a tipping point where the responsive changes and the fb-like-iframe is displayed.
I tried using this to hide it on mobile as well but no success do far:
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
   .fb-like-iframe.fb_iframe_widget {
      display: none !important;
   }
}

A: Instead of min-device-width and max-device-width you can use min-width and max-width.
Or better result you can use only max-width..
/* Smartphones (portrait and landscape) ----------- */
@media only screen (max-width : 480px) {
  .fb-like-iframe.fb_iframe_widget {
    display: none !important;
  }
}

A: currently you are using this:
@media screen and (min-width: 768px)
.fb-like-iframe.fb_iframe_widget {
    display: none !important;
}

just change (min-width: 768px) to (max-width: 768px)
let me know if this is what you need

A: There was conflict of style.css with a minified version that was causing it not to work only on mobile.

.fb-like-iframe.fb_iframe_widget {
    display: none !important;
}

I've fixed it and now the original code (above) works on both desktop and mobile. Thanks


text:
Q: Basic querying in freebase I am tinkering with Freebase, and trying things with the query editor and everything looks great. I'm still reading the fine manual, but can't seem to get the point if this may be used as a web search replacement for showing refined data to the user. The main question is:
If {q1, q2, q3 ....} be the query the user submits - how do I programatically map each query term to the freebase query key:value pair?

A: I am not sure if it can entirely replace the current search engines as of now.I have just written a blog post for handling a basic query(more will follow) in C# for freebase.
http://2guysfrommumbai.wordpress.com/
If you like the java stuff you can go to,
https://github.com/narphorium/freebase-java-api
this is a more complete api,and i have used it with good success.
You can append multiple queries using q1,q2,q3 as parameters,more details are available on the freebase developer site.
Hope this helps.


text:
Q: Referencing a morph in Squeak (Mophic) created by direct manipulation via 'code' How do I reference (i.e. program) a Morph created by direct manipulation, for instance dragging a text box from the supplies menu to the desktop, via Squeak/Smalltalk code in say the workspace?  I'm okay (well sort of - I'm just learning Morphic) when I instantiate a Morph  via Squeak/Smalltalk code but I'm at a loss when I've dragged a Morph into existence.

A: Thanks to Mike Stramba on the Squeak mailing list for the following:-
Drag and dropping the morph on a workspace is good start (you have to
click on the "square" in the workspace header, and turn on the "create
textual reference to dropped morphs" option).
Also when you create the morph it gets added to the current "desktop"
(world) submorphs instance variable.
You can MMB  on the "desktop", click the debug tab and explore the
current world.  You'll see it's a PasteUpMorph.
You can get all the PasteUpMorphs in the image with : p :=
PasteUpMorph allInstances, which returns an array of all the projects
"desktops" in the image.


text:
Q: How can I get sql string from hibernate criteria? I work in mysql, and using hibernate criteria to build query. But I don't know how to get sql query from that criteria, so any one can help me, that could be grate, many thanks ?
tungosper

A: Just go to hibernate config.xml and add
<property name="show_sql">true</property>

You can see SQL query in your console after executing criteria or any hibernate query now.


text:
Q: Hint on spinner on android spinner with Kotlin I'm trying to put a spinner on a layout for android app. Unlike other components, the spinner does not come with an option to give a hint. How can I do it?
This is my spinner:
<Spinner
    android:id="@+id/spinner_gender"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/gender"
    android:background="@android:color/white" />

When it's not selected I want to show a text like "Gender". When we select it i want that we can't select the option gender and that we only select Male or Female.
The options inside spinner are in an xml called where I keep the arrays.
Thanks.

A: Unfortunately Spinner don't have this feature built-in. Please check this post

A: This feature can be easily implemented through the library with so much customization:
https://github.com/Mobile-Innowise-Group/HintedSpinner
Usage of the library and with a lot of customized params:
<com.innowisegroup.hintedspinner.HintedSpinner
android:id="@+id/hintedSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
app:hintTextSize="24sp"
app:hintTextColor="@color/red"
app:hint="Custom hint"
app:withDivider="true"
app:dividerColor="@color/dark_green"
app:arrowDrawable="@drawable/example_arrow_4"
app:arrowTint="@color/colorAccent"
app:popupBackground="@color/light_blue"
app:items="@array/text" />


text:
Q: Create a straight line with SpriteKit How can I create a straight line using SpriteKit and UITouch?
I wanted a method that allowed me to add the start point and the end point instead of a path. Just like a rubber band.

A: *

*Create a SKShapeNode that is a line when user begins the touch movement e.g. in touchesBegan:.
SKShapeNode *line = [SKShapeNode node];
CGPoint startPoint = CGPointMake(..., ...)
CGPoint endPoint = CGPointMake(..., ...)

CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, startPoint.x, startPoint.y);
CGPathAddLineToPoint(pathToDraw, NULL, endPoint.x, endPoint.y);

line.path = pathToDraw;
line.strokeColor = [UIColor redColor]];
[self addChild:line];

*Modify its path to change its length in touchesMoved:


text:
Q: Why is every angreal, ter'angreal, and sa'angreal unique? It just seems odd to me that every angreal, ter'angreal, and sa'angreal has been completely unique. The only time duplicate ter'angeals are seen is when Egwene is mass-producing copies of Mat's weave-absorbing amulet, all of which are far less effective than the original.
Is there any mention of why this is, either from the author or from the books themselves? Perhaps back in the Age of Legends, creating duplicate angreals was considered 'uncool', or perhaps creating duplicate angreals resulted in less effectiveness, such as with the previously mentioned amulets?

A: It's not completely true.
Ter'angreals: not unique
Ter'angreals are used for many purposes, if we group them by their spesific functions we can say they don't have to be unique.
It's also can be said that there could be different shaped but same functional ter'angreals too.
We have some examples which are not unique neither by shape nor their function:

*

*A'dams

*Bloodknife ring
An example of different shape but same function is the a'dam Elayne produces which have no leash between the collar and the bracelet unlike the a'dams produced by Seanchans.
Angreals and Sa'angreals: may be or not unique:
As we know that to create an angreal or a sa'angreal is a long and tiring process. (Creatin an angreal). Their production is not mass but one by one. They have one same function, to draw more of the One Power to those who channel thruogh it.
We can say they are not unique by their function because all have only one and the same function despite the amount of One Power they allow differs. Because their production is not a mass production, we don't expect that the amount they allow should be the same but we can't say it's not possible to make two angreals which have the same limit on the amount.
What about shape? There is no evidence as we know that some angreals or sa'angreals are shaped the same but there is also no counter evidence saying it's impossible.

A: I must point out that the collars worn by the channeler slaves are all ter'angreal as well as a few other objects we hear about that are identical (the amulet copies being less powerful could be explained by either one she is doing it wrong or two the original is a product of non humans)
However as to your question it is never addressed in the books however the simplest answer is the more powerful artifacts were never mass produced so each would be somewhat unique the weaker ones could be the only one that survived the years or there could be crates of them in the white towers storerooms awaiting classification.  Testing grael object can be dangerous since form does not follow function you could have a crate of identical rings where half of them light up when you channel into them the other half blow up.


text:
Q: Why doesn't `reduce` evaluate the block for single element arrays? I was experimenting on ruby's reduce method, which is a great tool for enumerables manipulation.
I had a hard time understanding why the below is returning a string rather than an integer when the array contains  a single element:
["1", "2"].reduce { |sum, i| sum.to_i + i.to_i }
#=> 3 <- expected

["1"].reduce { |sum, i| sum.to_i + i.to_i }
#=> "1" <- not expected, expecting it to be 1

while the below work as expected:
["1"].reduce(0) { |sum, i| sum.to_i + i.to_i }
#=> 1

I know that I'm initializing the accumulator with value 0 in this case, but I'm curious why the former implementation does not work!

A: Well, I believe I have found an explanation. It seems that reduce will not enter the block iteration defined in reduce method, as it already took the first element as an accumulator thus the array is left empty, and no further work is needed, that's why the element will return as is.
Which makes total sense! as otherwise the accumulator will be counted twice.

A: The last one works because you give reduce an accumulator starting value and then it starts iterating. If you don't give it one it takes the first element of the sequence (array in this case or anything enumerable) and then it has nothing left to iterate over, so the block is never called.


text:
Q: How to set default timestamp to now() + n days? I am developing an auth flow, where tokens with expiry timestamp are used.
When a user logs in successfully, a token is generated and saved in the DB.
I know I can add expires timestamp that is equal to now(), but how do I add n hours/days to it automatically?

A: Just use that as the default expression:
create table token
(
   id integer primary key,
   token text,
   expires timestamp default current_timestamp + interval '8' hour
);

A: eg:
t=# create table t5(t timestamp default now() + '1 day'::interval);
CREATE TABLE
t=# insert into t5 default values;
INSERT 0 1
t=# select now(),t from t5;
              now              |             t
-------------------------------+----------------------------
 2018-01-26 08:05:06.641249+00 | 2018-01-27 08:04:57.035831
(1 row)


text:
Q: How to use std::acumulate for matrix #include <iostream>
#include <numeric>
#include <vector>

using matrix = std::vector<std::vector<int>>;

int main()
{
    matrix mtx{5, std::vector<int>(5)};

    int sum = 0;
    for (const auto i : mtx) // can be avoided ?
    sum += std::accumulate(i.begin(), i.end(), 0,
        [](int a, int b){a > 0 ? a + b : a;});

}

I want to use std::accumulate for std::vector<std::vector<int>> but I am curious if I can avoid the loop. Also I want to know if the last argument is ok.

A: Based on your lambda, looks like you want to just sum the positive entries:
#include <iostream>
#include <numeric>
#include <vector>

using Number = int;
using Matrix = std::vector<std::vector<Number>>;

int main() {
  Matrix mtx{5, std::vector<Number>(5, 1)};

  Number sum_positives = std::accumulate(
      mtx.begin(), mtx.end(), Number(0), [](Number const acc, auto const &v) {
        return std::accumulate(
            v.begin(), v.end(), acc,
            [](Number const a, Number const b) { return b > 0 ? a + b : a; });
      });

  std::cout << sum_positives << std::endl;  // 25
  return 0;
}

Don't forget that the lambda you pass to std::accumulate() must return a value.

A: C++20 ranges' join_views are especially useful for this, since they allow you to flatten a matrix into a vector.
So you end up with a code like:
int sum{0};
auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints
std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });

Unfortunately, ranges' accumulate won't be available until C++23:
auto sum{ std::ranges::accumulate(jv, 0, [](auto total, auto n) { return total + ((n > 0) ? n : 0); }) };

For a full sample filling the matrix with random numbers between [-100, 100]:
[Demo]
#include <algorithm>  // for_each
#include <iostream>  // cout
#include <random>  // default_random_engine, uniform_int_distribution
#include <ranges>  // for_each, join_view
#include <vector>

using matrix = std::vector<std::vector<int>>;

int main()
{
    matrix mtx{3, std::vector<int>(3)};

    // Fill matrix with random values between [-100, 100]
    std::default_random_engine re{ std::random_device{}() };
    std::uniform_int_distribution<int> dist{ -100, 100 };
    std::for_each(std::begin(mtx), std::end(mtx),
        [&dist, &re](auto& row) {
            std::for_each(std::begin(row), std::end(row),
                [&dist, &re](auto& n) { n = dist(re); }
            );
        }
    );

    auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints

    // Print matrix
    std::cout << "mtx = ";
    std::ranges::for_each(jv, [](auto n) { std::cout << n << " "; });
    std::cout << "\n";

    // Sum all positive values in the matrix
    int sum{0};
    std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });
    std::cout << "sum = " << sum << "\n";
}


text:
Q: Unable to create two instances of a class (using pygame, trying to make snake game with two snakes) I have created a class which defines and creates a snake using pygame. When I make one instance of the snake class, one snake will be correctly created, but when I try to make two instances, my code will not make the second snake. I'm not sure if this is because I used pygame wrongly, or because I'm doing something wrong in the classes.
Here's my code; it's a little bit long, but I've included it all because I don't know where the problem is. I'm quite sure that I'm handling all the variables and arguments correctly, and handling the keypresses is correct as well. If you copy and paste this code into the interpreter, it works fine if you say you want one snake, but doesn't work when you want to create two snakes.
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"; import pygame
import random
import time
import copy
black = pygame.Color(0, 0, 0)

class Snake():
    def __init__(self, game_window, controls, color, position, speed, window_specs,can_touch=True,respawn=True):

        self.game_window = game_window
        self.color = color
        self.window_x = window_specs[0]
        self.window_y = window_specs[1]

        self.can_touch = can_touch
        self.respawn = respawn

        self.snake_position = position.copy()
        self.snake_body = [position.copy()]
        self.speed = speed
        self.controls = controls.copy()

        self.direction = 'RIGHT'
        self.change_to = self.direction

        self.moving = True
        self.fps = pygame.time.Clock()
        self.start_moving()

    def start_moving(self):
        #Handles the controls and movement. Control first snake with 'wasd'. Control second snake with arrow keys.
        while self.moving == True:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == self.controls[0]:
                        self.change_to = 'UP'
                    if event.key == self.controls[1]:
                        self.change_to = 'LEFT'
                    if event.key == self.controls[2]:
                        self.change_to = 'DOWN'
                    if event.key == self.controls[3]:
                        self.change_to = 'RIGHT'
            if self.change_to == 'UP' and self.direction != 'DOWN':
                self.direction = 'UP'
            if self.change_to == 'DOWN' and self.direction != 'UP':
                self.direction = 'DOWN'
            if self.change_to == 'LEFT' and self.direction != 'RIGHT':
                self.direction = 'LEFT'
            if self.change_to == 'RIGHT' and self.direction != 'LEFT':
                self.direction = 'RIGHT'

            if self.direction == 'UP':
                self.snake_position[1] -= 10
            if self.direction == 'LEFT':
                self.snake_position[0] -= 10
            if self.direction == 'DOWN':
                self.snake_position[1] += 10
            if self.direction == 'RIGHT':
                self.snake_position[0] += 10
            self.snake_body.insert(0, list(self.snake_position))
            self.snake_body.pop()

            self.game_window.fill(black)
            for pos in self.snake_body:
                pygame.draw.rect(self.game_window,self.color,pygame.Rect(pos[0],pos[1],10,10))

            #Toggles whether snake will die if touching itself
            if self.can_touch == False:
                for block in self.snake_body[1:]:
                    if self.snake_position[0] == block[0] and self.snake_position[1] == block[1]:
                        self.die()

            #Kills snake if snake touches the edge of the window
            if self.snake_position[0] < 0 or self.snake_position[0] > (self.window_x - 10):
                self.die()
            if self.snake_position[1] < 0 or self.snake_position[1] > (self.window_y - 10):
                self.die()
            pygame.display.update()
            self.fps.tick(self.speed)

    def die(self):

        #Reset the snake
        self.moving = False
        self.game_window.fill(black)
        self.snake_body = []
        self.position = []
        pygame.display.update()
        time.sleep(1)

        #Makes the snake respawn in a random location
        if self.respawn == True:
            self.direction = 'RIGHT'
            self.change_to = self.direction
            self.snake_position = [random.randrange(1, (self.window_x//100)) * 10,
                     random.randrange(1, (self.window_y//100)) * 10]
            self.snake_body = [self.snake_position.copy()]
            self.moving = True
            self.start_moving()

class App():
    def __init__(self,num_players,can_touch=True,respawn=True):
        self.controls = [[pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d],
                                [pygame.K_UP,pygame.K_LEFT,pygame.K_DOWN,pygame.K_RIGHT]]
        self.starting_positions = [[100,50], [200, 100]]
        self.speed = 15
        self.window_specs = [720,480]
        self.num_players = num_players
        self.can_touch = can_touch
        self.respawn = respawn
        self.players = {}

        #Start up pygame
        pygame.init()
        pygame.display.set_caption('Snake Game')
        self.game_window = pygame.display.set_mode((self.window_specs[0], self.window_specs[1]))

        self.get_players()

    def get_players(self):
        #Let the players choose what color they want
        player_color = []
        for i in range(self.num_players):
            player_color.append(input(f'Player {i+1}, what color do you want your snake to be? '))
            if player_color[i] == 'red':
                player_color[i] = pygame.Color(255,0,0)
            elif player_color[i] == 'green':
                player_color[i] = pygame.Color(0,255,0)
            elif player_color[i] == 'blue':
                player_color[i] = pygame.Color(0,0,255)
            else:
                player_color[i] = pygame.Color(255,255,255)

        #Create the Snakes, this is the bit that does not work.
        for i in range(self.num_players):
            self.players[f'player{i+1}'] = Snake(self.game_window,self.controls[i],player_color[i],self.starting_positions[i],self.speed,self.window_specs)

if __name__ == "__main__":
    num_players = int(input('1 or 2 players: '))
    App(num_players)

A: You need one application loop for the entire application rather than a separate application for each snake. Remove the application loop from the Snake class:
class Snake():
    def __init__(self, game_window, controls, color, position, window_specs,can_touch=True,respawn=True):

        self.game_window = game_window
        self.color = color
        self.window_x = window_specs[0]
        self.window_y = window_specs[1]

        self.can_touch = can_touch
        self.respawn = respawn

        self.snake_position = position.copy()
        self.snake_body = [position.copy()]
        self.controls = controls.copy()
        self.direction = (1, 0)

    def move(self, event_list):
        #Handles the controls and movement. Control first snake with 'wasd'. Control second snake with arrow keys.
        for event in event_list:
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == self.controls[0] and self.direction[1] <= 0:
                    self.direction = (0, -1)
                if event.key == self.controls[1] and self.direction[0] <= 0:
                    self.direction = (-1, 0)
                if event.key == self.controls[2] and self.direction[1] >= 0:
                    self.direction = (0, 1)
                if event.key == self.controls[3] and self.direction[0] >= 0:
                    self.direction = (1, 0)

        self.snake_position[0] += self.direction[0] * 10
        self.snake_position[1] += self.direction[1] * 10
        self.snake_body.insert(0, list(self.snake_position))
        self.snake_body.pop()

        for pos in self.snake_body:
            pygame.draw.rect(self.game_window,self.color,pygame.Rect(pos[0],pos[1],10,10))

        #Toggles whether snake will die if touching itself
        if self.can_touch == False:
            for block in self.snake_body[1:]:
                if self.snake_position[0] == block[0] and self.snake_position[1] == block[1]:
                    self.die()

        #Kills snake if snake touches the edge of the window
        if self.snake_position[0] < 0 or self.snake_position[0] > (self.window_x - 10):
            self.die()
        if self.snake_position[1] < 0 or self.snake_position[1] > (self.window_y - 10):
            self.die()

    def die(self):
        self.snake_body = []
        self.position = []

        #Makes the snake respawn in a random location
        if self.respawn == True:
            self.direction = (1, 0)
            self.snake_position = [random.randrange(1, (self.window_x//100)) * 10,
                     random.randrange(1, (self.window_y//100)) * 10]
            self.snake_body = [self.snake_position.copy()]

But add an application loop in the App:
class App():
    # [...]

    def get_players(self):
        #Let the players choose what color they want
        player_color = []
        color_dict = {'red': (255, 0, 0), 'green': (0, 255, 0), 'blue': (0, 0, 255)}
        for i in range(self.num_players):
            color = input(f'Player {i+1}, what color do you want your snake to be? ')
            player_color.append(color_dict[color] if color in color_dict else (255, 255, 255))

        #Create the Snakes, this is the bit that does not work.
        for i in range(self.num_players):
            self.players[f'player{i+1}'] = Snake(self.game_window,self.controls[i],player_color[i],self.starting_positions[i],self.window_specs)

        clock = pygame.time.Clock()
        run = True
        while run:
            clock.tick(self.speed)
            event_list = pygame.event.get()
            for event in event_list:
                if event.type == pygame.QUIT:
                    run = False

            self.game_window.fill(black)
            for key in self.players:
                self.players[key].move(event_list)
            pygame.display.update()

        pygame.quit()

A: The issue here is that you did not set up a dedicated game loop for this game. The "game loop" for your game right now rests within an individual snake object. Your Snake.start_moving function is the thing that keeps on running and where you see your snake move etc. In the case where you create one snake, you are running that's snake's start_moving function, so everything looks fine on the surface.
If you are running with 2 snakes, the first snake's start_moving function is called and you are stuck there. The second snake is not yet created at all. To convince yourself, try adding a if event.key is q, return out of the function. Then you will see that when you ask for two snakes, the first snake will run, then you press q, the first snake will disappear and the second snake will appear.
The way to solve your issue is to make a dedicated game loop in your project, and delegate all of your game updats to there. There are a few different ways to do that so I'll leave that to you to design. But in broad strokes this is what I recommend in pseudocode:
snakes = [Snake() for _ in range(numplayers)]

while True:
    for event in pg.events():
        if event is keypress:
            for snake in snakes:
                snake.handle_keys(event.key)

    for snake in snakes:
        snake.update(dt)

    for snake in snakes:
        snake.draw(display)
    display.flip()
    tick() # or calculate dt


text:
Q: Using $wpdb as an alternative to WordPress meta_query I'm building a WordPress-based events website. Each event needs to have up to three date ranges applied to it (I've added these with the Advanced Custom Fields plug-in). The events are displayed on a simple page with a date and category filter. I tried this using a meta_query, but it's incredibly slow (see code below). I now understand this is a known-issue. So basically, I'm looking for an alternative. From what I read, $wpdb is a possible solution, but I don't have much experience with this.
Any help much appreciated. Thank you.
$events = new WP_Query(array(
'post_type' => 'post',
'category_name' => $category_list,
'meta_query' => array(
'relation' => 'OR',

array('relation' => 'AND', array('key' => 'event_start_date_1',  'compare' => '<=', 'value' => $date, 'type' => 'DATE'), array('key' => 'event_finish_date_1', 'compare' => '>=', 'value' => $date, 'type' => 'DATE'),
),

array('relation' => 'AND', array('key' => 'event_start_date_2',  'compare' => '<=', 'value' => $date, 'type' => 'DATE'),array('key' => 'event_finish_date_2', 'compare' => '>=', 'value' => $date, 'type' => 'DATE'),
),

array('relation' => 'AND', array('key' => 'event_start_date_3',  'compare' => '<=', 'value' => $date, 'type' => 'DATE'), array('key' => 'event_finish_date_3', 'compare' => '>=', 'value' => $date, 'type' => 'DATE'),
),

),
));

Update
The following appears to work
SELECT * FROM $wpdb->posts, $wpdb->postmeta m1, $wpdb->postmeta m2, $wpdb->term_relationships, $wpdb->term_taxonomy, $wpdb->terms

WHERE

$wpdb->posts.ID = m1.post_id AND $wpdb->posts.ID = m2.post_id
AND $wpdb->posts.ID = $wpdb->term_relationships.object_id
AND $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
AND $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id

AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->terms.slug IN ('$category_list')

AND $wpdb->posts.post_status = 'publish'

AND
(

((m1.meta_key = 'event_start_date_1' AND m1.meta_value <= '$date') AND (m2.meta_key = 'event_finish_date_1' AND m2.meta_value >= '$date'))
OR
((m1.meta_key = 'event_start_date_2' AND m1.meta_value <= '$date') AND (m2.meta_key = 'event_finish_date_2' AND m2.meta_value >= '$date'))
OR
((m1.meta_key = 'event_start_date_3' AND m1.meta_value <= '$date') AND (m2.meta_key = 'event_finish_date_3' AND m2.meta_value >= '$date'))
OR
((m1.meta_key = 'event_start_date_4' AND m1.meta_value <= '$date') AND (m2.meta_key = 'event_finish_date_4' AND m2.meta_value >= '$date'))

)

GROUP BY $wpdb->posts.ID

I'm not sure this is the most efficient solution, so any suggestions for improvements welcome.

A: (Try)Hope that helps:--
modify the where clause to filter meta data
  add_filter('posts_where', array($this, 'filter_meta_query_where'));

join the meta table to the posts query
add_filter('posts_join' , array($this, 'filter_meta_join'));

This is the main function that adds the meta query (I've added conditions for schedules_port, you'll have to build the rest yourself the way you want):--
function filter_meta_query_where($where = '')
{
    global $wpdb;
    global $wp_query;
    global $sf_form_data;

    if(!is_admin())
    {
        $where .= " AND (($wpdb->postmeta.meta_key = 'schedules_port' AND ($wpdb->postmeta.meta_value LIKE '%$sfrom%' OR $wpdb->postmeta.meta_value LIKE '%$sto%')))";
    }

    return $where;
}

And here's the code for the join:--
function filter_meta_join($join)
{
     global $wpdb;

     $join .= " LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";

     return $join;
}


text:
Q: iOS 13 Running on old targets I'm working to update the project to work with iOS 13.
After I updated the carthage the project works fine on the devices with  the latest iOS version.
When I tried to run on a older target I received a lot of errors related to "... is only available in iOS 13" for a lot of situations: layer, some viewcontrollers, custom uiviews .
Project suggestions advice me to add @available(iOS 13.0, *) but without any result.
I made some research and after I tried to add before viewcontrollers:
   #if canImport(SwiftUI) && DEBUG
    import SwiftUI
    @available(iOS 13.0, *)
    myviewcontroller

     #endif

I have this problem only in the situations when I try to run on old targets (the project target is 10.0).
I over tried to add @available(iOS 13.0, *) over the method name but still the error persist.
I have over 200 erors like in the image below.

A: If something – a method, for example – is annotated with @available (iOS 13.0, *), you cannot reference it without first checking that iOS 13 is available, such as:
if #available(iOS 13.0, *){
    methodRequiringIOS13(…)
} else {
    legacyAlternativeMethod(…)
}

or
guard #available(iOS 13.0, *) else {
    // Do legacy stuff here
    return
}
// Do stuff for iOS 13+ here

Otherwise you will get exactly the error you are seeing when compiling for an older target.
Since it sounds like your codebase already supported older versions, it should be a simple matter of checking what iOS 13 -specific stuff you have added since, and then wrap all of that in these checks. Of course this means you have to provide an alternative legacy implementation for everything until you are ready to up your minimum deployment target, so make sure any new additions are worth the effort.


text:
Q: Ignore space when converting String I've created a method which converts a String into **'s as I am creating a Hangman game, and I was wondering how I ensure that the space is just a space rather than a *. Below is an extract from my code:
secretPirateWord="ahoy there"

public void secretWordAsStars(){
for (int i= 0; i < secretPirateWord.length(); i++){
System.out.print("");
pirateWord = secretPirateWord.toCharArray()
}

A: You could use Arrays.fill(). I surmise here that your char[] will be of fixed length anyway, so, for one char array array you can:
Arrays.fill(array, '*');

And then pick individual characters to fill in the array and make a String out of it.

A: Just replaceAll "not space" with "*":
public static void main(final String[] args) throws Exception {
    final String secretPirateWord="ahoy there";
    System.out.println(secretPirateWord.replaceAll("\\S", "*"));
}

Output:
**** *****


text:
Q: How to call a php script using javascript and ajax? i have this code:

an i want to call this function when clicking on an img so i used this

but this doesn't work, is ther any one that can help me

A: $(function () {
    $('img').live('click', function () {
        $.ajax({
            url:"supcont.php",
            success:function (res) {
                alert(res);
            }
        });
    });
});

A: Put this anywhere:

Place this after you include JQuery.js

More info here : http://api.jquery.com/click/

A: Check w3schools website. Much helpful to you regarding this.


text:
Q: Parse.com Cloud Code Versioning, it it possible? I'm a iOS developer and I have just lunched my app to the AppStore.
I'm using Parse.com in my app. Cloud Code for the services. Heroku.com connected with my parse.com app for the Socket.
Now I need to change some functions in my app's CloudCode and in the iOS client too and resubmit the app, but I do not want the new version of the CloudCode worked with old version of the app.
I need to have a versioning on my Parse.com app's CloudCode. How can I achieve that?

A: You can setup your own versioning by providing a version key in the request to cloud code functions. Each cloud code function which supports multiple versions can check for this value to decide what logic should be applied. Any which don't will simply ignore the additional parameter.


text:
Q: Как отключить редирект с http на https в Wordpress? Перенес для разработки сайт с хостинга на локальный.
Там он с https, а на локальном надо http.

*

*В админке в settings->general стоит http

*В таблице wp-option siteurl и home - http

*htaccess закомментирован

*По всем таблицам https заменил на http

*Использовал 4 браузера, из которых не ходил на сайт
Все-равно, редиректит на https.
Что делать, уже не знаю, второй день борюсь.
Помогите, кто знает.

A:
По всем таблицам https заменил на http

Напрямую в базе? Значит поломал сайт. Да собсно поломал его раньше неправильным  переносом.  См Как правильно перенести сайт на WordPress?
А вообще не используй "локальный". См рядом https://ru.stackoverflow.com/a/863450.


text:
Q: Magento 2.3 & composer : update extension I would like to update my extension (I updated magento 2.2.6 to 2.3.1 from composer but looks like the extension also need to be updated because it's not working and it should be compatible).
Then i try :
composer.phar update Firebear_ImportExport

also tried :
composer.phar update Firebear/ImportExport

both returned

Package "firebear_importexport" listed for update is not installed.
  Ignoring.

also tried :
composer.phar require Firebear/ImportExport

returned :

[InvalidArgumentException]
                         Could not find
  package Firebear/ImportExport.

Then I suppose I am not using the correct syntax, which syntax should I use ?

A: the package name is firebear/importexport... You can check your composer.json in an editor etc.
https://firebearstudio.com/blog/improved-import-magento-2-extension-manual.html#via_Composer
Cheers
Jan

A: Upgrading the extension via composer
To upgrade the extension, navigate to your store root folder just as per instructions above and run the following commands:
composer update firebear/importexport

than
php bin/magento setup:upgrade

then
php bin/magento setup:static-content:deploy -f

and
php bin/magento cache:clean

A: The solution was to do a manual installation, it could also work with composer but anyway update is provided by the extension supplier and not automatic


text:
Q: Lightning data service - Edit mode & Spring'18 "new feature" I have components written during Winter'18. After the rollout of Spring'18 preview they stopped working. The components fetch fields (either via layoutType=FULL or mentioned by name) that happen to be formula/rollup fields and when the save operation is called an error is returned.

INVALID_FIELD_FOR_INSERT_UPDATE","message":"Unable to create/update fields: X__c, Y__c, Z__c. Please check the security settings of this field and verify that it is read/write for your profile or permission set."

A: I found a workaround. I wired a separate force:recordData markup and only included the formula fields there. Then in my original force:recordData, I excluded the formula fields.
You can then adjust references on the component accordingly.

A: Just realized that changing my layoutType to COMPACT resolved my issue. See below.
<force:recordData aura:id="contractLineData"
                    layoutType="COMPACT"
                    mode="EDIT"
                    targetRecord="{!v.contractLine}"
                    targetFields="{!v.contractLineFields}"
                    targetError="{!v.errorMessage}" />

A: I had the same problem show up with Spring 18, but SystemModstamp was being pulled in for every save after the first save, so the first save worked but not any save after that.  Instead of creating a separate force:recordData I created a list of the Id and the updateable fields.  I create a copy of the record and delete the fields that are not in that list from the copy, and return that for the save.
Also, I usually only use targetFields, but I also had to pull in targetRecord.fields and repeat this process on the object holding those fields too.  Hope I can remove this before going to production.


text:
Q: Hide Field In Edit View Only (Need hook name) I have added a field field_shortform to the basic page type and I wish to remove it if the node already exists (aka it shows up in Create, but not in Edit).  I am able to remove it with
$form['field_shortform'] = array();

however I need to figure out how to restrict this action to the node edit page only.  I tried using _form_node_edit_form_alter but that seems to have no effect...

A: It seems that the curse and beauty of posting to Stack Overflow is that regardless of how many hours I have spent searching for my answer, minutes after posting here I will magically stumble across it!
function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id){
    $node = $form_state['node'];

    if(isset($node->nid)){
        $form['field_shortform']= array();
    }
}

It was embarrassingly simple but I suppose too many hours in front of a small screen can make you a little simple :)


text:
Q: Not able to view all options in Ubuntu desktop I am not able to view all the options in Ubuntu desktop - scaled or windows mode.
Also, I am not able to find the setting to do same.
How to do it? I want all options to be view or there should be scroll bar to do the same.

A: Solved in comments:

Install the guest additions. Click Devices in the top bar and then Insert Guest Additions CD image. A CD will appear in Ubuntu Click it and it will open. Then you will see a button, at the top of the window that just opened that says "Run this software". Then click it, and click "run in terminal.


text:
Q: Process parameter as Types First of all, I know you can pass Type as a parameter by using Class<T>.
However, I have a scenario as follows:
Suppose I have a method for creating MyOwnType (the code below compiles):
public MyOwnType<? extends Type,? extends Type> createMyOwnType(String name, Class<? extends Type> T1, Class<? extends Type> T2)
What I really want to do is to use Type variables T1 and T2 to construct MyOwnType:
MyOwnType<T1,T2>

I know you can directly construct MyOwnType without using createMyOwnType method. But I want to use a proper factory pattern to construct MyOwnType for users + a few constraints I will code up.
I don't want to check all parameters one by one say if T1 is some type, and T2 is some type, then constrcut MyOwnType. Because in some cases, I could have many Ts, they all are subtypes of Type. Therefore, I will have T1xT2xT3xT_n combinations to check.
Therefore,my question is that is there a way of creating MyOwnType based on the parameters provided (T1 and T2), something similar like the following code:
MyOwnType<T1,T2> myowntype=new MyOwnType<T1,T2>(name);

The code above won't compile due to the Java compiler cannot find symbol T1,T2.

A: You can use java generics in this case. See example for your case:
class Type {}

// create some classes based on Type
class Car extends Type {}
class Bike extends Type {}
class Boat extends Type {}

@Data
class MyOwnType<T1 extends Type, T2 extends Type > {
    private String name;
    private T1 field1;
    private T2 field2;
}

public class SomeClass {

    public static <T1 extends Type, T2 extends Type> MyOwnType<T1, T2> createMyOwnType(String name) {
        MyOwnType<T1, T2> result = new MyOwnType<>();
        result.setName(name);
        return result;
    }

    public static void main(String[] args) {
        MyOwnType<Car, Boat> sample1 = createMyOwnType("orange");
        Car car = sample1.getField1();
        Boat boat = sample1.getField2();

        MyOwnType<Boat, Bike> sample2 = createMyOwnType("red");

    }
}

Here instead of passing parameters into factory method we just specify desired types in declaring of variables "sample1" and "sample2". I hope it is what you want.
But if you want to create real factory, i.e. use types inside method then it is not possible because Java does not support this. You just can to prepare classes like in my example. Inside method you just know that T1 and T2 extends Type.


text:
Q: Error running application using Oracle Forms Standalone Application Launcher (FSAL) I'm triggering an Oracle form using frmsal.jar for running the Form without browser.
As soon as I run the below frmsal command
java -jar frmsal.jar -url "http://localhost:9001/forms/frmservlet?config=standaloneapp" -t 10000
FRM-91145: fatal error in runtime process: missing serverArgs parameter
Contact your system administrator.


text:
Q: How to link elements of two linked list in java? This is my starting code for a van rental database.
List<String> manual = new LinkedList<>();
List<String> automatic = new LinkedList<>();
List<String> location = new LinkedList<>();

manual.add("Queen");
manual.add("Purple");
manual.add("Hendrix");

automatic.add("Wicked");
automatic.add("Zeppelin");
automatic.add("Floyd");
automatic.add("Ramones");
automatic.add("Nirvana");

location.add("CBD");
location.add("Penrith");
location.add("Ceremorne");
location.add("Sutherland");

How can I link the cars to the location.
For example, location CBD has Wicked,Zepplin and Floyd, and Penrith has Queen.
So if the command line arguement has "Print CBD" then it must show the vans available in CBD.
Any help will be appreciated.

A: This is hardly a database. They are just three separate data pieces. Use some object-oriented design technique to create classes, such as a class called Van. For example, it's not java code exactly, just for example.
Class Van {
    string name;
    VanType type; // e.x, Enum {auto, manual}
    Location location; // another class
}

A: I think you would be better off using the approach explained In This Post.   I believe this would be a much clearer implementation.
I hope this helps.

A: Ok thats the code.
We are using only linked list as you wanted.
(linked list keeps track on the input order so we are using that too)
As it is one to many relation we should have some kind of "foreign key" so we can see the related object. For each car you add no matter manual or auto, you should add a key for the location as you can see below
for example rels[0] = 3; means that your first car will have relation with 4th object of the locations list. thats implemented in the code - take a look.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class TestMain {

    public static void main(String[] args) {

        List<String> manual = new LinkedList<String>();
        List<String> automatic = new LinkedList<String>();
        List<String> location = new LinkedList<String>();
        int[] rels = new int[8];

        //cars with relations
        rels[0] = 1;
        manual.add("Queen");
        rels[1] = 1;
        manual.add("Purple");
        rels[2] = 1;
        manual.add("Hendrix");
        rels[3] = 1;
        automatic.add("Wicked");
        rels[4] = 0;
        automatic.add("Zeppelin");
        rels[5] = 0;
        automatic.add("Floyd");
        rels[6] = 1;
        automatic.add("Ramones");
        rels[7] = 2;
        automatic.add("Nirvana");

        //key-0
        location.add("CBD");
        //key-1
        location.add("Penrith");
        //key-2
        location.add("Ceremorne");
        //key-3
        location.add("Sutherland");

        //here is the value that you have from your input args[] for example
        String desiredLocation = "CBD";

        int index = getLocationIndex(location, desiredLocation);
        //if desired location not found we will print nothing
        if(index==-1)return;

        List mergedCars = new LinkedList<String>();
        mergedCars.addAll(manual);
        mergedCars.addAll(automatic);

        for (int i = 0; i < rels.length; i++) {
            if(index == rels[i])
            {
                System.out.println(mergedCars.get(i));
            }
        }

    }

    private static int getLocationIndex(List<String> location, String desiredLocation) {
        int counter=0;
        for (Iterator iterator = location.iterator(); iterator.hasNext();) {
            String temp = (String) iterator.next();
            if(temp.equals(desiredLocation))
            {
                return counter;
            }
            counter++;
        }
        return -1;
    }
}


text:
Q: Query taking long when i use user defined function with order by in oracle select I have a function, which will get greatest of three dates from the table.
create or replace FUNCTION fn_max_date_val(
    pi_user_id IN number)
  RETURN DATE
IS
  l_modified_dt      DATE;
  l_mod1_dt  DATE;
  l_mod2_dt DATE;
  ret_user_id        DATE;
BEGIN

  SELECT MAX(last_modified_dt)
  INTO l_modified_dt
  FROM table1
  WHERE id = pi_user_id;
  -- this table contains a million records
  SELECT nvl(MAX(last_modified_ts),sysdate-90)
  INTO l_mod1_dt
  FROM table2
  WHERE table2_id=pi_user_id;
  -- this table contains clob data, 800 000 records, the table 3 does not have user_id and has to fetched from table 2, as shown below
  SELECT nvl(MAX(last_modified_dt),sysdate-90)
  INTO l_mod2_dt
  FROM table3
  WHERE table2_id IN
    (SELECT id FROM table2 WHERE table2_id=pi_user_id
    );
  execute immediate 'select greatest('''||l_modified_dt||''','''||l_mod1_dt||''','''||l_mod2_dt||''') from dual' into ret_user_id;
  RETURN ret_user_id;
EXCEPTION
WHEN OTHERS THEN
   return SYSDATE;
END;

this function works perfectly fine and executes within a second.
-- random user_id , just to test the functionality
SELECT fn_max_date_val(100) as max_date FROM DUAL

MAX_DATE
--------
27-02-14

For reference purpose i have used the table name as table1,table2 and table3 but my business case is similar to what i stated below.
I need to get the details of the table1 along with the highest modified date among the three tables.
I did something like this.
SELECT a.id,a.name,a.value,fn_max_date_val(id) as max_date
FROM table1 a where status_id ='Active';

The above query execute perfectly fine and got result in millisecods. But the problem came when i tried to use order by.
SELECT a.id,a.name,a.value,a.status_id,last_modified_dt,fn_max_date_val(id) as max_date
FROM table1 where status_id ='Active' a
order by status_id desc,last_modified_dt desc ;
-- It took almost 300 seconds to complete

I tried using index also all the values of the status_id and last_modified, but no luck. Can this be done in a right way?

A: What if you don't use the function and do something like this:
SELECT a.id,a.name,a.value,a.status_id,last_modified_dt x.max_date
FROM table1 a
(
  select max(max_date) as max_date
  from (
    SELECT MAX(last_modified_dt) as max_date
    FROM table1 t1
    WHERE t1.id = a.id

    union

    SELECT nvl(MAX(last_modified_ts),sysdate-90) as max_date
    FROM table2 t2
    WHERE t2.table2_id=a.id

     ...
  ) y
) x
where a.status_id ='Active'
order by status_id desc,last_modified_dt desc;

Syntax might contain errors, but something like that + the third table in the derived table too.

A: How about if your query is like this?
select a.*, fn_max_date_val(id) as max_date
  from
    (SELECT a.id,a.name,a.value,a.status_id,last_modified_dt
       FROM table1 where status_id ='Active' a
      order by status_id desc,last_modified_dt desc) a;


text:
Q: jQuery window resizing messes up css outside query I am not sure if this question has been answered here before, but when I use jquery(window) as a condition to change css of a div, the rest of the css for that div gets messed up outside the query when resizing.
For example, in the code below, I am trying to reposition Div A when the window width is greater than 767px and less than 800px.  The only time this code works perfectly is if I load the page within this width.  However, if I move out of the specified width, for example, 800 or greater, DivA css gets messed up.  If I load the page in 800 or greater, DivA css is fine, however, if I then scroll into 767-800, the code below doesn't work.  Basically, what I am trying to do is have the code sensitive to resizing.
if ($(window).width() > 767 && $(window).width() < 800){
 $('.DivA').css({
  transform: 'translateX(180px)',
  MozTransform: 'translateX(180px)',
  WebkitTransform: 'translateX(180px)',
  msTransform: 'translateX(180px)'
 })
}


text:
Q: Why `type a = {} extends {a?:number}? true:false;` is true Why type a = {} extends {a?:number}? true:false; is true,
but type b = {a?:number} extends {}? true:false; is true too!
I think the {} is a super type and it can't extends any types, but if
here is a type which all properties of are optional(?), {} will extends this type, why ?
The core problem is how to judge compatibility betweens types.Before meeting this problem, i always use Set theory to explain them, but it's ineffective for this problem, so i need a new theory, unless typescript did something special to {}

A: You could interpret extends as 'can be assigned to'. Therefore, {} extends any type where all properties are optional.
const a: { a?: string, b?: number } = {}; // legal, no error


text:
Q: Integration Testing In Visual Studio With Different Project Types We are in the middle of developing a new CRM, and it uses both WPF for local users, and a Windows Universal App (Store App) for the users in the field.  The basic flow is this

*

*Customer calls in and gets scheduled on a field user in WPF app.

*Field user goes on service call and updates on Surface through Universal App.

*Customer gets billed from the WPF App.

All the modules are in place and working, but I do not seem to be able to integration test the entire project flow due to the different Project Types.
What I need to be able to do is add a reference to my Universal App in the unit test for my WPF app (or the other way around), so I can test the flow through both components.
I have been searching for a solution over the last few weeks, and have not been able to come up with any way to do this. If this is not directly possible (which I am guessing it is not), is there any way I can setup a test playlist so that the integration tests run in a particular order.
I am looking to avoid hard coding sample data into the db in order to test the Universal app, as this would not show the true flow of data from one app to another and back again.  Any help is appreciated.
UPDATE 8-21-2015:
We realize because of the Framework difference the best solution is going to be to run some type of ordered test.  We are using MSTest.  The problem with this is that Ordered Tests in Visual Studios are not solution wide, they are only allowed in a unit test project, which means it will be using the References from that project, and not allow both tests.
We don't care if we have to switch to a different testing framework, as having the proper tests is more important than using a specific framework.

A: You should use a Portable Class Library (PCL).  You can create a PCL in Visual Studio from the add new project screen.
When creating your PCL it will ask you what type of projects you want to target.  Since you stated WPF and Windows Store app you would .Net 4.5(or whatever version you are on) and WIndows 8.1 (or 8.0)
The PCL will allow you to write code in the Run Time with the lowest level of language features for the targeted projects.  In your case this would be the Window's Store app.
Now, instead of storing your logic inside your Window's store project, you will need to move your logic into the PCL.
Once you have compiled your PCL, you will need to add references to the Window's Store app so that you can use the logic within you Windows Store App (you will have to add the namespace for the PCL to make this work).  You will also add a reference to the PCL in your unit test project.  Because you targeted both Run times in your PCL, you will be able to call the code from your integration tests.
Since all your Logic is in the PCL, you should be able to test everything.  The only thing in your Window's Store app now should be the view specific data.
If you ever need to change the targets for your PCL (lets say want it to work with Windows Phone), you can edit the properties of the PCL project, and change the targets.  Be warned that if you add a target with a more constricted run time than one you currently selected, you will have to refactor your code to use only functions available in the lowest functional run time.


text:
Q: Embed .pdf file into latex-document goes wrong I have the following problem:
 ....
(here some text1)
(here should the .pdf file appear)
(here some text2)
....

I need that order which you can see above. But the situation is that .pdf file appears after text2. I have written the following:
 This is an example line for text1.

    \begin{figure}[ht]
    \centering
  \includegraphics[scale=0.5]{Figure1.pdf}
    \caption{example}
    \label{Fig1}
\end{figure}

This is an example for the text2 part.

What I have forgotten?
best regards,

A: LaTeX tries to find the best position for the figure in the document.
If you are not happy with the result.
Add \usepackage{float} to your preamble and use [H] instead of [ht] as the figure positioning option.
[H] means: exactly HERE, do not float


text:
Q: Android Editext - Enter negative number numberDecimal|numberSigned I have an edittext that I want to accept positive and negative numbers.
It works phone on my phone, the keyboard shows the "-" sign, however it doesn't work on some phone whereas the "-" doesn't show up on their keyboard. See the attached images. How to fix it so that it works on all Android phones. I set the edittext to android:inputType="numberDecimal|numberSigned" The first image is on my phone whereas the 2nd image shows the user's phone and he's having problem entering the "-" sign. He uses Android version 5.0.1.

<EditText
android:id="@+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:inputType="numberDecimal|numberSigned"
/>

Thank you.

A: Moving my comment to the answer:

I can see the - on both images. Probably on the lower one you need to hold the button for it though.

It worked, holding the button selects the -.

A: On the second keyboard the - can be found as option on the ) key. So you did everything right. Setting android:inputType="numberDecimal|numberSigned" should suffice. But eventually you might find keyboards not handling these types correctly. But then there's nothing you could do about it anyway.