text:
Q: Color picking in the openGL i've been trying to implement color picking and it just aint working right. the problem is that if initially paint my model in the different colors that are used for the picking (i mean, i give each triangle different color, which is his id color), it works fine (without texture or anything .. ), but if i put texture of the model, and that when the mouse is clicked i paint the model by giving each triangle a different color, it doesnt work..
here is the code:
public int selection(int x, int y) {
    GL11.glDisable(GL11.GL_LIGHTING);
    GL11.glDisable(GL11.GL_TEXTURE_2D);

    IntBuffer viewport = BufferUtils.createIntBuffer(16);
    ByteBuffer pixelbuff = BufferUtils.createByteBuffer(16);

    GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);

    this.render(this.mesh);

    GL11.glReadPixels(x, y, 1, 1, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, pixelbuff);

    for (int m = 0; m < 3; m++)
        System.out.println(pixelbuff.get(m));

   GL11.glEnable(GL11.GL_TEXTURE_2D);
   GL11.glEnable(GL11.GL_LIGHTING);

    return 0;
}

public void render(GL_Mesh m, boolean inPickingMode)
{
    GLMaterial[] materials = m.materials;   // loaded from the .mtl file
    GLMaterial mtl;
    GL_Triangle t;
    int currMtl = -1;
    int i = 0;

    // draw all triangles in object
    for (i=0; i < m.triangles.length; ) {
        t = m.triangles[i];

        // activate new material and texture
        currMtl = t.materialID;
        mtl = (materials != null && materials.length>0 && currMtl >= 0)? materials[currMtl] : defaultMtl;
        mtl.apply();
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, mtl.textureHandle);

        // draw triangles until material changes
        for ( ; i < m.triangles.length && (t=m.triangles[i])!=null && currMtl == t.materialID; i++) {
                drawTriangle(t, i, inPickingMode);

        }
    }
}

private void drawTriangle(GL_Triangle t, int i, boolean inPickingMode) {
    if (inPickingMode) {
        byte[] triColor = this.triangleToColor(i);

        GL11.glColor3ub((byte)triColor[2], (byte)triColor[1], (byte)triColor[0]);
    }

    GL11.glBegin(GL11.GL_TRIANGLES);

    GL11.glTexCoord2f(t.uvw1.x, t.uvw1.y);
    GL11.glNormal3f(t.norm1.x, t.norm1.y, t.norm1.z);
    GL11.glVertex3f( (float)t.p1.pos.x, (float)t.p1.pos.y, (float)t.p1.pos.z);

    GL11.glTexCoord2f(t.uvw2.x, t.uvw2.y);
    GL11.glNormal3f(t.norm2.x, t.norm2.y, t.norm2.z);
    GL11.glVertex3f( (float)t.p2.pos.x, (float)t.p2.pos.y, (float)t.p2.pos.z);

    GL11.glTexCoord2f(t.uvw3.x, t.uvw3.y);
    GL11.glNormal3f(t.norm3.x, t.norm3.y, t.norm3.z);
    GL11.glVertex3f( (float)t.p3.pos.x, (float)t.p3.pos.y, (float)t.p3.pos.z);

    GL11.glEnd();
}

as you can see, i have a selection function that's called everytime the mouse is clicked, i then disable the lightining and the texture, and then i render the scene again in the unique colors, and then read the pixles buffer, and the call of:
GL11.glReadPixels(x, y, 1, 1, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, pixelbuff);
gives me wrong values .. and its driving me nutz !
btw, the main render function is render(mesh m, boolean inPickingMode) as u can see, you can also see that there is texture on the model before the mouse clicking ..

A: there are several problems with the example.
First, you're not clearing the color and depth-buffer when clicking the mouse (that causes the scene with color polygons to be mixed into the scene with textured polygons - and then it doesn't work). you need to call:
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

Second, it is probably a bad idea to use materials when color-picking. I'm not familiar with the GLMaterial class, but it might enable GL_COLOR_MATERIAL or some other stuff, which modifies the final color, even if lighting is disabled. Try this:
if(!inPickingMode) { // === add this line ===
    // activate new material and texture
    currMtl = t.materialID;
    mtl = (materials != null && materials.length>0 && currMtl >= 0)? materials[currMtl] : defaultMtl;
    mtl.apply();
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, mtl.textureHandle);
} // === and this line ===

Next, and that is not related to color picking, you call glBegin() too often for no good reason. You can call it in render(), before the triangle drawing loop (but that shouldn't change how the result looks like):
GL11.glBegin(GL11.GL_TRIANGLES);
// draw triangles until material changes
for ( ; i < m.triangles.length && (t=m.triangles[i])!=null && currMtl == t.materialID; i++) {
        drawTriangle(t, i, inPickingMode);
}
GL11.glEnd();

--- now i am answering a little beyond the original question ---
The thing about color picking is, that the renderer has only limited number of bits to represent the colors (like as little as 5 bits per channel), so you need to use colors that do not have these bits set. It might be a bad idea to do this on a mobile device.
If your objects are simple enough (can be represented by, say a sphere, for picking), it might be a good idea to use raytracing for picking objects. It is pretty simple, the idea is that you take inverse of modelview-projection matrix, and transform points (mouse_x, mouse_y, -1) and (mouse_x, mouse_y, +1) by it, which will give you position of mouse at the near and at the far view plane, in object space. All you need to do is to subtract them to get direction of ray (origin is at the near plane), and you can pick your objects using this ray (google ray - sphere intersection).
float[] mvp = new float[16]; // this is your modelview-projection
float mouse_x, mouse_y; // those are mouse coordinates (in -1 to +1 range)
// inputs

float[] mvp_inverse = new float[16];
Matrix.invertM(mvp_inverse, 0, mvp, 0);
// inverse the matrix

float nearX = mvp_inverse[0 * 4 + 0] * mouse_x +
              mvp_inverse[1 * 4 + 0] * mouse_y +
              mvp_inverse[2 * 4 + 0] * -1 +
              mvp_inverse[3 * 4 + 0];
float nearY = mvp_inverse[0 * 4 + 1] * mouse_x +
              mvp_inverse[1 * 4 + 1] * mouse_y +
              mvp_inverse[2 * 4 + 1] * -1 +
              mvp_inverse[3 * 4 + 1];
float nearZ = mvp_inverse[0 * 4 + 2] * mouse_x +
              mvp_inverse[1 * 4 + 2] * mouse_y +
              mvp_inverse[2 * 4 + 2] * -1 +
              mvp_inverse[3 * 4 + 2];
float nearW = mvp_inverse[0 * 4 + 3] * mouse_x +
              mvp_inverse[1 * 4 + 3] * mouse_y +
              mvp_inverse[2 * 4 + 3] * -1 +
              mvp_inverse[3 * 4 + 3];
// transform the near point

nearX /= nearW;
nearY /= nearW;
nearZ /= nearW;
// dehomogenize the coordinate

float farX = mvp_inverse[0 * 4 + 0] * mouse_x +
             mvp_inverse[1 * 4 + 0] * mouse_y +
             mvp_inverse[2 * 4 + 0] * +1 +
             mvp_inverse[3 * 4 + 0];
float farY = mvp_inverse[0 * 4 + 1] * mouse_x +
             mvp_inverse[1 * 4 + 1] * mouse_y +
             mvp_inverse[2 * 4 + 1] * +1 +
             mvp_inverse[3 * 4 + 1];
float farZ = mvp_inverse[0 * 4 + 2] * mouse_x +
             mvp_inverse[1 * 4 + 2] * mouse_y +
             mvp_inverse[2 * 4 + 2] * +1 +
             mvp_inverse[3 * 4 + 2];
float farW = mvp_inverse[0 * 4 + 3] * mouse_x +
             mvp_inverse[1 * 4 + 3] * mouse_y +
             mvp_inverse[2 * 4 + 3] * +1 +
             mvp_inverse[3 * 4 + 3];
// transform the far point

farX /= farW;
farY /= farW;
farZ /= farW;
// dehomogenize the coordinate

float rayX = farX - nearX, rayY = farY - nearY, rayZ = farZ - nearZ;
// ray direction

float orgX = nearX, orgY = nearY, orgZ = nearZ;
// ray origin

And finally - a debugging suggestion: try to render with inPickingMode set to true so you can see what is it that you are actually drawing, on screen. If you see texture or lighting, then something went wrong.


text:
Q: Origin of Min/Max values fed to tickPositioner - bug? I noticed that min/max values that are fed to a custom tickPositioner function are not the same as min/max values of the data set. For example, my max value when chart is downloaded as CSV is 353116.2853, but max value provided to the tickPositioner is 390819.334993875.
Similarly, min value in the dataset is -400944.7087, but tickPositioner receives
-438647.758392375.
Is this a bug?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Enter a password using BOTH enter key and "Submit" button (HTML/Javascript) I'm relatively new to making websites, however, I am trying to use HTML/Javascript so the user can enter a password using either the ENTER key or the "Submit" button, whichever the user chooses. My code works when I simply print a message like "Welcome!" but when I want to redirect them to another page like "intro.html," thats when it stops working. I have attached my code. I understand event.keyCode may not be javascript and may be jquery? If so, please let me know how to implement jquery into html or any other ideas you all may have :) Thank you so much!

 Log In
<script language = "JavaScript">
    function showPass(form){

        var pass = form.pwd.value;
        var pass1 = "tanwebdesign"
        var pass2 = event.keyCode || event.which;

        if(pass == pass1 || ((pass == pass1) && pass2 == 13))
        {
            window.location.replace("intro.html");
        }
        else{
            window.open = "LogIn.html"
        }
    }
</script>

<form>

    Password: <input type = "password" name = "pwd" />

        <input type = "submit" style = "display: none"  onclick = "showPass(form)" />

        <input type = "button" value = "Log In" onclick = "showPass(form)" />
</form>

A: This how it can be done

*

*No need to add two inputs makes the same action

*Use e.preventDefault() to prevent form's default redirect .. see function showPass(form , e) and in html onSubmit = "showPass(this , event)" you can use onSubmit for a form instead of onClick for a submit input

*No need to catch the ENTER keypress it will work automatically with a form

*To redirect the page you can use window.location.href = 'https://www.google.com'

function showPass(form , e){
    e.preventDefault();
    var pass = form.pwd.value;
    var pass1 = "tanwebdesign";
    alert(pass);
    if(pass == pass1 || pass == pass1)
    {
        //window.location.replace("intro.html");
    }
    else{
        //window.open = "LogIn.html"
    }
}
<form onSubmit = "showPass(this , event)">
    Password:
    <input type = "password" name = "pwd" />
    <input type = "submit" value = "Log In" />
</form>


text:
Q: Java error for installation rasterframes (databricks) I have followed the steps in this notebook to install rasterframes on my databricks cluster.
Eventually  I am able to import the following:

from pyrasterframes import rf_ipython
from pyrasterframes.utils import create_rf_spark_session
from pyspark.sql.functions import lit
from pyrasterframes.rasterfunctions import *

But when I run:

spark = create_rf_spark_session()

I get the following error: "java.lang.NoClassDefFoundError: scala/Product$class".
I am using a cluster with Spark 3.2.1. I also installed Java Runtime Environment 1.8.0_341, but this made no difference.
Could someone explain what went wrong? And how to solve this error?
The full error log:

---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<command-2354681519525034> in <module>
      5
      6 # Use the provided convenience function to create a basic local SparkContext
----> 7 spark = create_rf_spark_session()

/databricks/python/lib/python3.8/site-packages/pyrasterframes/utils.py in create_rf_spark_session(master, **kwargs)
     97
     98     try:
---> 99         spark.withRasterFrames()
    100         return spark
    101     except TypeError as te:

/databricks/python/lib/python3.8/site-packages/pyrasterframes/__init__.py in _rf_init(spark_session)
     42     """ Adds RasterFrames functionality to PySpark session."""
     43     if not hasattr(spark_session, "rasterframes"):
---> 44         spark_session.rasterframes = RFContext(spark_session)
     45         spark_session.sparkContext._rf_context = spark_session.rasterframes
     46

/databricks/python/lib/python3.8/site-packages/pyrasterframes/rf_context.py in __init__(self, spark_session)
     37         self._jvm = self._gateway.jvm
     38         jsess = self._spark_session._jsparkSession
---> 39         self._jrfctx = self._jvm.org.locationtech.rasterframes.py.PyRFContext(jsess)
     40
     41     def list_to_seq(self, py_list):

/databricks/spark/python/lib/py4j-0.10.9.1-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1566
   1567         answer = self._gateway_client.send_command(command)
-> 1568         return_value = get_return_value(
   1569             answer, self._gateway_client, None, self._fqn)
   1570

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
    115     def deco(*a, **kw):
    116         try:
--> 117             return f(*a, **kw)
    118         except py4j.protocol.Py4JJavaError as e:
    119             converted = convert_exception(e.java_exception)

/databricks/spark/python/lib/py4j-0.10.9.1-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling None.org.locationtech.rasterframes.py.PyRFContext.
: java.lang.NoClassDefFoundError: scala/Product$class
    at org.locationtech.rasterframes.model.TileDimensions.<init>(TileDimensions.scala:35)
    at org.locationtech.rasterframes.package$.<init>(rasterframes.scala:55)
    at org.locationtech.rasterframes.package$.<clinit>(rasterframes.scala)
    at org.locationtech.rasterframes.py.PyRFContext.<init>(PyRFContext.scala:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:380)
    at py4j.Gateway.invoke(Gateway.java:250)
    at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
    at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
    at py4j.GatewayConnection.run(GatewayConnection.java:251)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: scala.Product$class
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
    at com.databricks.backend.daemon.driver.ClassLoaders$LibraryClassLoader.loadClass(ClassLoaders.scala:151)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
    ... 15 more

Many thanks in advance?

A: That version of RasterFrames (0.8.4) works only with DBR 6.x that uses Spark 2.4 & Scala 2.11, and will not work on Spark 3.2.x that uses Scala 2.12.  You may try to use version 0.10.1 instead that was upgraded to Spark 3.1.2, but it may not work with Spark 3.2 (I haven't tested it).
If you're looking for execution of the geospatial queries on Databricks, you can look onto the Mosaic project from Databricks Labs - it supports standard st_ functions & many other things. You can find announcement in the following blog post, more information is in the talk at Data & AI Summit 2022, documentation & project on GitHub.

A: I managed to get version 0.10.x of rasterframes working with Databricks runtime version 9.1 LTS. At the time of writing you cannot upgrade to a higher version of the runtime, because of pyspark version differences. Below you'll find a step-by-step guide on how to get this to work:

*

*Cluster should be single user, otherwise you'll get this error:
py4j.security.Py4JSecurityException: Constructor public org.apache.spark.SparkConf(boolean) is not whitelisted

*At the time of writing, the Databricks runtime version needs to be 9.1 LTS.

*An init script should install GDAL:
pip install gdal -f https://girder.github.io/large_image_wheels

*Rasterframe JAR should be build from source:
git clone https://github.com/mjohns-databricks/rasterframes.git
cd rasterframes
sbt publishLocal

*Rasterframe JAR should be uploaded to Databricks. After the build, the file is located at:
/pyrasterframes/target/scala-2.12/pyrasterframes-assembly-0.10.1-SNAPSHOT.jar


text:
Q: what is the most effective way to be able to use all opengl libraries developing application for webgl? i need to use some physics library for example bulletphysics in C++ in a physics simulation application. there is a restricton that i must use webgl and javascript.
i googled and saw using emscripten, some libs has been ported to javascript but some people say that code uses too much cpu and memory and is not effective.
also i searched for a way to develop code in c++ and port it to javascript, i found out emscripten but have given up because of inefficiency.
also i found mandreel but it is not free and i need a free way at first plan.
at this point i want to ask how can i use opengl libs that i need through webgl by the most effective way?
thanks

A: Most physics simulation libraries are tailored for compilation into native code, some may even use assembly at some time critical parts. So porting that to JavaScript will be very hard. I think the best thing to do, and in your case since it's home what what's probably expected is, that you write the stuff in JavaScript directly.
And just to get this clear: OpenGL just draws stuff. It's not a game or simulation framework. Bullet Physics is not OpenGL, ODE is not OpenGL. Just because most programs that use Bullet or ODE render stuff, this does not imply that this has something to do with OpenGL in the first place.


text: Q: VPN для исходящего трафика WP Имеется плагин Wordpress, который синхронизирует каталог товаров с Facebook и Instagram, но из-за известных событий и поскольку сервер сайта расположен в России - синхронизация перестала работать. Вопрос - как это технически правильно обойти? Есть решение кроме как сменить сам сервер? Что-то вроде VPN для исходящего трафика WP?


text:
Q: Proc syntax in Haskell Arrows leads to severe performance penalty Using proc notation for Arrow seems to kill performance in my project. Here is a toy example of the problem:
We define Coroutine newtype (mostly copying from Generalizing Streams into Coroutines) to represent Mealy machines (i.e. functions that carry some state) with instances of Category and Arrow, write scan wrapper function and evalList runner function for lists.
Then we have sumArr and sumArr' functions where the latter is the former called within proc block.
Compiling with stack ghc -- --make test.hs -O2 using ghc-8.0.2 on OS X I get runtime of 0.087 secs for sumArr and 3.263 secs for sumArr' (with a heavy memory footprint).
I would like to know if this in fact caused by using proc and if I can do something to have normal runtime behaviour when using proc notation (writing arrow code without it is painful). Thank you.
{-# LANGUAGE Arrows #-}
{-# LANGUAGE BangPatterns #-}

import Prelude hiding (id, (.))
import Control.Arrow
import Control.Category
import qualified Data.List as L

newtype Coroutine i o = Coroutine { runC :: i -> (o, Coroutine i o) }

instance Category Coroutine where
    id = Coroutine $ \i -> (i, id)

    cof . cog = Coroutine $ \i ->
        let (x, cog') = runC cog i
            (y, cof') = runC cof x
        in (y, cof' . cog')

instance Arrow Coroutine where
    arr f = Coroutine $ \i -> (f i, arr f)

    first co = Coroutine $ \(a,b) ->
        let (c, co') = runC co a in ((c,b), first co')

scan :: (o -> t -> o) -> o -> Coroutine t o
scan f = go where
    go i = Coroutine $ step i where
            step a b = let !a' = f a b in (a', go a')

evalList :: Coroutine a b -> [a] -> [b]
evalList a = L.map fst . L.drop 1 . L.scanl' (\(_, acc) v -> let !x = runC acc v in x) (undefined, a)

sumArr, sumArr' :: Coroutine Int Int
sumArr = scan (\acc x -> let !newAcc = acc + x in newAcc) 0
sumArr' = proc v -> do sumArr -< v

testData :: [Int]
testData = [1..1000000]

main = print $ L.last $ evalList sumArr' testData

A: Yeah, this is probably caused by proc notation. The desugaring is very low-level, introducing a lot of (needless) arrs and not taking advantage of &&& or *** at all.
For example, last I checked, this:
mulA f g = proc x -> do
  a <- f -< x
  b <- g -< x
  returnA -< a * b

Is desugared to something like this:
mulA f g = arr dup
  >>> first f
  >>> arr swap
  >>> first g
  >>> arr mul
  where
    dup x = (x, x)
    swap (x, y) = (y, x)
    mul = uncurry (*)

When it could be just this:
mulA f g = f &&& g >>> arr mul

And this:
proc x -> do
  a <- f -< x
  b <- g -< a
  returnA -< b

Becomes something like this:
arr id
  >>> f
  >>> arr id
  >>> g
  >>> arr id
  >>> returnA

Instead of this:
f >>> g

Moreover I don't think there are any GHC rewrite rules that take advantage of the arrow laws to help account for this.

A: I have found arrowp-qq which wraps proc blocks inside quasiquotes and seems to produce better output than native desugarer. Performance is restored in the following version of our example:
{-# LANGUAGE QuasiQuotes #-}
...
import Control.Arrow.QuasiQuoter
...
sumArrQQ = [proc| x -> do sumArr -< x |]

One issue that I bumped into is that these quasiquotes don't play nicely with raw numbers inside the quotation.
sumArrQQ' = [proc| x -> do sumArr -< x + 2 |] -- gives an error

sumArrQQ'' = [proc| x -> do sumArr -< plus2 x |] -- compiles fine
    where plus2 = (+) 2


text:
Q: Why is my frame not resizing? When you choose a state, the frame's content pane removes its components. Then depending on the state you chose, another class takes the content pane and adds onto it. After doing so, the frame gets packed to resize accordingly.
I want free control over whats in the Frame, such as being able to put panels side by side, above one another, ect.. so I really don't want to use CardLayout. (I'd much rather have 1 panel handle both loginscreen and chat. Then, be able to display another panel next to that one).
I'm using the JFrame's content pane for my login and chat screen, but when I run my code, I get a small frame (has SOME size, but hardly any) that's white on the inside.

*

*show frame

*switch to chat

*remove everything on pane (currently nothing)

*add components onto pane

*pack frame so it can size accordingly to the pane

*revalidate if needed (not sure when I need to revalidate or not)

Please tell me what I'm doing wrong, and maybe guide me in the right direction.
PS: There are no errors
EDIT: The only thing I can think of is that since I'm passing frame.getContentPane() through the method, and methods are pass-by-value, the actual reference to frame.getContentPane() might not be noticing the changes I'm asking for. But then I don't know why the inside of the frame would be white (as if my JTextArea tried rendering), and there's padding on the inside of the frame, so there has to be something happening..
Main.java:
package main;

import ui.Frame;

public class Main {
    public static Frame frame = new Frame();

    public static void main(String[] args) {
        frame.show();
        frame.switchState(State.chat);

    }

    public static enum State {
        login, chat;
    }
}

Frame.java:
package ui;

import main.Main.State;
import javax.swing.JFrame;

public class Frame {
        private Panel currentpanel; //from package ui, not AWT
        private ChatPanel chatpanel = new ChatPanel();

        private JFrame frame;
        public Frame() {
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
        }

        public void show() {
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

        public void switchState(State state) {
            frame.removeAll();

            switch(state) {
                 case chat:
                currentpanel = chatpanel;
                currentpanel.addComponentsTo(frame.getContentPane());
                break;
            }
            frame.pack();
            frame.revalidate();
        }
    }

Panel.java:
package ui;

import java.awt.Container;

public interface Panel {
    public void addComponentsTo(Container pane);
}

ChatPanel.java:
package ui;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JTextArea;

public class ChatPanel implements Panel {
    private JTextArea toparea = new JTextArea();
    private JTextArea bottomarea = new JTextArea();

    @Override
    public void addComponentsTo(Container pane) {
        pane.setPreferredSize(new Dimension(500, 500));
        pane.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        gbc.gridy = 0;
        gbc.gridx = 0;
        gbc.ipadx = 450;
        gbc.ipady = 350;
        pane.add(toparea, gbc);

        gbc.gridy = 1;
        gbc.ipady = 100;
        pane.add(bottomarea);
    }
}

A: I know that can be quite frustrating.
have you tried calling
pack(); or repaint();

A: I found the problem. It was calling frame.removeAll(); before adding anything to it.
When I tried if(frame.getComponents().length > 0), it still triggered removeAll(), but the problem wasn't fixed. Seeing how I haven't added anything yet, I checked to see what the component was (by printing out the object), and it was a JRootPane.
After that, I tried printing out frame.getContentPane().getComponents().length, it gave me 0 as expected.
Long story short: This is how switchPanel(State state) should look:
    public void switchState(State state) {
        if(frame.getContentPane().getComponents().length > 0)
             frame.removeAll();

        switch(state) {
             case chat:
                 currentpanel = chatpanel;
                 currentpanel.addComponentsTo(frame.getContentPane());
                 break;
        }
        frame.pack();
        frame.revalidate();
    }

A: NOTE: I still recommend CardLayout, but if you insists in dynamically setting the frame's content pane the here it is.
The frame class
public class SwitchingFrame extends JFrame {

    public static enum State {ONE, TWO}
    private PanelONE panel1 = new PanelONE();
    private PanelTWO panel2 = new PanelTWO();

    public SwitchingFrame() {

        getContentPane().setLayout(new BorderLayout());
        pack();
        setVisible(true);
    }

    public void switchState(State state) {

        setVisible(false);
        getContentPane().removeAll();
        if (state.equals(State.ONE))
            getContentPane().add(panel1, BorderLayout.CENTER);
        else
            getContentPane().add(panel2, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }
}

The two panel classes which are switched
public class PanelONE extends JPanel {

    public PanelONE() {

        add(new JLabel("ONE"));
    }
}

public class PanelONE extends JPanel {

    public PanelTWO() {

        add(new JLabel("TWO"));
    }
}

The main method which includes buttons to simulate changing the panels
public class TestSwitchingFrame {

    public static void main(String[] args) {

        final SwitchingFrame sframe = new SwitchingFrame();

        JFrame frame = new JFrame();
        JButton b1 = new JButton("ONE");
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sframe.switchState(SwitchingFrame.State.ONE);
            }
        });
        JButton b2 = new JButton("TWO");
        b2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sframe.switchState(SwitchingFrame.State.TWO);
            }
        });
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(b1);
        frame.getContentPane().add(b2);
        frame.pack();
        frame.setVisible(true);
    }
}

You do not need (not should) write your own interface (Panel). Your two panels should extend JPanel and set within the frames content pane. Your frame should extend JFrame and does not need to override its show method (let Swing do it for you). The specific implementation of the switchState function should eventually depend on the end result you want. There are similar ways to accomplish almost the same result.


text:
Q: What is the DC behavior of the switched BJT emitter follower configuration There is a circuit shown below where we have a sub-circuit I marked in red.
I know that it is a source follower with the AC behavior shown below.
As you can see the circuit has DC voltage input only.
What is the DC behavior of the part I marked with the red arrow?

A: let's consider linear vs non-linear differences.
We know from datasheet typical curves and min/typ/max specs how hFE varies with Ic, Temperature and Vce.

*

*since Zout is a direct function of hFE, and impedance applied to the base it is important to understand some variables and how impedance control rise fall time into some fixed charge , Q or estimated Ciss which is also Vgs voltage dependent.

*When Vce=Vce(sat) at Ic/Ib=10, and hFE typ is 100 we know that hFE has lost 90% of it's value due to forward conduction of Vcb.  Similar 10% ratio exists for hFE types >500 tested at Ic/Ib=50.  But since hFE is too dynamic, we standardize Vce(sat) at fixed Ic/Ib ratios even though we know Ic is only controlled by Vbe.  But with Re/Rfb ratios known it is easier to compute Vce(sat) from current ratios than otherwise.

*the Zout formula is better defined by hFE than gm because gm not given in datasheets.
$$Zo_{emitter}=( Z_{Input}/h_{FE})// Re//Ro. $$

*

*for Q3, Zinput=R6//Rce(Q2), neglecting flyback D1.
We assume R6>>Rce which is the saturation condition =Vce(sat)/Ic,

*therefore we know Zo rises when Q2 turns off leaving R6/hFE to define the Zo

*When Q2 turns on, it's Rce drops to 1 Ohm for PN2222A and equivalents. Vb will be <100 mV, then Ve depends solely on the passive pull down load resistance.

This means using a emitter follower will have a faster risetime due to R6/hFE than fall time due to the load resistance unless it is less than R6/hFE.
Since Complementary drivers like this always needs a deadtime to prevent shootthru, the final switch turn off time must be faster than turn on time.  that means emitter followers make poor half bridge drivers so push-pull drivers are used instead with controlled slew impedances.


text:
Q: Get value from datetimepicker in code behind c# I'm doing some Sharepoint webparts and i'm trying to use a jquery datetimepicker, but i can't quite retrieve the value from the datetimepicker in the C# code behind. Here is my script :
   <input type="hidden" id="StartDateHiddenField" name="StartDateHiddenField" value=""/>
     <script type="text/javascript">
         $(document).ready(function () {
             $(".datepicker1").datepicker({
                 changeMonth: true,
                 changeYear: true,
                 dateFormat: "dd-mm-yy",
                 showButtonPanel: false,
                 onClose: function (dateText, inst) {
                     $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
                     $('#StartDateHiddenField').val($(this).datepicker("getDate"));
                 }

             });
        });
    </script>

In code behind :
 var test = Page.Request.Form["StartDateHiddenField"];
 var startTime = DateTime.Parse(Page.Request.Form["StartDateHiddenField"]);

test value according to debugger is, for exemple :

"Sat Jul 01 2017 00:00:00 GMT+0200 (Romance Daylight Time)"

How can i get proper values from DateTime.Parse ?

A: Thanks to ADyson, a solution was to use $(this).datepicker("getDate").toISOString()


text:
Q: Barrier thread synchronisation in pairs I want to implement a function that blocks incoming threads until 2 threads of the same colour meet. Each thread is modelled by a unique id and colour. The function should return the id of the other thread it is matched to. I tried to use the idea for rendezvous and barrier to solve the question, which worked when there are only 2 threads at any one time, but when there are more than 2 threads, the id returned is incorrect. I am trying to solve for 1 colour first as the other 2 colors would have similar logic, but I am not sure what I need to change?
 int pack_thread(int colour, int id) {
if (colour == 1) {
    sem_wait(&d); map[0][count[0]] = id; count[0]++;
    if (count[0] == 1) {
        sem_post(&d);
        sem_post(&a1); sem_wait(&a2); sem_post(&barr);
        return map[0][1];
    } else if (count[0] == 2) {
        sem_post(&d);
        sem_wait(&a1); sem_post(&a2);
        return map[0][0];
    } else {
        sem_post(&d);
        sem_wait(&barr);
        map[0][1] = id;
        count[0] = 0;
        sem_post(&a2);sem_wait(&a1);
        return map[0][0];
    }
} else {
    return 0;
}


text: Q: Solving Kepler's Equation I've been working on simulating orbits. I've found that, when solving Kepler's equation, $M = E - \varepsilon\sin{E}$, I'm unsure about the solution to use. For a true anomaly $< \pi$, using the first solution is correct, but for angles larger than that the second solution must be used. Is this a pattern that repeats indefinitely? I'm having trouble consistently being able to identify the solution I should use. Thanks for any help!


text:
Q: SQL Server 2014 Wrong result in Where clause, help me to understand why I read online that specifically a where clause like this:

where Location2 <> ''

should evaluate to true for a column value of Null.
This behavior is consistently not working for me in SQL Server 2014.  That where clause will exclude my Null columns.  We can write a query to overcome this, but I need to know what to expect and if this is a new behavior.
Thank you.

A: Null compared with anything, anyway, is not true, always fails, check this:
NULL = NULL -- fails
NULL <> '' -- fails: can be translated as "it's not different to '' "
NULL = '' -- fails: can be translated as "it's not equal to '' ", surprised?

you should use
where Location2 <> '' or Location2 is null

ADDED: (er... copied & pasted from @Bacon Bits comment below, thanks)
Actually, the truth value for all those expressions is UNKNOWN. The complexity comes when combining UNKNOWN with AND and OR. UNKNOWN kind of behaves like FALSE, but it's kind of an odd duck. The bottom line: Always handle your NULLS.

A: The answer depends on the value of ANSI_NULLS.

When SET ANSI_NULLS is ON, a SELECT statement that uses WHERE
column_name = NULL returns zero rows even if there are null values in
column_name. A SELECT statement that uses WHERE column_name <> NULL
returns zero rows even if there are nonnull values in column_name.
When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>)
comparison operators do not follow the ISO standard. A SELECT
statement that uses WHERE column_name = NULL returns the rows that
have null values in column_name. A SELECT statement that uses WHERE
column_name <> NULL returns the rows that have nonnull values in the
column. Also, a SELECT statement that uses WHERE column_name <>
XYZ_value returns all rows that are not XYZ_value and that are not
NULL.

Presumably you are operating with SET ANSI_NULLS ON.  As the docs say, NULL means "unknown", and any operation that deals with unknown values is also unknown.
If you want to compare directly with NULL, you can set SET ANSI_NULLS OFF immediately before your query and turn it back on afterwards.  For example:
declare @x varchar(10)

set ansi_nulls on
if @x <> '' select 'yes' else select 'no' -- returns "no"

set ansi_nulls off
if @x <> '' select 'yes' else select 'no' -- returns "yes"

A better option is to explicitly do comparisons with IS NULL, IS NOT NULL, and ISNULL().  For example, you could use ISNULL to simplify comparisons like this:
declare @x varchar(10)

set ansi_nulls on
if isnull(@x, '') <> '' select 'yes' else select 'no' -- returns "no"

set ansi_nulls off
if isnull(@x, '') <> '' select 'yes' else select 'no' -- returns "no"

If you are curious whether the ANSI_NULLS is enabled during execution, you could check the @@OPTIONS bit 32:
if @@OPTIONS & 32 = 32
    select 'ANSI_NULLS is ON'
else
    select 'ANSI_NULLS is OFF'


text:
Q: Rails Simple-Form group_method I came across the following on the simple_form github repo:
f.input :country_id, :collection => @continents, :as => :grouped_select, :group_method =>   :countries

The thing that caught my attention was the :group_method wich would be exceptionally usefull when creating a selectbox that gives options based on what's in the database. The only thing I can't work out is what kind of input the :group_method expects, and where to put the method.
For instance, I want to create a selectbox for the table column :product_type. I imagine I would write something like this in my simple form:
= f.input :product_type_contains, :collection => @products, :as => :grouped_select, :group_method => :product_types

where :product_type would be the method that is being called. But I don't know what kind of method I should write, what kind of result simple_form expects, and if I should put it in the Product class, Product.rb. Any help would be greatly appreciated!

A: According to the test suite, simple_form seems to expect the type of arrays or hashes that you would use with grouped_options_for_select:
test 'grouped collection accepts group_label_method option' do
  with_input_for @user, :tag_ids, :grouped_select,
    :collection => { ['Jose', 'Carlos'] => 'Authors' },
  :group_method => :first,
  :group_label_method => :last
  [...]

test 'grouped collection accepts label and value methods options' do
  with_input_for @user, :tag_ids, :grouped_select,
    :collection => { 'Authors' => ['Jose', 'Carlos'] },
    :group_method => :last,
    :label_method => :upcase,
    :value_method => :downcase
  [...]

Presumably, you could write a class method on Product.rb that creates a structure similar, or even try using grouped_options_for_select(@products)...
Hope this gets you on the right path.


text:
Q: Network printer makes noise every time I insert/remove a USB device I know that I've encountered an answer to this question before, but I can't seem to figure out the right search terms to find the answer anywhere.
I have an Epson WF4630 at my office and an Epson 845 printer at home. Both are on wired networks.
Every time I log into any Ubuntu system or VM (12.04, 14.04, 14.10) on the local network, and most times I insert or remove a USB device (flash drive, webcam, fpga board... anything) my network printer 'spools'—it sounds like clearing the paper path and then moving and re-homing the print head.
Wireshark confirms stuff happens: every time I plug or unplug a usb device, i see BJNP and MDNS traffic broadcast, and then a TCP connection to the printer.
So the question is: what causes that to happen, and how can I disable it?

A: I had a similar problem with an Epson network printer. To find out what was causing it, I used netstat to monitor the network connections while inserting a USB device:
sudo netstat -t -u -a -p -c

One connection appeared a few moments after the device was inserted: a UDP connection by colord-sane. This binary is part of colord, a "system service to manage device colour profiles".
Unfortunately, disabling this service (at least on 15.04) is more difficult than it would seem. colord is not started directly by the init system systemd. Instead, dbus starts colord, or is asked to start colord by some other service (at least not the printer service cupsd). One way to prevent this is by renaming the relevant service file:
cd /usr/share/dbus-1/system-services/
sudo mv org.freedesktop.ColorManager.service org.freedesktop.ColorManager.service.disabled

I don't know what side-effects this action might have. Another possibility is to uninstall colord completely, using
sudo apt-get remove colord

As I don't really need colour profile functionality on my Ubuntu device, I didn't investigate what exactly colord does to "activate" the printer, or how to teach it not to do so.

A: The problem can be solved for my Epson WF3520 without breaking colord, which seems deeply integrated into most linux systems.
Comment out

net autodiscovery

in /etc/sane.d/epson2.conf and /etc/sane.d/epsonds.conf (with a # at the start of the line)
This may be applicable to other printers through their .conf files as well ("kodakaio"/"magicolor"?)
Credits go to: Link1 / Link2

A: I was having the same problem with my Epson WF-3640.  I have a desktop and a laptop both running Ubuntu 20.04 and every time they start up they both trigger the spool/cycle on the printer.  It only lasts about 3 seconds but it got very annoying.
sudo apt-get remove colord

The above answer worked for me (thanks) but then I couldn't access settings.  I found these three lines of code which you can run after uninstalling colord.  I hope the developer fixes this problem.
sudo apt-get remove gnome-control-center
sudo apt autoremove
sudo apt-get install gnome-control-center


text:
Q: jpg file is not showing up in chrome I am having a problem in viewing a jpg file in chrome.
I have 4 pictures in a folder. All the browsers are showing up except my google chrome. Actually chrome shows only 3 pictures :( I am confused.
Can you check that in your chrome please? If your chrome does the same would you please help me to find out where is the issue?
No 1:

No 2:

No 3:

No 4:

http://jsfiddle.net/h8KMP/
Note: I saved the file as "save for web" in photoshop cs6.
Thank you.

A: AdBlock for Chrome may cause images to be blocked based on image dimensions.
If you are using this extension, try disabling it.

A: I am using Google Chrome Version 23.0.1271.97 m and there are no issues with your 4 images.
Since Chrome does not have in-browser image info like Firefox does, I inspected the image in current version of Firefox via Right-Click Mouse >>> View Image Info and the image specs check out ok.

To verify the image itself is not the culprit, I downloaded it to a temp folder and checked out the specs using freeware IrfanView Image desktop application. The info validates well too, since IrfanView will detect any file-header issues if they exist.

EDIT:
A recent comment suggests the image disappears after it has been loaded. In that case I recommend that you check to insure your Chrome is updated to the current version.
From Chrome's settings, choose About Google Chrome to check if an update is available.

A: The issue I had was that Chrome wasn't showing jpeg files using sRGB color.  I just opened the image in Gimp and exported it out to jpeg to overwrite the original, and it worked!  I hope this helps someone out there.


text:
Q: jQuery UI position() options do not affect result I am working on a form validation script, and got stuck on a problem with jQuery UI position() function. No matter what options I would set, the result is still the same...
For example:
$(...).position({
        'of': $(obj),
        'my': 'bottom left', <--- left
        'at': 'top center'
})

and
$(...).position({
        'of': $(obj),
        'my': 'bottom right', <--- right
        'at': 'top center'
})

... position of object in totally the same place.
Test Fiddle HERE
At first I thought that jQuery maight not read the object width() properly, but as you can see in attached fiddle, msg_box has width().
Any ideas what may be wrong?

A: Ok the problem was trivial. It should be my': 'right bottom' not my': 'bottom right'. First horizontal, second vertical.


text:
Q: Modify expl3 command to take \vspace in argument How can this command (\wantedcontact) be modified to be able to take a \vspace{ } command in its argument? The other command \placetextbox works fine when given \vspace in its argument.
\documentclass{article}

\usepackage{xcolor}
\definecolor{wanted}{HTML}{3D2113}

\RequirePackage{eso-pic}

\newcommand{\placetextbox}[3]{% \placetextbox{<horizontal pos>}{<vertical pos>}{<stuff>}
        \AddToShipoutPictureFG*{%
        \put(\LenToUnit{#1\paperwidth},%
        \LenToUnit{#2\paperheight}){\parbox{\textwidth}{#3}}
  }%
}%

\ExplSyntaxOn

\NewDocumentCommand \wantedcontact { o +m }
 {
  \textbox_placement:ne { #1 } { #2 }
 }

\msg_new:nnnn { wantedcontact } { unsupported-argument }
    % When not using an accepted entry
  { Unsupported~ entry~ field~ `#1'~ }
  { Only~entries~'reward'~or~'noreward'~allowed. }

\tl_const:Nn  \c__page_placement_default_tl { reward }

\cs_new_protected:Npn \textbox_placement:nn #1#2
 {
  \tl_if_novalue:nTF {#1}
  {
    \textbox_placement:Vn \c__page_placement_default_tl { #2 }
  }
  {
    \str_case_e:nnF { \str_foldcase:n { #1 } }
     {
      { reward   } { \placetextbox{0.036}{0.369}{\fontfamily{cmtt}\selectfont\color{wanted}#2} }
      { noreward } { \placetextbox{0.036}{0.103}{\fontfamily{cmtt}\selectfont\color{wanted}#2} }
     }
     { \msg_error:nnn { wantedcontact } { unsupported-argument } { #1 } }
  }
 }

\cs_generate_variant:Nn \textbox_placement:nn {ne,Vn}

\ExplSyntaxOff

\begin{document}

Hello.

\wantedcontact[ReWaRd]{
a\vspace{2cm}\\b
}

\placetextbox{0.036}{0.369}{a\vspace{2cm}\\b}

\end{document}

May be useful to see: Expl3 syntax command not working

A: e is like \edef you can not use arbitrary latex constructs. Do you really need full expansion here? why not use the base nn form?

If I replace \textbox_placement:ne by \textbox_placement:nn it runs without error and typesets hello a and b


text:
Q: Creating a rule in postgresql to automatically add a json on INSERT I'm creating a discord member db in PostgreSQL but I'm still a beginner.
And I'm trying, as specified in the title, to create a rule that, when I add a new member to the db, adds a json to that member's column.
Here's the code I got so far and it's not working:
CREATE OR REPLACE RULE tank_json AS
ON INSERT TO public.members
DO (UPDATE members
    SET tank={"own_tank"=0, "engine"=0, "wheels"=0, "cannon"=0}
    WHERE NEW.name);

I think that the problem might be on the last part "WHERE NEW.name" but I'm not sure how else I'm supposed to specify where it should add that json without messing with the other member's data.
Thanks in advance.


text:
Q: Java Swing - Redrawing from handler class So I'll start off with putting my code here for my two classes.
SquareSimp.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SquareSimp
{

    public static void main( String[] args )
    {
        FilledFrame frame = new FilledFrame();

        frame.setVisible( true );
    }
}

class FilledFrame extends JFrame
{
    int size = 400;

    public FilledFrame()
    {
        JButton butSmall   = new JButton("Small");
        JButton butMedium  = new JButton("Medium");
        JButton butLarge   = new JButton("Large");
        JButton butMessage = new JButton("Say Hi!");

        SquarePanel panel = new SquarePanel(this);
        JPanel butPanel = new JPanel();

        butSmall.addActionListener(new ButtonHandler1(this, 200){
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                size = 200;
                panel.repaint();
            }
        });

        butMedium.addActionListener(new ButtonHandler1(this, this.size){
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                size = 300;
                panel.repaint();
            }
        });

        butLarge.addActionListener(new ButtonHandler1(this, this.size){
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                size = 400;
                panel.repaint();
            }
        });

        butPanel.add(butSmall);
        butPanel.add(butMedium);
        butPanel.add(butLarge);
        butPanel.add(butMessage);
        add(butPanel, BorderLayout.NORTH);
        add(panel, BorderLayout.CENTER);

        setSize( size+100, size+100 );
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Exercise 2.
        //Anonymous implementations of listeners are very efficient when you do not need to pass parameters to the
        // constructor of the implemented listener.
        butMessage.addActionListener(new ActionListener()
                // An anonymous function. Creates an actionListener that shows a dialog.
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                JOptionPane.showMessageDialog(null, "Hiiii");
            }
        });

    }

}

class SquarePanel extends JPanel
{
    FilledFrame theApp;

    SquarePanel(FilledFrame app)
    {
        theApp = app;
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.green);
        g.fillRect(20, 20, theApp.size, theApp.size);
    }
}

ButtonHandler1.java
package Lab2;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// This is a class whose object will handle the event.
public class ButtonHandler1 implements ActionListener{
    private FilledFrame theApp;
    private int theSize;
    ButtonHandler1(FilledFrame app, int size){
        theApp = app;
        theSize = size;
    }

    public void actionPerformed(ActionEvent actionEvent) {
    }

}

So far, it all works, which is great. However, as requirement I was asked to make one button handler for each class. Can someone explain to me what my buttonHandler is actually doing here? As I feel like instead of making anonymous functions, and overriding the actionPerformed event, I could have done it a better way (creating the event in the buttonhandler class and affecting the size from there based on what button is pressed). I do not know how to do this, so any help with an explanation would be great!
Thanks very much!
Brandon

A: Any handler of a *Listener is used to handle events generated from the object which is being listened too.  In the main program, it appears that you have several buttons which alter the size of the window.
In the case of your class which implements buttonHandler, you aren't doing anything because your actionPerformed method is not doing anything.
And anonymous classes are an acceptable way of implementing listeners.  However, I prefer to use inner classes because the are cleaner (imho) and still have access to the state of the enclosing class.
Here is how your handler class should look:
// This is a class whose object will handle the event.
class ButtonHandler1 implements ActionListener {
   private FilledFrame theApp;
   private int         theSize;

   ButtonHandler1(FilledFrame app, int size) {
      theApp = app;
      theSize = size;
   }

   public void actionPerformed(ActionEvent actionEvent) {
      theApp.size = theSize;
      theApp.repaint();
   }
}

And here are the calls that add that handler to your buttons.
      butSmall.addActionListener(new ButtonHandler1(this, 200));
      butMedium.addActionListener(new ButtonHandler1(this, 300));
      butLarge.addActionListener(new ButtonHandler1(this, 400));

A: ButtonHandler1 is not really used because the parameters passed to it are never used, and its single method is overridden when you construct it.
So this:
     butSmall.addActionListener(new ButtonHandler1(this, 200){
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                size = 200;
                panel.repaint();
            }
      });

Can be written without constructing ButtonHandler1:
    butSmall.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            size = 200;
            panel.repaint();
        }
    });

Or by using a lambda expression :
    butSmall.addActionListener(actionEvent -> {
        size = 200;
        panel.repaint();
    });

There are many ways you could achieve the functionality you want. Based on what you wrote, you could define ButtonHandler1 like so:
class ButtonHandler1 implements ActionListener{
    private final FilledFrame theApp;
    private final int theSize;
    ButtonHandler1(FilledFrame app, int size){
        theApp = app;
        theSize = size;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        theApp.size = theSize; //better use a setter in FilledFrame
        theApp.repaint();
    }
}

And use it like so:
    butSmall.addActionListener(new ButtonHandler1(this, 200));

    butMedium.addActionListener(new ButtonHandler1(this, 300));

    butLarge.addActionListener(new ButtonHandler1(this, 400));

Making ButtonHandler1 an inner class in FilledFrame makes things simpler:
class ButtonHandler1 implements ActionListener{
    private final int theSize;
    ButtonHandler1(int size){
        theSize = size;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        size = theSize;
        repaint();
    }
}

Use it by:
    butSmall.addActionListener(new ButtonHandler1(200));

    butMedium.addActionListener(new ButtonHandler1(300));

    butLarge.addActionListener(new ButtonHandler1(400));

A: I am not sure if I understood the question but there are 2 ways to refactor your code:

*

*Remove your ButtonHandler1 class altogether and implement all of the logic in the anonymous class:

    //FilledFrame.java

    butSmall.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    FilledFrame.this.size = 200;
                    panel.repaint();
                }
            });

*You can add some getter and setter methods on your FilledFrame class and call these in ButtonHandler1.actionPerformed to implement the logic there like the following:

    package Lab2;

    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    // This is a class whose object will handle the event.
    public class ButtonHandler1 implements ActionListener{
        private FilledFrame theApp;
        private int theSize;
        ButtonHandler1(FilledFrame app, int size){
            theApp = app;
            theSize = size;
        }

        public void actionPerformed(ActionEvent actionEvent) {
            theApp.setSizeMember(200); //do not use theApp.setSize(), create a method with a different name
            theApp.getSquarePanel().repaint();
        }

    }

I leave creating getters/setters on FilledFrame to you.


text:
Q: Is it possible to conditionally require_once, set globals, or set constants? I have a particular php class that I want to be able to upload identical copies to two different servers. Depending on the server though, the requires will be located in different places. (the constants and globals are slightly different as well) Can I conditionally set require_once, Globals, or constants at the beginning of the file?

A: Of course:
<?php

if (/* some conditions */) {
    require_once('some.file.php');
} else {
    require_once('another.file.php');
}

?>

A: You can. If that's the way you want to tackle the problem, you just need to decide how you're going to determine which server the code is being run on. You could try using the domain name:
if ($_SERVER['SERVER_NAME'] == 'mydomain1.com') {

} else {
    // default

}


text:
Q: Arithmetic mean of numbers in an interval divisible by given c Studying Python, I was solving an algorithmic problem:
find the arithmetic mean of numbers in an interval [a, b] divisible by given c.
Having solved it with loops, I wondered about a simple formula that uses only integer division.
I could not find one, even under assumptions of 0 < a <= b, c >0
Here's some solution with minimal use of conditions ( // is integer division and % is reminder):
if a % c == 0:
    first = a
else:
    first = (a // c + 1) * c

last = c * (b // c)

if first > last:
    print(0)
else:
    print((first + last) / 2)

Perhaps someone will be interested to find a single formula!

A: Finally
foo = - (- a // c)
bar = b // c

if foo == bar + 1:
    result = 'Undefined'
else:
    result = (foo + bar) * c / 2

print(result)


text:
Q: KivyMD on changing screen not creating MDList Items widget using root.ids and showing error I am trying build an app in Python using Kivymd and i just started learning this kivymd framework so the problem i am facing is when i am trying to change screen from LoginScreen to HomeScreen, it raises error. I am unable to understand what's wrong in my code.
I wanted it to change screen to HomeScreen and then show the list on pressing button 'Join Chat'.
Here is the code:

main.py

from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen,ScreenManager
from kivymd.uix.list import MDList, OneLineIconListItem,IconLeftWidget

class LoginScreen(Screen):
    pass

class HomeScreen(Screen):
    pass

class DemoApp(MDApp):
    def build(self):
        self.theme_cls.theme_style="Dark"

        self.sm=ScreenManager()
        self.sm.add_widget(LoginScreen(name="login"))
        self.sm.add_widget(HomeScreen(name="home"))

        screen=Builder.load_file("helper_file.kv")
        return screen

    def do_login(self):
        self.sm.current = "home"
        for i in range(20):
            st_name="student "
            list_item = OneLineIconListItem(text=f"student {str(i)}")
            list_item.add_widget(IconLeftWidget(icon= "alpha-a-box"))
            self.root.ids.users_lst.add_widget(list_item)

DemoApp().run()

helper_file.kv

ScreenManager:
    LoginScreen:
    HomeScreen:

<LoginScreen>:
    name: "login"
    Screen:
        MDLabel:
            text: "Demo App"
            halign: "center"
            pos_hint: {"center_x": .5, "center_y": .8}
            theme_text_color: "Primary"
        MDTextField:
            hint_text: "Enter username"
            helper_text: "to join the chat (test mode)"
            helper_text_mode: "on_focus"
            icon_right: "android"
            icon_right_color: app.theme_cls.primary_color
            pos_hint:{'center_x': 0.5, 'center_y': 0.5}
            size_hint_x:None
            width:311
        MDRoundFlatButton:
            text: "Join Chat"
            pos_hint: {"center_x": .5, "center_y": .4}
            on_release: app.do_login()
        MDLabel:
            text: "This is testing mode only"
            halign: "center"
            pos_hint: {"center_x": .5, "center_y": .2}
            theme_text_color:"Hint"

<HomeScreen>:
    name: "home"
    Screen:
        BoxLayout:
            orientation: "vertical"
            MDToolbar:
                title: "Demo Chat Application"
            ScrollView:
                MDList:
                    id: users_lst

On running this, the login screen working well but on pressing the button 'Join Chat' it raises the following error:
self.root.ids.users_lst.add_widget(list_item)
   File "kivy\properties.pyx", line 864, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

A: | 1 |
class HomeScreen(Screen):
    pass

<HomeScreen>:
    name: "home"
    Screen:
        BoxLayout:
            orientation: "vertical"
            MDToolbar:
                title: "Demo Chat Application"
            ScrollView:
                MDList:
                    id: users_lst

You have a screen which has a screen, that's not what you want to do.
<HomeScreen>:
    name: "home"
    BoxLayout:
        orientation: "vertical"
        MDToolbar:
            title: "Demo Chat Application"
        ScrollView:
            MDList:
                id: users_lst

#######################################################
#######################################################
| 2 |
Parent doesn't have access of the id of inner children children's. (Not clear I know, So I'm gonna give you a lot of print to help you understand).
    def do_login(self):
        self.root.current = "home"
        for i in range(20):
            st_name = "student "
            list_item = OneLineIconListItem(text=f"student {str(i)}")
            list_item.add_widget(IconLeftWidget(icon="alpha-a-box"))

            print("this is my App:", self)
            print("this is my ScreenManager:", self.sm)
            print("this is my global app visual widget (which is equal to ScreenManager here):", self.root)
            print("this is the ScreenManager's dictionnary containing the widgets referenced with their id:", self.root.ids)
            print("this is the current Screen:",self.root.current_screen)
            print("this is current Screen dictionnary containing the widgets referenced with their id:", self.root.current_screen.ids)
            print("this is the actual MDList", self.root.current_screen.ids["users_lst"])
            self.root.current_screen.ids["users_lst"].add_widget(list_item)


text:
Q: How can I pass a 10 bit value to a module that needs a 12 bit input in verilog? I have a module declared as:
module bin2BCD(
    input [11:0] bin12_in],
    output reg [3:0] thousands,
    output reg [3:0] hundreds,
    output reg [3:0] tens,
    output reg [3:0] ones,
);

I have another module which generates a 10 bit binary output (call it M) whose maximum value is 861 base 10.
Because of this, I would like instantiate this module with the first two bits of bin12_in set to 0, followed by the binary value of M (to make 12 bits).
How can I pass a 10 bit value to a module that needs a 12 bit input?

A: In this case, you want to concatenate two zero bits to the beginning of your 10 bit word to create a 12 bit word.
You can do this with the verilog concatenation operator {,} like this:
bin2BCD instance_name (
   .bin12_in({2'b00, M}),
   .thousands(digit3),
   .hundreds(digit2),
   .tens(digit1),
   .ones(digit0)
);


text:
Q: Math operator for disconnection in adjacency matrix? So I'm implementing the model of a Telecommunication Network as a mathematical network object. Lets say my adjacency matrix is $M$ and its $M_{ij}$ element is 1. So, to simulate a disconnection, I just switch 1 to 0: $M_{ij}\leftarrow 0$.
Is there a standard operator for this? Say $M=f_d(M,i,j)$ disconnects branch $(i,j)$ in $M$.
What about considering a threshold? I mean, something like $f_d^{p_d}(i,j,p)$ disconnects branch $(i,j)$ if $p>p_d$.
What's the actual name of this? Dropout is very ML jargon.
Thank you!


text:
Q: MASM Assembly: Floating-Point Calculations I've been racking my brain for a couple days now and am still actively debugging.  I'm trying to compute the average of a couple of numbers and round the result up or down.  Here are the necessary variable declarations:
totalNum        DWORD   ?
sum         DWORD   ?   ; sum of numbers
avg         DWORD   ?
rem         DWORD   ?
decimal     REAL4   0.5

Code snippet:
; ********************
; * calculateAverage *
; ********************
mov eax, sum
mov ebx, totalNum
cdq
div ebx
mov avg, eax        ; save average
mov rem, edx        ; save remainder

mov eax, rem        ; divide divisor (totalNum) by remainder to round up/down
mov ebx, totalNum
cdq
div ebx

cmp eax, decimal    ; compare result to .5
jge roundUp     ; if >= .5, jump to roundUp
jmp endRoundUp

roundUp:            ; round up average
    add avg, 1
endRoundUp:

; ******************
; * displayResults *
; ******************
mov edx, OFFSET countText1  ; display total numbers entered
call WriteString
mov eax, totalNum
call    WriteDec
mov edx, OFFSET countText2
call WriteString
call    Crlf
mov edx, OFFSET sumText     ; display sum of numbers entered
call WriteString
mov eax, sum
call    WriteDec
call    Crlf

mov edx, OFFSET avgText     ; display rounded average of numbers entered
call WriteString
mov eax, avg
call    WriteDec

When I try to just display the value in decimal, I mov eax, decimal and get a 10-bit number.  The program computes the sum and total numbers correctly, and even computes the average correctly, but I cannot get it to round properly or display a floating point number.

A: You're using div for your division; I believe div is an instruction that works on integer values, and you're doing floating point calculations. That's why you're getting the wrong result.
There's a few ways you can do floating point arithmetic on modern x86 CPUs:

*

*Using the x87 floating point instructions.

*There's all sorts of ways you can do it with SIMD & SSE. I'm sure AVX offers some solutions as well.

A: you can use div with dword but you can't use it with real4, you have to use fdiv
However, I don't really recommend using eax when dealing with floating numbers because you can just use fild for integers and fld for decimals ( which is much easier )
Also the answer would be in st(0) which you'll need to print by call writefloat instead of call writedec
if you want to just display 0.5 you can always say
     fld decimal
   call writefloat


text:
Q: How to write For loop with two index value in Kotlin? I have java code like the following:
class Solution {

    public String longestCommonPrefix(String[] strs) {
        // Argument checks
        if (strs == null || strs.length == 0) return "";
        if (strs.length == 1) return strs[0];

        StringBuilder sb = new StringBuilder();
        Arrays.sort(strs);
        char[] first = strs[0].toCharArray();
        char[] last = strs[strs.length - 1].toCharArray();
        for (int i = 0, j = 0; i < first.length && j < last.length; i++, j++) {
            if (first[i] != last[j]) break;
            sb.append(first[i]);
        }
        return sb.toString();
    }
}

My question is how I write for loop like for (int i = 0, j = 0; i < first.length && j < last.length; i++, j++) in Kotlin? Thanks!
===== Update ======== 29 July 2022
I think I am providing a bad code example here... please focus on the question: how I write for loop like for (int i = 0, j = 0; i < first.length && j < last.length; i++, j++) in Kotlin?

A: As Vadik's answer shows, in this particular case the indexes both take the same values, so only one is needed; that leads to a nice simplification of the code, with a neat Kotlin implementation.
However, there isn't always such a neat solution. So it's worth knowing that any old-style for loop (in C or Java) can be easily converted to a while loop:
for (<initialisers>; <condition>; <updates>) {
    // …loop body…
}

becomes:
<initialisers>;
while (<condition>) {
    // …loop body…
    <updates>;
}

That simple transformation can be done for any for loop, however complicated. And since Kotlin has while, the result translates directly into Kotlin.
A few points to be aware of:

*

*If the condition is blank, you'd have to substitute true.

*Any loop variables are now declared outside the loop, so their scope is larger. That brings the possibility of name clashes (if the outer scope already defines variables with those name(s) — e.g. from expanding an earlier loop), and subtle bugs. So you may need to rename them.

*Having the loop-control code split across three different places can be less concise, and harder to follow. However, that's more of an issue for simple, obvious loops, which are already well catered for in Kotlin — for the more complex ones that'd need this treatment, this may make them clearer.

A: In your case both indices are the same, so you can use min function to calculate last index:
import kotlin.math.min

fun longestCommonPrefix() {
    ...
    val first: CharArray = ...
    val last: CharArray = ...
    for (i in 0 until min(first.size, last.size)) {
        if (first[i] != last[i]) break
        sb.append(first[i])
    }
}

A: Another general thing you can do is use zip to pair up two sequences of values - the result will be as long as the shorter sequence (i.e. only complete pairs):
first.indices.zip(last.indices) { (a, b) ->
    // do something with them - you actually get a Pair so you could skip the
    // deconstruction into two variables, and just refer to it.first and it.second
}

which isn't super useful in this case since both values are incrementing from 0, but you can make it more general:
println(first.indices.zip(0 until last.size step 2))

>> [(0, 0), (1, 2), (2, 4), (3, 6), (4, 8), (5, 10)]

So you can define two separate sequences of values, and make a loop that uses a value from each on every iteration, which is similar to what your for loop is doing. And of course it doesn't have to be indices, you could create sequences of the actual elements you want to reference too.
It's not as efficient (creates a List and Iterables under the hood), but for that you'd really need to work directly with indices in a for loop or with a while like gidds is suggesting. (Unless you know for sure something is compiled to an efficient form, e.g. for (i in first.indices) does compile to a basic for loop with no iterator.)

Also this probably goes against the spirit of what you're doing, but if you keep them as Strings, you can do this:
first.commonPrefixWith(last)

Just in case you didn't know ;)


text:
Q: Testing basic http authenticaation with digest using curl How can we test authentication with digest as explained here using curl?
I am able to test Simple Basic example by setting Authorization header to Basic {SECRET} where SECRET is Base64::encode64("username:password") as explained here
I tried sending Authentication header with same value but getting NoMethodError (undefined method 'unpack' for nil:NilClass) on line having call authenticate_or_request_with_http_digest
Would anyone please explain what I am doing wrong here?

A: Finally I am able to fix the problem. Here is how I used curl to test http basic authentication with digest
curl --data {"red":"00"} --digest -u "username:password" "http://localhost:3000/api/statistics"


text:
Q: How do I properly register clients on a server in RMI? I'm currently working on a small project that manages attendance for a summer program that I'm helping run. The RMI server is run from the office and has a specific port set for it by using the following code:
Registry registry = LocateRegistry.createRegistry(4051);
RemoteManager stub = (RemoteManager) UnicastRemoteObject.exportObject(theServer, 4051);
registry.rebind(SERVER_NAME, stub);

where theServer is a reference to the object that will serve as the system's server and SERVER_NAME is simply a static String used to represent the server. As is shown the registry binds the server to port 4051 so that clients can query for it. Now I'm working on cross-communication between the server and multiple client instances (12 teachers running the same client program) and currently it is set such that the clients send stubs of themselves to the server for client registration.
public void registerClient(INTERFACE_Client teach) throws RemoteException {
.
.
.
}

where INTERFACE_Client extends the Remote interface and the client is sent down by calling:
server.registerClient((INTERFACE_Client) UnicastRemoteObject.exportObject(this, 4052));

where I just chose port 4052 because I didn't know what I was doing. I also didn't bind the stub to a registry. Is a good way to do it? Because I've hardcoded the client port, all 12 teachers will be exporting the object using port 4052 (at least that's how I see it) from their respective client instances. Should the ports be randomized? Should I not include a port (there's a method that doesn't require that as well)? Any helpful hints would be greatly appreciated.
As a disclaimer, I do need a reference to the client in the server so that people in the office can send messages to the teachers. (Server -> Client communication). The client already has the reference to the server because it can look it up on the registry.Any suggestion?

A:
I just chose port 4052 because I didn't know what I was doing.

That's OK, as long as port 4052 is open in both directions in both intermediate firewalls, if there are any firewalls. There's no real reason why you can't use the RMI Registry port 1099 for this, at both ends: it's already reserved by IANA, unless the hosts already contain some other RMI application.

I also didn't bind the stub to a registry. Is a good way to do it?

That's OK. You don't need a Registry at the client. All you need is your existing registration API.

Because I've hardcoded the client port, all 12 teachers will be exporting the object using port 4052 (at least that's how I see it) from their respective client instances.

That's OK as long as the 'client instances' are all separate TCP hosts.

Should the ports be randomized?

Not unless you have > 1 client per TCP host.

Should I not include a port (there's a method that doesn't require that as well)?

No.

Any helpful hints would be greatly appreciated.

Your clients must implement a remote interface and be exported and then registered with the server via your existing API. You're doing well. As long as there are no firewalls, or they are all under your control, you will be OK.


text:
Q: Oracle SQL Special Period Format I have a special fiscal period in format YYYYMMM, for example
Feb of 2015 is 2015002
Nov of 2014 is 2014011
I need to do subtraction from the period, 2 months ago from 2015002 is 2014012, but i cant do like
SELECT '2015001' - 2 FROM DUAL

How can i do that?

A: You should first convert it to a date, then subtract months and convert back to the format you need.
with x(y) as (
  select '2015002' from dual
)
select y,
       to_date(y,'YYYY"0"MM'),
       add_months(to_date(y,'YYYY"0"MM'),-2),
       to_char(add_months(to_date(y,'YYYY"0"MM'),-2),'YYYY"0"MM')
 from x

Results:
|       Y |     TO_DATE(Y,'YYYY"0"MM') | ADD_MONTHS(TO_DATE(Y,'YYYY"0"MM'),-2) | TO_CHAR(ADD_MONTHS(TO_DATE(Y,'YYYY"0"MM'),-2),'YYYY"0"MM') |
|---------|----------------------------|---------------------------------------|------------------------------------------------------------|
| 2015002 | February, 01 2015 00:00:00 |            December, 01 2014 00:00:00 |                                                    2014012 |


text:
Q: Java static TimerTask shutdown I have a static, periodic, java Timer/TimerTask that I would like to shutdown when the app does. I don't want the app hanging because some thread is still running (like what happens in debug mode in eclipse, some environments may kill the thing anyway). The reason I have it static is I plan to have some (very simple, probably just a counter) shared memory in all of the containing class's instances with the Timer so I feel class scope is appropriate.
My question is how best to do the shutdown of the Timer? Is this an appropriate time to use finalize? This timer seems benign enough that having a non-deterministic call to finalize may work? Would probably need to do some kind of instance counting to verify that there are no longer any instances of the class out there? Suggestions on ways to manage the shutdown of the static Timer are welcome.
pseudo code:
class foo {

private static Timer someTimer = null;

public foo() {
  if(someTimer == null) {
     someTimer = new Timer(new TimerTask(...));
  }

}

//how should I shut this thing down?
protected void finalize() throws Throwable {

}

//or is better to have shutdown() called explicitly?

}

A: It all depends on what your app actually does, but in general there will be some kind of event to signal that the app is being shutdown. For example if it's a GUI app, then maybe this will be the "user clicked on the Quit button" event. Or it's a webapp based on the servlet API, it will be an event fired by a ServletContextListener.
You should add a listener for this event, which calls some kind of shutdown method on your foo object. Inside this shutdown method the foo should take care of cleaning up its resources, including stopping the timer.
As a last resort, you might want to investigate JVM shutdown hooks


text:
Q: Mic Input properties I'm developing audio app(iOS/Android), and I can't find nowhere information:
How can a app read or set the microphone gain?
Are audio Digital Signal Processing tools available for the headphone jack?
Also I realize that some manufacturers develop specific accessibility features (like mono sound mode, or sound balance (left - right) on samsung devices), but they don't provide any API to check or control this feature. When I turn on/off mono mode on Samsung GS3 in logs I see:
I/AudioHardwareTinyALSA( 1904): setParameters(toMono=0)
I/audio_wfd_hw( 1904): adev_set_parameters() toMono=0
So I guess this feature provided by samsung specific hardware driver.
May be in some way is possible to get pointer to AudioHardwareTinyALSA an set mono on or off?
Thanks.

A: There's no API in Android for controlling the input volume (you can mute/unmute the mic during voice calls / VoIP, but that's about the level of control that you've got).
The mic gains are typically set by the OEMs as part of their acoustic tuning process, in order to optimize the performance for each use-case (speech recognition, camera recording, handset call, etc) for that particular product.
Mono/stereo recording should simply be decided by whether the app requests 1 or 2 channels for the recording. At least that's the way it has worked on every product I've worked on, as far as I can recall.


text:
Q: tablet POS system I have a project to create a point of sale system, which in each table in a restaurant will have a tablet. The idea is this tablet will communicate to the kitchen interface and send customer's order directly to the kitchen. I'm planning to use HTML 5 and phonegap for the tablet.
My question is:

*

*How can I connect each tablet to the kitchen interface? is it possible to send information over the wifi? Do I need a hub or router?

*I have seen API such as e-thor and square register, can I use those API to build this system?

*Is it possible to customize the tablet so it can only open the app?

Thanks, any answer would be appreciated.

A:

*

*how can I connect each tablet to the kitchen interface? is it possible to send information over the wifi? Do I need a hub or router?

Yes, a hub such as a linksys router with each tablet connected wirelessly to the same SSID on the router will allow you to talk to the internet or the intranet for your kitchen service.

*I have seen API such as e-thor and square register, can I use those API to build this system?

Yes, a webapp utilizing the apis for this system will receive orders from people and allow them to pay for them as well (given they have the ability to swipe their cards with a square for example). The hardest part to your question is the webapp and how it will store and use the information from users. This is the part that you need to think about as the rest of your questions are trivial.

*Is it possible to customize the tablet so it can only open the app?

Yes, many apps do this and it is usually in parental controls or administration of users for the tablet (depending on the operating system).


text:
Q: Compute $\int_{0}^{2\pi}\frac{\sin^2\theta}{5+3\cos\theta}\,d\theta$ I''m stuck in a exercise in complex analysis concerning integration of rational trigonometric functions. I have the solution but I don't understand a specific part. Here it goes:
We want to find $\int_{0}^{2\pi}\frac{\sin^2\theta}{5+3\cos\theta}\,d\theta$.
Let $z=e^{i\theta}$ so that $d\theta=dz/iz$, $\cos \theta = \frac12 (z+z^{-1})$ and $\sin \theta = \frac {1}{2i}(z-z^{-1})$.  We have
$$\begin{align}
I&=\int_0^{2\pi} \frac{\sin^2\theta}{5+3\cos \theta}d\theta\\\\
&=\oint_C \frac{-\frac14(z-z^{-1})^2}{5+3\frac12 (z+z^{-1})}\frac{dz}{iz}\\\\
&=\oint_C \frac{\frac i4 (z^2-2+z^{-2})}{5z+ \frac32 z^2 + \frac32}dz\\\\
&=\oint_C \frac{\frac i2 (z^2-2+z^{-2})}{3z^2 + 10z + 3}dz\\\\
&=\frac i2 \oint_C \frac{z^4-2z^2+1}{z^2(3z^2 + 10z + 3)}dz \quad (1)
\end{align}$$
where $C$ is the unit circle in the complex $z$-plane.
If I understand the last step correctly we multipliy numerator/denominator by $z^2$ in order to get rid of the negative power of $z$.
Now for the part that I don't understand in the solution. It is said that
$$(1) = \frac i2 \oint_C \frac{z^4-2z^2+1}{z^23(z+3)(z+\frac13)}dz = \frac i6 \oint_C \frac{z^4-2z^2+1}{z^2(z+3)(z+\frac13)}dz$$
Where does this $3$ come from in the denominator? If I factor out $3z^2 + 10z + 3$ I simply get $(z+3)(z+\frac13)$.
What is even stranger to me is that, after the computation of residues, the author is getting the correct solution of $\frac{2\pi}{9}$ (I verified with Wolfram) while I'm getting $\frac{2\pi}{3}$  so I'm missing a factor of $\frac13$ (i.e. I'm missing that $3$ in the denominator).
Can someone help me with this?

A: $$\begin{align*} 3z^2 + 10z + 3
&= 3 \left(z^2 + \frac{10}{3}z + 1\right) \\
&= 3\left(z^2 + 3z + \frac{1}{3}z + 1\right) \\
&= 3\left(z(z + 3) + \frac{1}{3}(z + 3)\right) \\
&= 3\left(z + \frac{1}{3}\right)(z+3). \end{align*}$$
You are missing a factor of $2$ when you go from step $3$ to step $4$.  The denominator should be $3z^2 + 10z + 3$.

A: $$I=\int_{0}^{2\pi}\frac{\sin^2\theta}{5+3\cos\theta}\,d\theta=\int_{0}^{\pi}\sin^2(\theta)\left(\frac{1}{5+3\cos\theta}+\frac{1}{5-3\cos\theta}\right)\,d\theta$$
hence:
$$ I = 10 \int_{0}^{\pi}\frac{\sin^2\theta}{25-9\cos^2\theta}\,d\theta = 20\int_{0}^{\pi/2}\frac{\cos^2\theta}{25-9\sin^2\theta}d\theta $$
and by setting $\theta=\arctan t$ we get:
$$ I = 20\int_{0}^{+\infty}\frac{dt}{(1+t^2)(25+16t^2)}=\frac{20}{9}\int_{0}^{+\infty}\left(\frac{1}{1+t^2}-\frac{16}{25+16t^2}\right)\,dt=\color{red}{\frac{2\pi}{9}}. $$

A: I think your error comes from the wrong use of the quadratic formula for factoring a second order polynomial. Factoring a polynomial and using the quadratic formula are two different things. Recall that for a quadratic polynomial
$$\color{blue}{ax^2+bx+c = a(x-x_1)(x-x_2)}$$
where you are missing the coefficient $a=3$. The quadratic formula will only give you the solutions of the quadratic equation.


text:
Q: What has gone wrong with this sorting code using Linked Lists? I want to say that I just started learning C++ and I'm having a fairly good grip on just insertion, deletion, reversing, finding the element and element in a position. I've tried to sort using Bubble Sort(?) and the program is crashing. Please help me.
struct node
{
int data;
struct node* link;
};
typedef struct node* NODE;

NODE rearr(NODE root)
{
NODE temp=root;
while(temp!=NULL)
{
    NODE curr=temp;
    while(curr!=NULL)
    {
        if(curr->data>(curr->link)->data)
    {
        int temp1=curr->data;
        curr->data=(curr->link)->data;
        (curr->link)->data=temp1;
    }
    curr=curr->link;
    }
    temp=temp->link;
}return root;
}

There are insert and delete functions too, but I haven't copied here. If you want, I'll post the whole program.

A: You never test to see if curr->link is null or not. Which causes a fault when you check its data memeber.
if(curr->link != NULL && curr->data>(curr->link)->data)


text:
Q: How add reboot button to my tweak using THEOS Hi, I need help to add a reboot button in the preference bundle of my tweak.
I have this in my tweakRootListController.m
-(void)reboot {
    [[UIApplication sharedApplication] reboot];
    return;
}
But when i try to compile the project, it's return me an error
MacBook-Pro-de-Valentin:respringx valentincocq$ make package install
 Making all for bundle RespringX…
==> Copying resource directories into the bundle wrapper…
==> Compiling respringRootListController.m (arm64)…
respringRootListController.m:20:40: error: 'UIApplication' may not respond to 'reboot' [-Werror]
    [[UIApplication sharedApplication] reboot];
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
1 error generated.
make[3]: *** [/Users/valentincocq/respringx/.theos/obj/debug/arm64/respringRootListController.m.5460b32b.o] Error 1
make[2]: *** [/Users/valentincocq/respringx/.theos/obj/debug/arm64/RespringX.bundle/RespringX] Error 2
make[1]: *** [internal-bundle-all_] Error 2
make: *** [RespringX.all.bundle.variables] Error 2
MacBook-Pro-de-Valentin:respringx valentincocq$
I have try this, but don't work too :
-(void)reboot {
    system("reboot");
}
Thank for you help.


text:
Q: What is Squid's default caching policy with no Cache-Control header? RFC2616 is somewhat vague about the "default" behavior of a caching proxy when no Cache-Control header is used in an HTTP response. For example, is it acceptable for Squid (or any other proxy cache) to cache the response indefinitely? Or is it necessary to revalidate on each request?

A: In the absence of explicit information (e.g., a Cache-Control: max-age or Expires header), caches can and do use "heuristic freshness" -- i.e., they guess.
However, when they do this, MOST (but not all) caches will look for a hint that it's useful to cache, such as a Last-Modified header.
More information:

*

*https://svn.tools.ietf.org/svn/wg/httpbis/draft-ietf-httpbis/latest/p6-cache.html#heuristic.freshness

*http://www.squid-cache.org/Versions/v3/3.HEAD/cfgman/refresh_pattern.html

*http://www.mnot.net/blog/2009/02/24/unintended_caching


text:
Q: passport-saml lib doesn't correctly decrypt saml EncryptedAssertion with a private decryption key I have an encrypted SAML 2.0 response/assertion that i need to decrypt. the format looks like this:
<saml:EncryptedAssertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
    <xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
      <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/>
      <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <xenc:EncryptedKey>
          <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/>
          <xenc:CipherData>
            <xenc:CipherValue>{some ciphers}</xenc:CipherValue>
          </xenc:CipherData>
        </xenc:EncryptedKey>
      </ds:KeyInfo>
      <xenc:CipherData>
        <xenc:CipherValue>{assertion body}</xenc:CipherValue>
    </xenc:CipherData>
    </xenc:EncryptedData>
</saml:EncryptedAssertion>

I also have a private decryption key with format like this:
-----BEGIN RSA PRIVATE KEY-----
{mumbo jumbos}
-----END RSA PRIVATE KEY-----

I have tried using OneLogin's saml decryption tools here to decrypt the encrypted SAML assertion (copy+paste to that input box), and it works like a charm.
https://www.samltool.com/decrypt.php
However, when I tried to use nodejs, passport-saml to import the private key file and try to decrypt the response, it gets a "Invalid PEM formated" if i omit the ("-----BEGIN----" or "---END---" banner), or it gets a "Invalid RSAES-OAEP padding" error.
This is my code snippet:
const fs = require('fs');
const Promise = require('bluebird');
const path = require('path');
const forge = require('node-forge');
let pkey = fs.readFileSync(path.join(__dirname,'./myTestKey.pem'), 'utf8');
//let testKey = new Buffer(pkey).toString('base64');
let SAML = require('passport-saml/lib/passport-saml/saml.js');
let saml = new SAML({...,decryptionPvk: pkey });
let validatePostResponseAsync = Promise.promisify(saml.validatePostResponse);

validatePostResponseAsync(myResponse, pkey)
.then(response=>{
})
.catch(error=>{
 // it always throw error of the 2 mentioned above.
})

Any workaround would be appreciated.

A: I think i figured it out. for those who is struggling with similar issue, you must include the ---BEGIN RSA PRIVATE KEY--- and ---END RSA PRIVATE KEY---. the node-forge library which passport-saml lib is depending on will throw error if the banner is not included.


text:
Q: multithreading in Ruby vs JRuby vs Java I am new to Ruby and the JRuby and I was trying to implement multithreaded code in Ruby and came to know that GIL doesn't allow my code to run in parallel then I moved to JRuby and implemented the same code and my execution time in JRuby was much better than the Ruby. I studied that JRuby threading is very much similar to threading in Java, so I implemented the same in code in Java as well and I got a performance(execution time) in Java to be almost 10x faster than JRuby, can someone explain me the reason for this? Thanks in advance

A: the explanation is quite simple when you think about JRuby being Ruby implemented in Java, which means that you have 'more' Java code to execute using the .rb piece compared to plain .java compiled to a .class ...
than even if the method dispatch was cost-less there's the dynamic nature of Ruby e.g. when you a+1 on Java it adding to ints while a+1 in Ruby its an addition with overflow checks etc.
your question is quite general and we also do not know what kind of performance measuring you did but in the end it all comes down to productivity when you do 'real-world' work + with JRuby if you feel like some part is worth being 10x faster you still have the option of re-doing that piece in "native" Java.


text:
Q: Firefox 35.0 and strange bug with fade on png transparent Well i'm using the responsive plugin ResponsiveSlides.js and it was working properly but after this new firefox update, some problems with PNG Transparent on fade comes, someone knows if that could be a bug or not?

very strange, i make some tests like putting a background-color these PNG pics then it works fine, it sound like the old IE problems with PNG on fade ... but idk.
Live example: http://www.arquitet.us/homologacao/


text:
Q: How to define a "base url" for resources when creating a zeep client? I'm trying to parse a WSDL file using zeep.
import zeep

zeep.Client('https://sede.agenciatributaria.gob.es/static_files/Sede/Procedimiento_ayuda/G417/FicherosSuministros/V_1_1/WSDL/SuministroFactEmitidas.wsdl')

This failes with the following error:
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://sede.agenciatributaria.gob.es/static_files/Sede/Procedimiento_ayuda/G417/FicherosSuministros/V_1_1/WSDL/SuministroInformacion.xsd

From what I understand, since the wsdl file points to SuministroInformacion.xsd using a relative path, zeep assumes both files are in the same directory. But in this case, all the resources are located in another directory.
Can I specify a base url for the resources? If not, is there a way around this ?
Thank you!

A: That service WSDL is broken.
The schemaLocation indicates the same folder as the WSDL document, but the XSDs are actually located at the address of the namespace.
Zeep does the correct thing, but it won't work with a broken WSDL.
If you have access to the provider of that service, tell them to fix it.
If they won't fix it, then download the WSDL, download all the XSD files that the WSDL is trying to import, place all files in one folder, then tell zeep to use the local WSDL with:
zeep.Client('C:\\Download_Folder_Or_Whatever\\SuministroFactEmitidas.wsdl')

This is a workaround that could work. The proper fix is for the service provider to repair their WSDL.


text:
Q: When to use Request.Cookies over Response.Cookies? Do I use response when at a page event (e.g. load) as this is a response from ASP.NET, and request when pressing a button as this is a response going to ASP.NET for processing? Or is there more to it?

A: In a web application the request is what comes from the browser and the response is what the server sends back.  When validating cookies or cookie data from the browser you should use the Request.Cookies.  When you are constructing cookies to be sent to the browser you need to add them to Response.Cookies.

A: The cookies comes from the browser in the Request.Cookies collection. That is where you read the cookies that was sent.
To send cookies back to the browser you put them in the Response.Cookies collection.
If you want to delete a cookie, you have to tell the browser to remove it by sending the cookie with an expiration date that has passed. The browser is using the local time of the client computer so if you are using the server time to create a date, be sure to subtract at least one day to be sure that it has actually passed in the clients local time.

A: When i create or update a cookie in .NET i normally do it to both the request and response cookie collection. That way you can be sure if you try to read the cookie further down the page request sequence it will have the correct information.

A: When writing a cookie, use Response but reading may depend on your situation. Normally, you read from Request but if your application is attempting to get a cookie that has just been written or updated and the round trip to the browser has not occured, you may need to read it form Response.
I have been using this pattern for a while and it works well for me.
public void WriteCookie(string name, string value)
{
    var cookie = new HttpCookie(name, value);
    HttpContext.Current.Response.Cookies.Set(cookie);
}

public string ReadCookie(string name)
{
    if (HttpContext.Current.Response.Cookies.AllKeys.Contains(name))
    {
        var cookie = HttpContext.Current.Response.Cookies[name];
        return cookie.Value;
    }

    if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name))
    {
        var cookie = HttpContext.Current.Request.Cookies[name];
        return cookie.Value;
    }

    return null;
}

A: They are 2 different things, one SAVES [Response], the other READS [Request]
in a Cookie (informatics speaking) :)
you save a small file for a period of time that contains an object of the type string
in the .NET framework you save a cookie doing:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);

// Add the cookie.
Response.Cookies.Add(myCookie);

Response.Write("<p> The cookie has been written.");

You wrote a cookie that will be available for one minute... normally we do now.AddMonth(1) so you can save a cookie for one entire month.
To retrieve a cookie, you use the Request (you are Requesting), like:
HttpCookie myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
   Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
   Response.Write("not found");

Remember:
To Delete a Cookie, there is no direct code, the trick is to Save the same Cookie Name with an Expiration date that already passed, for example, now.AddMinutes(-1)
this will delete the cookie.
As you can see, every time that the time of life of the cookie expires, that file is deleted from the system automatically.

A: Andrew's Code gave an error in "AllKeys.Contains" Method. So I corrected a little..
public void WriteCookie(string strCookieName, string strCookieValue)
    {
        var hcCookie = new HttpCookie(strCookieName, strCookieValue);
        HttpContext.Current.Response.Cookies.Set(hcCookie);
    }

    public string ReadCookie(string strCookieName)
    {
        foreach (string strCookie in HttpContext.Current.Response.Cookies.AllKeys)
        {
            if (strCookie == strCookieName)
            {
                return HttpContext.Current.Response.Cookies[strCookie].Value;
            }
        }

        foreach (string strCookie in HttpContext.Current.Request.Cookies.AllKeys)
        {
            if (strCookie == strCookieName)
            {
                return HttpContext.Current.Request.Cookies[strCookie].Value;
            }
        }

        return null;
    }


text:
Q: Problem in installing my android application I developed one android application and tested it in HTC desire (sdk 2.2), i can install it and i can work on it. But when i try to install it in lower android sdk devices like HTC EVO (SDK 2.1) or Sony xperia (sdk 1.6) it displaying "Parser Error". And in the manifest file i set the the following code.
<uses-sdk android:minSdkVersion="3" android:maxSdkVersion="8"/>

I dont know what is the solution for this anybody please help me if you know the answer.
Thanks and Regards,
Rajapandian.K

A: This error doesn't look like something related to the manifest, probably a function which has changed between versions. Look into logCat to see the stack trace of the error, and you'll probably be able to know a little more about your error.


text:
Q: I'm very confused coming from MYSQL, is it necessary to "connect" classes via matching IDs as attributes or are associations enough? I'm making a class diagram for my school project, an Inventory Management System. So far, I've made the use-case and activity diagrams, however, I'm struggling with the class diagram and mostly because of this one thing (stated in the title). Here's my diagram so far:

See how I use the same string "products" in Manufacturer and Stock. Is that okay? Or should I do something else (make one of the strings public etc)?

A: UML does not define a strict semantics on how associations are implemented in code (or, when used as a replacement for ER modeling, in a database schema).
Depending on the intended purpose of the diagram and the programming language, the developer / modeler / software engineer can decide whether they need a rigid form of implementation, or not. An implementation may use pointers, references or IDs, it may be done unidirectional or bidirectional, and sometimes it is just done implicitly by some values/references which can be derived from other values. Sometimes, the form of implementation of an association is intentionally left open.
So when you draw some UML diagram as a replacement for ERMs, it is up to you to make a decision which semantics you give the drawn associations and if you want or need a specific form of foreign keys to be linked with those.
Related: answer to a question from 2013 on UML semantics