text:
Q: Swift - Coredata Migration - Set new attribute value according to old attribute value One of my current core data entities - Entity1 - has a Boolean attribute called isSaved.
In the new core data model, I am planning to remove isSaved attribute and add a new Int attribute called type. And for all saved Entity1 objects, I'd like to set the value of type according to the value of isSaved in old core data model. (e.g. if isSaved is true, then type is 1, else type is 2).
I've read some articles about light weight core data migration, but none of them seems helpful.
Just wondering if there is any way that can make my planned migration work?

A: Lightweight migration can't do this. You'll have to create a mapping model and a subclass of NSEntityMigrationPolicy. It's not difficult but it's unfamiliar territory for most iOS developers. The steps run like this:

*

*Create the mapping model. In Xcode, File --> New --> Mapping Model. When you click "Next", Xcode will ask for the source (old) and destination (new) model files for this mapping.

*The model file will infer mappings where possible. Everything else will be blank. With your type and some other properties, it'll look something like the following. Entries like $source.timestamp mean to copy the existing value from before the migration.

*Create a new subclass of NSEntityMigrationPolicy. Give the subclass an obvious name like ModelMigration1to2. This class will tell Core Data how to map the old boolean value to the new integer value.

*Add a method to the subclass to convert the value. Something like the following. The method name doesn't matter but it's good if you choose something descriptive. You need to use ObjC types here-- e.g. NSNumber instead of Int and Bool.
 @objc func typeFor(isSaved:NSNumber) -> NSNumber {
     if isSaved.boolValue {
         return NSNumber(integerLiteral: 1)
     } else {
         return NSNumber(integerLiteral: 2)
     }
 }

*Go back to the mapping model and tell it to use your subclass as its custom mapping policy. That's in the inspector on the right under "custom policy". Be sure to include the module name and class name.

*Tell the mapping model to use that function you created earlier to get values for the type property from the old isSaved property. The following says to call a function on the custom policy class named typeForIsSaved: (the : is important) with one argument, and that the argument should be the isSaved value on $source (the old managed object).

Migration should now work. You don't have to tell Core Data to use the mapping model-- it'll figure out that migration is needed and look for a model that matches the old and new model versions.
A couple of notes:

*

*If you crash with an error that's something like Couldn't create mapping policy for class named... then you forgot the module name above in step 5 (or got it wrong).

*If you get a crash with an unrecognized selector error then the method signature in step 4 doesn't match what you entered in step 6. This can also happen if you forget to include @objc in the function declaration.

A: Using Xcode 9.1 Beta with Swift 4, I find migration works but you have to be careful how you specify the transform method name, also it seems you need to mark your functions as @objc.
For example, my Value Expression:
FUNCTION($entityPolicy, "changeDataForData:" , $source.name)

My transformation policy method name:
class StudentTransformationPolicy: NSEntityMigrationPolicy {
  @objc func changeData(forData: Data) -> String {
      return String(data: forData, encoding: .utf8)!
  }
}

Definitely tricky and took a lot of experimenting before I got it to trigger when launching my app after model changes.  It might be easier to implement "createDestinationInstances" for your policy if all of this doesn't work, but we'll leave that for another day...


text:
Q: Como carregar arquivo .JS dependendo da largura da tela Eu tenho um arquivo .js que gostaria de carregar apenas para versão Desktop, quando for em telas mais estreites gostaria que a requisição para esse .js não fosse feita, ou até mesmo fosse carregado outro .js. Tipo, para telas grandes > 768px carrega desktop.js, e para telas < que 786px carrega mobile.js
Sei que para CSS pode ser feito assim:
<link rel="stylesheet" href="css/mobile.css"  media="screen and (max-width: 767px)" />
<link rel="stylesheet" href="css/desktop.css" media="screen and (min-width: 768px)" />

E para imagens podemos fazer assim por exemplo:
<picture>
  <source srcset="desktop.jpg" media="(min-width: 768px)">
  <source srcset="mobile.jpg"  media="(max-width: 767px)">
  <img srcset="mobile.jpg" alt="…">
</picture>

Então ficou a dúvida, tem como fazer algo parecido para requisições de arquivos .js dependendo do width da tela?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex Help - specific years or range of years I'm not very good with these. I can't figure out how to match this scenario: 2012,2015 (specific  years) 2013-2015 (year range) 2013-* (any date after 2013 i.e., future years). I can get the first two scenarios to match but not the last.
/^[0-9]{4}(?:[,-*][0-9]{4})*,?$/
2012,2013,2014-2015,2016-* (no match)

A: You can split by comma and check the years one by one:

let s = "2012,2013,2014-2015,2016-*,foo,292992,322,2103-238";
let split = s.split(',');

for (let x of split) {
  console.log(determine(x));
}

// or to check if all are ok:
let allOk = split.every(determine);
console.log("every: ", allOk);

function determine(year) {
  let y = year.split('-');
  if (!y[0].match(/^\d{4}$/)) return false;
  if (typeof y[1] === 'undefined' || y[1] === '*') return true;
  return determine(y[1]);
}

A: Here's a regex that works for your year formats
[0-9]{4}\-?(?:[0-9]{4}|\*)?

check

A: Here's how to handle the whole thing. Since the comma can't be optional if you have more years and you don't want to end in a comma, you must repeat the year term:
^[0-9]{4}(?:-(?:[0-9]{4}|\*))?(?:,[0-9]{4}(?:-(?:[0-9]{4}|\*))?)*$


text: Q: How to use Schema Registry and AvroConverter in Kafka Source connector? I'm trying to write custom Source and Sink Kafka connectors for MongoDB with schema registry and Avro. I have configured the key and value converters as AvroConverter and the schema registry url in the properties. What code do i have to add in my connector so that it  converts the data to Avro and validates according to the schema ?


text:
Q: passing exclamation, brackets as part of executable arguments in powershell In git, if we want to exclude a file from diff output (on bash) we do something like follows:
git diff -- !(file.txt)

But this is disallowed in powershell. Hence is there a way to achieve this in the powershell prompt?

A: Simply single-quote your argument:
git diff -- '!(file.txt)'

Single-quoting makes PowerShell treat the string literally and prevents it from interpreting chars. such as ( as its own metacharacters.
Before invoking the target program, PowerShell re-quotes arguments if and as needed, behind the scenes; that is:

*

*It encloses an argument in "..." if it contains whitespace, and also in certain, less common scenarios (see link below).

*It passes it without quotes otherwise.
Note: There are pitfalls associated with this invisible re-quoting - see this answer.


text:
Q: How to print GWC layer? I have GWC layer on my GeoServer. Now I want to  print this layer using GeoServer print module but don't know how to do this.
When I try WMS layer all works fine. But how to print the GWC layer?
MORE INFO
In client side I have a GXP and try to print using gxp_print plugin. My problem is that I can't set URL to the GWC layer.
I read this and this: so I try this URL:
layer.setUrl("/geoserver/gwc/service/wms?BBOX=7637927.0361051%2C6845332.4516735%2C7750900.9638949%2C6971453.5483265&HEIGHT=256&WIDTH=256&TRANSPARENT=true&map_resolution=305.74811309814453&VERSION=1.1.1&FORMAT=image%2Fpng&TILED=true&SERVICE=WMS&format_options=dpi%3A100&LAYERS=gisurfo:atd&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&");

But GeoServer returns me error:
400: Requested horizontal resolution: 441.30440542890574 , best match:
305.74811309814453 exceeds 10% threshold. Perhaps the client is configured with an
incorrect set of scales (resolutions), or the DPI setting is off compared to the one in GWC ?

This same like in links above. So how to print GWC?
UPDATE
Good news. I changed scales in my config.yaml file to scales that I get from the GWC layer (but I get only left part of each scale). Now I try to print GWC layer but it not printing. In GeoServer log I found Bad Request:
java.io.IOException: Error (status=400) while reading the image from
http://geourfo.ru:9091/geoserver/gwc/service/wms?BBOX=6866019.0%2C7636631.0%2C6950767.0%2C7752196.5    &HEIGHT=625&WIDTH=458&VERSION=1.1.1&FORMAT=image%2Fpng&SERVICE=WMS&
format_options=dpi%3A75&LAYERS=gisurfo%3Aatd&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913
: Bad Request

After I change width and height to 256/256 and get my tile!
So question: why iprint plugin take tiles with HEIGHT=625 and WIDTH=458 but not with 256x256?


text:
Q: User account model with two or three possible profile My application will have at least two types of users: clients and companies, these are the types of profiles. Because each type of profile requires different additional information, it will be required to create a table for each type of profile.
How should I create my relationships so a user has zero or one client profile, or zero or one company profile, but in a way that he must have one and only one of the two types of profiles?
E.g. John is a client, then he has a row on Users table and UsersProfiles. He can't have a row in CompaniesProfiles at the same time.

A: I think you have two choices: either have one profile reference and an indicator in the user record to identify the profile type, or have two profile references and enforce your requirement using insert and update triggers. In the first case, you'll have to forego referential integrity (since your foreign key can reference two different tables), but you save space by only using one field. In the second case, you maintain referential integrity at the cost of added complexity due to the use of triggers (and possibly more complexity if you need to do bulk inserts, since triggers are often disabled for performance reasons when large amounts of data are inserted).


text:
Q: Need help groking code snippet in Hack ASM ROM This is/was for assignment four of From NAND to Tetris, and OCW from Hebrew University (I don't attend, I'm just doing the course for kicks). What it does is, when any key is held down, it blackens out every pixel. When the key is released, the "screen" is cleared.
Here's the ROM itself:
// Fill.asm

// Fills the 'screen' with black,
// one pixel at a time, when any
// key is pressed and held.

// When the key is released, the
// screen should clear.

// i = 0

@i
M=0

(LOOP)
 // color = 0xFFFF (black) = !0
 D=0
 D=!D
 @color
 M=D

 @KBD        // Location of keypress code
     // is RAM[24576] = RAM(0x600)
 D=M         // D != 0 if a key is pressed

 @SKIP_WHITE
 D;JNE

 // if (key == 0 )
 // {
 //   color = 0 (white)

 @color
 M=0

 // }

(SKIP_WHITE)
 // Ensure that the offset is
 // within the screen's 8K
 // memory area
        @i
 M=M+1
 @8191
 D=A
 @i
 M=M&D

 @i
 D=M
 @SCREEN
 D=D+A
 @target
 M=D
 @color
 D=M
 @target
 A=M      // GOTO Pixel specified by target
 M=D

 @LOOP // infinite loop, baby
 0;JMP

What I'm really curious about is the second to last block of code, the one about the offset of the screen's memory area. I wrote everything else, but the program didn't work until someone supplied me that block of code. Can anyone explain to me what it's doing?

A: I figured it out!
8191 is the maximum number of bits within the virtual screen's 8K memory area. By ANDing the iterator with the maximum value, we ensure that we do not try to write to pixels outside of the screen.


text:
Q: Is the sum of the amplitudes of an electromagnetic wave always 1? It's been a while, and I'm trying to verify my understanding. I remember reasoning (but never being taught) that the sum of the (normalized) electric and magnetic waves in a single electromagnetic wave at any single point in time is always one. Like so:
Given A of em-wave is normalized (max = 1, min = -1)

    abs(sum(A of m-wave, A of e-wave)) = 1

I haven't been able to find anywhere that says this specifically (I probably suck at searching, or am wrong). Am I correct in my understanding?

A: It would seem from this question, that I am incorrect, as it has both waveforms reaching their zero simultaneously. From that question, it seems that the sums of the amplitudes ranges from -2 to 2; essentially just a doubled amplitude of a single wave (as far as sums go). Sad, as I rather enjoyed the symmetry of my interpretation. Oh well.


text:
Q: How to hook into webservice I'm trying to hook into an external web service - not something I've done before.
Using VS2010/c#.
I've discovered the web service (if thats the correct terminology) and now have access to its methods and properties.
The following code was added automatically to my web.config file:
However, when i call the service I get an error:
An endpoint configuration section for contract 'PingTree.PayDayLoansSoap' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name.
Obviously, I can see that there are multiple configurations/endpoints however I'm not sure which one I need to specify. also do I remove the unwanted ones from the web.config or specify through the calling method (there are overloads that can do this)?
Any help appreciated.

A: You need to choose one of the binding name with overloaded version of the data.Which one to chose , it depends upon your requirement.
I can see there are two basicHttpBinding with only difference is the security. PayDayLoansSoap uses transport mode security where PayDayLoansSoap1 does not uses anything. so I would advise to go with the first one.
you don't need to remove the unused binding, let it be and use the overloaded version of the proxy.
PayDayLoansSoap12 is a custom binding so you might need to go over what it actually do.
let me know in case of any confusion/concerns.


text:
Q: Depth from Graphics3D Consider this simple 3D rendering with some geometric primitives:
Graphics3D[{Cylinder[{{-1, -1, 0}, {-1, -1, 1}}, .42], Cuboid[],
  Polygon[{{-2, -2, 0}, {2, -2, 0}, {2, 2, 0}, {-2, 2, 0}}],
  Sphere[{.3, -.6, .5}, .5]}, Boxed -> False]

How can I get the depth of each pixel of the rendering, i.e. the distance of the corresponding point to the camera?
Edit: The required depth image would be something like the OpenGL z-buffer. Vertices alone are not enough - I need the depth of every pixel in the rendered image.

A: We can set the Method option for Graphics3D:
dmap = Graphics3D[{Cylinder[{{-1, -1, 0}, {-1, -1, 1}}, .42], Cuboid[],
  Polygon[{{-2, -2, 0}, {2, -2, 0}, {2, 2, 0}, {-2, 2, 0}}],
  Sphere[{.3, -.6, .5}, .5]}, Boxed -> False,
  Method -> {"OneLayer" -> {"Depth", 1}}]

To get the distance values rescaled from 0 to 1, we can rasterize:
raster = ColorConvert[Rasterize[dmap], "Grayscale"];

We can view the depth map from different view points:
ListPlot3D[ImageData[raster], Axes -> False, Boxed -> False,
 ViewPoint -> {0, 0, -10}, ViewVertical -> {0, -1, 0}, Mesh -> None,
 SphericalRegion -> True]

A: It would certainly be helpful if you could specify your input data. As an example I'll use the scene you proposed above.
Let's first extract the vertices of the 3D scene. One way to achieve this is to export the scene as an .obj and then reimport the vertex data only. Let's neglect the fact that the vertices aren't uniformly distributed over the surfaces.
scene = Graphics3D[{Cylinder[{{-1, -1, 0}, {-1, -1, 1}}, .42], Cuboid[],
  Polygon[{{-2, -2, 0}, {2, -2, 0}, {2, 2, 0}, {-2, 2, 0}}], Sphere[{.3, -.6, .5}, .5]},
  Boxed -> False, ViewPoint -> {5, 5, 5}]

Export["scene.obj", scene];
impScene = Import["scene.obj", "VertexData"];

The camera location is at position $(5,5,5)$ as defined by ViewPoint above:
cameraLoc = {5, 5, 5};

These are all the lines connecting the camera to the vertices:
Graphics3D[Line[{cameraLoc, #}] & /@ impScene]

The distance from the camera to each of the vertices is easily obtained by:
dist = EuclideanDistance[cameraLoc, #] & /@ impScene;

A: One (very slow) method I've used is to sweep through the depth by increasing the ViewRange gradually, and rasterizing those scenes in black & white. You can then sum the resulting images to produce something that looks like a depth map.
drange = Range[12.0, 18, 0.05];
dimensions = {512, 512};

objects = {Cylinder[{{-1, -1, 0}, {-1, -1, 1}}, .42], Cuboid[],
   Polygon[{{-2, -2, 0}, {2, -2, 0}, {2, 2, 0}, {-2, 2, 0}}],
   Sphere[{.3, -.6, .5}, .5]};

dmasks = ParallelTable[ColorNegate@ColorConvert[Rasterize[
      Graphics3D[{FaceForm[Black], EdgeForm[Black], objects},
       Boxed -> False, ViewRange -> {0, r}],
      RasterSize -> dimensions], "Grayscale"], {r, drange}];

ImageAdjust@(Image[Total[ImageData /@ dmasks]])

This is of course inadequate for your purposes due to poor performance and low depth resolution.
Another option is to set the VertexColors of the mesh to a GrayLevel corresponding to the distance from the camera. This is faster, but it's not accurate as it interpolates the depth. Also there are some artifacts near polygon edges.
camera = {1.3, -2.4, 2.};
scene = Graphics3D[{Cylinder[{{-1, -1, 0}, {-1, -1, 1}}, .42],
    Cuboid[],
    Polygon[{{-2, -2, 0}, {2, -2, 0}, {2, 2, 0}, {-2, 2, 0}}],
    Sphere[{.3, -.6, .5}, .5]}, Boxed -> False, ViewPoint -> camera];
(* get the whole scene as one big mesh *)
polys = TriangulateMesh[ImportString[ExportString[scene, "OBJ"]]];

coords = MeshCoordinates[polys];
cells = MeshCells[polys, 2];

(* get all polygon vertices distances to camera, normalize, and set a GrayLevel *)
distances = GrayLevel /@ Rescale[EuclideanDistance[camera, #] & /@ coords];

(* render the scene with the VertexColors *)
Rasterize[
  Graphics3D[{EdgeForm[None], Lighting -> {{"Ambient", White}},
    GraphicsComplex[coords, cells, VertexColors -> distances]},
   Boxed -> False]] // ColorNegate


text:
Q: Open stack Magnum docker private repo I am working in Open stack Magnum,  and resent days I am facing issue in deploying magnum , due to docker pulling rate limit Magnum is not pulling the docker containers.  Please help me how to point private repo to mangum to avoid this pulling rate.
Hi Team,
I am working in Open stack Magnum,  and resent days I am facing issue in deploying magnum , due to docker pulling rate limit Magnum is not pulling the docker containers.  Please help me how to point private repo to mangum to avoid this pulling rate.


text:
Q: Alan Kay's Eval/Apply Einstein Moment Alan Kay said that reading the code closely and finding the 1 and only bug in the code on page 13 of the Lisp 1.5 manual, helped him understand Computer Science by a factor of 100 better.
The code in question is the 1st release of eval & apply that looks anything remotely like modern lisp (that I'm aware of).
Since the correct answer is likely known but lost (my google-fu is decent and I've searched for 20 mins at least)
I will award the 1st correct answer (I will be looking at edit times so don't try to cheat) a 250 point bounty As Soon As Possible.
I would suggest others contribute to the bounty as well,
remember from the video above Alan Kay said this stuff is reminiscent of the environment Einstein was in when he discovered the Theory of Relativity.
The code in the text is written in M-Expressions. I'm working on a translator to translate from M-expressions to S-expressions (lisp code) @https://github.com/Viruliant/MccarthyMCEval-1.5.
Anyways here is the translated quote from page 13:
;______________________________________Lisp Meta-Circular Evaluator S-Expression
;this code is written in the order it appears on pages 10-13 in the Lisp 1.5 Manual
;and is translated from the m-expressions into s-expressions

(label mc.equal (lambda (x y)
    (mc.cond
        ((atom x) ((mc.cond ((atom y) (eq x y)) ((quote t) (quote f)))))
        ((equal (car x)(car y)) (equal (cdr x) (cdr y)))
        ((quote t) (quote f)))))

(label mc.subst (lambda (x y z)
    (mc.cond
        ((equal y z) (x))
        ((atom z) (z))
        ((quote t) (cons (subst x y (car z))(subst x y (cdr z)))))))

(label mc.append (lambda (x y)
    (mc.cond
        ((null x) (y))
        ((quote t) (cons (car x)) (append (cdr x) y)))))

(label mc.member (lambda (x y)
    (mc.cond ((null y) (quote f))
    ((equal x (car y)) (quote t))
    ((quote t) (member x (cdr y))))))

(label mc.pairlis (lambda (x  y  a)
    (mc.cond ((null x) (a)) ((quote t) (cons (cons (car x)(car y))
    (pairlis (cdr x)(cdr y) a)))))

(label mc.assoc (lambda (x a)
    (mc.cond ((equal (caar a) x) (car a)) ((quote t) (assoc x (cdr a))))))

(label mc.sub2 (lambda (a z)
    (mc.cond ((null a) (z)) (((eq (caar a) z)) (cdar a)) ((quote t) (
    sub2 (cdr a) z)))))

(label mc.sublis (lambda (a y)
    (mc.cond ((atom y) (sub2 a y)) ((quote t) (cons (sublis a (car y))))
    (sublis a (cdr y)))))

(label mc.evalquote (lambda (fn x)
    (apply fn x nil)))

(label mc.apply (lambda (fn x a)
    (mc.cond ((atom fn) (
        (mc.cond
            ((eq fn car) (caar x))
            ((eq fn cdr) (cdar x))
            ((eq fn cons) (cons (car x)(cadr x)))
            ((eq fn atom) (atom (car x)))
            ((eq fn eq) (eq (car x)(cadr x)))
            ((quote t) (apply (eval (fn a)x a))))))
        ((eq (car fn) lambda) (eval (caddr fn) (parlis (cadr fn) x a)))
        ((eq (car fn) label) (apply (caddr (fn)x cons (cons (cadr (fn)))
            (caddr fn))a)))))

(label mc.eval (lambda (e a)
    (mc.cond
        ((atom e) (cdr (assoc e a)))
        ((atom (car e)) (mc.cond
            ((eq (car e) quote) (cadr e))
            ((eq (car e) cond) (evcon (cdr e) a))
            ((quote t) (apply (car e) (evlis (cdr e) a) a))))
        ((quote t) (apply (car e) (evlis (cdr e) a) a))))))

(label mc.evcon (lambda (c a)
    (mc.cond
        ((eval (caar c) a) (eval (cadar c) a))
        ((quote t) (evcon (cdr c) a)))))

(label mc.evlis (lambda (m a)
    (mc.cond
        ((null m) (nil))
        ((quote t) (cons (eval (car m) a) (evlis (cdr m) a)))))))

A: It is most likely a reference to the bug of dynamic scope (a bug since
the result isn't doing what it's supposed to do if it's expected to be
similar to the lambda calculus):
eq[car[fn];LAMBDA] -> eval[caddr[fn];pairlis[cadr[fn];x;a]];
                                    %^^^^^^^^^^^^^^^^^^^^^

And in the edited semi-lisp-like text:
((eq (car fn) lambda) (eval (caddr fn) (parlis (cadr fn) x a)))
                                      ;^^^^^^^^^^^^^^^^^^^^^^

But this is not helpful at all.  The fix must come not just there, in
that one place; and you need to understand how the whole thing works and
really follow it, to see how the bug happens.
As a quick hint in the right direction, the problem here is that the
lambda function's body is evaluated in an environment (the second
argument to eval) which is an extension of the current environment,
resulting in dynamic scope.  Solving it --- implementing lexical scope
--- involves more than just an edit here, since the information about
the lexical scope of the function is already lost.
(Any random decent book on PLs should have much more details.  In the
context of Lisp, digging deeper will indeed get you to the whole FUNARG
thing.)

A: update2: Here's the code from the paper, rewritten in some  pseudocode with list patterns and comprehensions (including parallel comprehensions), in all of 13 lines of code (15 with the addition of FUNARG device, discussed below), all here in one definition:
apply f args = eval [f, ...[[QUOTE, a] | a <- args]] []  {- McCarthy-LISP-paper    -}

eval e a | atom e    = head [v | [n, v] <- a, n == e]
         | otherwise = case e of
  [QUOTE,    x]     ->  x
  [FUNCTION, x]     ->  [FUNARG, x, a]     {- enclose the definitional environment! -}
  [CONS,  x, y]     ->  [eval x a, ...eval y a]
  [CAR,      x]     ->  head ( eval x a )
  [CDR,      x]     ->  tail ( eval x a )
  [ATOM,     x]     ->  atom ( eval x a )
  [EQ,    x, y]     ->  eval x a == eval y a
  [COND, ...xs]     ->  head [eval c a | [t, c] <- xs, eval t a]
  [[LAMBDA,p,b], ...xs] -> eval b [...[[n, eval x a] | n <- p | x <- xs], ...a]
  [[LABEL, n,x], ...xs] -> eval [x, ...xs]  [[n, [LABEL, n, x]], ...a]
  [[FUNARG,f,d], ...xs] -> eval [f, ...[[QUOTE, eval x a] | x <- xs]] d   {- d (sic) -}
  [x,            ...xs] -> eval [eval x a, ...xs] a             {- fixing the bug,   -}
                {-  eval [eval x a, ...[eval x a | x <- xs]] a  -- args eval'd twice -}

(2021 update:) to support variable length argument lists with (lambda p ....), we add another clause,
  [[LAMBDA,p,b], ...xs] | atom p ->                                {- this one -}
                           eval b [ [p, [eval x a | x <- xs]], ...a]
  [[LAMBDA,p,b], ...xs] -> eval b [...[[n, eval x a] | n <- p | x <- xs], ...a]

where pat | guard -> .... fires when guard evaluates to true when and if pat matches.

update: here's a video by Philip Wadler where he talks (at 22:30) about that "bug", and how using the "wrong variable" (for the environment to be used in evaluating a lambda-body, a instead of env in the pseudocode that follows) leads to "dynamic binding" rather than "static biding".

I've re-written the original M-expressions from the code in the book (Lisp 1.5 programmers manual) in some ad-hoc pseudocode which is easier for me to follow, using : for cons or ., with pattern-matching, etc., which follows shortly.
Actually, I can't see any double-evaluation problem with it. apply expects its arguments already evaluated, and eval evaluates them for it.
I think the bug was in the original paper "Recursive Functions of Symbolic Expressions" (update: yes! Rainer Joswig mentions at the end of his answer the Paul Graham article, which states that this was in reference to the code in the paper).
So indeed it looks likely that Alan Kay's remark was in reference to the dynamic scoping. He mentions looking "at the bottom of pg 13" (so, in the book)  and that's where the evlis definition is, which evaluates list's elements in the same, current environment. Look at the book's pages 70, 71 for the solution to this, requiring a programmer to explicitly tag their lambda definitions with a new keyword function, to create funarg-tagged lists packaging the lambdas together with (or closing over, as in "closure") the environment at the time the function form is evaluated - i.e. the definitional environment of that lambda form.
Moses 1970 calls it binding environment, discussing only implicit creation of closures when used as functional arguments in a higher-order function invocation (hence the "funarg" moniker). This is also the context in more contemporary discussions of "deep and shallow binding" (misusing the terminology, in my view) in the word of Perl etc.
But looking at that extended version in the book, it seems it would allow a programmer to  create such entities explicitly, store them in a variable, pass it around as just any other first class entity. Then, when a closure (a funarg-tagged list) is applied, the lambda definition is evaluated in its environment, not the current one (what Moses 1970 calls activation environment). This gets one very close to convincingly imitating lexical scoping with dynamic binding.
Here's that pseudocode, following the code from the book:
evalquote fn x = apply fn x []    {- `x` a list of arguments -}

apply CAR ((x:_):_) a = x         {- `a` an association-list, the environment -}
 |    CDR ((_:x):_) _ = x
 |   CONS (x:y:_)   _ = x:y
 |   ATOM (x:_)     _ = atom x
 |     EQ (x:y:_)   _ = eq x y
 | fn xs a , atom fn        = apply (eval fn a) xs a
 | (LAMBDA  args body) xs a = eval body (pairlis args xs a)
 | (LABEL  fn lambda)  xs a = apply lambda xs ((fn:lambda):a)
   {- and the FUNARG device, pg 70: -}
 | (FUNARG lambda env) xs a = apply lambda xs env           {- not `a`, NB! -}

eval e a , atom e      = assv e a
 | (QUOTE e)   _       = e
 | (COND (t c) : cs) a = { eval t a -> eval c a ; eval (COND:cs) a }
   {- the FUNARG device, pg 71: -}
 | (FUNCTION lambda) a = (FUNARG lambda a)  {- enclose the definitional environment! -}
 | (e1:es) a , atom e1 = apply e1 (evlis es a) a
 | (e1:es) a           = apply e1 (evlis es a) a

evlis (m : ms) a           = eval m a : evlis ms  | [] _ = []
equal (x:xs) (y:ys)        = equal x y && equal xs ys
 |    x y , atom x, atom y = eq x y               | _ _  = F
subst x y z , equal y z = x
 |    _ _ z , atom z    = z
 |    x y (h:t)         = subst x y h : subst x y t
append (x:xs) ys        = x : append xs ys        | [] ys = ys
member x (y:_) , equal x y = T
 |     x (_:ys)         = member x ys             | _ []  = F
pairlis (x:xs) (y:ys) a = (x:y) : pairlis xs ys a | _ _ a = a
assv x ((h:y):ys)       = { x==h -> y ; assv x ys }
sub2 ((x:v):xs) z   = { eq x z -> v ; sub2 xs z } | [] z  = z
sublis a y , atom y = sub2 a y    | a (y:ys) = sublis a y : sublis a ys

A: it looks like
equal[x;y] =
        [atom[x] -> [atom[y] -> eq[x;y]; T -> F];
         equal[car[x];car[y]] -> equal[cdr[x];cdr[y]];
         T -> F]

doesn't handle the case where x is a cons and y is an atom
edit: also assoc will fail to return nil if the key is not found.

A: There are two different issues:
First: Dynamic binding as a bug
Not sure what he means, but generally in McCarthy's EVAL the use of dynamic binding can be seen as a bug. He does not implement lexical scope for variables. The bug shows up for example here:
http://www-formal.stanford.edu/jmc/recursive/node3.html
See the functions maplist and diff. Both use x. This won't work as shown, since the early Lisp provides dynamic binding.
A simpler example, which shows that the evaluator uses dynamic binding
Note the use of eval., which is the eval from McCarthy.
CL-USER 36 > (eval. '((lambda (f)
                        ((lambda (x) (f))
                         'foo))
                      '(lambda () x))
                    nil)

This returns FOO, since the value of X is looked up from the dynamic binding.
If we look at the code, it requires us to pass a function as a list: '(lambda () x)). This evaluates to a list. Later the list will be called via (f) - with no arguments. The list then is interpreted as a lambda expression and x will be resolved by looking at the current dynamic binding for x. There is the binding of x to FOO introduced by ((lambda (x) (f)) 'foo). This will be used then.
In the Lisp 1.5 implementation from the 60s, one might write something similar to:
((lambda (f)
   ((lambda (x) (f))
    'foo))
 (function (lambda () x)))

Note that (function (lambda () x)) evaluates to a list of a marker, dynamic environment and the function. Unfortunately the Lisp 1.5 implementation still used dynamic binding. So that was already the right direction, but the bug wasn't really fixed then. Improved was the situation when one was passing functions to other functions as arguments.
The FUNARG problem
It took quite some time during the 60s/early 70s to figure out this problem. It was known as the FUNARG problem. See for example Joel Moses paper: The Function of FUNCTION in LISP, or Why the FUNARG Problem Should be Called the Environment Problem. There were various solutions to create closures and to use lexical binding. Often the interpreter used dynamic binding and the compiler used lexical binding. In the Lisp world this was basically solved in Scheme, which introduced lexical binding by default. This lexical binding then allows for example to use closures to emulate object systems (something that Kay probably finds useful). See the paper: SCHEME: An Interpreter for Extended Lambda Calculus from 1975.
In Common Lisp, which uses lexical scope by default like the Lisp dialect Scheme, above example would be an error (here we use the eval from Common Lisp, with slightly changed code to make it legal Common Lisp code):
CL-USER 43 > (eval '((lambda (f)
                       ((lambda (x) (funcall f))
                        'foo))
                     (function (lambda () x))))

Error: The variable X is unbound.

As you can see in Common Lisp (and Scheme), (lambda () x) is a real lambda expression, not a quoted list and (function (lambda () x)) evaluates to a function object - if there are bindings, then it is a closure - a function object and its bindings. This function object / clojure is passed and then later called via (funcall f). Since the x refers to nothing (it is a free variable) and is not looked up via bindings, an error occurs when the code is executed. That's what we want: we want lexical binding and this error in our code is a consequence. That this error does not happen in McCarthy's original Lisp is one result of the bug. Fixing this bug (which took more than a decade to full satisfaction), enables us to use closures in Lisp - like in Common Lisp, which learned it from Scheme.
Probably Kay also saw dynamic binding as a bug. This is a very fundamental problem and understanding/solving it, helped to design and develop better programming languages.
Note that typical early Smalltalk implementations (example Xerox' Smalltalk 80) also used dynamic binding.
McCarthy about that bug
In From LISP 1 to LISP 1.5 (1979) McCarthy writes (bold by me):

d. Free variables. In all innocence, James R. Slagle programmed the following LISP function definition and complained when it didn't work right:
The object of the function is to find a subexpression of x satisfying p[x] and return f[x]. If the search is unsuccessful, then the continuation function u[] of no arguments is to be computed and its value returned. The difficulty was that when an inner recursion occurred, the value of car[x] wanted was the outer value, but the inner value was actually used. In modern terminology, lexical scoping was wanted, and dynamic scoping was obtained.
I must confess that I regarded this difficulty as just a bug and expressed confidence that Steve Russell would soon fix it. He did fix it but by inventing the so-called FUNARG device that took the lexical environment along with the functional argument. Similar difficulties later showed up in Algol 60, and Russell's turned out to be one of the more comprehensive solutions to the problem. While it worked well in the interpreter, comprehensiveness and speed seem to be opposed in compiled code, and this led to a succession of compromises. Unfortunately, time did not permit writing an appendix giving the history of the problem, and the interested reader is referred to (Moses 1970) as a place to start. (David Park tells me that Patrick Fischer also had a hand in developing the FUNARG device).

This is unrelated to the second problem:
Second: bugs in a different version of EVAL in the same book
See Paul Graham's The Roots of Lisp for a discussion of a bug in a definition of EVAL later in the book. On page 12 you find a description of a bug in McCarthy's code which causes double evaluation of arguments to a named function.


text:
Q: Google kubernetes monitoring, stuck loading resources I have a kubernetes cluster created on GCP, it's fully functional, every logs/metrics are enabled on GKE but, when I go to Stackdriver/resources/kubernetes engine nothing is showed, stuck in loading page.
Can someone help me?
Thanks in advance.

A: It looks like a specific problem with GCP. I assume you don't have enterprise support in that case I recommend opening a ticket with the free trial support. Otherwise, you'll have to sign up for Silver level support which is $150/month


text:
Q: Adding a new span element to the label and writing an increment in the span for each new fieldset I have a plugin for cloning fieldsets in form. For each new fieldset, the plugin generates a new fieldset element with the same classes and subelements. In the beginning, I have only one fieldset and probably that is my problem.
I want to have a new span element in ".myClass" and in this span number, for every new +1.
I have:
Label
Label
Label
and I want to have:
Label 1
Label 2
Label 3
...
I have found jQuery code and ist working, but for each new fieldset set number 1:
$(".myClass").each(function(i) {
    $(this).append($("<span>"+(i+1)+"</span>"));
});

I think the problem is because I have only one fieldset in the beginning. When I click and clone a new filedset, jQuery sees the same element.
Any solution/hint/help?

A: Can you please share your code? I don't get any idea.
As per my understand
If you find the length of total span inside your myclass then Your issue will resolved
Like $(".myClass > span").length
Or Inside foreach
$(".myClass").each(function() { $(this).children('span').length });


text:
Q: How can I join the cell values from two pandas dataframe? How can I join the cell values from two pandas dataframe?
df1 is:

         F1   F2   M1   M2
    pos
    23  1.0  0.0  1.0  1.0
    24  1.0  1.0  1.5  1.0
    28  1.0  0.0  0.5  0.0

df2 is:

         F1   F2   M1   M2
    pos
    23  0.0  1.0  0.5  0.0
    24  1.0  1.0  1.5  1.0
    28  0.0  1.0  1.0  1.0

How can I combine the values (which have same column and row indexes) inside these dataframe with a comma?
Expected output like:
         F1       F2       M1       M2
    pos
    23  1.0,0.0  0.0,1.0  1.0,0.5  1.0,0.0
    24  1.0,1.0  1.0,1.0  1.5,1.5  1.0,1.0
same for other lines...
The value of df1 should be place before comma and df2 after that.

Thanks,

A: You can use concat both DataFrames, cast to string by astype and groupby by index with aggregate by agg function join:
df = pd.concat([df1,df2]).astype(str).groupby(level=0).agg(','.join)
df.index.name = df1.index.name
print (df)
          F1       F2       M1       M2
pos
23   1.0,0.0  0.0,1.0  1.0,0.5  1.0,0.0
24   1.0,1.0  1.0,1.0  1.5,1.5  1.0,1.0
28   1.0,0.0  0.0,1.0  0.5,1.0  0.0,1.0

A: You can sum them up as two DFs with "string" elements:
In [324]: d1.astype(str).add(',').add(d2.astype(str))
Out[324]:
          F1       F2       M1       M2
pos
23   1.0,0.0  0.0,1.0  1.0,0.5  1.0,0.0
24   1.0,1.0  1.0,1.0  1.5,1.5  1.0,1.0
28   1.0,0.0  0.0,1.0  0.5,1.0  0.0,1.0


text:
Q: Is this Cauchy-Schwarz Inequality correct? I am reading Theory of Probability and Random Processes
Book by Leonid B. Koralov. In the Lemma 1.28, the book said: If $E \xi_1^2$ and $E \xi_2^2$ are finite, then $E(\xi_1 \xi_2)$ is also finite and
$$E|\xi_1 \xi_2| \leq (E \xi_1^2 E \xi_2^2)^{1/2}$$
But the correct formula should be
$$|E(\xi_1 \xi_2)| \leq (E \xi_1^2 E \xi_2^2)^{1/2}$$
I use their method, and I get the correct formula which are consistent with online Wikipedia. Can anyone give a counter example to show the formula in the textbook is wrong?

A: The Cauchy-Schwarz inequality is true for $\sum|ab|$ since if we prove that $\left(\sum xy\right)^2<\sum x^2\sum y^2$ for $x_i, y_i\geq0$ for all $i$, then let $a_i=\pm x_i$ and $b_i=\pm y_i$ then $$\left(\sum x^2\right) \left(\sum y^2\right)=\left(\sum a^2\right)\left(\sum b^2\right)$$ and $$\sum xy=\sum|ab|\geq\left|\sum ab\right|$$
using $|a|+|b|\geq|a+b|$, so we have
$$
\sqrt{\left(\sum a^2\right)\left(\sum b^2\right)}\geq \sum|ab|\geq\left|\sum ab\right|.
$$


text:
Q: Looping from the limit of contents in a sheet to match and copy in VBA Excel I'm new here, and this is my problem; in vba, excel 2010 I want to search for a specific word or a list of words in every row with content in one sheet and if it matched then it copy the entire row of that sheet and paste it in a new one at the first row, and then continues looping back and foward from sheet to sheet after the list of words ends. At the end you get a new sheet with a bunch of rows collected from your search Query. I got some initial code, dont know if you guys will like to see it.
Thanks.
Sub Macro1()
    Dim sheetName As String
    Dim recintos As String
    Dim recintosArray() As String
    Dim namevar As Variant
    Dim sheetLimit As Integer
    Dim n As Integer

    'Words to search and copy in the sheet
    'Nombre del sheet a buscar en el documento abierto
    sheetName = InputBox("Nombre de la hoja o sheet en donde desea copiar los recintos :")

    'Save a string type data
    'Guarda los datos como tipo cadena
    recintos = InputBox("Introduzca los nombres  de los recintos separados por coma :", "Buscador de recintos", "00000,00000,00000...")

    'Split the words and save it in array type
    'Separa la cadena y los guarda en un arreglo
    recintosArray() = Split(recintos, ",")
    namevar = InputBox("Introduzca el nombre de la hoja que desea crear para pegar c/u :")

    'Makes a new sheet and defines a name
    'Crea un sheet nuevo y define el nombre
    Sheets.Add After:=Sheets(Sheets.Count)
    Sheets(Sheets.Count).Name = namevar
    sheetLimit = Sheets(sheetName).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

    'Array index
    'Indice del arreglo recintosArray
    n = 0

    For i = 1 To sheetLimit
        Sheets(sheetName).Activate
        currentCellName = Sheets(sheetName).Cells(i, 1).Value

        If n <= UBound(recintosArray) Then
            If Replace(currentCellName, Chr(32), "") = recintosArray(n) Then
                Sheets(sheetName).Rows(i).Copy
                newSheetLimit = Sheets(namevar).Cells(Rows.Count, 1).End(xlUp).Offset(0, 0).Row
                Sheets(namevar).Activate
                Sheets(namevar).Cells(newSheetLimit + 1, 1).Select
                ActiveSheet.Paste
                n = n + 1
                i = 1
            End If
        End If
    Next i
End Sub

A: You can read the code's comments and adjust it to fit your needs
Remember to use F8 jey to step through it
There were some parts of your code that I couldn't fully understand
EDIT: Added missing function
EDIT2: Copy entire row
Code
Public Sub Macro2()

    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet

    Dim sourceRange As Range
    Dim cell As Range

    Dim sourceSheetName As String
    Dim targetSheetName As String

    Dim recintos As String
    Dim recintosArray As Variant

    Dim lastRow As Long
    Dim targetRow As Long

    ' Set the starting row in which the cells are going to be copied
    targetRow = 1

    'Words to search and copy in the sheet
    'Nombre del sheet a buscar en el documento abierto
    sourceSheetName = InputBox("Nombre de la hoja o sheet en donde desea copiar los recintos :")
    Set sourceSheet = ThisWorkbook.Worksheets(sourceSheetName)

    'Save a string type data
    'Guarda los datos como tipo cadena
    recintos = InputBox("Introduzca los nombres  de los recintos separados por coma :", "Buscador de recintos", "00000,00000,00000...")

    'Nombre del sheet a crear
    targetSheetName = InputBox("Introduzca el nombre de la hoja que desea crear para pegar c/u :")

    'Split the words and save it in array type
    'Separa la cadena y los guarda en un arreglo
    recintosArray = Split(recintos, ",")

    ' You may want to check if user entered an array here

    ' Add a new sheet and set the reference
    Set targetSheet = ThisWorkbook.Worksheets.Add
    ' You may want to check here that the sheet doesn't exists...
    targetSheet.Name = targetSheetName

    ' Get the last row in column A
    lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, 1).End(xlUp).Row

    ' Set the range where you want to look up the values
    Set sourceRange = sourceSheet.Range("A1:A" & lastRow)

    ' Loop through the column A values begining in row 1
    For Each cell In sourceRange.Cells

        ' Check if value is in array
        If IsInArray(cell.Value, recintosArray) Then
            targetSheet.Range("A" & targetRow).EntireRow.Value = cell.EntireRow.Value
            targetRow = targetRow + 1
        End If

    Next cell

End Sub

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    ' Credits: https://stackoverflow.com/a/11112305/1521579
    IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

Let me know if it works


text:
Q: Можете пожалуйста объяснить, что этот метод делает? public static double[][] Allocate(int numberOfClusters, int numberOfFeatures)
{
    double[][] result = new double[numberOfClusters][];
    for (int k = 0; k < numberOfClusters; ++k) {
        result[k] = new double[numberOfFeatures];
        Console.WriteLine(k + "->" + result[k]);
    }
    return result;
}

A: Создаёт рваный двумерный массив numberOfClusters строк, каждая из которых содержит numberOfClusters элементов double. Ну и зачем-то выводит на консоль все строки-массивы.


text:
Q: file_get_contents(https://api.telegram.org/bot failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in telegram.php on line 49 I use this code in index.php page
function get_model_info($model)
        {
           $query="select * from mobile where model_name='".$model."' limit 1";

              return $query;

              }
        // $telegram = null;
        $query=get_model_info($text);
        $telegram->query=$query;
         $telegram->runqury();
         $result=$telegram->queryresult;
         $text=urlencode($result->fetch_object()->info);

     $telegram->sendmessage($userid, $text);

and used this code on telegram.php page
public function sendmessage($userid,$text)
  {
    $url='https://api.telegram.org/bot'.$this->token.'/sendmessage?chat_id='.$userid.'&text='.$text;
       file_get_contents($url);
     }

but it doesn't work.

A: sending text messages to telegram chat using php must be like bellow:
$url = "https://api.telegram.org/bot".$botToken."/sendMessage?chat_id=@yourtargetID&text=yourText";
file_get_contents($url);

You must replace sendmessage? with sendMessage? (Capital M)


text: Q: Understanding dependency injection I've been reading about the benefits of implementing DI on iOS, but I have one doubt: where should I put the code that actually creates instances of objects? Is it factory pattern the recommended way to go about this? should all instances be created on the same factory? I've been checking out some frameworks like Typhoon but they all seem over-engineered to me for something as simple as dependency injection. I don't want to overwhelmed my app by using any of these frameworks, so I'm trying to keep it simple, at least for now.


text:
Q: Oracle RDBMS; c#; InvalidCast exception while reading a decimal value   DbDataReader _dbReader = query.SendQuery(queryTxt, ref error, fromWhere) //custom method
  string value;
  ...
  try
  {
       DateTime dateTimeValue = (DateTime)_dbReader[i];
       value = dateTimeValue.ToString("yyyy-MM-dd HH:mm:ss");
  }
  catch(Exception ex)
  {
       **value = _dbReader[i].ToString();**  // culprit statement
  }
}
catch (System.OverflowException ex)
{
   // handled gracefully
}

If i am reading the results of a simple query like:
select 1, 1.4, 2/3 from dual

Then, code returns InvalidCastException while reading the last value 2/3
what is unknown to me is when it can convert every other decimal to string, why not 2/3?
I know it will have the maximum precison that Oracle RDBMS allows but still it is a decimal.
Added to the complexity of the problem above code is working fine with Oracle 11* client tools but the problem is only with Oracle 12c client tools. I tried to go through documentation for OracleDataAccess API, i could not find any update related to this problem.
I can add another catch block for InvalidCastException and try using GetDecimal or something like that to avoid an error, but what if the value is not a decimal and code in catch block raises an exception again.
Any thoughts/Ideas ?


text:
Q: How to use Triton server "ensemble model" with 1:N input/output to create patches from large image? I am trying to feed a very large image into Triton server. I need to divide the input image into patches and feed the patches one by one into a tensorflow model. The image has a variable size, so the number of patches N is variable for each call.
I think a Triton ensemble model that calls the following steps would do the job:

*

*A python model (pre-process) to create the patches

*The segmentation model

*Finally another python model (post-process) to merge the output patches into a big output mask

However, for this, I would have to write a config. pbtxt file with 1:N and N:1 relation, meaning the ensemble scheduler needs to call the 2nd step multiple times and the 3rd once with the aggregated output.
Is this possible, or do I need to use some other technique?

A: Disclaimer
The below answer isn't the actual solution to the above question. I misunderstood the above query. But I'm leaving this response in case of future readers find it useful.

Input
import cv2
import matplotlib.pyplot as plt

input_img = cv2.imread('/content/2.jpeg')
print(input_img.shape) # (719, 640, 3)
plt.imshow(input_img)

Slice and Stitch
The following functionality is adopted from here. More details and discussion can be found here.. Apart from the original code, we bring together the necessary functionality and put them in a single class (ImageSliceRejoin).
# ref: https://github.com/idealo/image-super-resolution
class ImageSliceRejoin:
    def pad_patch(self, image_patch, padding_size, channel_last=True):
        """ Pads image_patch with padding_size edge values. """
        if channel_last:
            return np.pad(
                image_patch,
                ((padding_size, padding_size),
                (padding_size, padding_size), (0, 0)),
                'edge',
            )
        else:
            return np.pad(
                image_patch,
                ((0, 0), (padding_size, padding_size), (padding_size, padding_size)),
                'edge',
            )

    # function to split the image into patches
    def split_image_into_overlapping_patches(self, image_array, patch_size, padding_size=2):
        """ Splits the image into partially overlapping patches.
        The patches overlap by padding_size pixels.
        Pads the image twice:
            - first to have a size multiple of the patch size,
            - then to have equal padding at the borders.
        Args:
            image_array: numpy array of the input image.
            patch_size: size of the patches from the original image (without padding).
            padding_size: size of the overlapping area.
        """
        xmax, ymax, _ = image_array.shape
        x_remainder = xmax % patch_size
        y_remainder = ymax % patch_size

        # modulo here is to avoid extending of patch_size instead of 0
        x_extend = (patch_size - x_remainder) % patch_size
        y_extend = (patch_size - y_remainder) % patch_size

        # make sure the image is divisible into regular patches
        extended_image = np.pad(image_array, ((0, x_extend), (0, y_extend), (0, 0)), 'edge')

        # add padding around the image to simplify computations
        padded_image = self.pad_patch(extended_image, padding_size, channel_last=True)

        xmax, ymax, _ = padded_image.shape
        patches = []

        x_lefts = range(padding_size, xmax - padding_size, patch_size)
        y_tops = range(padding_size, ymax - padding_size, patch_size)

        for x in x_lefts:
            for y in y_tops:
                x_left = x - padding_size
                y_top = y - padding_size
                x_right = x + patch_size + padding_size
                y_bottom = y + patch_size + padding_size
                patch = padded_image[x_left:x_right, y_top:y_bottom, :]
                patches.append(patch)

        return np.array(patches), padded_image.shape

    # joing the patches
    def stich_together(self, patches, padded_image_shape, target_shape, padding_size=4):
        """ Reconstruct the image from overlapping patches.
        After scaling, shapes and padding should be scaled too.
        Args:
            patches: patches obtained with split_image_into_overlapping_patches
            padded_image_shape: shape of the padded image contructed in split_image_into_overlapping_patches
            target_shape: shape of the final image
            padding_size: size of the overlapping area.
        """
        xmax, ymax, _ = padded_image_shape

        # unpad patches
        patches = patches[:, padding_size:-padding_size, padding_size:-padding_size, :]

        patch_size = patches.shape[1]
        n_patches_per_row = ymax // patch_size
        complete_image = np.zeros((xmax, ymax, 3))

        row = -1
        col = 0
        for i in range(len(patches)):
            if i % n_patches_per_row == 0:
                row += 1
                col = 0
            complete_image[
            row * patch_size: (row + 1) * patch_size, col * patch_size: (col + 1) * patch_size, :
            ] = patches[i]
            col += 1
        return complete_image[0: target_shape[0], 0: target_shape[1], :]

Initiate Slicing
import numpy as np

isr = ImageSliceRejoin()
padding_size = 1

patches, p_shape = isr.split_image_into_overlapping_patches(
    input_img,
    patch_size=220,
    padding_size=padding_size
)

patches.shape, p_shape, input_img.shape
((12, 222, 222, 3), (882, 662, 3), (719, 640, 3))

Verify
n = np.ceil(patches.shape[0] / 2)
plt.figure(figsize=(20, 20))
patch_size = patches.shape[1]

for i in range(patches.shape[0]):
    patch = patches[i]
    ax = plt.subplot(n, n, i + 1)
    patch_img = np.reshape(patch, (patch_size, patch_size, 3))
    plt.imshow(patch_img.astype("uint8"))
    plt.axis("off")

Inference
I'm using the Image-Super-Resolution model for demonstration.
# import model
from ISR.models import RDN
model = RDN(weights='psnr-small')

# number of patches that will pass to model for inference:
# here, batch_size < len(patches)
batch_size = 2

for i in range(0, len(patches), batch_size):
    # get some patches
    batch = patches[i: i + batch_size]

    # pass them to model to give patches output
    batch = model.model.predict(batch)

    # save the output patches
    if i == 0:
        collect = batch
    else:
        collect = np.append(collect, batch, axis=0)

Now, the collect holds the output of each patch from the model.
patches.shape, collect.shape
((12, 222, 222, 3), (12, 444, 444, 3))

Rejoin Patches
scale = 2
padded_size_scaled = tuple(np.multiply(p_shape[0:2], scale)) + (3,)
scaled_image_shape = tuple(np.multiply(input_img.shape[0:2], scale)) + (3,)

sr_img = isr.stich_together(
    collect,
    padded_image_shape=padded_size_scaled,
    target_shape=scaled_image_shape,
    padding_size=padding_size * scale,
)

Verify
print(input_img.shape, sr_img.shape)
# (719, 640, 3) (1438, 1280, 3)

fig, ax = plt.subplots(1,2)
fig.set_size_inches(18.5, 10.5)
ax[0].imshow(input_img)
ax[1].imshow(sr_img.astype('uint8'))


text:
Q: NET MVC Toggle between Seed Data and Real Data In Net MVC Core 2, Is there a method in Visual Studio, to Toggle between artificial in-memory Seed data, and real Test Environment sql connection? We are continuously testing between two environments.
This is how to create artificial data from source: "Pro ASP.NET Core MVC 2, Freeman".
To Toggle between Seed Data, I have to remove all this, and then add a real connection string again in Application.json, I am trying to prevent removing/adding code. Currently beginner in MVC, only programming for few months, so trying to learn. Thank you
Create seed data
new Product {
Name = "Kayak", Description = "A boat for one person",
Category = "Watersports", Price = 275 },

new Product {
Name = "Lifejacket",
Description = "Protective and fashionable",
Category = "Watersports", Price = 48.95m },

Then in Startup.cs
public void ConfigureServices(...
services.AddTransient<IProductRepository, EFProductRepository>();

public void Configure(...
SeedData.EnsurePopulated(app);

A: The feature, you're looking for, is in EF Core. It's .UseInMemoryDatabase option:
public TestDbContext Context => InMemoryContext();
    private TestDbContext InMemoryContext()
    {
        var options = new DbContextOptionsBuilder<TestDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .EnableSensitiveDataLogging()
            .Options;
        var context = new TestDbContext(options);

        return context;

}
This blog would fill the gaps: https://garywoodfine.com/entity-framework-core-memory-testing-database/

A: In order to automatically switch connection string, you'd need to use environment-based configurations. Then, based on your environment variable, your app would read different values.
Check this answer for more details: Setting Environment Variables in .net Core 2.0


text:
Q: I want to make mro_id column values are links to a particular action using ignited datatables How make values as links in ignited datatables? How to make it easy?
Controller
 function index()
    {

        $tmpl = array ( 'table_open'  => '
' );
        $this->table->set_template($tmpl);

        $this->table->set_heading('First Name','Last Name','Email');

        $this->load->view('subscriber_view');
    }
function datatable()
    {

        $this->datatables
        ->select("mro_id,mro_name,mctg_name,mctg_id")
        ->from('jil_mroproducts')
        ->join('jil_mrocategory', 'jil_mroproducts.mro_category=jil_mrocategory.mctg_id', 'INNER')
        ->unset_column('mro_id');
         echo $this->datatables->generate();

    }

A: Try this
$this->datatables->edit_column('mro_id', '$2', 'mro_id, mro_name');

$1 links to mro_id
and
$2 links to mro_name

Read this $this->datatables->edit_column($column, $content, $match_replacement);


text:
Q: Redirect PXE boot to normal boot I have a PXE server and few computers. Those computers have PXE boot enabled in the BIOS.
I would like to know if there is a way, from the PXE server, to tell the computers to boot normally (Linux) instead of continuing the PXE boot; without disabling the PXE boot on the BIOS.
Thanks in advance !

A: *

*Create new configuration in pxelinux.cfg folder, either MAC, IP (in hex) or portion of IP.

As an example, if the boot file name is pxelinux.0, the Ethernet MAC
  address is 88:99:AA:BB:CC:DD and the IP address 192.0.2.91, it will
  try following the files:
/var/lib/tftpboot/pxelinux.cfg/01-88-99-aa-bb-cc-dd
/var/lib/tftpboot/pxelinux.cfg/C000025B
/var/lib/tftpboot/pxelinux.cfg/C000025
/var/lib/tftpboot/pxelinux.cfg/C00002
/var/lib/tftpboot/pxelinux.cfg/C0000
/var/lib/tftpboot/pxelinux.cfg/C000
/var/lib/tftpboot/pxelinux.cfg/C00
/var/lib/tftpboot/pxelinux.cfg/C0
/var/lib/tftpboot/pxelinux.cfg/C
/var/lib/tftpboot/pxelinux.cfg/default

*Then make it default or ontimeout to boot local drive
LABEL BootLocal
        localboot 0

Source: Ubuntu Community Help Wiki: PXE Install Multi Distro


text:
Q: Grails: Use run-script to ppopulate a H2 database I have got some problem to populate my H2 datatase via the run-script command:
Here is my domain class:
class Lab {

String name

static constraints = {
}

String toString() {
    return name
}

static mapping = {
    sort "name"
}

}
I generated the controller and view using the grails generate-all command.
I wrote a simple groovy script to add new Lab:
import groovy.sql.Sql

def grailsApplication
def dataSource = ctx.getBean("dataSource")
def sql = new Sql(dataSource)

Lab a = new Lab(name: "AAAAAAAAAAAAAA")
assert a.save(flush: true)

if (!a.hasErrors()) {
  println "${a.name} saved successfully!"
}

Now, when I run it, everything looks to work fine:
AAAAAAAAAAAAAA saved successfully!
| Script scripts/createLab.groovy complete!

But when I refresh the webpage page http://localhost:8080/myapp/lab/index, I cannot see any new Lab created.
I am using the default H2 database setting.
Did I missed something?

A: You are using a h2 memory db called devDB (h2:mem:devDb;).
I see two options here. If you like to have a physical file to represent your db you can use file instead mem.
h2:file:devDb;

Or you can put your scripts insite Bootstrap.groovy, and every time you start your application these records will be generated.
This way:
Lab.findOrSaveWhere(name:'AAAAAAAAAA')


text:
Q: Keyboard shrinks SLDS Modal Size in Salesforce1 I have a VF Page that displays Contact records and clicking on the contact it opens an slds modal in edit modal.
Its works fine in browser but in Salesforce1 ,as soon as i click an any input form element in the modal, keyboard pops up and shrinks the size of the modal and makes the modal body scrollable.
Is there any way to fix this?
ScreenShot:
http://i.stack.imgur.com/ZxfIq.png
<apex:page standardController="Account" recordSetvar="accounts" showHeader="false" standardStylesheets="false" sidebar="false" applyHtmlTag="false" applyBodyTag="false" docType="html-5.0">
  <c:RemoteTK ></c:RemoteTK>

        <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
        <link rel="stylesheet" href="{!URLFOR($Resource.SLDS0121,'assets/styles/salesforce-lightning-design-system-vf.css')}" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/>

              {{contact.LastName}}

Edit {{selectedCont.Name}}

                      Name

                          <input id="sample1" class="slds-input" type="text" ng-model="selectedCont.Name"/>

                      Account

                          <input id="sample1" class="slds-input" type="text" ng-model="selectedCont.Account.Name"/>

                      Phone

                          <input id="sample1" class="slds-input" type="text" ng-model="selectedCont.Phone"/>

                      Email

                          <input id="sample1" class="slds-input" type="text" ng-model="selectedCont.Email"/>

                <button class="slds-button slds-button--neutral" ng-click="closeModal()">Cancel</button>
                <button class="slds-button slds-button--neutral slds-button--brand" ng-click="closeModal()">Ok</button>


text:
Q: How to convert client-server chat application running on command prompt into web based application? I have made a mutiple client- server chat application using socket programming, which I can deploy on command prompt as JAR files. Now what I have to make changes to run this application on web browser using tomcat server?
My code for server:
package com.Aricent;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
import java.sql.DriverManager;

public class Server {

    static ServerSocket serverSocket=null;
    static Socket clientSocket=null;
    static final int max=20;
    static clientThread[] threads=new clientThread[max];
    public static void main(String arg[])
    {
        int portNumber=2222;
        try{
        serverSocket=new ServerSocket(portNumber);
        }catch(IOException e)
        {
            System.out.println(e);
        }

        while(true)
        {
            try{
                clientSocket=serverSocket.accept();
                int i=0;
                for(i=0;i<max;i++)
                {
                    if(threads[i]==null)// searching for empty position
                    {
                        (threads[i]=new clientThread(clientSocket, threads)).start();
                        break;
                    }
                }
                if(i==max)
                {
                    PrintStream os=new PrintStream(clientSocket.getOutputStream());
                    os.println("Server too busy. Try later");
                    os.close();
                    clientSocket.close();
                }
            }catch(IOException e)
            {
                System.out.println(e);
            }
        }
    }

}

class clientThread extends Thread
{
    String clientName=null;
    DataInputStream is=null;
    PrintStream os=null;
    Socket clientSocket=null;
    clientThread[] threads;
    int max;
    String dbPath="jdbc:mysql://172.19.24.66:3306/chatdb";
    String dbUser="root";
    String dbPass="root";

    public clientThread(Socket clientSocket, clientThread[] threads)
    {
        this.clientSocket=clientSocket;
        this.threads=threads;
        max=threads.length;
    }

    public void run()
    {

        int max=this.max;
        clientThread[] threads=this.threads;
        boolean choice=false;
        String sender="";

        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection(dbPath,dbUser,dbPass);
            PreparedStatement ps=null;
            ResultSet rs=null;
            Statement stmt=con.createStatement();
            String query="";

            is=new DataInputStream(clientSocket.getInputStream());
            os=new PrintStream(clientSocket.getOutputStream());
            String name="";
            String ch="";
            boolean login=false;
            while(!login)
            {
                os.println("*** Press 1 to login or press 2 to register***");
                ch=is.readLine();
                os.println(ch);
                if(ch.equals("1"))
                {
                    os.println("Enter your username and password...");
                    String uname=is.readLine();
                    String upass=is.readLine();
                    query="Select * from user where username= '"+uname+"' and password= '"+upass+"'";
                    rs=stmt.executeQuery(query);
                    if(rs.next() && !rs.getString("status").equals("online"))
                    {
                        query="update user set status='online' where username='"+uname+"'";
                        stmt.executeUpdate(query);
                        login=true;
                        name=uname;
                    }
                    else
                        os.println("Sorry wrong credentials");
                }
                else if(ch.equals("2"))
                {
                    os.println("Enter your username and password and emailId for registration...");
                    String uname=is.readLine();
                    String upass=is.readLine();
                    String uemail=is.readLine();
                    query="Select username from user where emailId= '"+uemail+"'";
                    rs=stmt.executeQuery(query);
                    if(rs.next() )
                    {
                        os.println("Sorry user- "+rs.getString("username")+" already registered with this mail id");

                    }
                    else
                    {
                        query="insert into user (username,password,emailId,status) value('"+uname+"','"+upass+"','"+uemail+"','offline')";
                        stmt.executeUpdate(query);
                        os.println("Registration successful...");
                    }
                }
                else
                    os.println("Wrong input");
            }

            os.println("Welcome "+ name+" to chat room. \n To leave enter: /stop \n To start private chat enter: /Private USERNAME YOUR MESSAGE \n To stop private chat enter: /endPrivate");
            synchronized(this){
                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null && threads[i]==this){
                        clientName=name;
                        break;
                    }
                }

                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null&& threads[i]!=this)
                    {
                        threads[i].os.println("*NEW USER "+name+" ENTERed CHAT ROOM*");

                    }
                }
            }

            while(true)
            {
                int pos=0;
                String line=is.readLine();
                if(line.startsWith("/stop"))
                {
                    break;
                }
                if(line.startsWith("/endPrivate"))
                {
                    choice=false;

                }
                if(line.startsWith("/Private") || choice==true )
                {
                    choice=true;
                    //String words[];
                    if(line.startsWith("/Private"))
                    {
                        //pos=2;
                         String words[]=line.split("\\s",3);
                         sender=words[1];
                        synchronized(this)
                        {
                            for(int i=0;i<max;i++)
                            {
                                if(threads[i]!=null && threads[i]!=this && threads[i].clientName.equals(words[1]) )
                                {
                                    threads[i].os.println("<"+name+">"+words[2]);
                                    this.os.println(">>"+name+" "+words[2]); //showing the sender that msg is sent
                                    break;
                                }
                            }
                        }

                    }
                    else
                    {
                    String words[]=line.split("\\s",1);
                    synchronized(this)
                    {
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]!=null && threads[i]!=this && threads[i].clientName.equals(sender) )
                            {
                                threads[i].os.println("<"+name+">"+words[0]);
                                this.os.println(">>"+name+" "+words[0]); //showing the sender that msg is sent
                                break;
                            }
                        }
                    }
                    }
                    }
                else
                {
                    synchronized(this){
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]!=null  && threads[i].clientName!=null )
                            {
                                threads[i].os.println("< "+name+" > "+line);
                                //threads[i].os.println("** The user "+name+" is leaving the chat room **");
                            }
                        }

                    }
                }
            }

            //after while
            synchronized(this)
            {
                for(int i=0;i<max;i++)
                {
                    if(threads[i]!=null  && threads[i].clientName!=null )
                    {

                        threads[i].os.println("** The user "+name+" is leaving the chat room **");
                    }
                }
            }
                    os.println("** Bye "+name+" **");

                    synchronized(this)
                    {
                        for(int i=0;i<max;i++)
                        {
                            if(threads[i]==this)
                            {
                                threads[i]=null;
                            }

                }

            }
                    is.close();
                    os.close();
                    clientSocket.close();

        }catch(Exception e)
        {
            System.out.println(e);
        }

    }

}

Code for client:
package com.Aricent;

import java.io.*;
import java.net.*;

public class Client implements Runnable {

    static Socket clientSocket=null;
    static PrintStream os=null;
    static DataInputStream is=null;
    static BufferedReader inputLine=null;
    static boolean closed=false;

    public static void main(String arg[])
    {
        int portNumber=2222;
        String host="localhost";

        try{
            clientSocket=new Socket(host,portNumber);
            inputLine=new BufferedReader(new InputStreamReader(System.in));
            os=new PrintStream(clientSocket.getOutputStream());
            is=new DataInputStream(clientSocket.getInputStream());

        }
        catch(Exception e)
        {
            System.out.println(e);
        }

        if(clientSocket!=null&&os!=null&&is!=null)
        {
            try{
                new Thread(new Client()).start();
                while(!closed)
                {
                    os.println(inputLine.readLine().trim());
                }
                os.close();
                is.close();
                clientSocket.close();
            }catch(IOException e)
            {
                System.out.println(e);
            }
        }

    }

    //@Override
    public void run() {
        // TODO Auto-generated method stub

        String responseLine;
        try{
            while((responseLine=is.readLine())!=null)
            {
                System.out.println(responseLine);
                if(responseLine.indexOf("*** Bye")!=-1)
                    break;
            }
            closed=true;
        } catch(Exception e)
        {
            System.out.println(e);
        }

    }

}

My main query is how to introduce socket programming in local tomcat server?

A: I posted the complete solution few years ago, but it uses nodejs for server. Building a chat app that uses a node.js server in IOS. This app uses server push technology (web sockets).
If you would like to migrate your current code is the browser as it is, you will have few weeks of work only with adapting the server thread to work with HTTP from the browser. Browsers communicate with servers via HTTP protocol, which is one layer above your current solution. Your solution is using plain network sockets.
You can however build a long polling type of application with servlets on Tomcat and normal web application that repeatedly checks server for new chat messages (new request every few seconds), or experiment with latest Tomcat's Websocket support. There is example chat application in Tomcat's samples. Download zip, see  /apache-tomcat-8.0.35/webapps/examples/websocket/.

A: Your application doesn't rely on any standard protocol at all. So you'll have to recreate your client from the scratch using Javascript (to make it a web application).  And it will be a problem to make direct socket connections from browser using javascript (once you go out of localhost connections you will be under browsers security limitations).
As a strait-forward approach: run server as jar application, and client - custom Applet (Oh! that is so 90's - 00's). And I guess in year or two Applets become obsolete.
It would be better if you rewrite your application using something more standard, like STOMP over WebSockets. Then your server could be deployed into servlet container like Tomcat or Jetty.  And your client would be anything that supports websockets and STOMP.
From what I have seen your application has authentication and chat-rooms.  It is  better to deliver authentication and authorization to custom framework (anything you like, simply provide additional headers in websocket connections to merge WS connection and established session). And Chat-rooms in STOMP words become destinations.  So you would need to create app that is reacting on messages arriving on stomp destinations.
I would recommend for you to look at spring framework and its support for websockets.
Also, what I have seen you are establishing separate database connection per each user session, what in general is lavish use of resources. Create pool of connection and use one of them only when it is needed.

A: You could use pusherjs if you use NPM. Pusherjs has a free plan and it takes away the headache of creating and managing socket connections. Each user can be assigned individual channels(free plan supports unlimited channels) and messages just need to be submitted to that channel and you can have the client app continuously listen on that channel. Its very very easy.


text:
Q: Django: Reverse for 'thread' with arguments '(1,)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P[0-9]+)/\\Z'] I have tried to use two primary key at urls.py path but when I am using that  in template I cannot access that second primary key.
URL example: forum/1/2
urls.py
path('<int:forum_id>/<int:thread_id>/', views.thread, name='thread'),

views.py
def forum(request,forum_id):
    forums = get_object_or_404(ForumModel, id=forum_id)
    threads = ThreadModel.objects.filter(forum=forums)
    context={'forums':forums,'threads':threads}
    return render(request,'forumdetail.html',context)

def thread(request, thread_id):
    thread = get_object_or_404(ThreadModel, id=thread_id)
    posts = PostModel.objects.filter(thread=thread)
    context={'thread':thread,'posts':posts}
    return render(request,'threaddetail.html',context)

template

{% for thready in threads %}

{{ thready.title }}

{% endfor %}


text:
Q: unable to locate element by XPATH on Tripadvisor I don't know how to click on this image, I tried many things but it doesn't work. That says the XPATH is wrong.
what I want to click :

my code :
# TripAdvisor
driver.get("https://www.tripadvisor.fr/")
time.sleep(0.5)
driver.implicitly_wait(3)
driver.find_element(By.XPATH, '//*[@id="onetrust-reject-all-handler"]').click()
time.sleep(1.5)
driver.implicitly_wait(3)

if choices == "r":
    driver.find_element(By.CSS_SELECTOR, '#lithium-root > main > div.cBOoN > div.rGQXC._T.ivvQp > div > div > div:nth-child(4) > a').click()
    driver.implicitly_wait(1)
    driver.find_element(By.XPATH, '/html/body/div[3]/div/form/input[1]').send_keys(city)
    time.sleep(0.75)
    driver.implicitly_wait(2)
    driver.find_element(By.XPATH, '//*[@id="typeahead_results"]/a[1]').click()
    driver.implicitly_wait(2)
    try:
        driver.find_element(By.XPATH, '//*[@id="onetrust-reject-all-handler"]').click()
    except:
        pass

    time.sleep(2)
    driver.find_element(By.XPATH, '//*[@id="component_48"]/div/div[2]/div[2]/div[3]/div/label').click()
    time.sleep(1)
    driver.implicitly_wait(2)
    driver.find_element(By.XPATH, '//*[@id="component_36"]/div[1]/div[1]/div/span[2]/span').click()
    time.sleep(1)
    driver.implicitly_wait(2)
    driver.find_element(By.XPATH, '//*[@id="component_48"]/div/div[2]/div[2]/div[1]/div/label').click()
    driver.find_element(By.XPATH, '//*[@id="component_48"]/div/div[2]/div[2]/div[2]/div/label').click()
    time.sleep(2)
    driver.implicitly_wait(2)
    driver.find_element(By.XPATH, '//*[@id="component_2"]/div/div[1]/div/span/div[1]/div[1]/span[2]/a').click()

I also tried with coordinates but that don't work.
Thank you for anyone who helps me.

A: You need to improve your locators and use WebDriverWait expected_conditions explicit waits instead of driver.implicitly_wait.
the following code works:
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 10)

url = "https://www.tripadvisor.fr/"

driver.get(url)
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@data-test-target='nav-links']//a[contains(@href,'Restaurants')]"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[data-test-attribute*='RESTAURANTS'] input[type='search']"))).send_keys("Paris")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#typeahead_results a[href*='Restaurants']"))).click()
time.sleep(1)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for='checkbox_5']"))).click()
time.sleep(4)
wait.until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(),'Supprimer tous les filtres')]"))).click()
time.sleep(2)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for='checkbox_3']"))).click()
time.sleep(2)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label[for='checkbox_4']"))).click()
time.sleep(2)
wait.until(EC.presence_of_element_located((By.XPATH, "//a[contains(@href,'Review-')]//div[contains(@class,'carousel')]//span[@class]"))).click()

A: instead of digging through divs, you could try looping through elements that match a more specific xpath, like this
//a[contains(@href,"html")]//descendant::img[contains(@src,"https://media-cdn")]


text:
Q: MySQL unknown column ERROR I am getting an unknown column in the applicant table when I try and execute this statement. I am trying to update this column consistent with the rest of the database.
  UPDATE APPLICANT SET totskills
   = (SELECT count(sname) FROM SPOSSESSED
   WHERE SPOSSESSED.anumber = APPLICANT.anumber);

I am new with using MySQL, is this because I need to be joining the applicant class? If so, how would it be written. Thank you

A: Can you search if there is a column with the exact name as SPOSSESSED.anumber in your table , its seems that is not there that's why


text:
Q: IOS view updates to default IB layout whenever an action is fired I have a project that has most of its layout logic in the IB.  Some of the positioning I want to update dynamically so I put it in the viewDidAppear:
- (void)viewDidAppear:(BOOL)animated{
// Fill array of button tools
buttonArray = [[NSArray alloc] initWithObjects:
               self.filterButton, self.bulgeButton, self.stickerButton, self.textButton, self.drawButton, self.invertedBulgeButton, nil];

// Position button tools
int const X_POSITION = 175; // The x position of the tool buttons
int yPosition = 0; // The x position of the tool buttons
CGRect frame = CGRectMake(X_POSITION, yPosition, 100, 100); // The position and size of the tool buttons

// Loop through buttons and set properties
for (UIButton *button in buttonArray) {
    frame.origin.y = yPosition;
    button.frame = frame;
    yPosition += 75;
    button.hidden = false;
}
}

The problem I have is that whenever I press another button all the formatting I applied in the viewDidAppear is undone and the buttons positioning are changed to what they are in the IB.   How can I prevent my buttons from moving to the locations set in the IB?
edit: Here is some of the code that will cause the positioning to change:
// Undoes most recent edit to photo
- (IBAction)undoButtonPress:(id)sender {
    [self undoImage];
}

- (void)undoImage {
    // TODO:  Add all the other current actions.... none of them work because they need to be checked for here
    // Remove tools for the current action
    self.imageSticker.image = nil;
    [self refreshImageText];

    currentAction = NONE;
    self.mainImage.image = [_images pop];

}
// after done editing the text, this resets the text fields so you can create a second text
- (void) refreshImageText{
    self.hiddenTextField.text = @"";
    self.imageText.text = @"";

    self.imageText.transform = CGAffineTransformMakeRotation(0);
    [self.imageText setCenter:self.view.center];
}

A: You'll need to update the constraints, not the actual frames of your objects. So if you add your button frame y constraints as an IBOutlet you can edit it easily.
Here is a really cool tool to play with autolayout constraints:
https://autolayoutconstraints.com/

A: I found out that it is AutoLayout that is messing with my positioning.  I was able to set translatesAutoresizingMaskIntoConstraints to true to prevent AutoLayout from messing with my settings:
// Loop through buttons and set properties
for (UIButton *button in buttonArray) {
    frame.origin.y = yPosition;
    button.frame = frame;
    yPosition += 75;
    button.hidden = false;
    button.translatesAutoresizingMaskIntoConstraints = YES;
}


text:
Q: ASP.net4 sql connection issues Okay, some background first:
I have 2 servers at home, 1 of them runs the Webserver, while the other one is pretty much a data server.
Both of these servers have 2 Gigabit lan ports.
Lan port 1 on both servers are directly connected to the internet.
while Lan port 2 is connecting the two of them together.
(See Schematic: Schematic http://www.swan10.nl/stuff/schematic.png
This works all perfectly fine when I turn the internet connection off on one of these machines. However when I turn the internet connection on on both of these machines the Web server tries to obtain it's data through the internet connection, but I don't allow the SQL server to be seen over the internet.
Now I was wondering if it is possible to tell the Web server which connection to use, because I need both of these devices to have an independent internet access. So telling the Webserver to use connection 1 (internet) for just the internet connections, and use Connection 2 (link) solely to connect to the SQL server/Data Server
Both computers have their own static public WAN IP they are directly connected to the internet, they are also directly connected to each other, there is no router in-between them. So far i only managed to make it work when i made the SQL server visible to the internet which is not what I want.
Any help regarding this would be very much appreciated, thank you in advance.
ADD:
I have already tried various answers posted on the internet, I also tried and see if the SQL server is actually listening which it is, it just uses the wrong connection if both are connected independantly to the internet and to each other.

A: Make sure you use IP instead of Server Name in the connection string when using mentioned set up.
Thank you "Paige Cook" for refreshing my memory, and pretty much supplying me with my own answer!


text:
Q: SQLite getting ArrayList to display in a textview I'm having trouble getting my ArrayList from my SQLite database to display in a textview. The idea is to make it a "history" page so users can see their past entries. When I do tv.setText(db.getAllBalance), all I get is a crash and the logcat displays my projects package name followed by something like @4f58a392 over and over. This is my final step to complete my app, and it's struggling. Any assistance would be appreciated.
My database:
//Getting All Balance
public List<Balance> getAllBalance(){
    List<Balance> balanceList = new ArrayList<Balance>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_BALANCE;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Balance balance = new Balance();
            balance.setID(Integer.parseInt(cursor.getString(0)));
            balance.setAmount(cursor.getFloat(1));
            // Adding balance to list
            balanceList.add(balance);
        } while (cursor.moveToNext());
    }

    // return contact list
    return balanceList;
}

My history class:
public class History extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.history);

        final DatabaseHandler db = new DatabaseHandler(this);

        TextView tv = (TextView) findViewById(R.id.tvSQLinfo);

        Log.d("testing", "reading wallet " + db.getAllBalance());
        tv.setText((CharSequence) db.getAllBalance());
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        AdView adview = (AdView) findViewById(R.id.adView);
        AdRequest re = new AdRequest();
        //re.setTesting(true);
        adview.loadAd(re);
    }
}

I have a bad history of posting "bad questions". But I promise, I searched and searched and just could not find the solution.

A: You are returning a List in the getAllBalance(), and then you are casting it to a CharSequence. You can try to do a toString() call after getAllBalance() to try to get some String representation of the object. Remove the cast to CharSequence; toString() if you use `toString()'


text:
Q: How to enable animated page transitions with Phonegap + JQuery Mobile? Per the JQuery Mobile documentation ...

To enable animated page transitions, all links that point to an
  external page (ex. products.html) will be loaded via Ajax

How, if it is even possible, can one enable page transitions when building a Phonegap application where all the pages are local rather than sitting on a web server?

A: There isn't a difference if AJAX is loading from local file or web (except if web you need to whitelist the domains).
By default Phonegap/Cordova for iOS loads from www/index.html.
Here is an example with 2 pages, with in-line data attributes for the transitions.
First page, page1.html

...

    Local on same page

    same page

    Local in another page

    new page

    Same Page

...

A separate file page2.html.

    Page 2


text:
Q: speed up python3 np.where operation I wonder that is there anyway to speed up python3/numpy's np.where operation? I have a minimal working example as follows:
from time import time
import numpy as np

a = np.random.randint(0, 4, (768, 512, 512))
b = a.copy().astype(np.uint8)
c = b.copy()
print(a.shape)

ts = time()
a[a > 0] = 1
print(f'normalize in {time() - ts}s')

ts = time()
b[b > 0] = 1
print(f'normalize in {time() - ts}s')

ts = time()
c = np.where(c > 0, 1, c)
print(f'normalize in {time() - ts}s')

and the output is:
normalize in 0.9307191371917725s
normalize in 0.8891170024871826s
normalize in 0.7120938301086426s

as we can see that np.where gives the fastest result but it still pretty slow, as in my project I need to do such normalize operation about 50 times...
I am wondering that is there any faster way to do this? All I need is to convert any non-zero elements to 1. Thx!

A: The best way to accomplish your operation is to convert the matrix to the boolean datatype and then back to integer, especially if 8-bit integers are used:
import numpy as np
import timeit

a = np.random.randint(0, 4, (768, 512, 512))
a_short = a.astype(np.uint8)

# Time to initialize
%timeit b=a.copy()
201 ms ± 561 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit b=a.copy(); b=b.astype(bool).astype(int)
373 ms ± 347 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit b=a.copy(); b=np.where(b>0,1,b)
985 ms ± 150 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit b=a.copy(); b[b>0]=1
1.09 s ± 1.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# Time to initialize
%timeit b=a_short.copy()
26.7 ms ± 202 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

The best of the best:
%timeit b=a_short.copy(); b=b.astype(bool).astype(np.uint8)
77.5 ms ± 47.8 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit b=a_short.copy(); b=np.where(b>0,1,b)
570 ms ± 476 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit b=a_short.copy();b[b>0]=1
844 ms ± 4.09 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: You could try with numexpr:
import numpy as np
import numexpr as ne

# for timing reference
a = np.random.randint(0, 4, (768, 512, 512))
%timeit a[a > 0] = 1

782 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
a = np.random.randint(0, 4, (768, 512, 512))
%timeit a = ne.evaluate("where(a > 0, 1, a)")

254 ms ± 2.65 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Or with Numba:
import numba as nb

@nb.jit(nopython=True, fastmath=True, parallel=True)
def n(x):
    for a in nb.prange(x.shape[0]):
        for b in range(x.shape[1]):
            for c in range(x.shape[2]):
                if x[a,b,c]>0:
                    x[a,b,c]=1
    return x

# You should do this twice as it gets compiled first time through
%timeit c = n(a)
# Also, try re-assigning back on top of original, i.e. a=n(a)

113 ms ± 551 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


text:
Q: The User UID is not the same with document id in Firestore Android I have created a function to add a new user to Firestore Database:
public void addNewUser(String email, String username, String profile_photo){
        FirebaseFirestore db = FirebaseFirestore.getInstance(); // this is instantiated here, just to show you
        User user = new User(userID, (long) 1, email, StringManipulation.condenseUsername(username), username, profile_photo);

        db.collection("Users").add(user)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "Error adding document", e);
                    }
                });
    }

And a function to fetch the data from the database, waiting for all the fields to appear in-app.
public UserSettings RetrieveUserSettings(){
        Log.d(TAG, "getUserAccountSettings: retrieving user account settings from firebase");

        User settings = new User();
        DocumentReference userRef;
        FirebaseAuth firebaseAuth=FirebaseAuth.getInstance();

                try {
                    userRef = db.collection("Users")
                                .document(firebaseAuth.getCurrentUser().getUid());

                    userRef.get()
                            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                                @Override
                                public void onSuccess(DocumentSnapshot documentSnapshot) {
                                    if(documentSnapshot.exists())
                                    {
                                        settings.setDisplay_name(documentSnapshot.getString("display_name"));
                                        settings.setUsername(documentSnapshot.getString("username"));
                                        settings.setProfile_photo(documentSnapshot.getString("profile_photo"));
                                        settings.setEmail(documentSnapshot.getString("email"));
                                        settings.setPhone_number(documentSnapshot.getLong("phone_number"));
                                        settings.setUser_id(documentSnapshot.getString("user_id"));
                                    }
                                    else{
                                        Log.d(TAG, "doc not fount in getUserSettinghs ");
                                    }
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Log.d(TAG, "onFailure: failed to fetch data");
                                }
                            });

                } catch (NullPointerException e) {
                    Log.d(TAG, "getUserAccountSettings: NULLPointerException: " + e.getMessage());
                }
                Log.e(TAG, "getUserAccountSettings: retrieved user_account_settings information: " + settings.toString());

        return new UserSettings(settings);
    }

When I authenticate, this is the User UID that is generated: E5bBL0D9lCSKy5a0YdUJjuMVuUT2, but when I call the addNewUser function, my Firestore Database looks like this :
, so it is obvious that the User UID generated at authentication is not the same with the document id, which is :
XWwnRBklieJXSxokQuNe.Do you have any idea why this is happening?

A: As @HenryTwist mentioned in his comment, when using the following line of code:
db.collection("Users").add(user).addOnSuccessListener(/* ... /*);

You are adding a new "User" object to the "Users" collection using a random ID. The above line of code does the same thing as:
db.collection("Users").document().set(user).addOnSuccessListener(/* ... /*);

When you call CollectionReference's add() method or CollectionReference's document() method without passing any parameters, the built-in generator used by Firestore will always generate a random ID each time one of the methods is called.
As I see from the following line of code:
userRef = db.collection("Users").document(firebaseAuth.getCurrentUser().getUid());

You have already implemented Firebase Authentication, which is good. That being said, when you want to add new "User" object to the database, use the UID that comes from authentication process, as shown below:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
db.collection("Users").document(uid).set(user).addOnSuccessListener(/* ... /*);

In this way, the ID of the document will match the value of the "user_id" property in the database.


text:
Q: How to export my html to pdf and download it? I searched for topic to how export my html and found no simple solution! Why i have to write tons of codes and download some secondary staff? Here is my div id 'table' and i want to download it as pdf! How i can do it!?

A: I might be missing the idea here, but why not open the source code, go to print and do save as PDF?
In chrome you would right click on your page, click on "view page source" then go to print and select save as pdf.


text:
Q: Android NDK NativeActivity Memory Management Needed? I'm using NativeActivty with native_app_glue to program an OpenGL game for Android. It is hard to determine when is the best time to delete heap allocated objects and objects allocated by OpenGL.
In the NDK's NativeActivity sample they don't seem to delete objects after they are done with them. Right now I delete my objects with two delete functions: one for OpenGL objects and a regular one. I split them up because it seems only the event handling thread can delete OpenGL objects. Regular objects I allocate are deleted by the normal delete function.
When the user presses the back button and comes back to the app, the OpenGL resources are deleted and the app crashes (although I would think they should be reallocated by APP_CMD_INIT_WINDOW). This causes me to wonder if I should be deleting objects at all because it appears I should not delete OpenGL objects.
Are we supposed to delete heap allocated objects with the NDK. I understand that NDK apps are still sandboxed and have a JVM process, does this take car of memory management?
EDIT:
Another instance of my application crashing is when objects are deleted when a game state finishes. For example going from the actual game to the menu. Upon going back to the game the application crahses, even though the objects are reallocated. It only seems to work once.

A: It turns out the application crashing was never due to the deletion of heap allocated objects or OpenGL objects. Some pointers that were deleted but still contained in a vector were the cause of the problem. However it appears there is nothing wrong with deleting objects with the NDK.