text:
Q: Is @XmlElement necessary for Jaxb My question is, whether it is necessary to add @XmlElement before each element in your pojo to be picked up by jaxb, when making a JSON response. I am using jersey-json 1.17 . The reason I ask this is because, the example given on Jersey site does not use the annotation.
I get an out put as {}, but when I add @XmlElement before the attributes, I get the expected JSON output. Am I doing something wrong, because of which my JSON string is empty ?
My code :
The vertices list is populated in the constructor.
This produces the wrong output of {}
@XmlRootElement
public class SquareModel {
    List<Float> vertices = new ArrayList<Float>();
    ....
}

Whereas this produces the a correct JSON string :
@XmlRootElement
public class SquareModel {
    @XmlElement(name="vertices")
    List<Float> vertices = new ArrayList<Float>();
    ....
}

My resource class which returns the JSON
@GET
@Produces(MediaType.APPLICATION_JSON)
public SquareModel getJsonString() {
    return new SquareModel();
}

Thanks :)

A: No, by default a JAXB (JSR-22@) implementation will treat all public fields and properties (get/set combinations) as mapped (not requiring the @XmlElement annotation).

*

*http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html
If you wish to annotate a field I would recommend annotating your class with @XmlAccessorType(XmlAccessType.FIELD)

*

*http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html

A: According to this http://jersey.java.net/nonav/documentation/latest/json.html#json.jaxb.approach.section
You should have this annotation (I'm also using it in my code, even though it XML oriented, but it gives me cool JSON also)

Taking this approach will save you a lot of time, if you want to
  easily produce/consume both JSON and XML data format. Because even
  then you will still be able to use a unified Java model. Another
  advantage is simplicity of working with such a model, as JAXB
  leverages annotated POJOs and these could be handled as simple Java
  beans.
A disadvantage of JAXB based approach could be if you need to work
  with a very specific JSON format. Then it could be difficult to find a
  proper way to get such a format produced and consumed. This is a
  reason why a lot of configuration options are provided, so that you
  can control how things get serialized out and deserialized back.
Following is a very simple example of how a JAXB bean could look like.
Example 5.3. Simple JAXB bean implementation

@XmlRootElement
   public class MyJaxbBean {
     public String name;
     public int age;

     public MyJaxbBean() {} // JAXB needs this

     public MyJaxbBean(String name, int age) {
       this.name = name;
      this.age = age;
    }
  }


text:
Q: Absoluteness between $L_\kappa$ and $L$ Working in $L$, suppose $L \models \kappa$ is a cardinal and $(\mathbb{P}, <) \in L_\kappa$. Let $\varphi(x)$ be a $\Sigma_1^1$ formula. Let $\tau \in L_\kappa$ be a $\mathbb{P}$-name for an element of ${}^\omega\omega$. Is "$1_\mathbb{P} \Vdash \varphi(\tau)$" absolute between $L_\kappa$ and $L$?
It seems that if $L_\kappa$ satisfies enough of set theory to prove the Mostowski Absoluteness and some basic facts about the forcing relation, then this would be true. For instance if $\kappa$ was inaccessible or even regular uncountable. For any arbitrary cardinal $\kappa$, does $L_\kappa$ satisfy enough set theory for the Mostowski absoluteness.
A related question is what are the known fragments of ZF that all $L_\kappa$ (or the fine structures $J_\kappa$) where $\kappa$ is a cardinal satisfy?
Thanks for any information that can be provided.

A: The answer is yes, and much more. If $\kappa$ is any uncountable cardinal and $\mathbb{P}$ is a notion of forcing in $L_\kappa$, then for any projective statement $\varphi$, the assertion $1_{\mathbb{P}}\Vdash\varphi$ is absolute between $L_\kappa$ and $L$. To see this, note first that $G\subset\mathbb{P}$ is $L_\kappa$-generic if and only if it is $L$-generic, since all subsets of $\mathbb{P}$ in $L$ are already in $L_\kappa$. Next, observe that all the nice $\mathbb{P}$-names for reals that are in $L$ are already in $L_\kappa$, since a nice name for a real is essentially a function from $\omega$ to the antichains of $\mathbb{P}$, and all such functions that are in $L$ are already in $L_\kappa$, since subsets of set appear in $L$ before the next cardinal stage. It follows that if $\tau$ is any $\mathbb{P}$-name for a real with $\tau\in L$, then we may find a nice name $\sigma\in L_\kappa$ such that $1\Vdash \tau=\sigma$. Consequently, $$\mathbb{R}^{L[G]}=\mathbb{R}^{L_\kappa[G]},$$ and so any projective statement forced over $L$ is equally forced over $L_\kappa$ by the same condition.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Auto connecting to PDO only if needed I have a section of code that depending on the URL requested, will include one of fourteen other files.  Some of these fourteen files require a connection to one of three different databases, and additional files can be added at anytime.
I don't want to open PDO connections by default to all three database as its a waste of resources and will slow the execution time down.  So my thought is to wrap all SQL queries within a function.  The first time that a query is executed on a non-open PDO connection, the try {} error handler can catch it, find out what the problem was (in this case connection doesnt exist), then open the connection and re-execute the query.  That way, the database is only being connected to as and when needed - as long as the connection string (host, database, username, password) are all defined in advance, I can't see any problem in it working.
However, I need to push on with this, and don't have access to the dev box for about 7 days, so can anyone see any problem with that scenario?  Also, can anyone give me the error message that handler->errorInfo() will return if the connection isn't opened?

A: This is the right idea, but not the best implementation of it.
Wrapping the SQL operations is good. But why don't you do it this way:
class Wrapper {
    private static $db;

    public static function someQuery() {
        $db = self::getDatabase();
        // now go on to execute the query
    }

    private static function getDatabase() {
        if (self::$db === null) {
            self::$db = // connect here
        }
        return self::$db;
    }
}

This has a lot of advantages:

*

*Allows you to logically group SQL operations into one (or several!) classes

*Does not connect to database if not needed

*Does not depend on (brittle) error checks to function correctly

In your specific case, you should probably go with 3 separate Wrapper classes. Putting everything into one class is doable (three different $db variables) but probably more confusing than it's worth.

A: I took another approach using __call magic method so you don't need to create individual wrappers for every method.
class PDOLazyConnector
{
    private $dsn;
    private $username;
    private $password;
    private $driver_options;
    private $dbh;

    public function __construct ($dsn, $username, $password, $driver_options = array ())
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->driver_options = $driver_options;
    }

    public function __call ($function, $args)
    {
        // connect to db (first time only)
        $this->__init_dbh ();

        // invoke the original method
        return call_user_func_array (array($this->dbh, $function), $args);
    }

    public function __get ($property)
    {
        return $this->dbh->$property;
    }

    private function __init_dbh ()
    {
        // If db handler is not open yet, do it now
        if (empty ($this->dbh)) {
            $this->dbh = new PDO ($this->dsn, $this->username, $this->password, $this->driver_options);
        }
    }
}

You just have to replace your PDO instancing with PDOLazyConnector, so:
$dbh = new PDO($dsn, $user, $password, $driver_options);

with:
$dbh = new PDOLazyConnector($dsn, $user, $password, $driver_options);

A: Use this class exactly how you would use the PDO class.
class DB extends PDO {

    protected $_config = array();

    protected $_connected = false;

    public function __construct($dsn, $user = null, $pass = null, $options = null) {
        //Save connection details for later
        $this->_config = array(
            'dsn' => $dsn,
            'user' => $user,
            'pass' => $pass,
            'options' => $options
        );
    }

    public function checkConnection() {
        if (!$this->_connected) {
            extract($this->_config);
            parent::__construct($dsn, $user, $pass, $options)
            $this->_connected = true;
        }
    }

    public function query($query) {
        $this->checkConnection();
        return parent::query($query);
    }

    public function exec($query) {
        $this->checkConnection();
        return parent::exec($query);
    }

    //etc.
}

A: PDO has an option for persistent connections PDO::ATTR_PERSISTENT.
See the comments in http://php.net/manual/en/book.pdo.php

A: function &get_pdo()
{
    static $_PDO = null;

    if ($_PDO === null)
    {
        $_PDO = new PDO('your DSN', 'username', 'password');
    }

    return $_PDO;
}

Then you just do
$stmt = get_pdo()->prepare('...');

You could do the same by extending the PDO class and adding a static singleton function to it. I find this approach simplier. Also gives you the opportunity to call it from anywhere on the stack without having to put your connection in the arguments (which can be good or bad, depending on the situation).


text:
Q: Working with other date_format with laravel I'm trying to get other dateformat to work in laravel 4. I want that the user can input something like "31.12.2013" (Format: d.m.Y).
Therefore i'm using this rules in the model
public static $rules = array(
        'birthDate' => 'sometimes|date|date_format:d.m.Y'
    );

Now the user can enter the date in the wished format and the validator accepts the format. The Problem i have is, that the update statement is executed like this.
array(3) {
  ["query"]=>
  string(68) "update `people` set `birthDate` = ?, `updated_at` = ? where `id` = ?"
  ["bindings"]=>
  array(3) {
    [0]=>
    string(10) "30.11.2014"
    [1]=>
    string(19) "2014-06-19 19:39:57"
    [2]=>
    string(2) "22"
  }
  ["time"]=>
  float(0,67)
}

The birthDate-field has the type date and therefore needs a other format (like the "updated_at" field).
Do i have to work with my own setBirthDateAttribute($value) method? or id there a neater possibility to fix this?


text:
Q: Is there a way to always use the default.png when returning from background? In one of my apps when returning from background I get a non consistent behavior:
Sometimes I get the default.png and sometimes I get a snapshot of the last screen which the app was in.
In both cases it takes the UI a good second or two to respond again.
Therefore I would rather show the default.png rather then "unresponsive UI"
Is there a way to make the app display the default.png always until the app becomes active again?
Currently the "stupid" way to do it I thought about is by displaying some Modal view with the default.png and removing it on return to foreground.
Few Clarification:

*

*I am doing this to avoid unresponsive UI.

*I am using the default.png as it looks like loading and gives a better experience then unresponsive UI

*The app has to run in background.
(And to whoever asked - no it is not closed when I sometimes return and see the default.png and not the last UI state - App loading from the start has a very different path and I'm sure of that)
Thanks in advance.

A: This is not a correct behavior and you may experiencing a bug. Basically as long as your app is in the background, when you launch it, you should not see the default.png, unless you remove it from background (double click on home button and delete that app).

A: Most probably, you are taking too long (performing too many calculations) in methods such as applicationWillEnterForeground:, applicationDidBecomeActive:, etc. As a simple test, try commenting out the code in these methods and see if the problem occurs again.

A: For future people interested in this you can use the fact the last view in the app is used to be displayed when the app loads back.
You can display a VC as your moving to background which will represent some loading - hence achieving the desired behavior.
I've already seen a few other apps using the same behavior in cases operations are ran when coming back into the app.

A: Simply set in your Info.plist the property "Application doesn't run in background" to YES. The app will never go in background and when the home button is pressed it will be simply terminated. So you're back to the pre-iOS4 behavior.
Note that when you see now the default image at start-up it is simply because your app has been terminated while it was in background. This is normal especially for apps that take a lot of memory and then don't free it enough before going in the background (I think the threshold for the OS is about 18MB but I'm not sure)


text:
Q: Swift macOS label Gradient Text I have a label in a macOS project which when connected becomes an NSTextField. I want to make the text have a gradient overlay.
I have some code to do this with an iOS UIButton, but for this project I keep getting the error that NSView has no such thing called mask and I don't know what to mask it to
extension NSTextField {
func applyGradientText(colors: [CGColor]) {
    let gradient = CAGradientLayer()
    gradient.frame = bounds
    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    gradient.colors = colors
    layer?.insertSublayer(gradient, at: 0)
    let overlayView = NSView(frame: bounds)
    overlayView.layer?.insertSublayer(gradient, at: 0)

overlayView has nothing called mask, and I don't know what to mask to
    overlayView.mask = SOMETHING

    addSubview(overlayView)
  }
}

A: You need to call wantsLayer = true on the NSTextField as it doesn't have a layer by default. Then just set layer?.mask = gradient and the label will show where gradient is CGColor.clear.
label.applyGradientText(colors: [CGColor.black, CGColor.clear])

extension NSTextField {
    func applyGradientText(colors: [CGColor]) {
        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.colors = colors
        wantsLayer = true
        layer?.mask = gradient
    }
}

Does this do what you want?


text:
Q: cocos2d: my APP crashes but XCode doesn't give me any crash report It used to work fine but now I get this message when loading a certain scene and then the APP crashes.
2012-12-01 18:33:55.104 AppName[9561:707] cocos2d: CCSpriteFrameCache: Trying to use file 'art1-hd.png' as texture

I have no idea on where to start debugging this. Is there a way to get a more precise error message to understand why this happens?
Btw, I have changed my code signing identity to developer and XCode doesn't yet give me any trace of it on the console other than the plain message above. I checked as well the device logs on the Xcode-Organizer section but no trace.
I whish there was something like in Java + Eclipse, where I could get a precise STACKTRACE of where the crash happened.
Any suggestion on how to get a precise stacktrace (E.g. with function name generating the crash)?
PS: I have set strip debug symbols to "NO" in DEBUG, and to "YES" in Release, but I am builing on my own test iPod and hence I think it is automatically build for "Debug" (the section says build for running and testing which is confusing as the project settings allows only debug and release). But I think the problem is not here.. but in the issues above before the PS:
EDIT: If I look into the debug navigator I don't see any stacktrace of methods, as I want, but just threads.. I need to figure out how to use the global exceptions.

A:
I have no idea on where to start debugging this.

You have the cocos2d source code. I would start there.
Search for "trying to use file" in CCSpriteFrameCache to understand what the cause of this message is (which I agree is confusing, why shouldn't you use that file?).
As for the stack trace, it's available as soon as you add a global exception breakpoint. If the breakpoint triggers in OpenAL code make sure to set it to catch only Objective-C exceptions.


text:
Q: Manipulating the definition of $e$ I know that $\lim\limits_{n\rightarrow \infty}(1+\frac{1}{n})^n=e$
I'm trying to show $\lim\limits_{t\rightarrow \infty}(1+\frac{1}{t^2})^{t^2}=e$
If I write $n=t^2$ then $\lim\limits_{t^2\rightarrow \infty}(1+\frac{1}{t^2})^{t^2}=e$
Can I conclude from this that $\lim\limits_{t\rightarrow \infty}(1+\frac{1}{t^2})^{t^2}=e$?
Could it not imply $\lim\limits_{t\rightarrow\ -\infty}(1+\frac{1}{t^2})^{t^2}=e$ (note that $t$ tends to $-\infty)$

A: Both are true. Note that
$$\lim_{\circ\to\infty}\left(1+\frac{1}{\circ}\right)^\circ=e$$
and that $t^2\to\infty$ as $t\to\pm\infty$.

A: Let's have a look at a $\delta-\epsilon$ proof.
We know that if $\lim_{n\to \infty}(1+1/n)^n =e$, then for any given positive number $\epsilon>0$, there exists a number $N(\epsilon)$ that depends on $\epsilon$ such that
$$\left|\left(1+\frac1 n\right)^n-e\right|<\epsilon$$
whenever $n>N(\epsilon)$.
Now, let's have a look at
$$\left(1+\frac1 {t^2}\right)^{t^2}$$
If we take $t>T(\epsilon)=\sqrt{N(\epsilon)}$, then $t^2>N(\epsilon)$ and this implies that
$$\left|\left(1+\frac1 {t^2}\right)^{t^2}-e\right|<\epsilon$$
So, given $\epsilon>0$, there exists a $T(\epsilon)$ such that
$$\left|\left(1+\frac1 {t^2}\right)^{t^2}-e\right|<\epsilon$$
whenever $t>T(\epsilon)$. By definition, this means that
$$\lim_{t \to \infty} \left(1+\frac1 {t^2}\right)^{t^2}=e$$


text:
Q: Associating human tasks with a bugfix branch I am working on a bugfix in a branch, however, the bugfix won't work in production until a large amount of data has been deleted from our database.
I have therefore added a unit test to the branch:
/**
 * Before deploying this branch into production, the following data needs to be
 * deleted from such and such a table.
 *
 * With a detailed explanation of what needs to happen and so-on.
 */
@Test
public void humanTaskTest() {
    org.junit.Assert.fail("Before deploying this branch please perform the actions described in the Javadoc comment to this test");
}

Is there a better way to associate this kind of reminder with a particular branch?


text:
Q: How to get phase and frequency of complex CSI for channel impulse responses? I have measurements of channel impulse responses as complex CSI's. There are two transmitters Alice and Bob and the measurements look like
[real0], [img0], [real1], [img1], ..., [real99], [img99] (100 complex values).
Amplitude for the Nth value is ampN = sqrt(realN^2 + imgN^2)
How do I get the frequency and phase values out of the complex CSI's?
Any help would be appreciated.

A: complex-valued Channel State Information ?
python has cmath, a standard lib for complex number math
but numpy and scipy.signal will probably ultimately be more useful to you

A: In Matlab, you do abs(csi) to get the amplitude. To get the phase, angle(csi). Search for similar functions in python


text:
Q: wcf services for interprocess communication I have put together a .net winform application which consumes a wcf service exposed by another .net application running as a windows service.
Since the communication is within the same machine, I chose the NetNamedPipe as the communication channel, as it is the best choice suited for inter process communication in the same machine.
I want to know if I am using the correct property choices when defining the wcf service in the .net windows service.
The WCF service behaviour is defined as:
[ServiceBehavior(
    ConcurrencyMode = ConcurrencyMode.Single,
    InstanceContextMode = InstanceContextMode.Single)]

I chose the "InstanceContextMode" as Single so that I know objects in the wcf service are not recreated each time a wcf service method is called by the UI client.
However, while reading up the ConcurrencyMode property to choose on MSDN, I did get a little confused. At the basic level, I understand the ConcurrencyMode property dictates whether the wcf service supports a single, multiple or reentrant calls.
Does this mean, that if my UI client application is multithreaded and I call into the wcf service methods from those threads, I should choose "Concurrency" mode as "multiple" and if my UI client is not multi threaded, I should choose "Concurrency" mode as "single"? My UI client application is not running multiple threads. All operations are performed on the main UI thread through event handlers (through button clicks, combo box selections, etc...)
I am having situations where, after installing the application on a windows test machine, my UI client is sometimes not able to connect to the wcf service. It just keeps waiting on the call to the Connect method of the wcf client object and then eventually times out. I want to know if its related to the "ConcurrencyMode" choice I made. Or is this a "NetNamedPipe" communication channel problem?
Please advice.
Thanks in advance.
Subbu

A: Choose concurency mode as multiple only if your host object is thread safe i.e you have manually implemented locking on shared resource or your host object dont have any shared or class level objects at all. If host object is not thread safe use concurency mode as single as in this case wcf will automatically implement lock for you, only one request will be processed at a time on a context, parallel will be queued.  So here decision should really depend on if your host object is thread safe or not.


text:
Q: Difference between compiling and setup.sh What is the essential difference between apply this lines:
./configure
make
make install

and this command:
./setup.sh

Because depending the code, must be done one or the other. Essentially, is it the same?

A: Compiling does exactly that, compiles source code into a binary executable format.  setup.sh is just a filename for a shell script, an executable text file, that could do any number of things.  It could contain instructions that automate compiling source code, or it could just copy a bunch of files around, make directories, etc.
Usually it's a good idea to read the Readme as well as any setup scripts and such inside packages you download to see how the developer(s) intended for the software to be installed and used.


text:
Q: Getting warning while fetching the data from excel in selenium script While reading the data from excel using below I am getting the warnings:
I am using JDK 12.0.1
public static void main(String[] args) throws FileNotFoundException {
    File src = new File("FilePath");
    FileInputStream fis = new FileInputStream(src);
    try {
    wb = new XSSFWorkbook(fis);
    sheet = wb.getSheet("Contacts");
    }
    catch (IOException e)
    {
        e.getMessage();
    }

}
    public static String getdata(int rowNum, int colNum) throws IOException {
    cell = sheet.getRow(rowNum).getCell(colNum);
    String cellData =cell.getStringCellValue();
    return cellData;

}

}
Warnings:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.poi.openxml4j.util.ZipSecureFile$1 (file:/C:/Users/.m2/repository/org/apache/poi/poi-ooxml/3.17/poi-ooxml-3.17.jar) to field java.io.FilterInputStream.in
WARNING: Please consider reporting this to the maintainers of org.apache.poi.openxml4j.util.ZipSecureFile$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

A: From the Apache POI FAQ at https://poi.apache.org/help/faq.html (emphasis added):

*Can Apache POI be compiled/used with Java 11?

  Including the existing binaries on Java 11 as normal jar-files should work when
  using recent versions of Apache POI. You may see some warnings about
  illegal reflective access, but it should work fine despite those. We
  are working on getting the code changed so we avoid discouraged
  accesses in the future.
We also did some work to verify that compilation with Java 11 is
  working and that all unit-tests pass. So Apache POI should be ready to
  be used with current Java 11 releases.
NOTE: Apache POI does not yet fully support the Java module system as
  Apache POI is still supporting previous Java versions and the module
  system cannot be fully supported while maintaining such support. We
  are working on adding support for automatic modules.
FYI, jaxb in current versions also causes some warnings about
  reflective access, we cannot fix those until jaxb >= 2.4.0 is
  available, see https://stackoverflow.com/a/50251510/411846 for
  details, you can set a system property
  "com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize" to avoid this
  warning.
For compiling Apache POI, you should use at least version 4.1.0 when
  it becomes available or a recent trunk checkout until then.


text:
Q: While practicing a program in python that basically finds all the prime multiples of any number, I got stuck here in a while loop def prime_no(n):
    num = 0
    for i in range(1,n):
        if n%i == 0:
            num += 1
    if num == 1:
        return True
    if num > 1:
        return False

def factor_finder(n):
    fact = []
    for i in range(1,n):
        if n%i == 0:
            if prime_no(i):
                fact.append(i)
    return fact

def final_factor_finder(n):
    mul =1
    fact_l = factor_finder(n)
    for i in fact_l:
        mul = mul * i
    val = int(n/mul)
    if val == 1:
        return fact_l
    elif prime_no(val):
        fact_l.append(val)
        return fact_l
    else:
        while val != 1:
            mul =1
            fact_l = fact_l + factor_finder(val)
            for i in fact_l:
                mul = mul * i
            val = int(n/mul)
        return fact_l

I got a problem in the final_factor_finder function and it happens to be stuck in a while loop and do not give any error or results just keeps loading..
I have checked the program multiple times but still stuck with this problem..
Code with the problem. Stuck in the while loop:
 while val != 1:
            mul =1
            fact_l = fact_l + factor_finder(val)
            for i in fact_l:
                mul = mul * i
            val = int(n/mul)
        return fact_l

When I call final_factor_finder(16), I expect to get a result [2,2,2,2] but instead the program gets stuck in the while loop and never seems to break out of it in any case.
But when I call the function final_factor_finder(6) I get the correct results [3,2] as the else statement never executes and even the while loop. So definitely problem is there in the while loop at the end of the program.
 while val != 1:
            mul =1
            fact_l = fact_l + factor_finder(val)
            for i in fact_l:
                mul = mul * i
            val = int(n/mul)
        return fact_l

Thanks if anyone would help!

A: The wrong assumption you made here is in range(1, n). Range is including to excluding. I.e. from 1 (including) to n (excluding n). E.g. range(1, 3): [1, 2]. This means that if you want to know the factor's of a prime number you will always get an empty list. That's why you final_factor_finder will always get stuck on a 'val' for a prime number. You can fix this with range(1, n+1).


text:
Q: Is there a way to test if an Iterable contains a pattern using python's "match" statement? This has to do with the new Python 3.10 beta and the new match syntax.
Is there any way to check if a pattern is simply contained in an iterable? the most obvious solution, to simply put two wildcards on either side, but that raises a SyntaxError due to the unpacking syntax coming from iterable unpacking.
Is there any possible way to do this?
NOTE: the use of things like wrapper classes around numbers
in the example would be fine, as long as it works using the match blocks and is at least somewhat readable, but I have already tried this somewhat and not had much success
example:
numbers = [1, 2, 3, 5, 7, 8, 9] #does not have to be a list, could be a class if needed

match numbers:
    # this just raises a SyntaxError, but I need a way to do something equivalent to this
    case [*_, (5 | 6), *_]:
        print("match!")

A: No, we don't currently have any plans to support iterable containment checks as part of the structural pattern matching syntax.
The best way to rewrite your example in legal Python is with a normal if test:
if any(i in (5, 6) for i in numbers):
    print("match!")

If the containment check is just one part of a more complex pattern, you can write it as a guard instead:
match something:
    case [pattern, capturing, numbers] if any(i in (5, 6) for i in numbers):
        print("match!")

Of course, if you have a sequence, it is also possible to find an item at a known index:
match numbers:
    case [_, _, _, 5 | 6, *_]:
        print("match at position 3!")
    case [*_, 5 | 6, _, _, _]:
        print("match at position -4!")

With that said...

the use of things like wrapper classes around numbers in the example would be fine, as long as it works using the match blocks and is at least somewhat readable

...I suppose mapping patterns could be hacked to make this work (provided that all of your items are hashable and don't have unusual equality rules):
match dict.fromkeys(numbers):
    case {5: _} | {6: _}:
        print("match!")

I strongly recommend the if form over this, though.


text:
Q: Can fermions and bosons exist in the same representation? Some people have made theories where they claim fermions and bosons exist in the same representation for example $E_8$. I can't see how this is possible.
But say for example it is. This would imply that spin would be related to charge. For example if the root vectors of $E_8$ were of the form $(R_1,R_2,..,R_8)$ then the vector bosons (spin $\pm 1$) would be on the roots like $(2,-2,0,0,0,0,0,0)$ and the fermions (spin $\pm 1/2$) would be on roots like $(1,1,1,1,1,-1,-1,-1)$ and $(1,1,1,1,1,1,1,-1)$ and Higgs (spin 0) would be on $(2,2,0,0,0,0,0,0)$.
$E_8$ is very simple in that when two particles interact you can just add their root vectors.
One would therefor see a relation of spin $J$ to charged particles such that:
$$\pm J = \frac{1}{4}|R_1+R_2+R_3+R_4+R_5+R_6+R_7+R_8|-1$$
Now, this seems very implausable that a relation between spin and charge would exist. But if there was such a relation what could it possibly mean? Or is it just a coincidence that known particles seem to fit into this pattern. Or even the fermions and bosons might exist in separate representations but for some reason the lightest ones seem to follow this pattern. Why? (The relation would break down for chargeless particles like photon, $Z_0$ and two netural gluons).

A: There are many examples (maybe in nature, maybe not) of theories with bosons and fermions in the same representation of a gauge group. Any supersymmetric gauge theory, e.g. SuperQCD, will necessarily have gauge bosons and their corresponding fermionic gaugino partners in the same representation of the gauge group as demanded by supersymmetry.
Is this what you are asking?


text:
Q: nginx: variable expansion inside split_clients not working? i have the following config:
map $host $variant_a {
  default 'a';
}
map $host $variant_b {
  default 'b';
}
map $host $variant_c {
  default 'c';
}
map $host $variant_d {
  default 'd';
}
map $host $variant_default {
  default 'default';
}
# a/b testing
split_clients "abtest${remote_addr}${http_user_agent}${date_gmt}" $variant_chosen {
    20%     $variant_a;
    20%     $variant_b;
    20%     $variant_c;
    20%     $variant_d;
    20%     $variant_default;
}

server {
    # defaults test independent
    listen 80;
    server_name _;
    root /home/vagrant/www;
    index index.html;
    error_page 404 = 404.html;
    error_page 403 = 404.html;

    location / {
        echo a=$variant_a,variant_chosen=$variant_chosen
    }

}

when i execute a query against the server:
curl -i http://192.168.33.10/

i can see that the variables inside the 'split_clients' get never expanded.
sample output:
vagrant@precise32:~/www$ curl -i http://192.168.33.10/
HTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Mon, 04 May 2015 15:46:17 GMT
Content-Type: application/octet-stream
Transfer-Encoding: chunked
Connection: keep-alive

a=a,variant_chosen=$variant_default

anybody any idea why the variables are not expanded?
any help highly appreciated
cheers
marcel


text:
Q: Global variable priority over local variable when global function called in scope of local variable c++ I just wanted to clarify a gap in my knowledge.
Given the following code:
I would have expected that "Hi" is printed, based purely on the fact that in the scope of foo, the definition of FuncA is overwritten and hence should be called. This does not happen as shown here https://onlinegdb.com/LzPbpFN3R
Could someone please explain what is happening here?
std::function<void()> FuncA;

void FuncB() {
    if (FuncA) {
        FuncA();
    }
}

struct Foo {
    void FuncA() {
        std::cout << "Hi";
    }

    void FuncC() {
        FuncB();
    }
};

int main()
{
    Foo foo{};

    foo.FuncC();

    return 0;
}

A: As soon as you call a free function, you are no longer inside the class. And you have lost the special this pointer. A (rather C-ish) way could be:
void FuncB(struct Foo* a) {   // expect a pointer to a Foo object
    a->FuncA();               // call the method on the passed object
}

struct Foo {
    void FuncA() {
        std::cout << "Hi";
    }

    void FuncC() {
        FuncB(this);         // pass the special this pointer to the function
    }
};


text:
Q: FacebookSDK: Can we add the FBLoginView to UINavigation? We can add UIButton to a UINavigation but can we add the FBLoginView instead too?

A: Yes login is a view so therefore you can. I have done it using ibaction method and within it pushed my view to the controller. That maybe the way for you as well.


text:
Q: Taking inner class from new class I want to access class B (a subclass of AsyncTask) from class C where class B is an inner class of class A.
My code structure was
 class A{
     class B extends AsyncTask<>(){
     }
 }

 class C{
     public void method() {
       //here I want to access class B.
     }
 }

please help me.

A:  class A{
      Class B extends AsyncTask<>(){
      }
    }

Class C{
   public void method()
   {
      //First create root class object. Then call sub class and execute it as
      //below
      new ClassA().new ClassB().execute();
   }
}

A: First make Class B as public.
class A{
    public class B extends AsyncTask<>(){

    }
}

Then call it inside your Class C method.
class C{
  public void method(){
    A a = new A();
    A.B b = a.new B();
    b.execute();
  }
}

As a general note: Avoid an inner class AsyncTask because it can cause memory leak since it holds an implicit reference to your class A. It means that even if class A is destroyed your AsyncTask might outlive and will not release your class A, so that's a memory leak.
The easiest solution for that is making the AsyncTask static.
class A{
    public static class B extends AsyncTask<>(){

    }
}

class C{
   public void method(){
      B b = new B();
      b.execute();
   }
}

Aside from making the inner AsyncTask subclass as static you can also consider WeakReference as alternative solution.


text:
Q: Gaussian basis function selection - Linear Regression I'm looking to set up a linear regression using 2D Gaussian basis functions. My input training variables cover a two dimensional space. Before applying the machine learning (Bayesian linear regression), I need to select parameters for the Gaussians - mean and variance and also decide how many basis functions to use.
I am currently spacing the means (of a preallocated number of basis Gaussians) evenly over a grid, and just assuming constant variance. This is obviously not the best approach.
Any ideas on how to calculate these variables?


text:
Q: Bootstrap JS not working on JSP for multiple deleteButtons Sometimes only Jquery 2.2 works. if I comment it the delete confirmation button wont pop up. 3.1.1 not working it seems for this code.
w3schools and getBootstrap codes has been refered for this
The delete confirmation modal is popping up for only the first entry in the table i.e foreach loop.
Dont know why..
Please help..
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <title>Manage Books</title>

pmahend1

Add book from Google Books

            <form action="manageBooks" method="POST">
                <input type="hidden" name="action" value="searchGoogleBook" />
                <input type="search" placeholder="Enter Title or Author" name="query" style="width: 450px"/>
                <input type="submit" name="Search" value="Search"/>

            </form>

Add Books Manually

Book Details

                        Title
                        Author
                        Edition
                        Genre
                        ISBN10
                        ISBN13
                        Update
                        Delete

                        Adultery
                        Paulo Coelho

                        Fiction
                        1101874090
                        9781101874097
                        Edit

                            <button type="button" class="btn btn-default" id="deleteButton">Delete</button>

                                    <form role="form" action="manageBooks" method="POST">

                                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Delete Parmanently

Are you sure about this ?

                                                <input type="hidden" name="action" value="deleteBook">
                                                <input type="hidden" name="bookId" value="6" />
                                                <button type="submit" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                                <button type="submit" class="btn btn-danger" id="confirm">Delete</button>

                                    </form>

                        Twilight's Wrath
                        SnÃÂÃÂÃÂæbjÃÂÃÂÃÂörn

                        Fiction
                        1490735372
                        9781490735375
                        Edit

                            <button type="button" class="btn btn-default" id="deleteButton">Delete</button>

                                    <form role="form" action="manageBooks" method="POST">

                                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Delete Parmanently

Are you sure about this ?

                                                <input type="hidden" name="action" value="deleteBook">
                                                <input type="hidden" name="bookId" value="7" />
                                                <button type="submit" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                                <button type="submit" class="btn btn-danger" id="confirm">Delete</button>

                                    </form>

A: It got fixed automatically. May be I had to restart TomCat server.


text:
Q: How to run a complex query inside a Doctrine2 entity? My situation is the following: I developed an app which i'm trying to refactor. I found too much logic inside the controllers basically.
I have a few calculations i'd like to be able to perform from within the entities.
For instance, there is an Entity called Agent which is related to an entity called Account which is related to a Transaction entity.
At one point i'd like to get the sum of all the Transactions from all the Accounts associated with an Agent (whithin a certain date range).
As of now i was able to refactor the code into the Agent repository, creating a method such as:
AgentRepository::getTransactionSum(Agent $agent, \DateTimeImmutable $dateFrom, \DateTimeImmutable $dateTo)

It is working fine and it is better than the old version where the method was inside the controller, but I would like to be able to ask this question straight to the Agent, like:
Agent::getTransactionSum(\DateTimeImmutable $dateFrom, \DateTimeImmutable $dateTo)

I thought about using something like:
Agent::getTransactionSum(\DateTimeImmutable $dateFrom, \DateTimeImmutable $dateTo) {
   return $this->getRepository()->getTransactionSum( $this, $dateFrom, $dateTo );
}

But i read in other questions here that this is not particularly practical nor desirable, so... how should i structure this code?
Thanks
EDIT:
One thing that could be done is having the Agent class resolve it without any extra SQL. Something like:
Agent::getTransactionSum(\DateTimeImmutable $dateFrom, \DateTimeImmutable $dateTo)
{
     return array_sum(
         array_map(
            array_filter(
               $this->getTransactions(), function ( Transaction $t, $dateFrom, $dateTo ) {
       return $t->getDate() >= $dateFrom && $t->getDate() <= $dateTo;
    } ), function( Transaction $t ) {
        return $t->getAmount();
    } )
}

I guess this would make a more pure implementation from an OOP point of view... though it'd probably be far less efficient...

A: By "Tie a repository to the entity" I mean the following:
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="account")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\AccountRepository")
 */
class Account
{

}

That way you can have all your custom functions in the repository and keep the Entity as clean as possible meaning: properties, setters and getters.
Still not seeing why do you want a custom query inside an entity, that is what a repository is for. What you want to do does not mean better OOP.
More info:

*

*Organizing Custom Queries into Repository Classes

*How to Create custom Repository Classes


text:
Q: Error: fazer uma consulta(query) no dao que é um alias Essa query fuciona normalmente no postgreSQL:
select nome as "pessoas?" from pessoa

Mas no java eu fiz um dao que tem um método chamado encontrarAlias:
sql = "select nome as 'teste?' from pessoa where id=?";

Dá a mensagem:

ERROR: syntax error at or near "'teste?'"

PS.:Estou utilizando PreparedStatement.
@Override
    public Pessoa enncontrarAlias(int id) {
    Pessoa pessoa = null;

    sql = "select nome as \"teste?\" from pessoa where id=?";

    try {
        pst = conexao.prepareStatement(sql);
        pst.setInt(1, id);
        rs = pst.executeQuery();

        while(rs.next()){
            pessoa = new Pessoa();
            pessoa.setNome(rs.getString("nome"));
        }

        rs.close();

        return pessoa;

    } catch (SQLException e) {

         throw new RuntimeException(e);     }
}

A: Não usa aspas simples como escape de caractares no postgres e sim aspas duplas, nesse caso adicione uma barra para fazer o escape no java.
sql = "select nome as \"teste?\" from pessoa where id=?";

Para recuperar as informações do banco de dados use o alias:
rs.getString("teste?")


text:
Q: How could I identify this thermistor I've been scavenging for components on a deceased gadget and I've found a thermistor I'd like to use in the future. The problem is there's no serial code printed on it. Without knowing the manufacturer, finding the datasheet is going to be hard. I'm no EE, just a newbie. I'm assuming it is a thermistor because I've empirically verified that it resistance varies with temperature, and since it was inside  a cheap promotional gift I doubt they would have used a more expensive component. Here's a picture of it:

All I can tell for sure about it is that it is a negative temperature coefficient thermistor. I've taken a few measurements using my cheap multimeter and here are the values:

So my questions:

*

*Have you ever seen one like this? Do you happen to know which brand (or possible brands) could it be?

*Is there an online catalogue or DB so that I could identify the component just using the image and approximate resistance?

*In case I failed at identifying it, could I infer the function given the plot? I mean, are these measurements consistent with the behaviour or a thermistor? (I was expecting a linear behaviour, but considering my results either one of the values is an outlier or the function is not linear)

NOTES:
First measurement was made with the resistor inside an ice cube (took several readings to be sure). I'm assuming the temperature here was close to 0ºC.
The last measurement was done with thermistor inside a glass of warm water. I measured the temperature using a digital clinical thermometer.
These two measurements are the most accurate readings I have been able to obtain with the available means at home. I'd have taken a few more readings using the clinical thermometer approach but it only shows me values in the range of 34-44 ºC, so they are too close to be useful. I was thinking about measuring again at boiling point (100ºC) but I've no means to measure the water temp at these levels. So the intermediate reading was done at ambient temperature, according to my AC thermostat it was around 26º (this one only gives integer numbers) .
My cheapo multimeter has an inherent resistance of measuring cables: 0.5 ohm and the precision is +-0.8%, but this is nothing compared to the errors in temperature reading so I doubt this info is meaningful.

A: Looks like an 10kΩ NTC. Most NTC's aren't visibly branded, but the resistance at 25 degrees is the property that they are sold by.
Although chances are very slight that it is actually a Vishay part, this page lists a some datasheets for similar devices. Checking the datasheets for a similar part might give you a good feeling for how the device responds to temperature.

A: Knowing that it is a 10k NTC is still a bit inexact. At least another important characteristic should be mentioned, the beta value. You can have two different 10k thermistors with different beta values, and they will give you different readings. So this is an important parameter to know, at least if you need accuracy and not just some ballpark temperature.
You have already determined that it is a 10k NTC by measuring it at 25 degrees (or close to it). To determine the beta, you need to make another measurement at another specific temperature, this is usually 85 degrees or 50 degrees (though there are others too, these are probably the most common). Then use the formula/calculator on this page to get the beta. The beta that you calculate this way won't be exact, but manufacturers only use specific betas, so take take a list of existing standard betas (for example look at the parametric search options at digikey), and the closest standard beta to your measurement will be yours.
Some of the standard betas are so close to each other that you might only be able to narrow down your beta to 2 or 3 choices. Don't panic in this case, the reading difference between those is so small that your temperature error will be close to insignificant.


text:
Q: How to generate a matrix with certain conditions I want to generate a $n \times n$ matrix.

*

*I want the diagonal entries to be all 0

*I want a random choice of matrix elements with 0 or 1.

*The probability of having a 1 as a matrix element is $1/m$ and the probability of having a 0 as a matrix element is $1-1/m$.

I used the following command but it is wrong.
A[n_, m_] :=Table[If[i == j, 0,RandomVariate[BernoulliDistribution[m],{n,n}]]]

And I tried to test this command with n=4, m=0.4 but it didn't work.
Could anyone kindly tell me how to do this please?
Thank you!

A: Binary random variables are often modeled using the BernoulliDistribution. You can use the function RandomVariate to get a matrix of such variables.
mat = RandomVariate[BernoulliDistribution[0.9], {5, 5}];
mat - DiagonalMatrix[Diagonal[mat]]
% // MatrixForm

$$\begin{pmatrix}
0&1&1&1&1\\
1&0&1&1&1\\
1&1&0&1&1\\
1&0&1&0&1\\
0&1&1&1&0\end{pmatrix}$$
You can change the 0.9 to any value (this is your m). The second line sets all the diagonal elements to zero.
It's easy enough to make this into a function:
makeMat[n_, m_] := (mat = RandomVariate[BernoulliDistribution[m], {n, n}];
                    mat - DiagonalMatrix[Diagonal[mat]])

Then the above example is makeMat[5, 0.9]

A: You can use weight option in  RandomChoice
n = 5;
m = 2;
mat = RandomChoice[{1/m, 1 - 1/m} -> {1, 0}, {n, n}];
(mat - DiagonalMatrix[Diagonal@mat]) // MatrixForm

$\left(
\begin{array}{ccccc}
 0 & 1 & 1 & 0 & 1 \\
 1 & 0 & 1 & 0 & 1 \\
 1 & 0 & 0 & 0 & 1 \\
 0 & 0 & 1 & 0 & 0 \\
 0 & 0 & 0 & 1 & 0 \\
\end{array}
\right)$

A: Since all the simple answers have been given, here is a SparseArray[] solution that may be useful if you want to generate large matrices without storing unneeded zero entries:
tiffany[n_Integer?Positive, m_] :=
    SparseArray[{j_, k_} /; j != k && RandomReal[] < 1/m :> 1, {n, n}]

As an example:
BlockRandom[SeedRandom["tiffany"]; tiffany[7, 2.5] // Normal]
   {{0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 1},
    {0, 0, 0, 1, 0, 1, 1}, {0, 0, 0, 0, 1, 0, 0},
    {0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 1}, {0, 0, 0, 0, 0, 1, 0}}

A: m = 2;
n = 5;
rnd[x_] := If[RandomReal[{0, 1}] < 1/m, 1, 0];
t = Table[rnd[x_]*(1 - KroneckerDelta[i, j]), {i, 1, n}, {j, 1, n}];
t // MatrixForm


text:
Q: Prove any set S of three integers contains a pair $x\neq y$ such that $x^3y-xy^3$ is divisible by 10. Prove any set S of three integers contains a pair $x\neq y$ such that $x^3y-xy^3$ is divisible by 10.
My attempt was :
By the division algorithm, every integer $n$ can be written as $n = 10q + r,$ where $0\leq r \leq 9$. Since there are three integers in $S$ but only 10 possible values for the remainder r. By the pigeonhole principle, the set S contains x & y that leave the same remainder on division by 10, that is there exist s with $0\leq s \leq 9$ such that $x = 10q_1 +s$ and $y = 10q_2+s.$ From here plug x and y into $x^3y-xy^3$ and show there is a 10 I can factor out.
Am I going about this problem the right way?

A: The problem with your approach has been pointed out in the comments by lulu.
Note that $x^3y-xy^3=xy(x^2-y^2)=xy(x-y)(x+y)$.

*

*Show that at least one of the four factors must be even no matter what $x$ and $y$ are.

If $x$ or $y$ is a multiple of $5$, or if $x\equiv y\pmod5$, or if $x+y\equiv0\pmod 5$, then $x^3y-xy^3$ is a multiple of $10$. What combinations of $x$ and $y$ does that cover if neither is a multiple of $5$? Look at $x$ and $y$ modulo $5$:
$$\begin{array}{c|cc}
x\backslash y&1&2&3&4\\\hline
1&\checkmark&&&\checkmark\\
2&&\checkmark&\checkmark\\
3&&\checkmark&\checkmark\\
4&\checkmark&&&\checkmark
\end{array}$$

*

*Show that any set of three integers must contain a multiple of $5$ or two integers in one of that form one of the covered combinations.


text:
Q: two applications running on the same tomcat When running two applications on the same container
I would like to avoid duplication of code, and separate application responsibility and maintenance to different teams so they can maintain and package independently.
apps will reside in tomcat with different version (team A is responsible to App 1 while Team B is responsible to App 2)
So I would like to know if such scenario is possible:
Two applications running on the same tomcat
They share the same db.
They need to use the same security system (filter on app1 save a token on the session) or spring security.
They will differ only on the context as:
http://url:8080/app1     and     http://url:8080/app2

Both will register a spring mapping a:
@RequestMapping(value="/pathOnApp1/{id}")
@RequestMapping(value="/pathOnApp2/{id}")

A:
Two applications running on the same tomcat

Yes. Deploy two web application archive (war) files.

They share the same db.
They need to use the same security system (filter on app1 save a token on the session) or spring security.

This is just configuration. You could use the same xml file, properties file or database setup to configure your two (or more) applications. You might use two repositories (one for configuration, one for development). You might use Apache Zookeeper.


text:
Q: does any function has Indefinite integral I am talking about indefinite integration of a function what ever its nature be as far as continuity and differentiabilty is Concerned. Can we integrate any function irrespective of the result be in elementary form or some special functions or infinite series. For example
$$\int e^{x^2}dx=\int 1+\frac{x^2}{1!}+\frac{x^4}{2!}+\cdots=x+\frac{x^3}{3}+\frac{x^5}{10}+\cdots$$
$$\int |x|dx=\int x dx$$ if $x \gt 0$ and $$\int |x|dx=\int -x dx$$ if $x \lt 0$
So is it True that any function can have Indefinite integral?

A: No, of course not. If $f$ has an "indefinite integral" $F$, this means that $F' = f$, therefore your question is: "can any function be the derivative of some other function"? Well, it turns out that if $F$ is derivable, then $F'$ must posess the intermediate value property. Therefore, every function that does not have this property does not admit an indefinite integral. For instance, the function defined by $f(x) = \begin{cases} 1, x \in \Bbb Q \\ 0, x \notin \Bbb Q \end{cases}$ does not have Darboux's property. On the other hand, every continuous function has an indefinite integral.
This page has more of the information that you need. Notice that all the functions that do not admit an indefinite integral are somewhat pathological and artificial.


text:
Q: Keeping object in a map after removing it from a list With the following code I loose my object in the Map after removing from the List, but I want to keep it in the Map:
ArrayList<object> myList= new ArrayList<>();
Map<String, ArrayList<object>> map = new HashMap<String, ArrayList<object>>();

myList.add(object);
map.put(key1,myList);
map.get(key1); // return [object]
myList.remove(get(index));
map.get(key1); // return []

A: You have to perform the remove on a copy of your list:
List<object> myList2 = new ArrayList<>(myList);
myList2.remove(get(index));

A: It seems like you're sending the object as it is from your list to the map, i.e by reference. You might want to try to create a new object that has same values and send it to the map, instead of using the same object reference. This might be your problem.

A: ArrayList<object> myList = new ArrayList<>();
Map<String, ArrayList<object>> map = new HashMap<String, ArrayList<object>>();

myList.add(object);
map.put(key1, new ArrayList<>(myList));
map.get(key1);
myList.remove(get(index));
map.get(key1);

Read this topic could be useful Is Java "pass-by-reference" or "pass-by-value"?

A: When you have added the list then the list in the map and the individual list are having same memory address. So change in the individual list will also reflect in the change of list in map.
So you will have to create a copy of the list before adding it to the map.
Or the other solution is you can clone the map after the list has been added to the map.

A: It means that what you want to get done is getting the object without theobject leaving the list.
Simply use
 ArrayList.get(indexOfObjectToGet);

 //not
 ArrayList.remove(indexOfObjectToGet);


text:
Q: Can't use loaded font I have little problem with my code. I can't use variable "font" when I loaded it.
try{
       font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(new File("Font/M2c Light.ttf"))).deriveFont(Font.PLAIN,24);
 }catch(Exception ex){
       ex.printStackTrace();
 }

and when i want to use it on button
Button.setFont(font);

and that error shows me:
variable font might not have been initialized

A: try this code. let me know if it works
try {
 GraphicsEnvironment ge =
     GraphicsEnvironment.getLocalGraphicsEnvironment();
 ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
 //Handle exception
}


text:
Q: Inserting Javascript variable in php I'm passing some variables from one page form to another from AWeber. They provide Javascript to do this, but I'm trying to do it with PHP, because I don't know javascript. However, the variable names have spaces and () in them, which PHP doesn't like, so I'm trying to figure out how to get the variables to recognize.....
AWeber uses input field names such as "name (awf_first)" and "name (awf_last)", so my php is:
<?php
    $email=$_GET['email'];
    $awf_first=$_GET['name (awf_first)'];
    $awf_last=$_GET['name (awf_last)']; ?>

but the first and last fields don't work - I assume because of the space and parens. I can't change them because that's what AWeber uses...is there a way to escape them or get them to work somehow?
Thanks!

A: Try with:
$awf_first=$_GET['name_(awf_first)'];
$awf_last=$_GET['name_(awf_last)'];

As PHP transform the spaces for underscores in the variable names passed on the query string.
For the explanation about this PHP behaviour it's well explained in https://stackoverflow.com/a/283781/352672

A: I did the opposite once (PHP to Javascript), but I'm pretty sure it would work too for Javascript to PHP. It wouldn't be the cleanest solution, AJAX is better in my opinion, but still, you can try this out.
First, you have a PHP file who is passed as a Javascript file with this line at the top of your PHP file.
<?php header('Content-type: text/javascript'); ?>

What I used to do is this (PHP to Javascript):
var javascriptVariable = <?php echo("lala") ?>;

but for you, it would be the opposite (Javascript to PHP):
<? $var = ?> javascriptVariable;

Let me know if it works.


text:
Q: Using super vs creating new object of Object class Why can we access the clone() method using super. notation but cant access it by creating new object of type Object. For example if I do something like
Object obj = new Object();

then (using Eclipse) I cannot view the clone() method using the dot operator, which shows that obj is not able to view protected members of Object class (only public methods are visible).
Now if I were to use the super keyword i.e use super. I am able to view protected methods as well.
So my question is that in a class which does not explicitly inherit (extend) other class -- i know that it gives an implicit call to the Object class constructor, i.e. the Object class is its superclass-- why can super keyword access the protected members of Object class, but same is not achieved by creating instance of Object class (only the public members are visible to the instance of Object class)?
Here is clearer code (although it makes no sense but the first part complies and other doesn't):
public class temp {

    public temp() {
        // TODO Auto-generated constructor stub
        TestBikes t1 = new  TestBikes();
        Object ob1 = new Object();
        try {
            t1 = (TestBikes)super.clone(); //SUPER KEYWORD IS ABLE TO ACCESS
                                                   //PROTECTED MEMBERS OF Object
                                                   //CLASS
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            t1 = (TestBikes)ob1.clone();  // HERE IS THE ERROR SAYING clone()
                                                  // FROM Object CLASS IS NOT VISIBLE
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

A: protected means only accessible by a sub-class (or a class in the same package) So you can access it in a sub-class using this or super or nothing, but not another instance.
Your example compiles but it won't run.
    try {
        t1 = (TestBikes)super.clone(); // creates a clone of temp, not a TestBikes
        t1 = (TestBikes)this.clone(); // does the same thing
        t1 = (TestBikes)clone(); // does the same thing

    } catch (CloneNotSupportedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

BTW: I know this is just an example but cloning an object in it's constructor is a bad idea.

It has to be protected so you can access it in subclasses which implement Cloneable.  However, not all objects are cloneable so it is not generally accessible.
Using super can access protected methods.  Using a reference to make a method requires the method be accessible e.g. public or package local and in the same package.
AFAIK, It is generally accepted that the clone()/Cloneable API is broken and should be avoided (except for primitive arrays) e.g. The Cloneable interface doesn't have a Object clone(); method to make it public and it returns Object which have to cast.


text:
Q: Remove "," at end of foreach loop I've created a loop to list a set of meta values. I've been able to apply a class to the last item in the list, but I'd like to remove the "," at the end of the last value. Any help would be much appreciated.
<?php $count = count($subcategory); $num = 0; ?>
    <?php foreach ($subcategory as $subcategory): ?>
        <p
            <?php if($num == $count-1){ ?>
                class="subcategory-item subcategory-last-item inline-block"
            <?php } ?>

            class="inline-block subcategory-item"> <?php echo $subcategory;?>,

    <?php $num++ ?>
<?php endforeach; ?>

I may be taking an incorrect route by worrying about adding a class to the last item. If I can remove the "," from the last item I'll be happy.

A: Here's a quick rewrite which may lead you to a solution:
<?php $count = count($subcategories); $num = 0; ?>
<?php $classes = 'inline-block subcategory-item'; ?>
<?php foreach ($subcategories as $subcategory): ?>
    <p class="<?=$classes.($num==$count-1?' subcategory-last-item':'')?>">
        <?php echo $subcategory;?>
        <?php if ($num<$count-1): ?>
            ,
        <?php endif; ?>

    <?php $num++ ?>
<?php endforeach; ?>


text:
Q: java gui help needed I need some help with gui in java. I am an absolute beginner with java and programming. I copy pasted this code in BlueJ
import javax.swing.*;
class gui{
    public static void main(){
       JFrame frame = new JFrame("My First GUI");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(300,300);
       JButton button = new JButton("Press");
       frame.getContentPane().add(button); // Adds Button to content pane of frame
       frame.setVisible(true);
    }
}

and I didn't get the desired results and this is what showed up in the terminal window:

Device "Mobile Intel(R) 45 Express Chipset Family (Microsoft Corporation - WDDM 1.1)" (\.\DISPLAY1) initialization failed :
WARNING: bad driver version detected, device disabled. Please update your driver to at least version 8.15.10.2302

Can anyone tell me how to fix this error?

A: Just like it says, download the latest graphics driver on the official Intel website and install,then try it again.


text:
Q: Using the parameter passed by URL in JavaScript I need to add a 'Send Message' button which takes the username of the user that message will be sent to, goes to a link and put this username to the 'To' field of the message form.
This is my code
function sendmessage() {
  var x;
  //geting the username
  x = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
  var x = x.substring(x.indexOf(":") + 1);

  //passing the username parameter by URL
  window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;

  //to get the username parameter from URL on new page
  var z=window.location.search.substr(1);

  //to get rid of some part of the username parameter
  var a = z.substring(z.indexOf("0") + 1);
  a = a.substring(0, a.length - 8)

  //to put the username to 'To' field
  document.getElementById("search-q").value= a;
}

Now the problem is that the new page is opened with the parameter. And as a seperate case I can get a parameter from a URL then put it in a field. But I cannot do these two together.
Thanks for the answers!

A: What you are trying to do is impossible.
As I said in my comment you are navigating away from the page when you set the location. The code after that will not run on the next page. That code needs to live on the next page. That code would have to be executed on page load or document ready.

A: ok. thanks for the answers. I solve the issue and it works. I am posting the code to help anyone struggling on this problem like me.
The code is divided into two pieces.
<script>
function sendmessage() {
  var y;
  //geting the username
  y = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
  var x = y.substring(y.indexOf(":") + 1);
//passing the username parameter by URL
  window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
}
</script>

<script>
//code running after page-load
window.onload = function() {
  var z=window.location.search.substr(1);
  var a = z.substring(z.indexOf("0") + 1);
  a = a.substring(0, a.length - 8)
  document.getElementById("search-q").value= a;
}
</script>


text:
Q: Springboot + jpa hibernate + myslq caching writes Apologies that I am working with inherited code and don't understand it well enough to create a minimal reproducible example.
The application is saving data to a MySQL database, through a JPA repository.
The application works, but the data is not apparent through a second application (eg DBeaver) until the MySQL server is restarted.
Is there something I need to set in MySlq (5.6.21) or is there some way I should be configuring the connection in my application to change this behavior?
I have the following in my application.yml:
spring:
  lifecycle:
    timeout-per-shutdown-phase: 5s
  datasource:
    password: MYPASS
    url: jdbc:mysql://localhost:3306/myDB?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useServerPrepStmts=true
      &rewriteBatchedStatements=true&cachePrepStmts=true
    username: MYUSER
    auto-commit: true
    hikari:
      auto-commit: true
  jpa:
    hibernate:
      ddl-auto: none
      use-new-id-generator-mappings: false
      connection:
        provider_disables_autocommit: false


text:
Q: Refused to execute script from 'xxx.xxx.xxx.xxx.ajax.js' because its MIME type ('image/jpg') is not executable I am developing an application on a platform. In this app I have a .html page which calls an external .js file.
This is the header of my page:
<script type="text/javascript" src="ajax.js"></script>

When I am on Chrome and Opera I have a strange behaviour:

*

*sometimes I have no problem;

*other times i get this message:Refused to execute script from 'http://192.168.1.249/ajax.js'
because its MIME type ('image/jpg') is not executable.;

What am I doing wrong?


text:
Q: Saving button's enable disable state and getting this last state on create I'm newbie in android and I'm trying to develop some applications. But last two weeks I've been stuck in this code. In short, I have two buttons in a layout. These buttons are Add and delete button. If I clicked the add button, add will be disabled and delete will be enabled. Or if I clicked the delete, delete will be disabled add will be enabled. I want to save state of these two buttons (which one is clicked) and get the last clicked state on create. But the problem is it's not working. When I open the app both buttons are show disable state. Or not saving either. Never working.
public class UserVideoInfoActivity2 extends AppCompatActivity {

    SharedPreferences.Editor editor;
    SharedPreferences preferences;
    SharedPreferences.Editor editor2;
    SharedPreferences preferences2;

    Button buttonadd;
    Button buttondelete;

    private static final String ADD = "ADD_KEY";
    private final static String DELETE = "DELETE_KEY";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_video_info_layout_2);

        buttonadd = (Button) findViewById(R.id.buttonaddlayout);
        buttondelete = (Button) findViewById(R.id.buttondeletelayout);

        preferences = getSharedPreferences(ADD, Context.MODE_PRIVATE);
        preferences2 = getSharedPreferences(DELETE, Context.MODE_PRIVATE);

        buttonadd.setEnabled(GetState());

        buttondelete.setEnabled(GetState2());

        buttonadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonadd.setEnabled(false);
                buttondelete.setEnabled(true);

                SaveState(buttonadd.isEnabled());

            }
        });

        buttondelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                buttonadd.setEnabled(true);
                buttondelete.setEnabled(false);

                SaveState2(buttondelete.isEnabled());

            }
        });

    }

    private void SaveState(boolean isChecked) {
        editor = preferences.edit();
        editor.putBoolean(ADD, isChecked);
        editor.commit();
    }

    private void SaveState2(boolean isChecked2) {
        editor2 = preferences2.edit();
        editor2.putBoolean(DELETE, isChecked2);
        editor2.commit();
    }

    public boolean GetState() {
        return preferences.getBoolean(ADD, false );

    }

    public boolean GetState2() {
        return preferences2.getBoolean(DELETE, false);
    }

}

<Button
    android:id="@+id/buttondeletelayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="delete" />


text:
Q: my current array format is not being interpreted by datatables using aaData format I'm using aaData array datasource , while displaying the value into table only one character is appearing. why is this displaying only one character? It is supposed to display [0] element. May be this is a simple question, but its looks hard to me. Please help me.
data value format : ["T moniter","Software","W CPU","Software","Global","Softe"]
jQuery.ajax({
 url : '<s:url action="part" method="finder" />',
 dataType : 'json',
 success : function(data){
 alert(data);
 var obj = JSON.stringify(data);
 alert(obj);
$('tbody tr:nth-child(odd)').addClass('odd');
var prodTable = $('#products').dataTable({
            "aaData": data,
            "bDeferRender": true,
            "bPaginate": false,
            "aoSearchCols" : false,
            "bDeferRender": true,
            "aoColumnDefs": [
                {"fnRender": function(o, val){
                console.log("fnRender");
                        console.log(o.aData[0]);
                        return o.aData[0];
                    },
                    "sClass":"Nbr first", "aTargets": [ 0 ]

                    }]

            });

i'm getting null values in the datatable.

A: I hope you found it before you'll see my answer :
var obj = JSON.stringify(data);
"aaData": data,
You stringify your data, and you don't use it.
The correct way is :
"aaData": obj,

or
"aaData": JSON.stringify(data),

Hope i answer to your question.


text:
Q: Form submits twice I have a form that processes a payment, but approximately one in every 300 payments comes though twice, my logs show that there were two requests for all these occurrences.
I implemented some JavaScript that disables the submit button after it's clicked, and it seems to work fine for me, but I'm still getting double submissions every now and then.
Does anyone know anything else that could be causing the form to be submitted twice?

A: As Dagon says, server-side checks are your friend here. Give each instance of the form a randomly generated key (guid would be nice), and store that in the database. Don't accept forms that contain a key that already exists in the db.
Also, are you simply displaying HTML after your form processing logic executes? If so, try redirecting after you process the form.

A: It is a way: after user presses form submit button, disable it with javascript. That should prevent user from double submitting the form accidently. It works for all sites we implement it like because. Because sometimes user gets impatient and clicks form submit button several times, thats why you get double requests. What you need to make sure it works for all the browsers (disabling the button I mean).
Also you could do it on server side, it just is harder.
We use similar to the upvoted answer in Enable/disable submit button with jQuery and Coldfusion server code


text:
Q: Before Trigger is not picking up BillingCountry on the Account Object My class is suppose to pick up The Billing Country and Billing Postal Code and populate the state based on those two fields, however when debugging the before trigger It doesn't pick up the Billing country even though it's populated and it picks up all of the other populated fields.
This only happens on before insert and only happens on the account object, It works fine on Lead and contact objects. There is a state validation rule that doesn't allow the user to save if the state is not populated but the state auto population wouldn't work if the system doesn't recognize the Country being populated on Trigger.new .
Here is what the trigger looks like with the debug:
trigger AccountMasterTrigger on Account (before insert, before update) {
     if (Trigger.isBefore) {
        Sales_AutoPopulateState.Sales_AutoPopulateState(Trigger.new);
        for(Account acts : Trigger.new){
            System.debug('State: '+acts.Billingstate);
            System.debug('PostalCode: '+acts.BillingPostalCode);
            System.debug('Country: '+acts.BillingCountry);
        }
    }
}

Picture of the Billing Account populated on before insert:

Picture of the Logs from the developer console:

A: You will have to check the code of Sales_AutoPopulateState.Sales_AutoPopulateState(Trigger.new);, you must be nulling out the value of Billing Country field in Sales_AutoPopulateState method.
I tried with your code and created records both in Classic and Lightning (although it should not matter) and I was able to get the value of Billing Country in logs.
You can confirm this by moving your debug statements before calling Sales_AutoPopulateState method, I am sure you would be able to find the value of Billing Country in logs.

Update
But from the screenshot that you mentioned in your question, it appears that you enabled State and Country picklists in your organization because both these fields are displayed as picklists and not text fields.
If that's the case, you will have to use BillingStateCode and BillingCountryCode in your trigger to get the selected values. And your logic should be based on those fields rather than BillingState and BillingCountry.
Change your trigger to below and you should be able to get the values in log
trigger AccountMasterTrigger on Account (before insert, before update) {
     if (Trigger.isBefore) {
        Sales_AutoPopulateState.Sales_AutoPopulateState(Trigger.new);
        for(Account acts : Trigger.new){
            System.debug('State: '+acts.BillingStateCode);
            System.debug('PostalCode: '+acts.BillingPostalCode);
            System.debug('Country: '+acts.BillingCountryCode);
        }
    }
}

A: You can debug this functionlity by two ways:

*

*Comment below method and check the value of country and state is coming or not in debug log.

Sales_AutoPopulateState.Sales_AutoPopulateState(Trigger.new);

*You have used standard Billing country and Billing state field of account in code. The Account Standard Billing fields(all) are the text fields, but from above screenshot, I can see the state and Country are picklist on account, I belive those must be custom fields.

Make sure you are using correct field API names of account object which you have added on page layout.


text:
Q: Differences between Safari for Windows and Safari for Mac What are the differences from a developer point of view between Safari for Mac and Safari for Windows?
I think it boils down to evaluate differences between (if I missed something, please correct):
- Layout rendering
- Javascript behavior
The final decision to be made being:
Can developers test only on Safari Windows (knowing that we can't afford to miss important bugs)?
Thanks,
JB

A: Style sheet rendering is significantly different between Safari and Windows.  To see this, try creating a page that has an element with a z-index of -1.  The windows version will function without issue, the Mac version will not allow you to select the elements. Trust me, I wasted about three hours trying to figure out by trial and error why a page would work in one system but not the other.  The worst bit is that when Safari doesn't render something properly, it does so without any indication.  You have to debug line for line, a dreadful experience.

A: I have also seen problems in Safari for Windows that don't exist in Safari for Mac on CSS heavy websites. Can't remember the specifics, but they were there.

A: I am currently experiencing an issue where floating images in a blog with text wrapping around the image do not properly pad themselves in OS X; works fine in windows. Basically I've added padding to make the image align flush left or right such that the edge of the image is at the same offset as the edge of the text of the post; on OS X the image sticks out past the edge of the text.

A: As far as rendering and JavaScript are concerned, there is no difference. What is different is underlaying UI library used for browser itself, but page render is the same.

A: Font rendering can be different between Mac and Windows Safari as the systems typically have different fonts. As long as your page can gracefully handle missing fonts or different font sizes it should be fine.

A: A site I am working on now has a problem in safari for mac that isn't in safari 3 or 4 for windows. I cant figure it out for the life of me.

A: A call to java from javascript throws:
java.net.MalformedURLException: no protocol:
    at java.net.URL.(Unknown Source)
    at java.net.URL.(Unknown Source)
    at java.net.URL.(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation.checkLiveConnectCaller(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation.access$000(Unknown Source)
    at sun.plugin.liveconnect.SecureInvocation$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin.liveconnect.SecureInvocation.CallMethod(Unknown Source)
on Safari windows but not safari mac.

A: Just wanted to add this experience I came across for Safari. Our devs are still going to look into this but not high priority for us since Windows Safari isn't much of our user base unlike Mac. But I think it relates to either (or both) - actual browser low level implementation of Safari by Apple, and/or javascript differences.
Our website recently implemented an HTML5 multiple file uploader. Single file uploads work fine on both versions of Safari. But when uploading multiple files, it fails on Windows. We had two different upload clients & endpoints for the uploader (think A/B testing flow), and one of them provided more details that may or may not point at the cause of the problem. On one of the client & endpoints, the client would send details of the filenames & filesizes of files to upload (as JSON array object) to the server endpoint (as seen via web inspector). On Mac where it worked, filesizes were valid, on Windows, they were 0 bytes.
I think the uploader is JQuery based or some other JS library. But I'm not the dev, so can't be sure. But I have a hunch this issue goes beyond JS libraries...

A: I had an issue with the popup blocker in Safari in Windows XP. I guess the blocker didn't accept that the user clicked a link an Flash that then triggered a JavaScript that opened the Window. The did work in the other major browsers and Safari in OS X, though. Chrome also blocked my window in XP, but not in OS X or Ubuntu.

A: In Mac Safari I'm able to do cross script ajax with file:/// protocol, but in Windows Mac I'm unable to do this.

A: I am working on a website that has pretty standard layout. I have a box that contains other divs. It works on all major browsers, from IE6+, FF3+, etc. On Safari 5 on OSX, the box is totally to the left, outside the borders of my website. On the same safari version in windows, no problem.
I am going crazy over this.


text:
Q: Add a "Cloud drive available for mount" link to nautilus Nautilus default interface includes a list of "mountable" drives (eg. plugged USB drives). Click it to mount then access the contents, right click > eject to unmount. Once you add a google account to Nautilus general config, this list also includes the associated google drive.
I'm using mega.nz, and configured rclone to mount it via rclone mount --daemon. Could I "add it" to nautilus so that I can mount/unmount it with a click instead of opening the terminal each time?
Bonus: is it also possible to add it in the gnome sidebar, like USB drives do (but google drive accounts don't)


text:
Q: Converting to PDO Many thanks for reading my post.
I am fairly new to PHP. I have been working on a project for a while now that uses mysqli and I am trying to convert it to using PDO. In my current set up I have a database class. But I have read on and off that when using PDO, its pointless or at least not necessary to have a database class when using PDO. I wanted to get some opinions on this. I know its a general question but I want to make sure that as I convert my site, I am proceeding in the right way.
Many thanks
Ok so here is the most basic example of my first stumbling block. Please try not to laugh too hard...look at this
  try {

  $handler = new PDO('mysql:host=localhost;dbname=app', 'root', 'fidelio');
  $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e){

    echo $e->getMessage();
    die();
 }

  $name = "pdotest";
  $message = "Test message";
  $sql = "INSERT INTO guestbook (name, message, posted) VALUES (?, ?, NOW())";
  $query = $handler->prepare($sql);
  $query->execute(array($name, $message));

This works.
But why does this not work....
  class Database {

   private $handler;

    function Connect() {
    $db_host = "localhost";
    $db_name = "app";
    $db_user = "root";
    $db_pass = "fidelio";
    try {
        $this->handler = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name,  $db_user, $db_pass);
    } catch(PDOException $e) {
        die($e);
    }
}

}
database = new Database;
$name = "pdotest";
$message = "Test message";
$sql = "INSERT INTO guestbook (name, message, posted) VALUES (?, ?, NOW())";
$database->handler->prepare($sql);
database->execute(array($name, $message));

A: Firstly $handler is private, you cannot access them directly
Secondly you forgot to use $database->Connect();
class Database {
  .....
  public function getHandler() {
    return $this->handler;
  }
}

$database = new Database;
$database->Connect();
$name = "pdotest";
$message = "Test message";
$sql = "INSERT INTO guestbook (name, message, posted) VALUES (?, ?, NOW())";

$database->getHandler()->prepare($sql);
$database->getHandler()->execute(array($name, $message));

note getHandler() function.
As "@Your Common Sense" said, note that Connect function should be called only once - so for this you can call this function in class constructor.
You can call Connect() function in class constructor __construct()
class Database {
  .....
   /**
    * Class constructor called when creating new object
    */
   public function __construct() {
       $this->Connect();
   }
}


text:
Q: Using Ito's lemma to find a SDE I was given the following problem:

Let $W$ denote a standard one-dimensional Brownian motion.
Let $S_t = e^{\sigma W_t}$ for $\sigma>0$. Use Ito's lemma to write a  stochastic differential equation (SDE) for $dS_t$ in terms of $S_t$.

The solution key starts off as:

$f(x,t) = e^{\sigma x}$. Then $f_x = \sigma f$, and $f_{xx} = \sigma^2 f$. Then $\sigma(x) = 1$...

Here, I'm not able to work out how they got $\sigma(x)=1$. If I have a SDE $dX_t=bdt +\sigma dW_t$ then I know the $\sigma(x)$ function is just the coefficient of $dW_t$ but in this case where I have a solution to a SDE which I have to find I don't understand how to find the $\sigma(x)$ function.
Any help would be much appreciated.

A: For $f(x) := e^{\sigma x}$ we have
$$f'(x) = \sigma f(x) \qquad \text{and} \qquad f''(x) = \sigma^2 f(x).$$
Applying Itô's formula, we find
$$\begin{align*} e^{\sigma W_t}-1 = f(W_t)-f(0)  &= \int_0^t \sigma f(W_s) \, dW_s + \frac{1}{2} \int_0^t \sigma^2 f(W_s) \, ds \\ &= \sigma \int_0^t S_s \, dW_s + \frac{\sigma^2}{2} \int_0^t  S_s \, ds \end{align*}$$
where we used that, by definition, $S_s = f(W_s) = e^{\sigma W_s}$. Hence, $(S_t)_{t \geq 0}$ satisfies
$$S_t - 1 = \sigma \int_0^t S_s \, dW_s + \frac{\sigma^2}{2} \int_0^t S_s \, ds$$
which is equivalent to saying that $(S_t)_{t \geq 0}$ solves the SDE
$$dX_t = \sigma X_t \, dW_t + \frac{\sigma^2}{2} X_t \, dt, \qquad X_0 =1.$$


text:
Q: Asp.net - Creating 2 linked Drop Down Lists from Database I have 2 linked database tables (Similar to Country -> State) - how can I dynamically populate 2 drop down lists with these tables such that:
If I pick a Country, only the states for that country show up in the second drop down list?
Update:
There seems to be a solution on this page -> Populate DropdownList based upon other DropDownList VB -> the one that uses the SQL Data connection on the aspx page itself, databinding the dropdowns - how do I do this with LINQ? I think I can figure it out from here.

A: You have your state control hidden, and autopostback = true on your Country dropdownlist.
On the SelectedIndexChanged, you pull that value and query your database with that, and then set your state drop down list to visible.
In the ASPX page:
<asp:DropDownList ID="CountryDD" runat="server" AutoPostBack="true" OnSelectedIndexChanged="CountryDD_IndexChanged" />

<asp:DropDownList ID="StateDD" runat="server" Visible="false"/>

In the Code Behind:
Protected Sub CountryDD_IndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    StateDD.Items.Clear()
    Using conn As SqlConnection = New SqlConnection("Connection String")
        conn.Open()
        Using cmd As SqlCommand = New SqlCommand("get_states_by_country", conn)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@country_id", CountryDD.SelectedValue)
            Using dr As SqlDataReader = cmd.ExecuteReader()
                StateDD.Items.Add(New ListItem(dr("state_name").ToString(), dr("state_id")))
            End Using
        End Using
    End Using
End Sub

A: This will require one of two things:

*

*Non-trivial JavaScript.  (Make it easier with JQuery.  Provide one set of data associating states with countries, and use JavaScript to create/populate the list each time the user selects a new country.

*Lots of communication back and forth from the server.  (Each time the user picks a country, you ask the server for a new list of states, and use AJAX to update the state drop-down.)

A: If you're not opposed to using the Microsoft Ajax Control Toolkit, they have a control called the Cascading Dropdown that would do what you want.

A: I ended up using one of the answers on Populate DropdownList based upon other DropDownList VB - I put the 2 dropdowns in an AJAX Update Panel. This is the same as databyss's answer, except it uses data binding in the page definition itself, no back-end code required.
Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

        <asp:DropDownList ID="DropDownList1" runat="server"
            DataSourceID="Countries" DataTextField="Name" DataValueField="Id"
            AutoPostBack="true"
        />
        <asp:LinqDataSource ID="Countries" runat="server"
            ContextTypeName="YourDataContext"
            Select="new (Id, Name)" TableName="AssessmentTypes">
        </asp:LinqDataSource>

        <asp:DropDownList ID="DropDownList2" runat="server"
            DataSourceID="States" DataTextField="Name" DataValueField="Id"
        />
        <asp:LinqDataSource ID="States" runat="server"
            ContextTypeName="YourDataContext"
            Select="new (Id, Name, CountryId)" TableName="Modules"
            Where="CountryId == @CountryId">
            <WhereParameters>
                <asp:ControlParameter ControlID="DropDownList1" DbType="Guid"
                    Name="CountryId" PropertyName="SelectedValue" />
            </WhereParameters>
        </asp:LinqDataSource>

    </ContentTemplate>
</asp:UpdatePanel>


text:
Q: Parsing html with changing div id I'm trying to parse the following HTML in order to get to the link that I marked below by using jsoup:

In order to do so, I did the following:
Document doc = Jsoup.parse( url );
Elements links = doc.select(".list-item-wrapper").select(".list-item")----> HERE IM STUCK

I would have continued by using:
doc.select(".list-item-wrapper").select(".list-item").select(#SEARCH_RESULT_RECORDID_dedupmrg914683993).select()....

But the problem is that _dedupmrg914683993 is changed between every page.
I also tried:
doc.select(".list-item-wrapper").select(".list-item").select(.list-item-primary-content result-item-primary-content layout-row).select()....

But I got 0 results.
How can I parse it so I could get eventually to the link inside <img class="main-img fan-img-1"...>?
Thank you

A: You can search for string match on any attribute, if your id always start with SEARCH_RESULT_RECORDID string you can look for it using the following syntax
doc.select(".list-item-wrapper").select(".list-item").select('[id^=SEARCH_RESULT_RECORDID]').select()....

I assuming that selectors are using jquery scheme


text:
Q: Android Studio doesn't push all files in Github I am pushing my project to github,but the java files are not there. However,I can see the res folder and its files...The proceedure I followed was.
VCS-->Enable Version Control->Git.
And then
VCS-->Import into version control-->Share project on Github.
Any ideas? I am new to github.
To have a better idea of my problem please check this link. You will notice what files are missing
Thanks.

A: Check if you added the files missing to be handled by Git. (Select them, right click Git -> Add OR VCS -> Git -> Add)