text:
Q: Compute Aspect Ratio of a Rectangle in Perspective A popular question but for which I can't find a definitive answer. Math wizards we need you!
The Problem is the following
We have a unmodified photograph (not cropped) of a rectangular object taken from some angle. We don't know the real size of the rectangle or any info about that picture.
GOAL : We want to find the aspect ratio / proportions of the rectangle with only this image as input.
This question isn't linked to a particular programming language (pseudo code allowed) but I want to implement the solution in Python using NumPy.

In this photograph it's an A4 paper sheet so the code/algorithm should find a ratio of 1.4142 : 1
My Questions

*

*What is the best solution (See Info section below), handling edges cases ? Is there another one I not listed ?

*Is there an implementation (C++, Python, ...) in a maintained library package (OpenCV, SciPy, ...) ?
Info
After digging the internet it's seems that this problem isn't easy to solve, there is some info :

*

*Research Paper by Zhengyou Zhang , Li-Wei He, "Whiteboard scanning and image enhancement" http://research.microsoft.com/en-us/um/people/zhang/papers/tr03-39.pdf / https://www.microsoft.com/en-us/research/publication/2016/11/Digital-Signal-Processing.pdf

*Research Paper by Shen Cai,* Longxiang Huang, and Yuncai Liu, "Automatically obtaining the correspondences of four
coplanar points for an uncalibrated camera" https://sci-hub.hkvisa.net/10.1364/AO.51.005369

*A blog post named "Aspect Ratio of a Rectangle in Perspective" by Andrew Kay https://andrewkay.name/blog/post/aspect-ratio-of-a-rectangle-in-perspective/
Others StackOverflow related questions
There is some questions on StackOverflow with the same topic/subject/goal:

*

*proportions of a perspective-deformed rectangle

*Calculating aspect ratio of Perspective Transform destination image

*Perspective correction of UIImage from Points

*Get image(rect on a plane) with perspective correction from camera (2d image)
BUT the answers seems to differ in the implementation(even though they claim to be based on the same research paper) and be incomplet (not always handling parallel opposite sides).
My current working implementations
Based on all the info above I implemented the two methods in Python with OpenCV & NumPy:
Method #1
def compute_aspect_ratio(image, corners):
    # Based on :
    # - https://andrewkay.name/blog/post/aspect-ratio-of-a-rectangle-in-perspective/

    # Step 1: Get image center, will be used as origin
    h, w = image.shape[:2]
    origin = (w * .5, h * .5)

    # Step 2: Points coords from image origin
    # /!\ CAREFUL : points need to be in zig-zag order (A, B, D, C)
    a = corners[0] - origin
    b = corners[1] - origin
    c = corners[3] - origin
    d = corners[2] - origin

    # Step 3: Check if the camera lie into the plane of the rectangle
    # Coplanar if three points are collinear, in that case the aspect ratio cannot be computed
    M = numpy.array([[b[0], c[0], d[0]], [b[1], c[1], d[1]], [1., 1., 1.]])
    det = numpy.linalg.det(M)
    if math.isclose(det, 0., abs_tol=.001):
        # Cannot compute the aspect ratio, the caller need to check if the return value is 0.
        return 0.

    # Step 4: Create the matrixes
    A = numpy.array([[1., 0., -b[0], 0., 0., 0.],
                     [0., 1., -b[1], 0., 0., 0.],
                     [0., 0.,    0., 1., 0., -c[0]],
                     [0., 0.,    0., 0., 1., -c[1]],
                     [1., 0., -d[0], 1., 0., -d[0]],
                     [0., 1., -d[1], 0., 1., -d[1]]], dtype=float)
    B = numpy.array([[b[0]-a[0]],
                     [b[1]-a[1]],
                     [c[0]-a[0]],
                     [c[1]-a[1]],
                     [d[0]-a[0]],
                     [d[1]-a[1]]], dtype=float)

    # Step 5: Solve it, this will give us [Ux, Uy, (Uz / λ), Vx, Vy, (Vz / λ)]
    s = numpy.linalg.solve(A, B)

    # Step 6: Compute λ, it's the focal length
    l = 0.
    l_sq = ((-(s[0] * s[3]) - (s[1] * s[4])) / (s[2] * s[5]))
    if l_sq > 0.:
        l = numpy.sqrt(l_sq)
    # If l_sq <= 0, λ cannot be computed, two sides of the rectangle's image are parallel
    # Either Uz and/or Vz is equal zero, so we leave l = 0

    # Step 7: Get U & V
    u = numpy.linalg.norm([s[0], s[1], (s[2] * l)])
    v = numpy.linalg.norm([s[3], s[4], (s[5] * l)])

    return (v / u)

Method #2
def compute_aspect_ratio(image, corners):
    # Based on :
    # - https://www.microsoft.com/en-us/research/publication/2016/11/Digital-Signal-Processing.pdf
    # - http://research.microsoft.com/en-us/um/people/zhang/papers/tr03-39.pdf

    # Step 1: Compute image center (a.k.a origin)
    h, w = image.shape[:2]
    origin = (w * .5, h * .5)

    # Step 2: Make homeneous coordinates
    # /!\ CAREFUL : points need to be in zig-zag order (A, B, D, C)
    p1 = numpy.array([*corners[0], 1.])
    p2 = numpy.array([*corners[1], 1.])
    p3 = numpy.array([*corners[3], 1.])
    p4 = numpy.array([*corners[2], 1.])

    k2 = numpy.dot(numpy.cross(p1, p4), p3) / numpy.dot(numpy.cross(p2, p4), p3)
    k3 = numpy.dot(numpy.cross(p1, p4), p2) / numpy.dot(numpy.cross(p3, p4), p2)

    # Step 3: Computing U & V vectors, but at this point the z value of these vectors are in the form z / f
    # Where f is the focal length
    u = (k2 * p2) - p1
    v = (k3 * p3) - p1

    # Step 4: Unpack vectors to avoid using accessors
    uX, uY, uZ = u
    vX, vY, vZ = v

    # Step 5: Check if two opposite sides are parallel (or almost parallel)
    if math.isclose(uZ, .0, abs_tol=.01) or math.isclose(vZ, .0, abs_tol=.01):
        aspect_ratio = numpy.sqrt((vX ** 2 + vY ** 2) / (uX ** 2 + uY ** 2))
        return aspect_ratio

    # Step 6: Compute the focal length
    f = numpy.sqrt(numpy.abs((1. / (uZ * vZ)) * ((uX * vX - (uX * vZ + uZ * vX) * origin[0] + uZ * vZ * origin[0] * origin[0]) + (uY * vY - (uY * vZ + uZ * vY) * origin[1] + uZ * vZ * origin[1] * origin[1]))))

    A = numpy.array([[f, 0., origin[0]], [0., f, origin[1]], [0., 0., 1.]]).astype('float32')
    Ati = numpy.linalg.inv(numpy.transpose(A))
    Ai = numpy.linalg.inv(A)

    # Step 7: Calculate the real aspect ratio
    aspect_ratio = numpy.sqrt(numpy.dot(numpy.dot(numpy.dot(v, Ati), Ai), v) / numpy.dot(numpy.dot(numpy.dot(u, Ati), Ai), u))

    return aspect_ratio

If you have any info / help don't hesite to share!

A: After intensively reading the research papers (links in the question), here it's my implementation based on both methods I shared. Enjoy!
Optimized working implementation (Python3 & NumPy)

def compute_aspect_ratio(image, corners):
    # Based on :
    # - https://www.microsoft.com/en-us/research/publication/2016/11/Digital-Signal-Processing.pdf
    # - http://research.microsoft.com/en-us/um/people/zhang/papers/tr03-39.pdf
    # - https://andrewkay.name/blog/post/aspect-ratio-of-a-rectangle-in-perspective/

    # Step 1: Get image center, will be used as origin
    h, w = image.shape[:2]
    origin = (w * .5, h * .5)

    # Step 2: Homeneous points coords from image origin
    # /!\ CAREFUL : points need to be in zig-zag order (A, B, D, C)
    p1 = numpy.array([*(corners[0] - origin), 1.])
    p2 = numpy.array([*(corners[1] - origin), 1.])
    p3 = numpy.array([*(corners[3] - origin), 1.])
    p4 = numpy.array([*(corners[2] - origin), 1.])

    # Step 3: Zhengyou Zhang p.10 : equations (11) & (12)
    k2 = numpy.dot(numpy.cross(p1, p4), p3) / numpy.dot(numpy.cross(p2, p4), p3)
    k3 = numpy.dot(numpy.cross(p1, p4), p2) / numpy.dot(numpy.cross(p3, p4), p2)

    # Step 4: Compute the focal length
    f = 0.
    f_sq = -((k3 * p3[1] - p1[1]) * (k2 * p2[1] - p1[1]) + \
             (k3 * p3[0] - p1[0]) * (k2 * p2[0] - p1[0]) ) / ((k3 - 1) * (k2 - 1))
    if f_sq > 0.:
        f = numpy.sqrt(f_sq)
    # If l_sq <= 0, λ cannot be computed, two sides of the rectangle's image are parallel
    # Either Uz and/or Vz is equal zero, so we leave l = 0

    # Step 5: Computing U & V vectors, BUT the z value of these vectors are in the form: z / f
    # Where f is the focal length
    u = (k2 * p2) - p1
    v = (k3 * p3) - p1

    # Step 6: Get U & V
    u = numpy.linalg.norm([u[0], u[1], (u[2] * f)])
    v = numpy.linalg.norm([v[0], v[1], (v[2] * f)])

    return (v / u)

Same version without comments:
def compute_aspect_ratio(image, corners):
    h, w = image.shape[:2]
    origin = (w * .5, h * .5)

    p1 = numpy.array([*(corners[0] - origin), 1.])
    p2 = numpy.array([*(corners[1] - origin), 1.])
    p3 = numpy.array([*(corners[3] - origin), 1.])
    p4 = numpy.array([*(corners[2] - origin), 1.])

    k2 = numpy.dot(numpy.cross(p1, p4), p3) / numpy.dot(numpy.cross(p2, p4), p3)
    k3 = numpy.dot(numpy.cross(p1, p4), p2) / numpy.dot(numpy.cross(p3, p4), p2)

    f = 0.
    f_sq = -((k3 * p3[1] - p1[1]) * (k2 * p2[1] - p1[1]) + \
             (k3 * p3[0] - p1[0]) * (k2 * p2[0] - p1[0]) ) / ((k3 - 1) * (k2 - 1))
    if f_sq > 0.:
        f = numpy.sqrt(f_sq)

    u = (k2 * p2) - p1
    v = (k3 * p3) - p1

    u = numpy.linalg.norm([u[0], u[1], (u[2] * f)])
    v = numpy.linalg.norm([v[0], v[1], (v[2] * f)])

    return (v / u)

Handling parallel sides
Before calling this method you can check if the paper deformation is negligible to avoid all these computations:
PAPER_DEFORMATION_TOLERANCE = 0.01
def compute_paper_size(image, corners):
    # Vectors of the side of the contour (clockwise)
    side_top_vec = corners[1] - corners[0]
    side_rgh_vec = corners[2] - corners[1]
    side_btm_vec = corners[2] - corners[3]
    side_lft_vec = corners[3] - corners[0]

    # Step 1: Compute average width & height of the paper sheet
    paper_avg_width = 0.5 * (numpy.linalg.norm(side_top_vec) + numpy.linalg.norm(side_btm_vec))
    paper_avg_height = 0.5 * (numpy.linalg.norm(side_lft_vec) + numpy.linalg.norm(side_rgh_vec))

    # Step 2: If deformation is negligible avoid computation and return the average dimensions
    #         Checking if the opposite sides are parallel
    if math.isclose((side_top_vec[0] * side_btm_vec[1]), (side_top_vec[1] * side_btm_vec[0]), abs_tol=PAPER_DEFORMATION_TOLERANCE) and \
        math.isclose((side_lft_vec[0] * side_rgh_vec[1]), (side_lft_vec[1] * side_rgh_vec[0]), abs_tol=PAPER_DEFORMATION_TOLERANCE):
        return (paper_avg_width, paper_avg_height)

    # Step 3: Compute aspect ratio
    aspect_ratio = compute_aspect_ratio(image, corners)

    return (paper_avg_width, paper_avg_width * aspect_ratio)


text:
Q: How can I mix absolute and relative sizes? I want to create a custom list item. Basically it should 3 areas in a horizontal LinearLayout. The most left one is supposed to be 50dp wide, the right most one as well. I would like the one in the middle to take up the rest of the space. In the end it should be 50px | width - 100px | 50px.
Can I do this in XML?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:gravity="right" >

    <FrameLayout
        android:id="@+id/frameLayout1"
        android:layout_width="50dp"
        android:layout_
        android:layout_height="match_parent"
        android:layout_weight="0">
    </FrameLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="fill"
        android:orientation="vertical"
        android:layout_weight="0">

    </LinearLayout>

    <FrameLayout
        android:id="@+id/frameLayout2"
        android:layout_width="50dp"
        android:layout_height="match_parent"
        android:layout_weight="0" >

    </FrameLayout>

</LinearLayout>

A: Just set the layout-weight of the middle item to 1. And layout_width to fill_parent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React native - The native module for Flipper seems unavailable Im using react redux toolkit. This is my store configuration.
My app doesn't start becouse this warn: The native module for Flipper seems unavailable. Please verify that react-native-flipper is installed as yarn dependency to your project and, for iOS, that pod install is run in the ios
directory.
import {configureStore} from '@reduxjs/toolkit';
import authorization from 'redux/slices/authorization';
const createDebugger = require('redux-flipper').default;

export const store = configureStore({
  reducer: {authorization: authorization},
  middleware: [createDebugger],
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;


text:
Q: Move Controls and Graphics I have a twincat device and Windows Ce 6 device.
I am listining a twincat for get data from machine.
After get data I am making graphicals process.moving picture box,drawing image,changing images
so my program is very slow I can not catch real time datas.
What Can I do?
Do I have to use Usercontrol for different image process or Thread?
Thanks a lot
There is a Property in Form1
Bitmap MyImage
{

  get
  {
//  A Lot of difficult process Drawing Image
   return Im;
  }

}

When I call this property from Thread.Which thread is make this process Form thread or MyThread ?

A: without using Threads you'll face the same problem with UserControls , It's recommended to separate UI tasks from other stuff that you're working with It means that if your program is too slow for getting data in real-time you can use two threads , one for getting data and the other for drawing and doing other stuff with UI in this way UI thread won't affect the data thread but remember you may need to optimize your drawing stuff as well by using some Image Processing Libraries or even using faster technologies designed for Working with Graphics like WPF
here's a very good tutorial for getting started with Threads in C# :
Multithreaded Programming Using C#
please keep in mind if you provide us more details and codes we can help you even more :)


text:
Q: Solving the Theta and Value of X (Sine Law) I have this kind of equation that I produced using the Sine Law when I was answering a physics problem. How can I solve the value of $\theta$ and the value of $x$?
Sample Equation:
$$\frac{x}{\sin(44^\circ)} = \frac{250}{\sin(16^\circ + \theta)} = \frac{200}{\sin(120^\circ- \theta)}$$


text:
Q: System.ObjectDisposedException when trying to list an object Trying to fix this error
public ActionResult MyEvents()
{
    Personne personne = (Personne)Session["User"];
        personne.Evenements.ToList();
        return View(personne);

}

Got the System.ObjectDisposedException and Evenements is null
Using many to many relation between Personne and Evenement so cannot read the join table in the db.

A: The problem is that the Evenements are probably being loaded using lazy loading (i.e. not retrieved until the property is accessed).
When you are coding web applications the connection used to fetch information is usually closed when the HTTP request ends.
Thus when you on the second request try to access Evenements property the connection have been closed. And you therefore get the ObjectDisposedException.
You can activate eager loading by using the Include method: http://www.entityframeworktutorial.net/EntityFramework4.3/eager-loading-with-dbcontext.aspx
That way the property have been loaded and stored for all future requests.


text:
Q: How to map fields in RDD[String] to broad cast? How does one get particular fields from RDD[String] to a List of maps with the specific field. I have an RDD[String]: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[19] Each entry is  JSON in this format:
{
  count: 1,
  itemId: "1122334",
  country: {
    code: {
      preferred: "USA"
    },
    name: {
      preferred: "America"
    }
  },
  states: "50",
  self: {
    otherInfo: [

    ],
    preferred: "National Parks"
  },
  Rating: 4
}

How do I get a list of maps that have only itemId as the key and self.preferred as the value ({itemid , self.preferred}):
itemId : 1122334 self.preferred : "National Parks"
itemId : 3444444 self.preferred : "State Parks"
...

Is it efficient to broadcast the resulting map across all nodes? I need this map to be shared/referenced by further calculations.

A: You can try :
    val filteredMappingsList = countryMapping.filter(x=> {
    val jsonObj = new JSONObject(x)
    jsonObj.has("itemId")

})

val finalMapping = filteredMappingsList.map(x=>{
    val jsonObj = new JSONObject(x);
    val itemId = jsonObj.get("itemId").toString()
    val preferred = jsonObj.getJSONObject("self").get("preferred").toString()
    (itemId, preferred)
}).collectAsMap

To Broadcast :
val broadcastedAsins = sc.broadcast(finalMapping)


text:
Q: How to enable auto suspend to RAM on ReadyNAS 104? I've recently bought a ReadyNAS 104 and I want to save energy by suspending it to RAM. This should be done automatically after a user defined idle time. How do I configure the NAS do behave in this way. Of course the NAS shall wake up if receiving WOL packets. This works already.
I didn't find any option on the web interface of the NAS. Is there any plug-in (app) I can install or do I have to alter the system over SSH?


text:
Q: How to analyse z3 performance issues? I have 37 similar SMT2 problems, each in two equisatisfiable versions that I call compact and unrolled. The problems are using incremental SMT solving and every (check-sat) returns unsat. The compact versions are using the QF_AUFBV logic, the unrolled versions use QF_ABV. I did run them in z3, yices, and boolector (but boolector only supports the unrolled version). The results of this performance evaluation can be found here:
http://scratch.clifford.at/compact_smt2_enc_r1102.html
The SMT2 files for this examples can be downloaded from here (~10 MB):
http://scratch.clifford.at/compact_smt2_enc_r1102.zip
I run each solver 5 times with different values for the :random-seed option. (Except boolector which does not support :random-seed. So I simply run boolector 5 times on the same input.) The variation I get when running the solvers with different :random-seed is relatively small (see +/- values in the table for the max outlier).
There is a wide spread between solvers. Boolector and Yices are consistently faster than z3, in some cases up to two orders of magnitude.
However, my question is about "z3 vs z3" performance. Consider for example the following data points:
| Test Case         | Z3 Median Runtime | Max Outlier |
|-------------------|-------------------|-------------|
| insn_add unrolled |    873.35 seconds |     +/-  0% |
| insn_add compact  |   1837.59 seconds |     +/-  1% |
| insn_sub unrolled |   4395.67 seconds |     +/- 16% |
| insn_sub compact  |   2199.21 seconds |     +/-  5% |

The problems insn_add and insn_sub are almost identical. Both are generated from Verilog using Yosys and the only difference is that insn_add is using this Verilog module and insn_sub is using this one in its place. Here is the diff between those two source files:
--- insn_add.v  2017-01-31 15:20:47.395354732 +0100
+++ insn_sub.v  2017-01-31 15:20:47.395354732 +0100
@@ -1,6 +1,6 @@
 // DO NOT EDIT -- auto-generated from generate.py

-module rvfi_insn_add (
+module rvfi_insn_sub (
   input                                rvfi_valid,
   input [                32   - 1 : 0] rvfi_insn,
   input [`RISCV_FORMAL_XLEN   - 1 : 0] rvfi_pc_rdata,
@@ -29,9 +29,9 @@
   wire [4:0] insn_rd     = rvfi_insn[11: 7];
   wire [6:0] insn_opcode = rvfi_insn[ 6: 0];

-  // ADD instruction
-  wire [`RISCV_FORMAL_XLEN-1:0] result = rvfi_rs1_rdata + rvfi_rs2_rdata;
-  assign spec_valid = rvfi_valid && insn_funct7 == 7'b 0000000 && insn_funct3 == 3'b 000 && insn_opcode == 7'b 0110011;
+  // SUB instruction
+  wire [`RISCV_FORMAL_XLEN-1:0] result = rvfi_rs1_rdata - rvfi_rs2_rdata;
+  assign spec_valid = rvfi_valid && insn_funct7 == 7'b 0100000 && insn_funct3 == 3'b 000 && insn_opcode == 7'b 0110011;
   assign spec_rs1_addr = insn_rs1;
   assign spec_rs2_addr = insn_rs2;
   assign spec_rd_addr = insn_rd;

But their behavior in this benchmark is very different: Overall the performance for insn_sub is much worse than the performance for insn_add. Furthermore, in the case of insn_add the unrolled version runs about twice as fast as the compact version, but in the case of insn_sub the compact version runs about twice as fast as the unrolled version.
Here are the times before creating the median. The :random-seed setting obviously does not seem to make much of a difference:
insn_add unrolled:  868.15  873.34  873.35  873.36  874.88
insn_add compact:  1828.70 1829.32 1837.59 1843.74 1867.13
insn_sub unrolled: 3204.06 4195.10 4395.67 4539.30 4596.05
insn_sub compact:  2003.26 2187.52 2199.21 2206.04 2209.87

Since the value of :random-seed does not seem to have much of an effect, I would assume there is something intrinsic to those .smt2 files that makes them fast or slow on z3. How would I investigate this? How would I find out what makes the fast cases fast and the slow cases slow, so I can avoid whatever makes the slow cases slow? (Yes, I know that this is a very broad question. Sorry. :)
<edit>
Here are some more concrete questions along the lines of my primary question. This questions are directly inspired by the obvious differences I can see between the (compact) insn_add and insn_sub benchmarks.

*

*Can the order of (declare-..) and (define-..) statements in my SMT input influence performance?

*Can changing the names of declared or defined function influence performance?

*If I split a BV into smaller BVs, and then concatenate them back again, can this influence performance?

*If I either compare two BVs for equality, or split the BV into single bit variables and compare each of the bits individually, can this influence performance?

*Also: What operations in z3 do actually change when I chose a different value for :random-seed?

</edit>
Making small changes to the .smt2 files without changing the semantics can be very difficult for large test cases generated by complex tools. I'm hoping there are other things I can try first, or maybe there is some existing expert knowledge about the kind of changes that might be worth investigating. Or alternatively: What kind of changes would effectively be equivalent to changing :random-seed and thus are not worth investigating.
(Tests performed with git rev c67cf16, i.e. current git head of z3 on an AWS EC2 c4.8xlarge instance with make -j40. The runtimes are CPU seconds, not wall-clock seconds.)
Edit 2:
I have now three test cases (test1.smt2, test2.smt2, and test3.smt2) that are identical except that I've renamed some of the functions I declare/define. The test cases can be found at http://svn.clifford.at/handicraft/2017/z3perf/.
This is a variation of the original problem that takes ~2 minutes to solve instead of ~1 hour. As before, changing the value of :random-seed only has a marginal effect. But renaming some of the functions without changing anything else changes the runtime by more than 2x:

I've now opened an issue on github, arguing that :random-seed should by tied into whatever thing I change randomly inside z3 when I rename the functions in my SMT2 code.

A: As you say, there can be many things that may be creating that perf difference in add vs sub.
A good start is to check if the formulas after preprocessing are equal modulo add/sub (btw, Z3 converts 'a - b' into 'a + (-1) * b').  If not, then trace down which preprocessing step is at fault. Then trace down the problem and send us a patch :)
Alternatively, the problem could be down the line, e.g., in the bitblaster. You can also dump the bit-blasted formulas of both of your files and check if there is a significant difference in terms of number of variables and/or clauses.
Anyway, you'll need to be prepared to invest a day or two (maybe more) to track down these issues. If you find something, let us know and/or send us a patch! :)


text:
Q: gradle version x is required try editing distributionurl getting this after downloading gradle 2.10 with android studio 1.5.1. when running gradle form the command line. gradlew complains about not finding tools.jar.
changing the plugin to: classpath 'com.android.tools.build:gradle:1.5.0' (from 1.3.1) makes gradle iD work. gradlew iD still fails with not finding tools.jar.
how do i fix the tools.jar problem?
is there an easy/proper way to get the wrapper to use the 2.10 version?
edit: solved the tools.jar problem (was using jdk1.9.0) but that has intoduced a bunch of: Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.E
  xecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe''

edit: got those to go away by removing the: compile files("${jdkHome}/lib/tools.jar") dependency. so what worked was to switch from jdk 1.9 to jdk 1.8.


text:
Q: Testing a service object job with rspec I have the following job:
class Test::MooJob < ApplicationJob
  queue_as :onboarding

  def perform
     avariable = Test::AragornService.build("a").call
     if avariable.status == true
        puts "job succeeded"
     end
  end
end

and the service looks like this:
module Test
  class AragornService

    def self.build(x)
      self.new(x)
    end

    def initialize(x)
      @x = x
    end

    def call
      10.times do
        Rails.logger.info @x
      end

      return ServiceResult.new :status => true, :message => "Service Complete", :data => @x

    rescue => e
      Bugsnag.notify(e, :context => 'service')
      return ServiceResult.new :status => false, :message => "Error occurred - #{e.message}"
    end

  end
end

I am trying to test it with the following spec:
# bundle exec rspec spec/jobs/test/moo_job_spec.rb
require "rails_helper"

describe Test::MooJob do
  subject(:job) { described_class.perform_later }
  subject(:job_now) { described_class.perform_now }

  let(:key) { "a" }

  it 'queues the job' do
    ActiveJob::Base.queue_adapter = :test
    expect { job }.to have_enqueued_job(described_class)
      .on_queue("onboarding")
  end

  it 'calls the aragorn service once' do
    allow(Test::AragornService.new(key)).to receive(:call).and_return(ServiceResult.new(:status => true))
    expect_any_instance_of(Test::AragornService).to receive(:call).exactly(1).times
    job_now
  end

end

Why is it that avariable value keeps returning nil
I get the following error "undefined method `status' for nil:NilClass"
however, when I return a simple boolean,
allow(Test::AragornService.new(key)).to receive(:call).and_return(true)
It sets avariable value to true
here's the ServiceResult class:
class ServiceResult
  attr_reader :status, :message, :data, :errors

  def initialize(status:, message: nil, data: nil, errors: [])
    @status = status
    @message = message
    @data = data
    @errors = errors
  end

  def success?
    status == true
  end

  def failure?
    !success?
  end

  def has_data?
    data.present?
  end

  def has_errors?
    errors.present? && errors.length > 0
  end

  def to_s
    "#{success? ? 'Success!' : 'Failure!'} - #{message} - #{data}"
  end

end

A: Its because you are just setting expections on a unrelated instance of Test::AragornService in your spec:
allow(Test::AragornService.new(key)).to
   receive(:call).and_return(ServiceResult.new(:status => true))

This does nothing to effect the instance created by Test::AragornService.build
class Test::MooJob < ApplicationJob
  queue_as :onboarding

  def perform
     avariable = Test::AragornService.build("a").call
     if avariable.status == true
        puts "job succeeded"
     end
  end
end

You can solve it by stubbing Test::AragornService.build to return a double:
double = instance_double("Test::AragornService")
allow(double).to receive(:call).and_return(ServiceResult.new(status: true))

# bundle exec rspec spec/jobs/test/moo_job_spec.rb
require "rails_helper"

describe Test::MooJob do
  let(:perform_later) { described_class.perform_later }
  let(:perform_now ) { described_class.perform_now }
  let(:service) { instance_double("Test::AragornService") }

  before do
     # This injects our double instead when the job calls Test::AragornService.build
     allow(Test::AragornService).to receive(:build).and_return(service)
  end

  it 'queues the job' do
    # this should be done in `rails_helper.rb` or `config/environments/test.rb` not in the spec!
    ActiveJob::Base.queue_adapter = :test
    expect { perform_later }.to have_enqueued_job(described_class)
      .on_queue("onboarding")
  end

  it 'calls the aragorn service once' do
    expect(service).to receive(:call).and_return(ServiceResult.new(status: true))
    perform_now
  end
end


text:
Q: How to change UIAlertAction font or show UIAlertActionStyle.cancel style ActionButton on second position? I don't want to change UILabel.appearance as it will apply to all labels.
How I can show UIAlertController that will look like below image?
Need to show bold button in the second position.

By default, when I am setting UIAlertActionStyle.cancel it shows it on the Confirm button in the first position.
It looks like this now:

I did some research but I didn't find any solution.

A: Swift 4.2/Swift 5
You need to set preferred action method,
//Create alertController
let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)

//Create and add the Confirm action
let confirmAction = UIAlertAction(title: "Confirm", style: .default, handler: { (action) -> Void in
    //Do Something here...
})
alert.addAction(confirmAction)

//Create and add the Cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in

    //Do Something here...
})
alert.addAction(cancelAction)

// Set Preferred Action method
alert.preferredAction = confirmAction

self.present(alert, animated: true, completion: nil)

The output will be,

A: You need to add them to the alertView in the right order!  If you want the order to change just add the confirm button second!
alert.addAction(cancelAction)
alert.addAction(confirmAction)

Instead of:
alert.addAction(confirmAction)
alert.addAction(cancelAction)

A: Sure, you can. Try this
let alertView = UIAlertController(
    title: "Home",
    message: "Are you sure for delete Reminder",
    preferredStyle: .alert)
alertView.view.tintColor = .green
let confirmAction = UIAlertAction(title: "Confirm", style: .cancel) { (_) in
     // Do confirm
}
alertView.addAction(confirmAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (_) in
    // Do cancel
}
alertView.addAction(cancelAction)
self.present(alertView, animated: true, completion: nil)


text:
Q: How can I test DB2 9.5 -> 9.7 Migration/Upgrade? I am going to migrate a DB2 9.5 database into DB2 9.7. I hope that it will be a smooth process. But I want to be sure that the applications are not affected in a negative manner.
"you can run your application and see if everything works" would be a way to ensure the database functionality needed.
What I want to know is

*

*Is there any subject/DB2 functionality that I need to pay particular attention to.

*What is the best testing way that I can choose.

*Is there a functionality that improves the performance that i must add to my old DB Structure.

Any help will be welcome..

A: IBM has a very nice upgrade guide that covers those topics (and more!) on the Information Center.  I highly recommend you check it out!

A: You can use a capture replay tool named iReplay to capture your db traffic and test it against DB2 9.7. http://exact-solutions.com/products/iReplay


text:
Q: Parameterized array of Interface SystemVerilog Im trying to create a parameterized array of interface instances in SystemVerilog, but somehow fail to do so.
interface if_dma();
logic [31:0] addr;
logic [31:0] data;
endinterface

module mux(clk, rst, if_dma dma_ports[n-1:0]);

//logic

endmodule

module dma_top();

if_dma dma();

mux #(n=3)(.clk(clk), .rst(rst), dma_ports[0](rx_channel), dma_ports[1](tx_channel));

endmodule

A: You cannot have dma_ports[0] and dma_ports[1] as separate ports. Put them together in one go: .dma_ports({tx_channel,rx_channel})
Your header for mux is odd. Not sure if you were trying are simplifying you header for mux or it is what you really have. If you are using non-ANSI port style, then do not specify the ranges in the port list. Range specification goes in the port definition (ex: input clk;, output [7:0] out;, if_dma dma_ports[N];). With ANSI port then port-list and definition are the same. Ex:
module mux #(parameter N=1) (input clk, rst, if_dma dma_ports[N-1:0]);

Do not mix ANSI and non-ANSI port styles. ANSI style is generally recommended.


text:
Q: Can't edit last line in restricted editing in Microsoft Word I'm using the Restrict Editing feature in Word to limit what users can change in a document. When they go to format the area that is open for them to edit they can't change the formatting if they have the last line selected.
I can change formatting on all other lines and change create a new last line and edit above that. As soon as the last line before the Restrict Editing box ends is selected, it won't let you apply formatting like bold or centered.
How do I fix this?
Thanks.

A: At the end of the last line, Word has an (normally invisible) symbol which carries the section format.
A) put a return behind the last line. That moves that symbol in the next line (where they still can't edit it, but it  might not bother anyone). Or
B) have them select the text only up to the last character (a bit tedious), leaving that symbol out of the formatting


text:
Q: Global Style not working in WPF Why ist this Style not working in WPF? The TextBlock should be red, but it is not. It stays black. This is just happing when the TextBlock is in a Template.
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Red"></Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <ListView>
            <ListView.Items>
                <ListItem></ListItem>
            </ListView.Items>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock>Hallo</TextBlock>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

    </Grid>
</Window>

A: Implicit Styles in templates are limited to controls that inherit from System.Windows.Controls.Control unless they are defined in Application.Resources so either give your style x:Key and use it explicitly:
<Window.Resources>
    <Style TargetType="TextBlock" x:Key="myTextBlockStyle">
        <Setter Property="Foreground" Value="Red"></Setter>
    </Style>
</Window.Resources>

<TextBlock Style="{StaticResource myTextBlockStyle}">Hallo</TextBlock>

or move it to Application.Resources
<Application.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Red"></Setter>
    </Style>
</Application.Resources>

A: If you want to define a style and have it automatically apply to all controls of that type (without manually specifying the style for each control) you need to define it like this instead.
E.G.
<Style x:Key="{x:Type TextBox}" TargetType="TextBox">
        <Setter Property="IsUndoEnabled" Value="True"></Setter>
        <Setter Property="UndoLimit" Value="10"></Setter>
        <Setter Property="ContextMenu" Value="{StaticResource textContextMenu}"></Setter>
        <Setter Property="SpellCheck.IsEnabled" Value="True"></Setter>
    </Style>


text:
Q: Magento 2 how to check serialized conditions against product in frontend? I have created an admin form which contains name and catalog price rule conditions. I have saved these values in a custom table. The conditions are saved as serialized. Now I want to check these conditions against each product in catalog product list page, product page, widgets etc. If the condition satisfied then need to display the name in each product.
How can I do this. Please help me.

A: You can use as example the standard Magento class Magento\Rule\Model\AbstractModel or just extend it in your custom class. The algorithm is pretty simple:
1) Load conditions data ($conditionsSerialized = $this->getConditionsSerialized())) and unserialize it ($conditions = $this->serializer->unserialize($conditionsSerialized);)
2) Get the conditions object (instance of \Magento\Rule\Model\Condition\Combine or what ever you use) and load it using recently loaded data as array ($this->_conditions->loadArray($conditions);)
3) Validate your object using this condition ($this->_conditions->validate($object);)

A: Option 1
Native PHP method:
    /**
     * Check if value is serialised
     *
     * @param string $data
     * @param bool $strict
     * @return bool
     */
    protected function isSerialised(string $data, bool $strict = true): bool
    {
        try {
            // If it isn't a string, it isn't serialized.
            if (!is_string($data)) {
                return false;
            }
            $data = trim($data);
            if ('N;' === $data) {
                return true;
            }
            if (strlen($data) < 4) {
                return false;
            }
            if (':' !== $data[1]) {
                return false;
            }
            if ($strict) {
                $lastc = substr($data, -1);
                if (';' !== $lastc && '}' !== $lastc) {
                    return false;
                }
            } else {
                $semicolon = strpos($data, ';');
                $brace     = strpos($data, '}');
                // Either ; or } must exist.
                if (false === $semicolon && false === $brace) {
                    return false;
                }
                // But neither must be in the first X characters.
                if (false !== $semicolon && $semicolon < 3) {
                    return false;
                }
                if (false !== $brace && $brace < 4) {
                    return false;
                }
            }
            $token = $data[0];
            switch ($token) {
                case 's':
                    if ($strict) {
                        if ('"' !== substr($data, -2, 1)) {
                            return false;
                        }
                    } elseif (false === strpos($data, '"')) {
                        return false;
                    }
                    // Or else fall through.
                case 'a':
                case 'O':
                    return (bool) preg_match("/^{$token}:[0-9]+:/s", $data);
                case 'b':
                case 'i':
                case 'd':
                    $end = $strict ? '$' : '';
                    return (bool) preg_match("/^{$token}:[0-9.E+-]+;$end/", $data);
            }
            return false;
        } catch (Exception $e) {
            return false;
        }
    }

Thanks to Wordpress core code
Option 2
Use Magento\Framework\Serialize\SerializerInterface
    /**
     * Check if value is serialised
     *
     * @param string $string
     * @return bool
     */
    protected function isSerialised(string $string): bool
    {
        try {
            $unserialised = $this->serialize->unserialize($string);
            return (is_array($unserialised))
                ? true
                : false;

        } catch (InvalidArgumentException $e) {
            return false;
        }
    }

Option 3
Steal code from Magento\Framework\Serialize\SerializerInterface (in case you don't have access to it for whatever reason).
    /**
     * JSON Encode Serialisation (stolen from Magento\Framework\Serialize\SerializerInterface) but I didn't want to use constructors here ;)
     *
     * @see Magento\Framework\Serialize\SerializerInterface
     * @param string $string
     * @return mixed
     */
    protected function unserialise(string $string)
    {
        $result = json_decode($string, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new InvalidArgumentException("Unable to unserialize value. Error: " . json_last_error_msg());
        }

        return $result;
    }

    /**
     * Check if value is serialised
     *
     * @param string $string
     * @return bool
     */
    protected function isSerialised(string $string): bool
    {
        try {
            $unserialised = $this->unserialise($string);
            return (is_array($unserialised))
                ? true
                : false;

        } catch (InvalidArgumentException $e) {
            return false;
        }
    }


text:
Q: log4j - logging System.out and System.err concurrently to the console We have a java webapp which schedules and runs several other tools in variety of languages /java, perl, bash, python etc.../ and  'eats' their out/err streams using StreamGobblers for troubleshooting purposes;
Is it possible to use log4j /in a core java app/ to log both System.err and System.out so they can be captured in the way described above?
Will this not lead to out and err messages interleaving /appearing out of order/?

Thank you

A: Yes. log4j can be used to log to both System.err and System.out in to a separate file/stream.
Yes. The messages can be interleaved.

A: Yes, this is possible.  Check out this documentation:
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/ConsoleAppender.html


text:
Q: How can I print "\n" using exec()? ab = open("bonj.txt","w")

exec(f'''print("Hi I'm Mark\n", file=ab)
print("\tToday I'm tired", file=ab)
''')

ab.close()

I would absolutely need to use exec() to print some informations on a txt doc. The problem is that when I use exec(), I lost the possibility of put newlines or tabs on my text, and I dont understand why, could you help me ?
This is the error message that I receive : "SyntaxError: EOL while scanning string literal"

A: You just need to escape \n and \t properly
ab = open("bonj.txt","w")

exec(f'''print("Hi I'm Mark\\n", file=ab)
print("\\tToday I'm tired", file=ab)
''')

ab.close()

A: You need to prevent python from interpreting the \n early.
This can be done by specifying the string as a raw string, using the r prefix:
ab = open("bonj.txt","w")
exec(rf'''print("Hi I'm Mark\n", file=ab)
print("\tToday I'm tired", file=ab)
''')
ab.close()

Anyway, using exec is odd there, you would rather try to see if you can write your code as something like:
lines = ["Hi I'm Mark\n", "\tToday I'm tired"]
with open("bonj.txt", "w") as f:
    f.write("\n".join(lines))

Note that you need to use "\n".join to obtain the same result as with print because print adds a newline by default (see its end="\n" argument).
Also, when handling files, using the context manager syntax (with open ...) is good practice.


text:
Q: Making one method contingent on another running successfully I have a situation where I need a service to have a few fields set before I can execute an HTTP call.  Those fields come from another HTTP call, so I can't run them asynchronously -- without that data, the second call will fail.  I think I have a way to do this, but I'm missing something -- the first method (getSystemConfiguration()) simply isn't firing, even though by the end of the chain there's definitely a subscribe() call.
I'm somewhat new to RxJs, so I feel like this should be simple, but what am I missing?
// Method that gets system configuration
setApiInformation(): Observable<void> {
    if (!this.apiKey || !this.checkUrl) {
        return this.systemConfigurationService.getSystemConfiguration()
            .pipe(
                map(config => {

                // None of this ever executes
                this.apiKey = config.apiKey;
                this.checkUrl = config.objectExistsUrl;
            }));
    } else {
        return of();
    }
}

// Method I'm trying to run
checkServerData(data: RequestParameters): Observable<ServerResponseData> {
    return this.setApiInformation()
        .pipe(map(() => {
            let httpOptions = { headers: new HttpHeaders({ "serverApiKey" : this.apiKey }) };
            return this.httpClient.put<ServerResponseData>(this.checkUrl, request, this.httpOptions);
        }));
}

// Ultimate caller
let params: RequestParameters = { tenantId: 1, requestorId: 1 };
this.service.checkServerData(params)
   .subscribe((response: ServerResponseData) => { this.dataExists = response.success; });

A: There are few rxjs operators that can help you with this. i personally prefer switchMap. and this is how i would implement it:
this.setApiInformation().pipe(switchMap(data => {
  // do something here if needed
  return this.checkServerData();
})).subscribe( data => {
  // do something
});

A: so, there's a couple things here. First, your observable chain has issues, you generally want to keep things INSIDE the observable sequence, and you want to do this in a repeatable fashion. I might rewrite this like so:
interface Config {
  apiKey: string
  checkUrl: string
}

@Injectable()
export class MyService {
  private configSource = new ReplaySubject<Config>(1) // stores config

  private setApiInformation() { // private method to load config, call once
    this.systemConfigurationService.getSystemConfiguration().subscribe(this.configSource)
  }

  // all calls go through here to ensure config is ready
  private awaitConfig<T>(action$: (config: Config) => Observable<T>) {
    return this.configSource.pipe(
      first(),
      switchMap(client => action$(client)) // switchMap subscribes to inner observables
    )
  }

  constructor(private systemConfigurationService: SystemConfigurationService) {
    this.setApiInformation() // call once here
  }

  checkServerData(data: RequestParameters): Observable<ServerResponseData> {
    return this.awaitConfig(config => { // use config from here
      let httpOptions = { headers: new HttpHeaders({ "serverApiKey" : config.apiKey }) };
      return this.httpClient.put<ServerResponseData>(config.checkUrl, request, this.httpOptions);
    }));
  }
}

This is a good way to solve this problem of all calls needing something asynchronous, you could in theory write a base service that the rest extend from or preferably inject and use to make their calls, BUT, if this is an app wide thing, you might be better served by using an APP_INITIALIZER to ensure something gets done (liek loading a config) before the rest of the application runs.


text:
Q: IDE for Cocos2dx on Linux I'm normaly using QtCreator for c++ and I have Linux. I want to write a game in Cocos2dx. I installed Cocos2dx without problem, created HelloWorld using "cocos new", opened it with QTC and builded it. Everything is ok. BUT Cocos2dx uses cmake. When I create new class in project in Qt Creator I can't see it. So which ide is useable for cocos2dx? I tried VS 2013 but i don't like Windows.
 (pls sorry for my bad English, I hope you will understand)

A: In QTCreator you need to add new sources to your project's root CMakeLists.txt and then run cmake again. After doing this you can see your new classes.
Suppose we have AppDelegate.cpp and MainMenuScene.cpp and want to add NewScene class (defined in NewScene.h and NewScene.cpp). Then in MyGame/CMakeLists.txt find "set(GAME_SRC" and add NewScene.cpp and NewScene.h files as below:
set(GAME_SRC
  Classes/AppDelegate.cpp
  Classes/MainMenuScene.cpp
  Classes/NewScene.cpp
  ${PLATFORM_SPECIFIC_SRC}
)

set(GAME_HEADERS
  Classes/AppDelegate.h
  Classes/MainMenuScene.h
  Classes/NewScene.h
  ${PLATFORM_SPECIFIC_HEADERS}
)

Then run CMake using "Build>Run CMake" menu. New files will apear in Project's hierarchy.

A: Instead of QTCreator you can use CLion. Clion is cross-platform C++ IDE from JetBrains. This IDE have default support CMake. Setup the build system is very easy. I use this for development my game on the cocos2d-x engine - it's good tool.

A: I'm using Clion https://www.jetbrains.com/clion/ and it works fine with cocos2dx. Just open folder which contains CMakeLists.txt.Created classes are automaticaly updated in CMakeLists.txt by ide.


text:
Q: Composer installs Extensions to /vendor but Magento path is /app/code Fails to Load I installed a magento extension via composer require
I can see the files in /vendor but when I click on the extension from the admin panel it gives me an Exception that the Class does not exist as the link to the extension is set to /app/code. If I copy the /vendor folder to /app/code it works but then I get errors if I use php bin/magento setup:upgrade about the extension already being defined in vendor
There must be a path set somewhere telling magento to look for extensions in /app where I do have some webkul extensions installed.
What should I do?


text:
Q: Merge data from local database to remote database of Mongodb I have a remote central database(MongoDb) that must contain all records coming from using a application by many clients!
The application save data in local collection, then should save data in remote database !
we're good until now… the problem comes when there is no internet, we go in offline mode.
So lets suppose that we have a remote MongoDb Central database and 2 clients : client A and client B => local database A + local database B
(the two databases are independent).
We are offline ! I have created a document doc1 in the Local DB-A and document doc2 in the Local DB-B .
Online mode is active so the db A must push the doc1 in DB central also the db B must push the doc2 in DB central.
I am using MEAN stack application.

*

*I have checked ChangeStream, but not sure during network break how it will work..

Anyhelp will be much appreciated.

A: I am not sure about the realm and change-stream, you need to brainstorm do your own logic as per your requirement,
I had the same situation and asked in the MongoDB forum in this topic, but got a suggestion to implement change-stream, I tried but was not worked for me,
After that, I developed my own logic using NodeJS, ExpressJS, and MongoDB driver APIs to sync data from local to live and wise versa,
If I explain to you in simple steps and examples:

*

*added a timestamp property that is created timestamp for every collection's documents, _id objectId will also work

*

*ex: createdAt: ISODate("")

*created 2 collections for settings in the local server (one for local to live sync and second for live to local sync), that store the db+collection name, timestamp property that is the last sync document's timestamp

*

*ex: dbName.live_to_local_settings collection

{
   "db_collection": "dbName.collectionName",
   "syncProperty": "createdAt",
   "lastSync": ISODate("")
},
...

*created 2 scripts in local server: (both will execute as provided interval)

*

*live to local sync:

*

*loop dbName.live_to_local_settings collection documents and do the below steps for each collection

*query to live collection (live."dbName.collectionName") and check is createdAt >= settings.lastSync and sort by createdAt in ascending order

*query to local collection (local."dbName.collectionName") and check only above steps found documents by _id { $in: _ids }

*loop the live collections found documents and do the below steps:

*

*insert document in the local collection (local."dbName.collectionName") if it not exists in local

*update the document if _id exists in local, there are 3 conditions:

*

*ignore the update if both dates local.createdAt == live.createdAt are equal

*check if live.createdAt < local.createdAt then merges both documents but the primary consideration is the local document because the createdAt is latest, and after merge replace that whole document in both the places local and live collections using replace query

*check else if local.createdAt < live.createdAt then merges both documents but the primary consideration is the live document because the createdAt is latest, and after merge replace that whole document in both the places local and live collections using replace query

*update lastSync date in dbName.live_to_local_settings collection, that is document's createdAt timestamp

*local to live sync:

*

*the above steps would be the same but you need to change it query location wise versa

This looks complex but, works perfectly with less internet connectivity, and resumes when the internet comes back!


text:
Q: Is it possible to import big oracle database(600+ GB) to jupyter notebook? Is it possible to import a large database to the jupyter notebook? Is it restricted to certain types of database and is it possible to do with oracle database?

A:
Is it possible to import [600+ GB] to the jupyter notebook?

No. At the moment it seems Jupyter has a maximum limit of 100MB. Check out the source.
Notebooks are for sharing analyses and the data to drive them. They are not intended for the sort of heavy duty data crunching suggested by 600GB.

Is it restricted to certain types of database and is it possible to do with oracle database?

You can do anything with Jupyter that you could do with any other Python tool. So you can use the cx_oracle library to import data into a Pandas dataframe and work with that in Jupyter. The CERN site has some very useful information on working with Oracle, Pandas and Jupyter (and they wrangle huuuuge amounts of data). Find out more


text:
Q: prevent angularjs from rebinding when navigating to another view I added a console.log to a method in my controller that is being bound from my view. I can see that it is binding as expected when this particular view loads. The problem is, when I click a link in this particular view to navigate to another view, the method is being called again. Is there a way to turn this off? I don't want it to rebind when navigating away.
.controller('FeedCtrl', function ($scope, FeedFactory, $location, $stateParams) {

$scope.bindChart = function (m1, m2, m3, index) {

        console.log('binding chart');
        new ChartService().buildTriangleChart(m1, m2, m3, index);

}

})

The above console.log gets called when loading the page(as expected) and also gets called when navigating to another page(not expected). Basically I don't want any binding to be called on the page that is being navigated away from.
The html code that is binding to the method 'bindChart()' is shown below:


text:
Q: Can't redirect stdin to another process and have that process answer back correctly I have a project to do in C where I have to make a game where 2 clients talk with a server, and that server handles the plays, and then responds to each of them, one at the time, until the game is finished.
I'm doing this for weeks now and I managed to do something like:

*

*Server has a fork somewhere where the child, exec() a game (supplied by me) and I redirect that output to the client (very crudely I might add ...), and an unnamed pipe for speaking with his parent.

*The client receives that output, sees the game board and sends a play to the server.

*The parent uses the other end of the unnamed pipe to receive what the client sent and sends it to the child.
As soon as the first play is done, the server enters in a loop of "invalid plays" but I don't send anything. What is going on? Can anyone point me in the right direction?
Restrictions of this project are that we can only use pipes and fifos (not threads or sockets) and open, close, read and write. Only printfs allowed on the game.c code.
Example of a run:
Open server with ./server, open client with ./client John. In client, type 1 and enter. Then type 1 1 and enter to make a play. Then, the error occurs.
client.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <stdlib.h>
#include <signal.h>

void main(int argc, char *argv[])
{

int fdfifo_CS, fdfifo_SC, fd, conta;
char buffer[400];
int num=0;

fdfifo_CS = open("fifo_publico_cliente_servidor", O_WRONLY);

fdfifo_SC = open("fifo_privado_servidor_cliente", O_RDONLY);

write(fdfifo_CS, argv[1], strlen(argv[1])+1);

while(1)
{
    num = read(fdfifo_SC,buffer,sizeof(buffer));
        write(1,buffer,num);

    num = read(0,buffer,sizeof(buffer));
        write(fdfifo_CS, buffer, num);

    num = read(0,buffer,sizeof(buffer));
        write(fdfifo_CS, buffer, num);
}

server.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <stdlib.h>
#include <signal.h>
#include <dirent.h>

void main(int argc, char *argv[])
{
int fdfifo_CS, fdfifo_SC, num=0, pid=0, fd, pipefd[2];
char buffer[1024];

write(1, "\nServer ON !\n", strlen("\nServer ON !\n"));

mkfifo("fifo_publico_cliente_servidor",0777);

fdfifo_CS = open("fifo_publico_cliente_servidor", O_RDWR);

mkfifo("fifo_privado_servidor_cliente",0777);

fdfifo_SC = open("fifo_privado_servidor_cliente", O_WRONLY);

num = read(fdfifo_CS,&buffer,sizeof(buffer));

do
{
    write(fdfifo_SC,"\n\n!!! Menu !!!\n", strlen("\n\n!!! Menu !!!\n"));
    write(fdfifo_SC,"----------------------------------------------\n", strlen("----------------------------------------------\n"));
    write(fdfifo_SC,"1) Play.\n", strlen("1) Play.\n"));

    write(fdfifo_SC,"Choose: ", strlen("Choose: "));

    read(fdfifo_CS,buffer,sizeof(buffer));

    switch(buffer[0])
    {
        case '1':

                    pipe(pipefd);

                    pid = fork();
                    if (pid == 0)
                    {
                        fd = open("/dev/pts/8", O_RDWR, 0777); //To redirect to the bash of the client used. Must be changed to the correct tty.
                            dup2(fd,1);
                            close(fd);

                        close(pipefd[1]);
                        dup2(pipefd[0],0);
                        close(pipefd[0]);

                        execl("game","game",(char*) NULL);
                    }
                    else
                    {
                        close(pipefd[0]);

                        num = read(fdfifo_CS, buffer, sizeof(buffer));
                            write(pipefd[1], buffer, num);

                        close(pipefd[1]);

                    }

                break;

        default:
            printf("DONE");
            break;
    }
    }while(1);
}

game.c
#include <unistd.h>
#include <stdio.h>
#include <string.h>

void print_table(char *p, char t[3][3]) {
    printf("\nO:%s:  %c|%c|%c\n", p, '1', '2', '3');
    printf("O:%s:1 %c|%c|%c\n", p, t[0][0], t[0][1], t[0][2]);
    printf("O:%s:  -+-+-\n", p);
    printf("O:%s:2 %c|%c|%c\n", p, t[1][0], t[1][1], t[1][2]);
    printf("O:%s:  -+-+-\n", p);
    printf("O:%s:3 %c|%c|%c\n\n", p, t[2][0], t[2][1], t[2][2]);
}

/* check if this was a winning play */
int winning_play(int x, int y, char t[3][3]) {
    int v = t[y-1][x-1];
    if (t[y-1][0] == v && t[y-1][1] == v && t[y-1][2] == v)
            return 1;
    if (t[0][x-1] == v && t[1][x-1] == v && t[2][x-1] == v)
            return 1;
    if ((x + y % 2 == 0 && /* part of a diagonal */
        t[0][0] == v && t[1][1] == v && t[2][2] == v) ||
        (t[0][2] == v && t[1][1] == v && t[2][0] == v))
            return 1;
    return 0;
}

int main() {
    char table[3][3] =
        { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} };
    char play[16];
    int stop = 0, win = 0, turn = 1, turns = 0;
    do {
        int x, y, check;
        /* display table to both players */
        print_table("12", table);
        turn = (turn + 1) % 2;
        turns++;
        do {
            /* display message to the current player */
            printf("OUT:%d: play (format \"x y\")?\n", turn+1);
            /* ask for input from current player */
            printf("IN:%d\n", turn+1);
            fgets(play, sizeof(play), stdin);
            check = (sscanf(play, "%d%d", &x, &y) == 2 &&
                x >= 1 && x <=3 && y >= 1 && y <= 3 &&
                table[y-1][x-1] == ' ');
            if (check == 0)
                /* display message to current player */
                printf("OUT:%d: invalid play\n", turn+1);
        } while (!check);
        table[y-1][x-1] = (turn == 0 ? 'X' : 'O');
        win = winning_play(x, y, table);
        stop = (turns == 9);
    } while (!stop && !win);
    /* display final table to both players */
    print_table("12", table);
    /* display final score to both players */
    if (win)
        printf("RES:12: winner %d\n", turn+1);
    else
        printf("RES:12: draw\n");
    return 0;
}


text:
Q: UML( Domain Class Diagram) is my Domain Class Diagram correct? Currently I am dealing with UMl diagrams of the SOS game that I am planning to create, But I am not sure if my domain class diagram is correct. Can please someone tell me that if I have aany problem with my domain class diagram?
Thanks.
interface sketch 1
interface sketch 2
interface sketch 3

A: as @ThomasKilian said in the comments, It is hard to correct this model without proper domain documents.
I offer some hints just by my knowledge from your pictures,
You have some mistakes and some bad designs:

*

*Human Player 1 and Human Player 2 are not Classes. They are instances of one class can be named : Human Class that be inherited from Player.

*Score can be an attribute of Player, not a class. If it should be class, a relationship needs between Score and Player.

*Your Menu class can be decompose to it's sub classes.

*7*7 Grid class can be changed to Grid class with the rows and columns attribute.

*After Frame class, you can use a class named Cell, then Filled with S Class, Filled with O and Empty Class can be Inherited from Cell (Not Frame)

*In professional view, You SOS Game class is a GOD Class. (See this book: Object Oriented Design Heuristics, Arthur J. Riel, 1996, to handle it)


text:
Q: Do not display forms in JSF I started making a project (JSF+MAVEN) and immediately encountered some problems:
1)First one - my input textFields,buttons etc. do not displays on google page, something like on this picture. picture1
2)Second problem - "outputStylesheet" in home.xtml do not see my CSS folder and css file.picture2
I run this from home.xhtml->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
   <title>#{msg.index_title}</title>
   <h:outputStylesheet library="CSS" name="home.css"/>
</h:head>
<h:body>

 Please,enter your name

      <h:form>
        <h:inputText  id="username" size="25" value="#{user.username}"
        required="true" requiredMessage="#{msg.login_required}" />
        <h:commandButton action="main?faces-redirect=true" value="Enter"/>
      </h:form>

</h:body>

This is my project structure->
project structure
pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>MySiteGroup</groupId>
<artifactId>MySiteMaven</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>MySiteMaven Maven Webapp</name>

<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.1.7</version>
</dependency>

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>

  <dependency>
      <groupId>com.sun.faces</groupId>
      <artifactId>jsf-impl</artifactId>
      <version>2.1.7</version>
  </dependency>

</dependencies>

<build>
 <finalName>MySiteMaven</finalName>
<pluginManagement>
  <plugins>
    <plugin>
      <artifactId>maven-clean-plugin</artifactId>
      <version>3.0.0</version>
    </plugin>

    <plugin>
      <artifactId>maven-resources-plugin</artifactId>
      <version>3.0.2</version>
    </plugin>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.7.0</version>
    </plugin>
    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.20.1</version>
    </plugin>
    <plugin>
      <artifactId>maven-war-plugin</artifactId>
      <version>3.2.0</version>
    </plugin>
    <plugin>
      <artifactId>maven-install-plugin</artifactId>
      <version>2.5.2</version>
    </plugin>
    <plugin>
      <artifactId>maven-deploy-plugin</artifactId>
      <version>2.8.2</version>
    </plugin>
  </plugins>
 </pluginManagement>
 </build>
</project>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     id="WebApp_ID" version="2.5">

<welcome-file-list>
<welcome-file>faces/home.xhtml</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

</web-app>

faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">

<application>
    <resource-bundle>
        <base-name>nls.message</base-name>
        <var>msg</var>
    </resource-bundle>
</application>

</faces-config>

I will be very grateful to you for your help.


text:
Q: AttributeError: 'NoneType' object has no attribute 'text' (USING requests AND BeautifulSoup) `import requests
from bs4 import BeautifulSoup

class Temperature:
    def temperature(place):
        placeTemp = []
        placeWeather = "Weather in", place
        url = f"https://www.google.com/search?q={placeWeather}"
        r = requests.get(url)
        soup = BeautifulSoup(r.text, "html.parser")
        placeTemp.append(soup.find("div", class_="wob_t q8U8x").text)
        print(placeWeather,"is",placeTemp)

t = Temperature.temperature("Delhi")
print(t)`

I am making a program that finds the temperature of a place using requests and BeautifulSoup. Whenever I run the code I get this error:
placeTemp.append(soup.find("div", class_="wob_t q8U8x").text)
AttributeError: 'NoneType' object has no attribute 'text'

I've tried changing the class_ part but it always gives the same error.

A: It is a bit tricky and you always should take a look into your soup first.

*

*To avoid consent redirect, send cookies:
cookies = {'CONSENT':"YES+"}

*To get your values, select your elements more specific:
list(soup.select_one('div:has( > span:has(>:-soup-contains("Weather"))) ~ div > div').stripped_strings)
import requests
from bs4 import BeautifulSoup

params = {'q':'weather in Delhi', 'hl': 'en'}
headers = {'User-Agent': 'Mozilla/5.0'}
cookies = {'CONSENT':"YES+"}

url = 'https://www.google.com/search'

soup = BeautifulSoup(requests.get(url, params=params, headers=headers, cookies=cookies).content)

list(soup.select_one('div:has( > span:has(>:-soup-contains("Weather"))) ~ div > div').stripped_strings)

Output
Simply slect value by index:
['14°C', 'Sunday 21:32\nCloudy', 'More on weather.com']

A: It is possible to get the temperature by only using beautiful soup. Google uses https://weather.com to show weather. You can use it, to get temperature:
import requests
from bs4 import BeautifulSoup

class Temperature:
    def temperature(place):
        session = requests.session()
        session.headers.update({"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"})

        placeTemp = []

        placeWeather = f"Weather in {place}"
        url = f"https://www.google.com/search?q={placeWeather}"

        page = session.get(url)
        page.raise_for_status()
        soup = BeautifulSoup(page.content, "html.parser")

        url = soup.find("div", class_="YfftMc").find("a", href=True).get("href")

        page = session.get(url)
        page.raise_for_status()
        soup = BeautifulSoup(page.content, "html.parser")

        placeTemp.append(soup.find("span", {"data-testid": "TemperatureValue"}).text)
        print(placeWeather,"is",placeTemp)

        return placeTemp

t = Temperature.temperature("Delhi")
print(t)

Outputs:
Weather in Delhi is ['14°']
['14°']

A: Try using selenium instead. I am not sure but Google loads the data using JavaScript so, BeautifulSoup will not work.
Here is an example code for you :-
from selenium import webdriver
from selenium.webdriver.common.by import By

class Temperature:
    def temperature(place):
        placeWeather = f"Weather in {place}"
        url = f"https://www.google.com/search?q={placeWeather}"
        driver = webdriver.Firefox()
        driver.get(url)
        placeTemp = driver.find_element(By.ID,"wob_tm").text

        print(placeWeather,"is",placeTemp)
        return placeTemp

t = Temperature.temperature("Delhi")

output:-

Weather in Delhi is 57


text:
Q: Drill down Fusioncharts PHP class Can anyone tell me how do i create drill down fusioncharts using PHP class wherein all the data is present in one file and i can link the chart to the another chart present in that same file?

A: You actually need to create LinkedCharts (as per FusionCharts coined it). PHPClass does not allow you to create the data for the LinkedCharts. You would need to create the data using
your own PHP code and the pass the data to the chart.
Also, to change chart type, you would need to add JavaScript LinkedChart configuration.


text:
Q: terminating input at the end of input in java How to terminate scanner without entering any EOF character like this problem in codeforces.com(http://codeforces.com/problemset/problem/661/C).
Which gives in each line of input an integer and after n line
(n isn't a specified number by problem) the input hasn't any new line. so give some way to determine there is no more lines in the input!

A: in the example you posted is too broad, you can for sure define a timeOut timer to close the Scanner, but I think something more simple would do that for beginner levels like catching if the input is empty (which is some how entering a EOF character too IMHO)
Example:
public static void main(String[] args) {
    System.out.println("hi type some numbers, but just enter to finish");
    Scanner scan = new Scanner(System.in);
    String c = scan.nextLine();
    while (!c.equalsIgnoreCase("")) {
        System.out.println("nice, try again ");
        c = scan.nextLine();
    }
    System.out.println("ok bye");
}


text:
Q: HttpWebrequest/WebClient/HttpClient/CookieContainer bug? Does not add cookie if Response Uri does not contain it's path I was trying to log in to my WordPress admin panel using C# (WebClient/HttpWebRequest).
I send a POST request to /wp-login.php.
It responds with cookies like this:
Set-Cookie: wordpress_26...cf9e; path=/wordpress/wp-content/plugins; httponly
Set-Cookie: wordpress_26...cf9e; path=/wordpress/wp-admin; httponly
Set-Cookie: wordpress_logged_in_26...43b3; path=/wordpress/; httponly

And it also redirects to /wp-admin/: Location: http://109.120.169.99/wordpress/wp-admin/
The problem is that the second cookie (with path=/wp-admin) is not added to CookieContainer, so login fails.
I looked into HttpWebRequest source code and http://referencesource.microsoft.com/#System/net/System/Net/_CookieModule.cs (OnReceiveHeaders) and found out that it uses ResponseUri for all cookies.
I tried to add the cookie manually using response uri and got an exception that path is invalid. After that I found this answer CookieException with CookieContainer: The 'Path' part of the cookie is invalid : it says that the Uri has to match the path from the cookie when adding to CookieContainer.
I ended up disabling AllowAutoRedict (handling it manually) and manually adding these cookies.
Here is my code:
public static void Auth(string url, string username, string password)
{
    var webClient = new CookieAwareWebClient();

    // load page to get some cookies
    string loginPageHtml = webClient.DownloadString(url);

    webClient.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
    webClient.Headers.Add(HttpRequestHeader.Referer, url);

    var postValues = new NameValueCollection()
        {
            {"log", username},
            {"pwd", password},
            {"wp-sumbit", "Log In"},
            {"redirect_to", url.Replace("wp-login.php", "wp-admin/") },
            {"testcookie", "1"}
        };

    webClient.AllowRedirects = false; // to handle cookies and redirect manually

    byte[] response = webClient.UploadValues(url, postValues);
    string html = Encoding.UTF8.GetString(response);

    // <FIX>, handle cookies and redirect manually

    string cookies = webClient.ResponseHeaders[HttpResponseHeader.SetCookie];
    var cookiesArr = cookies.Split(',');

    foreach (var cookieStr in cookiesArr)
    {
        var parts = cookieStr.Split(';').Select(s => s.Trim());

        foreach (var part in parts)
        {
            if (part.Contains("path="))
            {
                string path = part.Replace("path=", "");

                var uri = new Uri(url);

                if (path != "/" && !uri.LocalPath.Contains(path))
                {
                    var uriBuilder = new UriBuilder(uri.Scheme, uri.Host, 80,
                        path);

                    webClient.CookieContainer.SetCookies(uriBuilder.Uri, cookieStr);
                }
            }
        }
    }
    // </FIX>

    while (webClient.StatusCode() == HttpStatusCode.Redirect)
    {
        string redirectUrl = webClient.ResponseHeaders[HttpResponseHeader.Location];

        html = webClient.DownloadString(redirectUrl);
    }

    if (html.Contains("?action=logout"))
        Console.WriteLine("Login success");
    else
        Console.WriteLine("Login fail");
}

WebClient:
// WebClient with CookieContainer
public class CookieAwareWebClient : WebClient
{
    private WebRequest _request = null;
    private WebResponse _response = null;

    public CookieContainer CookieContainer { get; private set; }

    public string UserAgent { get; set; }

    public bool AllowRedirects { get; set; }

    public CookieAwareWebClient()
    {
        UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36";
        CookieContainer = new CookieContainer();
        AllowRedirects = true;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        _request = base.GetWebRequest(address);
        if (_request is HttpWebRequest)
        {
            var httpRequest = (HttpWebRequest)_request;
            httpRequest.CookieContainer = CookieContainer;
            httpRequest.UserAgent = UserAgent;

            httpRequest.AllowAutoRedirect = AllowRedirects;

            httpRequest.ProtocolVersion = HttpVersion.Version11;

            httpRequest.Timeout = 50000;
        }
        return _request;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        _response = base.GetWebResponse(request);

        return _response;
    }

    // Returns status code of the last response
    public HttpStatusCode StatusCode()
    {
        var httpResponse = _response as HttpWebResponse;

        if (httpResponse == null)
            throw new InvalidOperationException("Unable to retrieve the status code, maybe you have not made a request yet.");

        var result = httpResponse.StatusCode;

        return result;
    }
}

I also tried using .NET 4.5 HttpClient but the same result (I think it uses HttpWebRequest underneath too):
public static void Auth2(string url, string username, string password)
{
    using (var httpClient = new HttpClient())
    {
        var loginPageHtml = httpClient.GetStringAsync(url).Result;

        var postContent = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("log", username),
                new KeyValuePair<string, string>("pwd", password),
                new KeyValuePair<string, string>("wp-submit", "Log In"),
                new KeyValuePair<string, string>("redirect_to", url.Replace("wp-login.php", "wp-admin/")),
                new KeyValuePair<string, string>("testcookie", "1")
            };

        var response = httpClient.PostAsync(url, new FormUrlEncodedContent(postContent)).Result;

        string html = response.Content.ReadAsStringAsync().Result;

        if (html.Contains("?action=logout"))
            Console.WriteLine("Login success");
        else
            Console.WriteLine("Login fail");
    }
}

Am I doing something wrong or is it a bug in HttpWebRequest/CookieContainer?
Here is the full source code for convenience if someone wants to test it: https://gist.github.com/AlexP11223/5c176972426605ee2112 (my test website and login/password also should work)
And Fiddler logs:

*

*http://1drv.ms/1qyAgGi — webbrowser (Chrome), it adds this cookie

*http://1drv.ms/1kqsLDI — WebClient

*http://1drv.ms/1kqsC2Y —
HttpClient


text:
Q: Variational problem is equivalent to minimizing the energy functional The variational problem Poisson's equation reads "For given $f \in L^2(\Omega)$ find $u \in H_0^1(\Omega)$ such that $$\int_{\Omega} \nabla u \cdot \nabla v \, \mathrm dx= \int_{\Omega}fv \, \mathrm dx \quad \forall v\in H_0^1(\Omega).$$
Very often I read that it is equivalent to minimizing the energy functional
$$J(v):=\frac{1}{2}a(v,v)-F(v)$$
where $a(u,v)=\int_{\Omega} \nabla u \cdot \nabla v \, \mathrm dx$ and $F(v)=\int_{\Omega}fv \, \mathrm dx.$ I get the proof, but what is the added value of introducing such equivalence, e.g. what relevance does the energy functional have? Sometimes I just see it randomly squeezed in and not being mentioned further in the literature.

A: Depending on the context, there can be a few different answers.

*

*In cases outside of Poisson's equation, variational problems often emerge initially as finding the extrema of a functional which sometimes can be intepreted as "energy." For Poisson's equation this is not the case historically (the PDE was derived first, and the variational formulation later). But depending on what you study, it can be the case that more often than not, the PDE comes out of the optimization problem, and not vice versa.

*Knowing that a solution (should one exist) must be a minimizer of some energy functional can sometimes be useful for deducing that one must exist and/or be unique. For instance, given the form of the energy functional, one may be able to conclude that it is coercive and weakly lower semi-continuous. This is enough to conclude that a minimizer exists; moreover, such a minimizer can, in principle, be constructed by taking a weak infimizing sequence and upgrading the weak convergence to strong convergence (after possibly modding out the symmetries of the underlying problem: this is referred to sometimes as compensated/concentration compactness). In the case of Poisson's equation, the existence and uniqueness problems are relatively tame and may be possible to resolve with other methods, but this sort of thing becomes valuable for more difficult nonlinear PDEs. Therefore it's a good idea to learn how to solve Poisson's equation using energy methods, since this easy case generalizes to a large class of contexts.


text:
Q: Why doesn't strptime() set tm_wday properly in this example? I'm using strptime(3) to parse a string representing a date:
#include <time.h>
#include <stdio.h>

int main () {
  struct tm t;
  strptime("2015-04-19 12:00:00", "%F %T", &t); /* Sunday */
  printf("%d\n", t.tm_wday); /* Should print 0 */
  return 0;
}

That date is a Sunday, according to the output of cal -y 2015. But when I compile this on OSX (presumably with clang) it prints 6:
$ gcc timetest.c ; ./a.out
6

whereas on Debian it prints the (correct) 0:
$ gcc timetest.c ; ./a.out
0

Any explanation for the difference?
UPDATE
Here is the same program, except that t is initialised with a valid time and I'm reporting the return value of strptime():
#include <time.h>
#include <stdio.h>

int main () {
  time_t epoch = 0;
  struct tm t;
  char *ret;
  t = *localtime(&epoch);
  ret = strptime("2015-04-19 12:00:00", "%F %T", &t); /* Sunday */
  printf("%d\n", t.tm_wday); /* Should print 0 */
  printf("strptime() returned %p (%d)\n", ret, *ret);
  return 0;
}

Here is the output:
$ gcc timetest.c ; ./a.out
6
strptime() returned 0x10c72af83 (0)

Here is the clang version I use:
$ clang -v
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin16.1.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

A: I think the reason is simply that, by design, the strptime function only sets the fields that appear in the format.  Essentially, strptime(3) just parses fields from a given string using a supplied format into a referenced structure and performs no other computation or logic.  Since your code uses the format %F %T then only the fields corresponding to %Y-%m-%d and %H:%M:%S (namely tm_{year,mon,mday,hour,min,sec}) are modified.
You can experiment by explicitly setting t.tm_wday to some known value that shouldn't by set by strptime (e.g. 123) and verify that it is not changed by that call.  Note that you should probably initialize your struct tm before playing with it since any of those fields may contain random values, e.g. struct tm t; memset((void *) &t, 0, sizeof(t));.
Moreover, this Linux strptime(3) man page contains the following note which leads me to believe that the special behavior it describes is non-standard (though obviously desirable):

The glibc implementation does not touch those fields which are not explicitly specified, except that it recomputes the tm_wday and tm_yday field if any of the year, month, or day elements changed.

This answer shows how you can use the trio of strptime/mktime/localtime (or gmtime) to populate the tm.tm_wday field for dates after the UNIX epoch.

A: Following on from the observation in the comments, here's a program derived from your code which illustrates, even if it does not explain, what is going on:
#include <time.h>
#include <stdio.h>

static void dump_struct_tm(const char *tag, const struct tm *t)
{
    printf("%s:\n", tag);
    printf("  Time: %.2d:%.2d:%.2d  ", t-> tm_hour, t->tm_min, t->tm_sec);
    printf("  Date: %.4d-%.2d-%.2d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
    printf("  Wday: %d Yday: %.3d (DST %d Zone [%s] offset %ld)\n",
           t->tm_wday, t->tm_yday, t->tm_isdst, t->tm_zone, t-> tm_gmtoff);
}

int main(void)
{
    time_t epoch = 0;
    struct tm t;
    char *ret;
    t = *localtime(&epoch);
    dump_struct_tm("Epoch", &t);
    putchar('\n');

    ret = strptime("2015-04-19 12:00:00", "%F %T", &t);
    dump_struct_tm("strptime()", &t);
    time_t rt = mktime(&t);
    dump_struct_tm("mktime()", &t);
    printf("Weekday: %d\n", t.tm_wday);
    printf("strptime() returned %p (%d)\n", ret, *ret);
    printf("Unix time: %lld\n\n", (long long)rt);

    t.tm_isdst = -1;
    ret = strptime("2015-04-19 12:00:00", "%F %T", &t);
    dump_struct_tm("strptime()", &t);
    rt = mktime(&t);
    dump_struct_tm("mktime()", &t);
    printf("Weekday: %d\n", t.tm_wday);
    printf("strptime() returned %p (%d)\n", ret, *ret);
    printf("Unix time: %lld\n\n", (long long)rt);

    return 0;
}

This analyzes the struct tm (as defined by the manual page on macOS Sierra) at different points.  Note how the setting of tm_isdst alters the behaviour.
Epoch:
  Time: 16:00:00    Date: 1969-12-31
  Wday: 3 Yday: 364 (DST 0 Zone [PST] offset -28800)

strptime():
  Time: 12:00:00    Date: 2015-04-19
  Wday: 6 Yday: 108 (DST 0 Zone [(null)] offset -28800)
mktime():
  Time: 13:00:00    Date: 2015-04-19
  Wday: 0 Yday: 108 (DST 1 Zone [PDT] offset -25200)
Weekday: 0
strptime() returned 0x100c82f0c (0)
Unix time: 1429473600

strptime():
  Time: 12:00:00    Date: 2015-04-19
  Wday: 6 Yday: 108 (DST -1 Zone [(null)] offset -25200)
mktime():
  Time: 12:00:00    Date: 2015-04-19
  Wday: 0 Yday: 108 (DST 1 Zone [PDT] offset -25200)
Weekday: 0
strptime() returned 0x100c82f0c (0)
Unix time: 1429470000

I'm still not clear why strptime() mispopulates the tm_wday field, especially since it seems to get the tm_yday field correct.  The 19th of April is day 108 of the year when the 1st of January is day 0.


text:
Q: How can I set `backoff-time-in-millis` parameter when creating a Camunda configuration programmatically? I have the class below in which I want to configure my Camunda process engine.
I want to make the engine deployment-aware and set the backoff-time-in-millis.
I can do the former using config.setJobExecutorDeploymentAware(true);.
How can I set the backoff-time-in-millis and other parameters of the job executor?
The obvious solution (config.getJobExecutor().setBackoffTimeInMillis(100);) is not applicable because when the method org.example.Config#processEngineConfiguration is called, config.getJobExecutor() is equal to null.
@Configuration
@Import( SpringProcessEngineServicesConfiguration.class )
public class Config {
    private static final Logger LOGGER = LoggerFactory.getLogger(Config.class);

    @Autowired
    @Qualifier("camundaBpmDataSource")
    private DataSource dataSource;

    @Autowired
    @Qualifier("camundaTxManager")
    private PlatformTransactionManager txManager;

    @Autowired
    private ResourcePatternResolver resourceLoader;

    @Bean
    public SpringProcessEngineConfiguration processEngineConfiguration() {
        final SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();

        config.setJobExecutorDeploymentAware(true);
        config.setIdGenerator(new StrongUuidGenerator());
        config.setDataSource(dataSource);
        config.setTransactionManager(txManager);
        config.setDatabaseSchemaUpdate("true");

        config.getProcessEnginePlugins().add(new SpinProcessEnginePlugin());

        config.setHistory(HistoryLevel.HISTORY_LEVEL_FULL.getName());
        config.setJobExecutorActivate(true);
        config.setMetricsEnabled(false);
        final Logger logger = LoggerFactory.getLogger("History Event Handler");

        final HistoryEventHandler testHistoryEventHandler = new HistoryEventHandler() {

            @Override
            public void handleEvent(final HistoryEvent evt) {
                LOGGER.debug("handleEvent | " + evt.getProcessInstanceId() + " | "
                        + evt.toString());
            }

            @Override
            public void handleEvents(final List<HistoryEvent> events) {
                for (final HistoryEvent curEvent : events) {
                    handleEvent(curEvent);
                }
            }
        };

        config.setHistoryEventHandler(new CompositeHistoryEventHandler(Collections.singletonList(testHistoryEventHandler)));

        try {
            final Resource[] bpmnResources = resourceLoader.getResources("classpath:*.bpmn");
            final Resource[] dmnResources = resourceLoader.getResources("classpath:*.dmn");
            config.setDeploymentResources(addAll(bpmnResources, dmnResources));
        } catch (final IOException exception) {
            exception.printStackTrace();
            LOGGER.error("An error occurred while trying to deploy BPMN and DMN files", exception);
        }

        return config;
    }
}

A: Add following code to the method processEngineConfiguration() above:
final ThreadPoolJobExecutor executor = new DefaultJobExecutor();
executor.setMaxJobsPerAcquisition(3);
executor.setWaitTimeInMillis(500);
executor.setLockTimeInMillis(300000);
executor.setMaxBackoff(150);
executor.setMaxWait(50);

final SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();

config.setJobExecutor(executor);
config.setJobExecutorDeploymentAware(true);


text:
Q: Freemarker nesting elements the wrong way I am having an issue when using <#nested in FreeMarker
If I do:

    <#nested "header">
    <#nested "info">
    <#nested "form">

NOT WHITE

Even the div with NOT WHITE text has a white background. The div itself also gets nested inside the previous div for some reason. Can someone help me here?

A: Probably your actual nested content (which you don't show in your question) has an unclosed div. Thus the
 you have after <#nested "from"> closes that unclosed div, and so the div that sets the white background stays open.


text:
Q: How to generate a random double with (separately) minimum / maximum limits? This is what I want to achieve:
public double NextMin (double min)
{
    //Returns a double that is greater than or equal to "min".
}

public double NextMax (double max)
{
    //Returns a double that is lesser than "max".
}

I tried range expanding but it returns lots of "Infinity" due to overflow:
// Range expanding for min
random.NextDouble() * (double.MaxValue - min) + min;

// Range expanding for max
random.NextDouble() * (max - double.MinValue) + double.MinValue;

Clarification: I need the return ranges to be as great as possible, which means they should include both negatives and positives.

A: I believe this works for the general case (provided min is less than max).
private Random rng = new Random();

private double GetRandomDouble(double min, double max)
{
    var half_min = min / 2.0;
    var half_max = max / 2.0;
    var average = half_min + half_max;
    var factor = max - average;

    return (2.0 * rng.NextDouble() - 1.0) * factor + average;
}

Calling Console.WriteLine(GetRandomDouble(double.MinValue, double.MaxValue)); then correctly produces values between double.MinValue and double.MaxValue.
Then you just flesh out the two methods you desire, like this:
public double NextMin(double min)
{
    return GetRandomDouble(min, double.MaxValue);
}

public double NextMax(double max)
{
    return GetRandomDouble(double.MinValue, max);
}

A: Try this one:
random.NextDouble() * (double.MaxValue - min) + min;
random.NextDouble() * (double.MinValue + max) - max;

A: private Random rng = new Random();

private double GetRandomDouble(double min, double max)
{
    // Get the base value, scale first and then shift.
    return rng.NextDouble()*(max - min) + min;
}

EDIT: I'm a bit bemused as to why this is working for me and not for others.  I just ran this code is VS 2015.3 and not once in three runs did it detect an infinite value:
class Program
{
    static void Main(string[] args)
    {
        const int maxIterations = 100000;
        var infinityDetected = false;

        for (int i = 0; i < maxIterations; i++)
        {
            var d = GetRandomDouble(double.MinValue, double.MaxValue);

            if (double.IsInfinity(d))
            {
                infinityDetected = true;
                Console.WriteLine("Infinity detected");
                break;
            }

            Console.WriteLine(d);
        }

        if (!infinityDetected)
        {
            for (int i = 0; i < maxIterations; i++)
            {
                var d = GetRandomDouble(-1.0, double.MaxValue);

                if (double.IsInfinity(d))
                {
                    infinityDetected = true;
                    Console.WriteLine("Infinity detected");
                    break;
                }

                Console.WriteLine(d);
            }
        }

        if (!infinityDetected)
        {
            for (int i = 0; i < maxIterations; i++)
            {
                var d = GetRandomDouble(double.MinValue, 1.0);

                if (double.IsInfinity(d))
                {
                    Console.WriteLine("Infinity detected");
                    break;
                }

                Console.WriteLine(d);
            }
        }

        Console.ReadLine();
    }

    private static Random rng = new Random();

    private static double GetRandomDouble(double min, double max)
    {
        // Get the base value, scale first and then shift.
        return rng.NextDouble() * (max - min) + min;
    }
}

A: This should play more nicely with overflows.
// Range expanding for min
double.MaxValue - random.NextDouble() * (double.MaxValue - min);

// Range expanding for max
double.MinValue + random.NextDouble() * (max - double.MinValue);

The second one is actually the same as the one you posted, and I don't see why that one wouldn't have worked.


text:
Q: Override a member inherited? Here is my class :
public class PrimtivePropertyProxy<T> : FrameworkElement
{
    public string Name
    {
        get;
        private set;
    }
    [....]
}

There already is a field Name in FrameWork element but still, I'd like to define a property name so that when I do :
myPrimtivePropertyProxy.Name;

it returns the Name I defined in my class, and not the one from FrameworkElement.
I know this is a complete hiding but, well, that's what I need to do !

A: is this what you want?
public new string Name
{
     get;
     private set;
}

A: And to avoid the compiler's warning, use the new keyword.
public new string Name
{
    get;
    private set;
}


text:
Q: Writing a regular expression with special characters As preface, I am new to (and really bad at) writing regular expressions.
I am trying to use a regular expression in the PHP function preg_split, and am looking to delineate by
*
**
`

I'm having trouble because these characters are commands. How can I write a regular expression to do this?

A: For PCRE and other so-called compatible flavors, you must escape these outside character classes.
. ^ $ * + ? () [ { \ |

The backtick has no special meaning, so you don't need to escape it.
preg_split('/\*{1,2}|`/', $text);

See Demo
Note: For future reference, you may want to look into using preg_quote()

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

A: preg_split("(?:\*{1,2}|\`)", $string);


text:
Q: why i can't do Web scraping python bs4 in steam market price skins I don't understand, I'm trying to take data from the steam community market for the price of the skin and I get a quote at the place where the price is located (Please help.
from bs4 import BeautifulSoup as bs44
import requests

url = "https://steamcommunity.com/market/listings/730/AWP%20%7C%20Hyper%20Beast%20%28Well-Worn%29"
info = requests.get(url)

soup = bs44(info.content, "html.parser")
name = soup.find(id='market_buyorder_info').find(id='market_commodity_buyrequests')
print(name)

A: This particular website is a real time web app. When you open the page javascript fires up in the background and keeps requesting sale details every few seconds and updates the page.
If you developer tools of your browser (usually F12 key) and click network tab you'll see these requests are being made:

To url: https://steamcommunity.com/market/itemordershistogram?country=US&language=english&currency=1&item_nameid=49399562&two_factor=0
If you click on it you'll see it returns sale information in json format.
All you have to do in your web-scraper is request this url instead of the one you're requesting. Most important parameter here seems to be item_nameid which is ID of the sold item - you can find it in the html of your original url:

You can use regex to search html body for it:
re.findall(r"Market_LoadOrderSpread\( (\d+) \)", html)


text:
Q: TextField Redirects to main page after animation finishes I have been trying to use a sylized input field from @material-ui but when doing this:
<TextField
  id="outlined-basic"
  className={classes.inputField}
  color="primary"
  label="Message"
  variant="filled"
  onChange={this.handleChange}
/>

After the animation occurs when the user clickes on it they are redirected from localhost:3000/some-page to localhost:3000 in my tests. Here is the handleChange function as well:
handleChange = (e) => {
  this.setState({text: e.target.value})
}

I have the exact same code in another react project yet I am still getting this problem and cannot figure out why. All help on this would be appreciated! Thanks.
Edit:
Here is the full code:
import React, { Component } from "react";
import ".././App.css";
import { Title } from "../Components/Title";

// MUI Stuff
import { withStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button/Button";

// Theme
import theme from "../Util/theme";

const styles = {
  ...theme.spreadIt,
};

class BugsMain extends Component {
  constructor(props) {
    super(props);
    this.id = "0";
  }

  handleChange = (e) => {
    this.setState({text: e.target.value})
  }

  render() {
    const { classes } = this.props;
    return (

          <Title title="Bugs | Root_Directory" />

 Feedback

            <Button className={classes.button} href="">Submit A Bug Report</Button>

            <TextField
              id="outlined-basic"
              className={classes.inputField}
              color="primary"
              label="Message"
              variant="filled"
              onChange={this.handleChange}
            />

            <Button className={classes.button} href={"/bug-viewer?id=" + this.id}>Find A Bug Report</Button>

            <Button className={classes.button} href="/">Return to home</Button>

    );
  }
};

export default withStyles(styles)(BugsMain);

A: That's because TextField is placed inside the a tag.
Please move TextField outside of the a tag.

A: The <className="App-link" href="/"> its the reason, you should have a Redirection or some logic if send with no error to redirect to certain page...