text:
Q: Why doesn't JavaScript warn me when I use arr.lenght (misspelt) instead of arr.length in a loop? I also use strict mode I spent hours just to find out that I misspelt the word .length as .lenght. It can run normally with no warning at all. Why...?
I use 'use strict' and run on Node.js 10.13.0.
Code:

'use strict';
let arr = [1, 2, 3, 4];
for(let i = 0; i < arr.lenght; i++) {
  console.log(arr[i]);
}

A: Why
Standard JavaScript arrays aren't really arrays at all¹, they're objects, and if you read an object property that doesn't exist (like lenght), you get the value undefined (even in strict mode):

console.log(({}).foo); // undefined

When you use undefined in a relational operation like < or > with a number, it gets converted to a number, but the number value it gets is the special number NaN, which has the bizarre property of always causing comparisons to be false:

console.log(NaN < 0);     // false
console.log(NaN > 0);     // false
console.log(NaN === 0);   // false
console.log(NaN === NaN); // false!!

What you can do about it
Linter tools will often pick these things up in simple cases.
Alternately, TypeScript provides a full static typing layer on top of JavaScript which can catch these sorts of errors.
If you wanted (and this would probably be overkill), you could wrap a Proxy around your objects that threw a proactive error when you tried to read a property that didn't exist:

function proactive(obj) {
  return new Proxy(obj, {
    get(target, propName, receiver) {
      if (!Reflect.has(target, propName)) {
        throw new TypeError(`Property '${propName}' not found on object`);
      }
      return Reflect.get(target, propName, receiver);
    }
  });
}

const a = proactive(["a", "b"]);
a.push("c");
for (let i = 0; i < a.length; ++i) {
  console.log(a[i]);
}
console.log(`Length is: ${a.lenght}`); // Note the typo
.as-console-wrapper {
  max-height: 100% !important;
}

There's a significant runtime penalty, though.

¹ (that's a post on my anemic little blog)

A: Because when you try to get a property that doesn't exist, it returns undefined, and 0 < undefined is false.

let arr = [1, 2, 3, 4];
console.log(arr.lenght) // undefined
console.log(arr.qwerty) // undefined
console.log(arr.lenght < 9999) // false
console.log(arr.lenght > 9999) // false

arr.length = 7 // <-- it's not a good idea
for(let i = 0; i < arr.length; i++) {console.log(arr[i])}

EDIT
I said 'javascript is not a strongly typed language' and it is true. But this way of adding new properties it is a feature of prototype-based programming, as @Voo said.
I also said .length=7 it's a bad idea. After reading a little more, in this case I still think it's a little weird to increase the length property after adding elements. Maybe it's fine to truncate, delete elements or empty an array, although in the latter case I would prefer arr=[] instead of arr.length=0.
There are some interesting examples about length property in the Mozilla documentation.

A JavaScript array's length property and numerical properties are
  connected. Several of the built-in array methods (e.g., join(),
  slice(), indexOf(), etc.) take into account the value of an array's
  length property when they're called. Other methods (e.g., push(),
  splice(), etc.) also result in updates to an array's length property.
var fruits = [];
fruits.push('banana', 'apple', 'peach');
console.log(fruits.length); // 3

When setting a property on a JavaScript array when the property is a
  valid array index and that index is outside the current bounds of the
  array, the engine will update the array's length property accordingly:
fruits[5] = 'mango';
console.log(fruits[5]); // 'mango'
console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
console.log(fruits.length); // 6

Increasing the length.
fruits.length = 10;
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 10

Decreasing the length property does, however, delete elements.
fruits.length = 2;
console.log(Object.keys(fruits)); // ['0', '1']
console.log(fruits.length); // 2

A: You could easily add new properties to arr object, JavaScript won't warn you about it, instead it will try to find the property you're calling, and if it didn't find anything such result will be undefined, so the comparison is actually i < undefined everytime because you're calling a property that hasn't been created on the object. I'll suggest you to read What does "use strict" do in JavaScript, and what is the reasoning behind it?.

A: The upper bound of the loop is specified as lenght, a typo for the local variable length. At runtime, lenght will evaluate to undefined, so the check 0 < undefined is false. Therefore the loop body is never executed.

A: JavaScript arrays are treated as objects (though they are instances of Array). Hence, when you write arr.lenght, it treats lenght as a property of an object that is undefined. Hence, you don't get an error.
It simply tries to get a property that is undefined. Also, in your case, the loop just does not execute as the condition of the loop is never satisfied.

A: By default, all objects in JavaScript are extensible, which means that you can add additional properties to them at any time simply by assigning a value to them.
Arrays are no different; they're simply objects that are instances of the Array type (at least for the purposes of extensibility).
In this case, had you added:
Object.preventExtensions(arr);

after creating the array, then in combination with 'use strict' this would have raised an error -- had you tried to write to a typo'd property.  But for a read usage like this, there is still no error at all; you just get undefined.
This is just one of the things you have to live with in a loosely-typed language; with the added flexibility comes added risk of bugs if you're not careful.


text:
Q: How to load js files with multiple functions (of the same name per file) in java/graalvm and invoke functions by file name I have a server application that loads several script files (for processing specific dataset-fields) at startup. the scripts should be parsed and the "expression"-data of the script should be stored in a map (by column name) so that they can be accessed and executed from there later.
There are two types of scripts. The "simple" ones just contain a process function, the complex ones currently have a structure similar to the example below (might have more private functions/fields):
// public
function process(input) {
    return _doSomething(input);
}
function selfTest() {
    if (process("123") !== "123") throw "failed";
    // ...
}

// private
var _allowedSymbols = ['H', 'L', 'M'];
function _doSomething(input) {
    // _allowedSymbols is used here
}

process and selfTest are the "public" functions that will be used by the server-app. selfTest will be executed once after the file is loaded/evaluated and process will be executed for incoming data when needed.

I've started with the old JSR 223 way:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js");
engine.eval("function process(input) { return input.toUpperCase(); }");
// engine.eval("function process(input) { return input + '123'; }");
Invocable inv = (Invocable) engine;
Object result = inv.invokeFunction("process", "peter");

This approach has the problem that the function-data is stored in the javascript engine instance and therefore i can't have multiple "process" methods in my map.
I Could continue that way and dynamically generate name-prefixes for functions and global variables based on the column name... but thats... "ugly"...

I've tried the graalvm-context-way (with help from SO and Oleg, How to store function handles from ScriptManager for later usage?):
var ctx = Context.newBuilder("js").allowAllAccess(false).build();
var src = Source.newBuilder("js", "(function u(input) { return input.toUpperCase(); })", "test.js").build();
var script = ctx.eval(src);
var result = script.execute("peter");

That works for "simple" functions. But for complex scripts the function-expression way from above doesnt work.

EDIT (Solution):
Modified the answer from Oleg slightly and this seems to do the job...
var jsCode = """
(function() {
    function process(input) { return input; }
    function selfTest() { if (process("123") !== "123") throw "failed"; return true; }
    return { process, selfTest };
})();
             """;
var ctx2 = Context.newBuilder("js").allowAllAccess(false).build();
Source source = Source.newBuilder("js", jsCode, "test.js").build();
var script = ctx2.eval(source);
var fnProcess = script.getMember("process");
var result = fnProcess.execute("123");
var fnSelfTest = script.getMember("selfTest");
var result2 = fnSelfTest.execute();

A: It's either functions are declared in the top level namespace, and then name collisions are a problem, or they are in their custom scopes and then you have to have some way to access and call them.
When you're evaluating a source like that:
(function u(input) { return input.toUpperCase(); })

The result of that evaluation is the last expression in the script.
You can think of the line:
var result = ctx.eval("js", "(function u(input) { return input.toUpperCase(); })");

Approximately as if it'd be in JS like:
result = (function u(input) { return input.toUpperCase(); })

And consequently, you can run it with:
result("HelloWorld");

That means you can return multiple functions using helper objects:
// public
function process(input) {
    return _doSomething(input);
}
function selfTest() {
    if (process("123") !== "123") throw "failed";
    // ...
}

// private
var _allowedSymbols = ['H', 'L', 'M'];
function _doSomething(input) {
    // _allowedSymbols is used here
}

returnMe = {process, selfTest};

Which is exactly what you'd do in JavaScript (I think).
Then you can either get the process function with
var returnedObject = ctx.eval(src);
var processFunction = returnedObject.getMember("process");
var result = processFunction.execute("peter");

And similarly access the selfTest function.
It might not be ideal that you need to modify the JS sources for that, but I think that's necessary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Checkbox that adds a class to tr in which it is located Structure of my table looks like this. How to make that if the input is checked it will add a class "selected" to
  in which it is located ? And if the checkbox will be unchecked it will remove class "selected" from
 ? Please help me :)

    <input type="checkbox">

    tryb
    png

    <input type="checkbox">

    test
    png

[..]

A: You bind an onchange event to the checkbox:
$("input[type=checkbox]").change(function () {
    $(this).closest('tr').toggleClass('selected', this.checked);
}).change(); // manually trigger change after the binding

Each time the checkbox changes, you set the parent row to selected based on the checked status.

A: This is easy.
$('input[type=checkbox]').change(function(){
    if(this.checked)
        $(this).closest('tr').addClass('selected');
    else
        $(this).closest('tr').removeClass('selected');
});

A: you can do like this:
$(':checkbox').change(function () {
  $(this).parent().toggleClass('selected');
});

References:

*

*toggleClass()

*change()


text:
Q: Creating proxy between application queries and Internet Is it possible (for example with C++, but it does not really matter) to create a bridge/proxy application to get the data requested by another application? To be more detailed, I'm talking about a Adobe Air based game. (I want to create a report with stats based on the data acquired, but that is not actually part of this question.)
Rather than simple "boolean" answer please provide some link to example/documentation. Thanks

A: It would always be possible, and depending on the your target operating system, may require a fair amount of effort, which begs the question - is there a reason you cannot use Fiddler or some packet sniffing software for your target OS?

A: You can write a proxy by hand, in python can be quite easy. All you have to do is to set localhost as proxy, then forward the request and pass it back to the calling socket.
I've started writing something like this some times ago. The idea was to write a simple replacement for dansguardian.
I've uploaded it on github so you can give it a look if it can help.
I do not remember well (I've started writing it the last year) but maybe with some modification can fit well your requests.

A: Conceptually, this is your configuration:
app_client -> [app_channel] -> proxy ->  [server_channel] -> app_server

Your proxy starts a server socket, the app_client connects to it. This is our app_channel. Now your proxy creates a connection to the app_server. This is your server_channel.
Now start 2 threads, one which reads from the app_channel and writes to the server_channel, the other reads from the server_channel and writes to the app_channel.
This will create a transparent connection to the app_server via your proxy. You can extract the data as you wish. If the data is encrypted though, there's very little you can actually do by way of analysis.


text:
Q: Can I use Azure IoT Hub as a MQTT bridge? I have some devices that sends their data to my Azure IoT Hub. For now, a Stream analytics job processes the data, but I would also like to "forward" the data stream to an external Mosquitto server. How can I do that? Can I set up the IoT Hub to function as a MQTT Bridge?
Thanks in advance for help! (Sorry, I'm a little new to this...)

A: One option: You can use Azure Functions to process the incoming data and forward it to your Mosquito server.


text:
Q: Find Custom (changing) Image in other Image I need to detect a specific shape that I generate from a Image in a bigger Image.
Here is an Example of that:

For Explanation: I have a picture of 2 identical Parts, but one Part is flipped upside down. Now I want to detect the Orientation of the Parts via Python. The tricky part is, that the parts that I want to detect can sometimes lay a little bit different on the image.
What I already tried:

*

*Multi Score Template Matching

*Multi Scale Template Matching

*Feature Matching

*Depth analysis

Note that The angle, in which the photo is taken of the sample image and the to detect parts will be the same eventually.
I think the most discrete feature is the orientation of the gaps in the part. If they are pointing upwards the sample is in the TOP position but if they are pointing down, the sample is in BOTTOM position.
Do you guys have any leads as to how I can do that? Is there a Way in OpenCV?

A: The centroid of the black pixels appears higher (relative to the longest diametric line of the shape) in the images labelled "top" and lower (relative to that line) in the images labelled "bottom".
Maybe do some analysis of the moments with cv2.moments().


text:
Q: Baloney detection kit for Math There are folks who claim they proved Fermat's Last Theorem, Riemman Hypothesis offering no more than a half a dozen pages (sometimes one or two pages) of proof, very few if any citations of previous works (where are the giants whose shoulders they stepped in?), among other suspicious characteristics.
I am not suggesting the one can measure the quality of a work by their number of pages alone, but for problems like those I mentioned, common sense suggest that their proofs must be really very complex and probably very long because if they were so simple as to be solved in a few pages, then someone would have discovered how to solve them much before the genius of Wiles or Perelman.
I also have seen various things like functions, theorems, etc which carries the name of its discoverer and that are considered by some to be trivial or/and of dubious importance for Math.
It is easy for a professional mathematician to the faults in those works and sometimes it is not too difficult for someone like me, that have little knowledge of math to see some faults, for they are common outside math, like lack of references.
What worries me is that if some particular work deals with advanced Math, it is not obvious for almost everyone if the work has or has not value, more or less like the Bogdanov affair. The Bogdanovs write about something that has a jargon and concepts so complex/advanced that seemed esoteric or post-modern to almost anyone, so in the absence of another easily identifiable clues one cannot see the work's real value unless that one is very well-versed in whatever the work deals with and those are unfortunately few.
This being so, I can elaborate the question: has someone designed a baloney detection kit specific/optimized for math, that can help in identifying if not all, most of the Math works that have no value even if they seemed at first sight elaborate, serious and erudite?
I can risk some opinions: lack of formalism, non-trivial notions that are not properly explained/defined, incomplete reasoning which omits intermediate calculations/deductions that are also non-trivial. But that is not specific to Math but for other sciences too.

A: Behold, the Aaronson crank detector kit:
http://www.scottaaronson.com/blog/?p=304
This is directed at complexity theory (in CS) but that doesn't make a difference.

A: In addition to the "crank detector" listed in Sam's answer, we also have a couple of "crackpot indices:"
http://primes.utm.edu/notes/crackpot.html
http://math.ucr.edu/home/baez/crackpot.html (for physics, but still applies)

A: Let me play the Devil's advocate here. It's my personal opinion that such a "kit" can't exist. Hardy almost threw Ramanujam's letter before he detected its value.
Galois's work was not taken seriously by leading mathematicians.
Also, sometimes there are genuine mistakes in proofs that can't be fixed- but we do get some insights into the problem, esp. if the work is by a leading mathematician. At least we know one more approach that looked promising, and yet was wrong. These are small but significant progresses.
Of course, cranks exists aplenty, but if a crank detector mechanically threw away Ramanujam's or Galois's works, then the world would be much poorer.


text:
Q: Do municipal airports connect cities similar to rail and roads? Just looking for a bit of clarification. If I build municipal airports, do they connect cities across the region when those cities are not connected by rail or road?

A: The municipal airport provides limited functionality when connecting cities. It does not allow the exchange of utilities such as power, water, and sewage because those agents move via road. It also does not allow you to share city services, as those need to travel along roads. It will however, allow workers, shoppers, and tourists to move between cities. It will also ship Freight between cities.
It will raise the happiness of any industrial buildings in proximity, but make any residents nearby unhappy presumably due to noise.
It can be expanded to generate more tourists and higher wealth tourists as well, in fact, adding a municipal airport (or the international airport great work)seems to be the single best way to increase high income tourist traffic.


text:
Q: Compile::cplist: error from MapThread What is the cause of this error?
Compile[{{r, _Integer, 2}, {d, _Integer, 2}},
  pos = Position[MapThread[#1 > #2 &, {r, d}, 2], x_ /; x == True]]

Compile::cplist: MapThread[#1 > #2&, {r, d}, 2] should be a tensor of type Integer, Real, or Complex; evaluation will use the uncompiled function. >>

A: Compile[{{r, _Integer, 2}, {d, _Integer, 2}},
 a = Position[Sign@MapThread[#1 - #2 &, {r, d}], 1]
 ]


text:
Q: GIF files are not animated in the Swiper slider I need gifs to be animated always. When the page loads, the gif animates for the first second, and then stops. In order for it to start, I have to press the left mouse button.
When I remove the cursor from the image, it becomes inactive again.
What can be done to make gifs animated? What are the ways to solve this problem.

var swiper = new Swiper('.swiper-container', {
        effect: 'cube',
        grabCursor: true,
        slidesPerView: 'auto',

        cubeEffect: {
           shadow: true,
           slideShadows: true,
           shadowOffset: 50,
           shadowScale: 0.3,
           centerSlidesBounds: true,
        },

        direction: 'horizontal',
        loop: true,

        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        pagination: {
            el: '.swiper-pagination',

        },

        });
.main {
  position: absolute;
  //padding: 16px;
  //margin-top:60px;
  width: 50%;
}

.swiper-button-prev{
left:  2%;
}

.swiper-button-next{
left:  92%;
}

.swiper-pagination-bullets.swiper-pagination-horizontal {
  width: 100%;
  bottom: -25%;
  position: relative;
}

.left-element {
    background: silver;
    display: inline-block;
    position: absolute;
    left: 100%;
    width: 80%;
    margin-top: 0;
}
h1.left-element {
width: 80%;
height: 90%
}

 img{
width: 100%;
height: 100%;
}
<!DOCTYPE HTML>

  <title>Gif</title>
  <link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css">

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

12345


text:
Q: Use command options (like -f) from Perforce Visual Client I get an error while adding few files to Perforce which has WILDCARD characters in their name. The error is clear, asking to use the '-f' option while running p4 add.
Now I am using the p4 visual client app on my work machine and could not find a way to add options while running the command. Is this something that we can do only on the command line ?
P.S -  I am on a corporate network. And I don't have rights to install softwares freely from internet and as such can't install the perforce command line.

A: P4V should give you the option to add the files (i.e. it should use the -f option for you when appropriate).  If it's instead giving you the command line error message that sounds buggy; I'd recommend raising it with Perforce tech support.
I would also recommend negotiating with your IT team to allow you to install the p4 command line tool; if they've already approved P4V there's no earthly reason to not approve P4 (which is just a very thin wrapper around the p4 client libraries that P4V is built on, and also completely open-source so therefore easily auditable).  Once you're able to run the appropriate p4 add command, the server commands will return the escaped versions of the wildcards and other commands based on those escaped paths will work without any special handling, so P4V might just work correctly from that point on.


text:
Q: How can I store the values of the variables in the class? class Player():
    money = 0
    level = 0
    xp = 0
    xp_until_level = 20
    taxi_car = "Cabbie"
    busines = "No"
    busines_income = 1000
    upgrade_cost = 10000
    car_speed = 10
    car_level = 0
    drives_until_new_car = 20

p = Player()

I need the value of these variables to be saved and loaded when entering the game
i tried to use picklе library
but nothing happened

A: if you want the Values to be associated with the instance Player, the easiest way is as follows:
class Player:
    def __init__(self):
        self.money = 0
        self.level = 0
        self.xp = 0
        self.xp_until_level = 20
        self.taxi_car = "Cabbie"
        self.busines = "No"
        self.busines_income = 1000
        self.upgrade_cost = 10000
        self.car_speed = 10
        self.car_level = 0
        self.drives_until_new_car = 20

Then instantiate the Player by
p = Player()

and access the values by:
p.money
p.level

etc.


text:
Q: TouchImageView Scaletype centerCrop ?? I have an imageview where i have implemented the TouchImageView class for zoom functionality. But i'm not able to set the scaletype. I want the initial scaletype to be centercrop but i dosen't work.
When i try
img.setScaleType(ScaleType.CENTER_CROP);
the zoom functionality stops working and the image becomes center-cropped. I want both to work together.
How can i make the initial image to be center cropped that is being selected from my SDcard into an imageview with zoom functionality.

A: The patch for supporting scale types other than FIT_START and FIT_XY have been made. If anyone needs help with this please refer to this :
https://github.com/MikeOrtiz/TouchImageView/commit/475b552b468c1da10d6802cefaa00cf5e39b27d1

A: Has anyone tried this patch and the getZoomedImageFromSource() with scaleType centre crop
the bitmap it returns does not match the zoomed image.


text:
Q: Interpreting $H^n(BG,\mathbb Z)$ when $G$ is an infinite discrete group Suppose $G$ is a two-dimensional space group, for example a semidirect product of $\mathbb Z^2$ with a crystallographic point group such as $\mathbb Z_2$, where the action of $\mathbb Z_2$ on $\mathbb Z^2$ corresponds to reflection about the origin. I am trying to understand the object $H^n(BG,\mathbb Z)$. In particular, I would like to equate this to something that can be computed with group cohomology functions from GAP. I have read that for compact Lie groups, one can say that $H^n(BG, \mathbb Z) \cong H^{n}_B(G,\mathbb Z)$ where $H^*_B$ is the Borel group cohomology. Therefore,
1) Can a similar statement be made for space groups, which are infinite discrete?
2) Naively using the GAP function GroupCohomology(G,n) seems to give incorrect results for particular space groups. Should I be computing something different?


text:
Q: Quasilinear PDE with ambiguous quadratic equation solution
Suppose we have
$$u_t + [u^2]_x = 0,~~~~u(x,0) =
\begin{cases}
\sqrt{-x}, &x < 0 \\\\
0, &x > 0
\end{cases}
$$
and we want to find some solution utilizing shocks and entropy conditions.

Attempt:
Solving by the Method of Characteristics gives the implicit solution $u(x,t) = g(x - 2ut)$, for some $g$. If we parameterize by $s$ we can get characteristics of form $x = 2tg(s) + s$. Then, for $s > 0$, we clearly see
$$u(x,t) = 0, ~~~~ x > 0,$$
but for $s < 0$, we look at $g(s) = \sqrt{-s}$. So,
$$ x = 2t\sqrt{-s} + s \Rightarrow s^2 + (4t^2 - 2x)s + x^2 = 0,$$
which is a quadratic equation. Solving this gives
$$s = x - 2t^2 \pm 2t\sqrt{t^2 - x},$$
and so we have
$$u(x,t) = \sqrt{2t^2 - x \pm 2t\sqrt{t^2 - x}}, ~~~~ x - 2t^2 \pm 2t\sqrt{t^2 - x} < 0.$$
I'm struggling with how to interpret this since we have a "$\pm$". Do we treat these as two separate equations, and then check for shocks that way?

A: To gain insight into the problem, let us plot the base characteristics curves $x = 2tg(s) + s$ deduced from the method of characteristics for several values of $s$:

Solving $x = 2 t \sqrt{-s} + s$ for $s<0$, we find the two families
$$
s = x-2t^2 \pm 2t\sqrt{t^2 - x} \, ,\qquad
u = \sqrt{2t^2 - x \mp 2t\sqrt{t^2 - x} }
$$
valid for $x<t^2$. These two families correspond to lines that intersect in the figure.
Note that the characteristic curves should be stopped once they have intersected, as the method of characteristics becomes obsolete. Here are some ways to choose the correct family of curves:

*

*Graphically: by stopping the curves at the smallest positive time where they intersect another one, we are able to choose the correct family. For instance, setting $(x,t) = (0,0.5)$ leads to $s = -0.5\pm 0.5$, which suggests that the expressions with the bottom sign are the correct ones.

*Initial conditions: here, both solutions issued from the method of characteristics satisfy $u = \sqrt{-x}$ at $t=0$, thus we won't learn anything from the initial condition (see e.g. this related post where it works). To overcome this issue, let us evaluate the partial derivatives of $u$, and then
$$
\left.\frac{u_t}{u_x}\right|_{t=0} = \pm 2\sqrt{-x} \, .
$$
Since the above quantity must equal $-2u|_{t=0}$, we conclude that the expressions with the bottom sign are the correct ones.
Note that the characteristic curves issued from negative $s$ intersect with those issued from positive $s$. Thus, the Rankine-Hugoniot condition will be required to compute the discontinuity that emanates from this interaction (cf. this post).


text:
Q: spring-kafka can't work with kafka-cluster I've configured 3 kafka cluster and I'm trying to use with spring-kafka.
but when I kill a kafka, I'm not able to send other messages to queue.
Kafka version 2.0.0
spring-kafka version 2.0.1
kafka-topics.sh --describe --zookeeper=zoo1:2181
print
KAFKA_SWARM_TEST  PartitionCount:1        ReplicationFactor:2     Configs:
        Topic: KAFKA_SWARM_TEST Partition: 0    Leader: 2       Replicas: 1,2   Isr: 2,1

spring-kafka config
spring.kafka.bootstrap-servers="kafka2:9094,kafka1:9093"

the leader is kafka2.when I kill kafka1. leader still kafka1. but spring-kafka will throw
 Connection to node 1 could not be established.Broker may not be available.
 Discovered group coordinator kafka1:9093

look like the spring-kafka connect just use kafka1;
my java code
    @GetMapping(path = "/send",produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonNode send() throws JsonProcessingException {
        ObjectNode put = JsonNodeFactory.instance.objectNode().put("status", "success");
        String topic = "KAFKA_SWARM_TEST";
        val msg = MessageBuilder
                .withPayload(objectMapper.writeValueAsString(put))
                .setHeader(KafkaHeaders.TOPIC, topic)
                .build();
        kafkaTemplate.send(msg);
        return put;
    }

    @Bean
    public NewTopic topic() {
        return new NewTopic("KAFKA_SWARM_TEST", 1, (short) 2);
    }

    @KafkaListener(groupId="#{T(java.util.UUID).randomUUID().toString()}",topics = "KAFKA_SWARM_TEST")
    void testGetInfo(String message) throws IOException {
        log.error("getMessage: =====> " + message);
    }

kafka config
version: '3.7'

services:

  zoo1:
    image: wurstmeister/zookeeper
    restart: always
    ports:
      - 2181:2181
    environment:
      ZOO_MY_ID: 1
      ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888
  zoo2:
    image: wurstmeister/zookeeper
    restart: always
    ports:
      - 2180:2181
    environment:
      ZOO_MY_ID: 2
      ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888

  kafka1:
    image: wurstmeister/kafka
    restart: always
    ports:
    - "9093:9093"
    depends_on:
      - zoo1
      - zoo2
    privileged: true
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ADVERTISED_HOST_NAME: $KAFKA_ADVERTISED_HOST_NAME
      KAFKA_ZOOKEEPER_CONNECT: zoo1:2181,zoo2:2181
      KAFKA_LOG_DIRS: /kafka
      KAFKA_SSL_KEYSTORE_LOCATION: /kafka_broker_cert/server.keystore.jks
      KAFKA_SSL_KEYSTORE_PASSWORD: ksstone430
      KAFKA_SSL_KEY_PASSWORD: ksstone430
      KAFKA_SSL_TRUSTSTORE_LOCATION: /kafka_broker_cert/server.truststore.jks
      KAFKA_SSL_TRUSTSTORE_PASSWORD: stsstone430
      KAFKA_LISTENERS: "PLAINTEXT://:9092,SSL://:9093"
      KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://:9092,SSL://$KAFKA_ADVERTISED_HOST_NAME:9093"
      KAFKA_SSL_CLIENT_AUTH: required
      LEADER_IMBALANCE_CHECK_INTERVAL_SECONDS: 60
      KAFKA_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM: "null"
    volumes:
      - ./kafka_broker_cert:/kafka_broker_cert
      - /var/run/docker.sock:/var/run/docker.sock

  kafka2:
    image: wurstmeister/kafka
    restart: always
    ports:
    - "9094:9093"
    depends_on:
      - zoo1
      - zoo2
    environment:
      KAFKA_BROKER_ID: 2
      KAFKA_ADVERTISED_HOST_NAME: $KAFKA_ADVERTISED_HOST_NAME
      KAFKA_ZOOKEEPER_CONNECT: zoo1:2181,zoo2:2181
      KAFKA_LOG_DIRS: /kafka
      KAFKA_SSL_KEYSTORE_LOCATION: /kafka_broker_cert/server.keystore.jks
      KAFKA_SSL_KEYSTORE_PASSWORD: ksstone430
      KAFKA_SSL_KEY_PASSWORD: ksstone430
      KAFKA_SSL_TRUSTSTORE_LOCATION: /kafka_broker_cert/server.truststore.jks
      KAFKA_SSL_TRUSTSTORE_PASSWORD: stsstone430
      KAFKA_LISTENERS: "PLAINTEXT://:9092,SSL://:9093"
      KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://:9092,SSL://$KAFKA_ADVERTISED_HOST_NAME:9093"
      KAFKA_SSL_CLIENT_AUTH: required
      LEADER_IMBALANCE_CHECK_INTERVAL_SECONDS: 60
      KAFKA_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM: "null"
    volumes:
      - ./kafka_broker_cert:/kafka_broker_cert
      - /var/run/docker.sock:/var/run/docker.sock

A: Try checking if the new leader election of the Kafka cluster is working when you kill one of the nodes (e.g. the leader, kafka1)
Also, check if there are other configurations that overrides spring.kafka.bootstrap-servers. There could be a bean that just points to kafka1:9093 as the broker.
However even if the bootstrap-servers property points to kafka1:9093 only, the consumer should find the other nodes of the broker in case of node adjustments.


text:
Q: How to preview/display video from bytes How could I display/preview input video using Black Magic Design DecklinkAPI.dll? I could get video frame by frame but I do not know how could I display the frame in the Form/Window. I could implement IDeckLinkInputCallback:
void IDeckLinkInputCallback.VideoInputFrameArrived(IDeckLinkVideoInputFrame video,
    IDeckLinkAudioInputPacket audio)
{
    IntPtr pData;
    video.GetBytes(out pData);

    // What should I do to get the preview?

    System.Runtime.InteropServices.Marshal.ReleaseComObject(video);
}

Another way I see is to implement IDeckLinkScreenPreviewCallback:
void IDeckLinkScreenPreviewCallback.DrawFrame(IDeckLinkVideoFrame theFrame)
{
    // Constructor: m_ph = new CDeckLinkDX9ScreenPreviewHelper();
    m_ph.SetFrame(theFrame);

    // Should I use this method instead to get the preview?

    System.Runtime.InteropServices.Marshal.ReleaseComObject(theFrame);
}

There more complete code samples but they are still missing the important bit of code:
blackmagic SDK in c#.
BMD Decklink SDK documentation could be found here.
Thanks.

A: If you are using DeckLink SDK to capture video, then it is your responsibility to convert frames into format, which can be consumed by presentation API (GDI, GDI+, DirectShow, Media Foundation etc) - certain effort is expected here since you typically capture in non-RGB pixel format, and possibly at non-standard stride.
Alternatively, you can use DeckLink DirectShow video capture source which captures video and makes it available as a feed compatible with DirectShow API. You can use standard components to preview and process video. You can build and control DirectShow graphs in C# through DirectShow.NET library.


text:
Q: Help identifying this chip
Can anyone identify this chip? It came out of a central locking kit fitted to my car. But I didn't get the keyfob with it. From what I can tell it's a Fairchild semiconductor. With the writing on the bottom. The power pins are 2 and 3, which is unusual. Maybe a micro controller?


text:
Q: ubuntu 13.04 damaged google earth After upgrade to ubuntu 13.04 google earth stopped working in versions 6 and 7.
in 6.---- the fly to function quit working and in version 7.---- the fly to works but no
user uploaded pics will display all you get is a blank white box and on some, when you click the mouse on them G.E. shuts down. I know this is a ubuntu caused problem because I just installed G.E.  in windows 7 and it is fully functional. Ubuntu forums shows that many or maybe all users of 13.04 have this problem.Surely by this time someone has taken time to find the fix. I don't have programming skill so I can't do so.
Harlie
further result.....
I went back to ubuntu 12.04 and now it too will not work properly with google earth
in ver. 7.- - - - so now it's back to windows for G.E.
Harlie

A: Reinstalling Google Earth will solve your problem.
sudo apt-get install --reinstall google-earth-stable


text:
Q: Does outerHTML have the same XSS vulnerabilities as innerHTML? Our company's security scan seems to keep getting hung up on this outerHTML property in swfobject.js:
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';

I'm familiar with the XSS vulnerabilities associated with innerHTML, but can you give me some examples of how outerHTML can be exploited in this case? I'm wondering if the scan is producing a false positive - I would think that the team behind swfobject would have addressed all XSS issues.
Thanks!

A: If you understand how innerHTML and outerHTML works, you can answer the question for yourself:

*

*innerHTML replaces all childNodes of the el node with the NodeList that was parsed from the assigned string value.

*outerHTML replaces the node el itself with the NodeList that was parsed from the assigned string value.

An example: if el is the inner div in the following example:

 …

Then setting innerHTML and outerHTML with foobar results in:

*

*innerHTML:

foobar

*outerHTML:

foobar

So it doesn't matter whether you use innerHTML or outerHTML. Both are vulnerable to XSS.


text:
Q: jQuery how to get number from string? I have this HTML:
179,00 DKK

or it could be:
1.750,00 DKK

How do I get the number?

A: Try this:
parseInt($('.price-old').text().replace(/[^0-9.]/g, ""));  //<-- Remove parseInt() to include value after decimal point

Demo

A: Try this,
Live Demo
 parseInt($('.price-old').text().replace(',', '').replace('DKK', ''))

A: try:
var value=$('.price-old').val();
value=value.split(' ')[0];
alert(val);//just for check

A: You need to remove DKK and swap spaces with commas. replace will help you:
+$('.price-old').text().replace( /[^0-9,]/g, '' ).replace( ',', '.' );

(the + at the start converts it into a number)
The . / , swapping is necessary because JavaScript parses numbers in English form; . is the decimal point, , is a group separator.

A: This should work:
parseInt($('.price-old').text().replace(/[^\d]/g, ''), 10)

Where:
$('.price-old').text().replace(/[^\d]/g, '') is for stripping off all non-numeric characters from the text
parseInt(string, 10) is for converting to numeric on base 10.
You can also do the same with:
Number($('.price-old').text().replace(/[^\d]/g, ''))


text:
Q: error while building a view on Application designer "invalid number of column names specified " SELECT EMPLID
, LST_ASGN_START_DT
  FROM PS_JOB A
 WHERE A.EFFDT = (
 SELECT MAX(EFFDT)
  FROM PS_JOB
 WHERE A.EMPLID = EMPLID
   AND A.EMPL_RCD = EMPL_RCD
   AND EFFDT <= SYSDATE )
   AND A.EFFSEQ = (
 SELECT MAX(EFFSEQ)
  FROM PS_JOB
 WHERE A.EMPLID = EMPLID
   AND A.EMPL_RCD = EMPL_RCD
   AND A.EFFDT = EFFDT )
   AND HR_STATUS='A'

When running it directly on the db i get no errors but when i compile and build it on application designer I get an error of "invalid number of column names specified "
I have also tried this but still getting the same error.
SELECT A.EMPLID
 , A.LST_ASGN_START_DT
  FROM PS_JOB A
 WHERE A.EFFDT = (
 SELECT MAX(EFFDT)
  FROM PS_JOB
 WHERE A.EMPLID = EMPLID
   AND A.EMPL_RCD = EMPL_RCD
   AND EFFDT <= SYSDATE )
   AND A.EFFSEQ = (
 SELECT MAX(EFFSEQ)
  FROM PS_JOB
 WHERE A.EMPLID = EMPLID
   AND A.EMPL_RCD = EMPL_RCD
   AND A.EFFDT = EFFDT )
   AND A.HR_STATUS='A'

and this also but nothing..
SELECT A.EMPLID
 , A.LST_ASGN_START_DT
  FROM PS_JOB A
 WHERE A.EFFDT = (
 SELECT MAX(EFFDT)
  FROM PS_JOB B
 WHERE A.EMPLID = B.EMPLID
   AND A.EMPL_RCD = B.EMPL_RCD
   AND B.EFFDT <= SYSDATE )
   AND A.EFFSEQ = (
 SELECT MAX(EFFSEQ)
  FROM PS_JOB C
 WHERE A.EMPLID = C.EMPLID
   AND A.EMPL_RCD = C.EMPL_RCD
   AND A.EFFDT = C.EFFDT )
   AND A.HR_STATUS='A'

A: You have two columns on your select, and probably have a different number of columns on the record definition.
The sql statement and the record definition should have the same number of columns (but not necessarily the same field names)
Look at this example:
record has 5 fields

and select has 5 fields:


text:
Q: UIAlertview not working fine in ios7 Clicking on ok or cancel button in UIAlertview is not working fine. When I am clicking ok or cancel button, UIAlertview is not dismissed but if i clicking twice on ok or cancel button then and only then UIAlertview get dismissed.
This is my code.
alert = [[UIAlertView alloc] initWithTitle:@"Plese Enter comma seperated sets"
                                                             message:@"\n"
                                                            delegate:self
                                                   cancelButtonTitle:@"Cancel"
                                                   otherButtonTitles:@"Save", nil] ;
            CGRect rect = {12, 60, 260, 25};
            dirField = [[UITextField alloc] initWithFrame:rect] ;
            dirField.backgroundColor = [UIColor whiteColor];

        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        dirField.text = setString;
        [dirField setText:@"test"];
        [dirField becomeFirstResponder];
        [alert addSubview:dirField];
        [alert show];

A: Meghaji
I think there is problem in your method , I mean it is calling 2 times.
Thanks


text:
Q: Runtime detection of Linux/ARM "kuser_helper" functions Normally on Linux/ARM, a special page mapped at 0xffff0000 is used for implementing the "read TLS pointer" operation, atomic compare-and-swap, and memory barriers. This system is called "kuser helpers" (CONFIG_KUSER_HELPERS) and is necessary to work around the lack of support for atomic compare-and-swap in earlier arm models. However, recent kernel versions offer an option to disable this feature on the principle that it's a security risk (facilitating attacks based on return to a fixed executable address, since these functions are not subject to ASLR); this option can be used if all applications are built to make direct use of synchronization instructions available on newer ARM models.
My problem is that I want to be able to support both old ARM models (which lack synchronization instructions) and new hardened kernels (which lack kuser helpers) with the same binaries, so I'm looking for a reliable way, from userspace, to detect the availability of the kuser helper page (using it if it's available, and assuming if it's not that the newer instructions must be available). Reliable excludes things like /proc that might not always be available. Is there any way to probe for the existence of the kuser helper page short of trying to use it and trapping SIGSEGV?

A: the vectors page is set up in arch/arm/kernel/traps.c:early_trap_init() during kernel initialisation and will still be present, just without the helpers, so you shouldn't get a SEGV in the first place; for the same reason the mmap trick won't work (i haven't checked either of these assumptions).
but: the vectors page is initialised to zero by early_alloc_aligned(), so you're lucky, since the number of kuser_helpers at 0xffff0ffc will not be filled in and is thus zero.
tl;dr: read the number of kuser helpers from 0xffff0ffc. if zero => no support for them


text:
Q: What is wall crossing? I know that it must have something to do with (gauge?) theories with N=2 supersymmetry, BPS states and even black holes, but most papers on the subject are too technical for me. So what is wall crossing?

A: Wall crossing is any discontinuous change of an integer (or at least rational) quantity - or, more generally, any qualitative change of the spectrum etc. - that occurs when one moves to the opposite side from a "wall" in a moduli space or parameter space.
A would-be index may suddenly change discontinuously.
The wall - a codimension one locus in the parameter space - is then referred to as the "wall of marginal stability". One one side, an object may be stable while it is unstable on the other side. It is typically unstable because a decay suddenly becomes plausible because the hypothetical decay product get light enough, if you wish.
The objects are typically BPS objects on the stable side and they can also be BPS black holes or any other BPS objects.
To see objects that may be exactly stable, BPS, but that are also sufficiently diverse, $N=2$ supersymmetry or eight supercharges is an ideal number of supercharges. That's why those considerations played an important role in the Seiberg-Witten insights about $N=2$ gauge theories, among related situations.
Paul Aspinwall liked to say that 8 supercharges is the optimum number for nice physics. Only Nature didn't manage to choose the number 8 for supercharges, but that's not Aspinwall's fault.


text:
Q: very simple but i got lost, sorting alphabetically xml using xsl and visualize output in html I'm creating something like a dictionary online where users can add their words using a simple form and then they can see all the words in a page, in alphabetical order of the words, the problem is that it doesn't show it alphabetically but in the order of insertion.
I got 3 files, res.xml, which is the file with the data, tt.xsl which is supposed to sort res.xml in alphabetical order, and index.html which shows the data to the user, i would like to sort the data contained in the xml file alphabetically using the attribute 'WORD', but when i run index.html it doesn't sort it , it just shows it in the order of reading data, what's the easiest way to make it work?
Here are the 3 files
THIS IS THE HTML FILE WITH A SCRIPT I'M USING TO VISUALIZE IT

//------------------------------
THIS IS THE XML FILE res.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<?xml-stylesheet type="text/xsl" href="tt.xsl"?>

<LIBRARY>
<TERM>
<EDITBY>giovanni</EDITBY>
<WORD>ciao</WORD>
<LANGUAGE>Italian</LANGUAGE>
<DESCRIPTION>
it means hi
</DESCRIPTION>
</TERM>

<TERM>
<EDITBY>giacomo</EDITBY>
<WORD>all</WORD>
<LANGUAGE>italian</LANGUAGE>
<DESCRIPTION>
significa tutto
</DESCRIPTION>
</TERM>

</LIBRARY>

//----------------------------------
THIS IS THE XSL tt.xsl
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

<xsl:for-each select="LIBRARY/TERM">
  <xsl:sort select="WORD"/>

    <xsl:value-of select="LANGUAGE"/>
    <xsl:value-of select="WORD"/>

</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

RESULT, IT SHOWS THE DATA BUT NOT IN ALPHABETICAL ORDER
ANY HELP WOULD BE GREATLY APPRECIATED

A: You need to add an output element to your XSL like the below:
<xsl:output method="html"/>

That would go right below your stylesheet tag.
That is the minimum information that you can add to the output tag. Without it, some (all?) processors won't handle the XSL at all.
As a side note, I'm not entirely sure what you are doing with your javascript but you should be able to create your entire table structure within the XSL without all of the extra scripting. But that would be the topic of a second question.
So when you run this XML
<LIBRARY>
  <TERM>
    <EDITBY>giovanni</EDITBY>
    <WORD>ciao</WORD>
    <LANGUAGE>Italian</LANGUAGE>
    <DESCRIPTION>
      it means hi
    </DESCRIPTION>
  </TERM>
  <TERM>
    <EDITBY>giacomo</EDITBY>
    <WORD>all</WORD>
    <LANGUAGE>italian</LANGUAGE>
    <DESCRIPTION>
      significa tutto
    </DESCRIPTION>
  </TERM>
</LIBRARY>

With this XSL
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <xsl:for-each select="LIBRARY/TERM">
      <xsl:sort select="WORD"/>

        <xsl:value-of select="LANGUAGE"/>
        <xsl:value-of select="WORD"/>

    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

You get this HTML, with the information sorted by the WORD element.

italian	all

Italian	ciao

A: Looking at the javascript, after getting the XML, you are performing commands such as getElementsByTagName("WORD"). WORD is an element in your input XML, but your XSLT would transform your XML input tr and td. This should give you a clue that your XSLT is doing actually being called, and your XML is not being transforming. All your javascript is doing is reading the elements from the XML in the order they appear.
Now, in your XML you do have this processing instruction:
<?xml-stylesheet type="text/xsl" href="tt.xsl"?>

But this 'instruction' is only going to be 'processed' if the XML was access directly in the browser (i.e you type "res.xml" into the URL to display the XML). Reading the XML file with javascript will not actually pay any attention to this processing instruction. You are simply reading the contents of the file at this point, and it is up to you to write code to act on it.
It is not too hard to write javascript to perform an XSLT transformation. The main fiddliness comes from IE doing it different to Firefox and Chrome. I did a quick search on Stack Overflow, and found this question which explains how to do it
http://stackoverflow.com/questions/5722410/how-can-i-use-javascript-to-transform-xml-xslt

Here is the adaptation of the javascript provided that should work in this case

The only thing to note here, is that it would be better to output the "table" element in your XSLT too. So, you XSLT would look something like this
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">

<xsl:output method="html" />

<xsl:template match="/">

<xsl:for-each select="LIBRARY/TERM">
  <xsl:sort select="WORD"/>

    <xsl:value-of select="LANGUAGE"/>
    <xsl:value-of select="WORD"/>

</xsl:for-each>

</xsl:template>
</xsl:stylesheet>


text:
Q: Get latest artifact from maven nexus for a certain minor version in my nexus 2 repository i have following structure:
snaphosts/
  com/example/group/
    artifact/
      1.0.0-SNAPSHOT
      1.0.1-SNAPSHOT
      1.0.2-SNAPSHOT
      1.1.0-SNAPSHOT
      1.1.1-SNAPSHOT

When i query:
http://ip/nexus/service/local/artifact/maven/content?g=com.example.group&a=artifact&v=LATEST&r=snapshots
Then i get 1.1.1-SNAPSHOT.
My question is how can i get the latest 1.0 version? Is there a query that downloads 1.0.2-SNAPSHOT?

A: If you want to update a POM with latest versions in the 1.0.x range, I would use the versions maven plugin. It is unlikely that Nexus 2 has such a feature.


text:
Q: Список файлов в каталоге linux Какая есть команда bash чтобы получить список файлов в некотором каталоге? причем нужны их полный адреса, а не только названия. И только это. Без указания прав доступа и прочей информации.
A: 1) с помощью find
find `pwd` -mindepth 1
find <folder> -mindepth 1

find `pwd`/*
find <folder>/*

2) с помощью ls
ls | xargs -n 1 -i echo "`pwd`/{}"
ls <folder> | xargs -n 1 -i echo "<folder>/{}"

A: $ tree -i -f -L 1

f — выводить полные пути,
L — уровень вложенности
Если нужно обрезать родительский каталог и итоговый вывод, то:
$ tree -i -f -L 1 | head -n -2 | tail -n +2


text:
Q: Buck converter output This is my first design of a asynchronous buck converter, Vin 36V, Vout 24V, Iout 1A, Frequency switch 100KHz, based on "Basic Calculation of a Buck Converter's Power Stage" - slva477b Texas Instruments. It works as intended, while 1A load connected, without load outputs 29V. From other posts I understand that for this type of buck, duty cycle MUST be adjusted properly for different loads. How can this be accomplished, if possible, without feedback? Does the circuit need a minimum load ? Thank you

A: Using a buck converter as a pre-regulator to drop the input voltage for a linear regulator is a valid approach and way simpler than a full regulated buck converter. An unregulated buck converter avoids a lot of the headaches you'd have with a regulated one.
You can avoid the output voltage rise without load by replacing D4 with another N-MOSFET. This FET should be on when Q3 is off and vice-versa. Make sure to include some dead-time so you don't have shoot-through between the FETs.
With those two FETs (that form a half-bridge), energy can flow back from the output capacitor to the input of the buck converter when the voltage at the output is too high, allowing the converter to always operate in CCM mode and giving you the desired output voltage even with no load. As a bonus, it will also be more efficient because the voltage drop across D4 will be avoided.
As Bimpelrekkie already stated in the comments above, you should probably drop the voltage to about 8V for the 7805 and use a second identical buck converter to create a higher-voltage rail.


text:
Q: Can I submit iPhone X screenshots to the App Store now? As I submitted my app to the App Store with screenshots from the iPhone X in iTunes Connect, it got rejected with the following reason:

The screenshots contain inappropriate images. iPhone X is not released hardware.

This raised so many questions. Do they allow iPhone X design screenshots in the App Store now? Will they change the screenshot approving process in the future?

A: YES

iPhone X screenshot support in iTunes Connect.
October 27, 2017
You can now upload screenshots for iPhone X. You'll see a new tab for 5.8-inch displays under Screenshots and App Previews on your iOS app version information page.
Note that iPhone X screenshots are optional and cannot be used for smaller devices sizes. 5.5-inchdisplay screenshots are still required for all apps that run on iPhone.
iPhone X Screenshot Resolutions
1125 by 2436 (Portrait)
2436 by 1125 (Landscape)
Learn more about uploading screenshots in iTunes Connect Developer Help.
Learn about updating apps for iPhone X.
Source: - iTunes-partner

A: Edit after the official release: The date seemed to be correct. As a general rule, you should wait until the specific device is released.

You should wait until Apple officially releases the iPhone X. (According to market news, Apple is going to release it on November 3, 2017).


text:
Q: Common method to check if a service is stopped I m looking for common method that check if a service is really stopped after executing /etc/init.d/<service> stop
Are there a common way for all services?

A: You can normally use
/etc/init.d/<service> status

Open the /etc/init.d/<service> file, they are normally very clear and easy to understand.
Also, you can check the processes with
ps -ef | grep <service>

but will not be that clear.


text:
Q: Prevent public IP address binding on Kubernetes single master/node set-up I'm following the instructions here to spin up a single node master kubernetes install.  And then planning to make a website hosted within it available via an nginx ingress controller hosted directly on the internet (on a physical server, not GCE, AWS or other cloud).
Set-up works as expected and I can hit the load balancer and flow through the ingress to the target echoheaders instance, get my output and everything looks great.  Good stuff.
The trouble comes when I portscan the server's public internet IP and see all these open ports besides the ingress port (80).
 Open TCP Port:     80          http
 Open TCP Port:     4194
 Open TCP Port:     6443
 Open TCP Port:     8081
 Open TCP Port:     10250
 Open TCP Port:     10251
 Open TCP Port:     10252
 Open TCP Port:     10255
 Open TCP Port:     38654
 Open TCP Port:     38700
 Open TCP Port:     39055
 Open TCP Port:     39056
 Open TCP Port:     44667

All of the extra ports correspond to cadvisor, skydns and the various echo headers and nginx instances, which for security reasons should not be bound to the public IP address of the server.  All of these are being injected into the host's KUBE-PORTALS-HOST iptable with bindings to the server's public IP by kube-proxy.
How can I get hypercube to tell kube-proxy to only bind to docker IP (172.x) or private cluster IP (10.x) addresses?

A: You should be able to set the bind address on kube-proxy (http://kubernetes.io/docs/admin/kube-proxy/):

--bind-address=0.0.0.0: The IP address for the proxy server to serve on (set to 0.0.0.0 for all interfaces)


text:
Q: Is Wine stable enough for production? I have a open relationship with Linux, i use it on and off and i just got into the latest ubuntu and got a change to try out wine and it seemed to take any windows app and make it like i was actually using windows.
I wanted to know is wine that stable to use in production/businesses or are there problems that i haven't come across yet?

A: Wine v1 is considered stable.  "Stable" is always a bit relative and I think that because of the nature of Wine and its complexity as well as the always-changing applications running on it themselves it would always be somewhat touchy.
That said, I think that if you go by the different classes of application compatibility in the Wine App DB and only use Gold ones then one can probably safely say it is reasonably stable.  The Wine community is great and I'm sure will be a great help.
For multiple workstation, mission-critical use I think you would be better off going with a commercial spin-off of Wine like CodeWeavers CrossOver Linux and have the benefit of commercial support.


text:
Q: Excel is closing unexpectedly when closing C# WinForms App called in a DLL I have a C# Winforms-Application. I have set the Output Type of the Project to 'Class Library' and made it COM visible so I can reference it in my VBA Code in Excel. Hence I can start my WinForms-App through Excel.
Everything works fine so far. In my VBA Code I'm calling the Application like this (Macro):
Dim app As MyWinFormsApp.Program
Set app = New MyWinFormsApp.Program
Dim result As Integer
result = app.Main()

My Program Class in my C#-Code looks like this:
public int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        return 0;
    }

When I start my Macro the WinForms Window opens and and the program works fine.
My Problem is: When I'm closing the WinForms Window by clicking on the red X, Excel also closes unexpectedly.
What I've already found out is:
In my C# Class Form1.Designer.cs I have this Dispose-Method:
protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

When I call the base.Dispose()-Method passing 'false'
base.Dispose(false);

Excel is not closing unexpectedly when I close the WinForms-Window, but when I want to close Excel afterwards, it's not possible. I get this 'Mouse-Wait-Symbol' and can't do anything so I have to kill the Excel-Process in TaskManager.
(I've also tried using a new WinForms-Project that really does nothing to provide that in my original project I'm doing something wrong... I had exactly the same behaviour.)
So my question is: Does anyone know how I can close my WinForms-App and afterwards close Excel in a 'normal way'.
Thank you very much!

A: Try to change the Application.UserControl Property to true, before closing the winform.
"When the UserControl property is False for an object, that object is released when the last programmatic reference to the object is released. If this property is False, Microsoft Excel quits when the last object in the session is released."
https://msdn.microsoft.com/library/office/ff841219.aspx

A: the Problem is the using of Application.Run().
If you are calling a form from VBA you should use frm.show().
Then it will work like a charm.
Example in c#:
        public void InitializeForm()
    {
        Form1 Form = new Form1();
        Form.Show();
    }

Example in VBA:
Sub OpenForm()
Dim CallForm As New CallAndInitialize
CallForm.InitializeForm End Sub


text:
Q: Dell Windows 7 Synaptic Touchpad behaving erratically UPDATE:: solution: For anyone who may land on this in the future: I ended up having the entire trackpad/armrest replaced, as nothing else seemed to fix the issue.
Short version: My touchpad on a Dell Studio 1558 running Windows 7 behaves erratically. When trying to move the cursor, it randomly teleports around the screen and clicks (both left and right) randomly. It occasionally left clicks when nothing it touching the trackpad. Also, left clicking sometimes causes the entire computer to hang up a bit (cursor movement and program response seems to lock up, but if music is playing that will continue normally).
Short list of what I did to fix/troubleshoot:

*

*Uninstalled/installed drivers

*Examined internal touchpad hardware

*Checked with Ubuntu from live usb

*Tested with usb mouse

Long version/background:
Not too long ago, I was beginning to have overheating issues with my laptop while gaming. This had happened to me before, so I opened up my laptop to clean dust away from the fan/heat sink. Reassembled, everything seemed fine. (This may or may not be related to the issue).
A few days later, the application TwoFingerScroll stopped working properly. It would run for about 10 minutes after starting my computer, then stop. If I closed/restarted the application, it would give me the error "No Synaptic Touchpad Device Found". This didn't seem to start happening after any updates (though I'm not 100% sure about that), but I assumed it must be a driver issue anyways. I removed my current drivers and installed the most recent Synaptic Touchpad drivers. This is when the erratic touchpad behavior began. I assumed the new drivers must have caused these problems (I had switched to just Synaptic Touchpad drivers, instead of Dell specific Synaptic drivers), so I reverted to the Dell-specific Synaptic touchpad drivers (though I did start using the latest version; I'm not sure if that is the same version I had been using previously). No change.
At this point, I began to think I might have messed something up hardware-wise when cleaning my fan, so I opened up the case again and inspected the touchpad. I didn't see anything obviously wrong (wasn't entirely sure what to look), but I cleaned away a little dirt/dust from the area and reassembled the computer. The touchpad issues persisted.
In order to discern if this was a software or hardware issue, I then booted into Ubuntu from a live usb. The touchpad issues weren't nearly as severe, but they were still there.
I also tested it with a usb mouse, and as I expected, everything worked smoothly with the mouse.
EDIT: Unusually enough, after using my computer for a while (1-2hrs), most of the erratic behavior seems to have died down. I'm not sure if this is a one time thing, or if the issue will remain gone following a reboot, or it will always take a period of time for the erratic behavior to go away. Also not sure what this indicates about the source of the problem.
EDIT 2: And another hour or so later, the trackpad has stopped responding entirely. This happened once or twice before, and previously has always cleared up when the computer is turned back on. I haven't turned it back on yet this time.
--
I believe that this must be a hardware issue, but I am not sure how to go about fixing it (or even determining exactly what the issue is). I would assume it was an unplugged cable internally or something like that, but when I opened the case again to check I couldn't find anything like that.
Am I right in assuming this is probably a hardware issue?
What else can I do to troubleshoot this?
And is this likely something that I (with limited hardware fixing experience--I'm mostly a software guy) can fix myself, or will this need to be taken to a shop?

A: This seems to be a hardware issue. But I got it resolved by reducing the Touch Sensitivity of my touchpad. I felt that sometimes the trackpad senses my finger even when i am a centimeters away.
I am using MSI laptop with Synaptics drivers. Go to Synaptics Settings -> Pointing -> Sensitivity -> Touch Sensitivity. Increase it to Heavy.


text:
Q: Ebay Restful API createshippingfulfillment Bad Request 400 error I tried to use PostMan to send a request to eBay's createShippingFulfillment, and that works.  However, when I tried to post it in VS, I got Bad Request Error.
StatusCode: 400, ReasonPhrase: 'Bad Request'

Below is detailed error
{[
  {
    "errorId": 32200,
    "domain": "API_FULFILLMENT",
    "category": "REQUEST",
    "message": "Invalid line item id: ''"
  }
]}

When I checked the value of lineItemId it is correct and also I've use string and long for lineItemId but still the same error.
{"lineItems":[{"lineItemId":"100224635xxxxx","quantity":1}],"shippedDate":"2020-01-24T01:25:15.604Z","shippingCarrierCode":"Couriers Please","trackingNumber":"6J7042xxxx"}

Codes below:
string endpoint = string.Format("sell/fulfillment/v1/order/{0}/shipping_fulfillment", orderFromOrd.StoreOrderId);
Fullfillment fulfillment = new Fullfillment();

            fulfillment.trackingNumber = orderFromOrd.TrackingNo;
            fulfillment.shippingCarrierCode = base.GetCarrierName(_carriers, orderFromOrd);
            fulfillment.shippedDate = DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ss.fffZ");

            foreach (var ol in sentOrigOLOrd)
            {
                var checkIfsentinOrd = checkOLinStore.Where(x => x.lineItemId == ol.StoreOrderLineId).FirstOrDefault();
                if (checkIfsentinOrd != null)//Only not fulfilled orderlines & sent orderlinestatus in Ordmation
                {

                    FulfillmentLineItems line = new FulfillmentLineItems();
                    line.lineItemId = Convert.ToInt64(ol.StoreOrderLineId); // line-item-id from store Order
                    line.quantity = ol.Qty;
                    fulfillment.lineItems.Add(line);
                }
            }

HttpResponseMessage response = _requestHelper.PostHttpResponse(endpoint, fulfillment);

public HttpResponseMessage PostHttpResponse(string requestUri, object data)
        {
            // Serialize our concrete class into a JSON String
            var stringPayload = JsonConvert.SerializeObject(data);
            // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
            using (var client = CreateHttpClient())
            {
                try
                {
                    HttpResponseMessage response = client.PostAsJsonAsync(requestUri, httpContent).Result;
                    //response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        return response;
                    }
                    else
                    {
                        GetErrorsResponse(response);
                        throw new HttpRequestException(string.Format("There was an exception trying to post a request. response: {0}", response.ReasonPhrase));
                    }
                }
                catch (HttpRequestException ex)
                {
                    throw ex;
                    //return null;
                }
            }
        }

private HttpClient CreateHttpClient()
        {
            var client = new HttpClient();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            string baseAddress = WebApiBaseAddress;
            if (string.IsNullOrEmpty(baseAddress))
            {
                throw new HttpRequestException("There is no base address specified in the configuration file.");
            }
            client.Timeout = new TimeSpan(0, 5, 59);
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", _cred.eBayToken));
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
            client.DefaultRequestHeaders.Add("LegacyUse", "true");
            return client;
        }


text:
Q: R. Setting value in data frame based on values in different data frame Say I have two dataframes:
df.trial.params =
Session     Trial.Start    Trial.End    Trial.Num
1           30             50           1
1           51             80           2
2           30             50           1
2           51             80           2
3           30             50           1
3           51             80           2

df.data =
Session    Time
1          31
1          33
1          52
1          72
2          31
2          33
2          52
2          72
3          31
3          33
3          52
3          72

I want to add a column (df.data$trial.num), which is based off of parameters in df.trial.params. This matching is done in 2 steps:
Step 1: Match the session
if(df.data$Session == df.trial.params$Session)

Step 2: Match the time so that it sits within the trial start and end times
if((df.data$Time >= df.trial.params$Trial.Start) & (df.data$Time <= df.trial.params$Trial.End))

The end results would be this:
Session    Time    Trial.Num
1          31      1
1          33      1
1          52      2
1          72      2
2          31      1
2          33      1
2          52      2
2          72      2
3          31      1
3          33      1
3          52      2
3          72      2

I am really at a bit of a loss, as I have very limited experience with using R. I have seen a few posts using with() but I am not sure how to use multiple data frames with this.
Any and all help is appreciated, my apologies if this question has been answered elsewhere (I couldn't find it)
Edited to show desired final product.

A: You can merge the data frame by Session and then filter by the time:
library(dplyr)
merge(df.trial.params, df.data, by = 'Session') %>%
      filter(Time >= Trial.Start, Time <= Trial.End) %>%
      select(Session, Time, Trial.Num)

#    Session Time Trial.Num
# 1        1   31         1
# 2        1   33         1
# 3        1   52         2
# 4        1   72         2
# 5        2   31         1
# 6        2   33         1
# 7        2   52         2
# 8        2   72         2
# 9        3   31         1
# 10       3   33         1
# 11       3   52         2
# 12       3   72         2

A: We can do this with data.table
library(data.table)
setDT(df.data)[df.trial.params, on = "Session", allow.cartesian=TRUE
     ][Time >=Trial.Start & Time <= Trial.End][,  (3:4) := NULL][]
#     Session Time Trial.Num
# 1:       1   31         1
# 2:       1   33         1
# 3:       1   52         2
# 4:       1   72         2
# 5:       2   31         1
# 6:       2   33         1
# 7:       2   52         2
# 8:       2   72         2
# 9:       3   31         1
#10:       3   33         1
#11:       3   52         2
#12:       3   72         2

Or using foverlaps
df.data1 <- transform(df.data, Trial.Start = Time, Trial.End = Time)[-2]
setDT(df.trial.params, key = c("Session", "Trial.Start", "Trial.End"))
setDT(df.data1, key = c("Session", "Trial.Start", "Trial.End"))
foverlaps(df.data1, df.trial.params, type="within")[,
               Time := i.Trial.Start][, c(1, 7, 4), with = FALSE]
#    Session Time Trial.Num
# 1:       1   31         1
# 2:       1   33         1
# 3:       1   52         2
# 4:       1   72         2
# 5:       2   31         1
# 6:       2   33         1
# 7:       2   52         2
# 8:       2   72         2
# 9:       3   31         1
#10:       3   33         1
#11:       3   52         2
#12:       3   72         2

A: watch out with using if, if(df.data$Time >= df.trial.params$Trial.Start) will check if the total column is the higher.
To loop through each row you will need the vectorised version ifelse()


text:
Q: What is meant by this notation of the real forms of $E_6$? There are five real forms of the exceptional Lie group, $E_6$. Four of them are notated as in the following:

*

*The split form as EI or $E_{6(6)}$

*The quasi-split form as EII or $E_{6(2)}$

*EIII or $E_{6(-14)}$

*EIV or $E_{6(-26)}$
What do the annotations to $E_6$ actually indicate and are they also used for real forms for Lie groups in general?

A: The notation is a bit complicated to make precise, but the number in parentheses is the character, which is defined on page 353 section C of Helgason, Differential Geometry, Lie Groups and Symmetric Spaces. The character is the difference $\dim \mathfrak{p}_0 - \dim \mathfrak{k}_0$ in dimensions in a Cartan decomposition of a real form. As Helgason explains, the character of an exceptional real simple Lie algebra determines the Lie algebra, but for the classical real simple Lie algebras, it doesn't, so the notation is only used for exceptionals.

A: $E_{6(n)}$ means that $n$ is the dimension of the group $E_6$ minus twice the dimension of a maximal compact subgroup.
example: $E_{6(6)}$ of dimension 78 has maximal compact subgroup ${\rm Sp}(4)/\mathbb{Z}_2$ of dimension 36.


text:
Q: How to add image to sprite so TouchEvent responds? I create my sprite and event listener like this:
public function init():void
{
    var mySprite:Sprite = new Sprite();
    mySprite.graphics.beginFill(0x336699);
    mySprite.graphics.drawRect(100,100,150,50);
    addChild(mySprite);

    mySprite.addEventListener(TouchEvent.TOUCH_BEGIN, start);
}

private function start(event:TouchEvent):void
{
    // do stuff
}

But how would I add an image to the sprite so that the TouchEvent responds to touching the image?

A: Create the image (e.g. using a Bitmap) and add it to mySprite using addChild().
The events use a special sequence of "bubbling" up and down the display list so a touch triggered in the child of a sprite will trigger the event in the parent (and on the stage, etc.)


text:
Q: how is page size determined in virtual address space? Linux uses a virtual memory system where all of the addresses are virtual addresses and not physical addresses. These virtual addresses are converted into physical addresses by the processor.
To make this translation easier, virtual and physical memory are divided into pages. Each of these pages is given a unique number; the page frame number.
Some page sizes can be 2 KB, 4 KB, etc. But how is this page size number determined? Is it influenced by the size of the architecture? For example, a 32-bit bus will have 4 GB address space.

A: You can find out a system's default page size by querying its configuration via the getconf command:
$ getconf PAGE_SIZE
4096

or
$ getconf PAGESIZE
4096

NOTE: The above units are typically in bytes, so the 4096 equates to 4096 bytes or 4kB.
This is hardwired in the Linux kernel's source here:
Example
$ more /usr/src/kernels/3.13.9-100.fc19.x86_64/include/asm-generic/page.h
...
...
/* PAGE_SHIFT determines the page size */

#define PAGE_SHIFT  12
#ifdef __ASSEMBLY__
#define PAGE_SIZE   (1 << PAGE_SHIFT)
#else
#define PAGE_SIZE   (1UL << PAGE_SHIFT)
#endif
#define PAGE_MASK   (~(PAGE_SIZE-1))

How does shifting give you 4096?
When you shift bits, you're performing a binary multiplication by 2. So in effect a shifting of bits to the left (1 << PAGE_SHIFT) is doing the multiplication of 2^12 = 4096.
$ echo "2^12" | bc
4096

A: The hardware (specifically, the MMU, which is part of the CPU) determines what page sizes are possible. There is no relation to the processor register size and only an indirect relation to the address space size (in that the MMU determines both).
Almost all architectures support a 4kB page size. Some architectures support larger pages (and a few also support smaller pages), but 4kB is a very widespread default.
Linux supports two page sizes:

*

*Normal-sized pages, which I believe are 4kB by default on all architectures, though some architectures allow other values, e.g. 16kB on ARM64 or 8kB, 16kB or 64kB on IA64. These correspond to the deepest level of descriptors on the MMU (what Linux calls PTE).

*Huge pages, if compiled in (CONFIG_HUGETLB_PAGE is necessary, and CONFIG_HUGETLBFS as well for most uses). This corresponds to the second-deepest level of MMU descriptors (what Linux calls PMD) (or at least it usually does, I don't know if this holds on all architectures).

The page size is a compromise between memory usage, memory usage and speed.

*

*A larger page size means more waste when a page is partially used, so the system runs out of memory sooner.

*A deeper MMU descriptor level means more kernel memory for page tables.

*A deeper MMU descriptor level means more time spent in page table traversal.

The gains of larger page sizes are tiny for most applications, whereas the cost is substantial. This is why most systems use only normal-sized pages.
You can query the (normal) page size on your system with the getconf utility or the C function sysconf.
$ getconf PAGE_SIZE
4096

Using huge pages requires mounting the hugetlbfs filesystem and mmapping files there.

A: The processor determines the page sizes available. For most purposes, the  hardware implemented page size on x86 and x86_64 processors is 4kb. However, the operating system can allocate more than one page at a time if it wants to, and thereby effectively implement 8kb, 16kb or 32kb pages in software.
The x86 and x86_64 processors can respectively also intermix 4mb and 2mb pages along with the standard 4kb  pages. If that capability is used at all, it would mostly be used to allocate kernel space.

A: The page size depends mostly on the processor architecture. On x86, from the times of the 386 processor which introduced protected mode, the page size has been 4 kB.
In x64 mode, there can be also huge pages, which are 2 MB in size. However, using those is a bit complicated.
You can find more information on page size in Wikipedia article


text:
Q: Cannot get Android Studio to ignore changes files when committing to GitHub I am using Android Studio 1.3.2 under Windows 7 in combination with GitHub.
I would like changes made (most often automatically) in some files (class, apk, bin, etc.) and directories (build, etc.) to be ignored.
I have tried putting a ".gitignore" in the project folder and also using the "configure ignored files" button of the "version control" panel, but changes I would like to ignore still seem to get detected in the build folder for instance.
Can anybody recommend the right way to do this?
Regards,
SV

A: first, add the files you need and exclude the ones you don't (after the add) with git checkout . (yes, with the dot). Sadly, those files get modify every time and you must exclude if don't need it to push.


text:
Q: Require Once Failing Relative Path I have the following file structure in my project:
+ server
  + api
    + product
      - get.php
  + database
    - product.php
  + model
    - product.php
  + service
    - product.php
  + utilities
    - controller.php
    - database.php

Then in my server/api/product/get.php I have the following lines:
require_once("../../service/product.php");
require_once("../../utilities/controller.php");

I believe this is properly loading the service because when I use Insomnia to hit the endpoint I am getting this error in the server/api/service/product.php file:

Warning: require_once(../model/product.php): failed to open stream: No
such file or directory in C:\full path removed\server\service\product.php on line 2
Fatal error: require_once(): Failed opening required
'../model/product.php' (include_path='C:\xampp\php\PEAR')

In my server/service/product.php file I have the following:
require_once("../model/product.php");
require_once("../database/product.php");

And it is failing on the first require_once.
So my question to y'all is why would the relative path in my controller layer work, but the relative path in the service layer fail?

A: You could as an alternative use the __DIR__ magic constant as per the documentation the constant gives: 'The directory of the file. If used inside an include, the directory of the included file is returned'. Which reduces the likelihood of errors through relative pathing.
Example:
require_once(__DIR__ . "/../../service/product.php");

A: Use include and require never without __DIR__. A relative path that starts with. or .. has the current directory as a base. The current working directory depends on various settings. __DIR__ is always the directory where the file itself is located.
For include the
server/service/product.php
from the file
server/api/product/get.php
you can do this:
require_once __DIR__."/../../service/product.php";


text:
Q: Why Cookie name and value is 'http' and 'proxy' respectively without having created one in eclipse? I am trying to create a simple cookie program in servlet using eclipse.
This is how it is:-
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Cookie[] cookies = request.getCookies();

    if(cookies == null)
    {
        out.print(" Hello Stranger
");

    }
    else
    {
        for(Cookie cookie:cookies)
        {
            out.print(" Hello" + cookie.getValue() + "");
        }
    }

    out.print("<form action = '' method = 'post'>");
    out.print("What is your name?");
    out.print("<input type = 'text' name = 'username'>
");
    out.print("
");
    out.print("<input type = 'submit'>");
    out.print("</form>");

}

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");

    String str = request.getParameter("username");

    Cookie[] cookies = request.getCookies();

    if (cookies == null)
    {
        Cookie c  = new Cookie("username",str);
        c.setMaxAge(-1);
        response.addCookie(c);
    }

    for(Cookie cookie: cookies)
    {
        out.print(" Hello," + cookie.getName() + "");
    }
}

When running it in the tomcat server using eclipse
instead of getting output as Hello Stranger I am getting Hello http
Even after clicking on submit
It is showing the same thing instead of the name entered.

A: You're iterating through (and printing) the list of cookies contained in the inbound HttpServletRequest, but you're adding the new cookie to the HttpServletResponse.
While the HttpServletResponse has an addCookie() method, it doesn't have a matching getCookies(), so you would need to work around this if your wish to see the cookies you have added to the response object.  There are several posts that cover this, for example here and here.


text:
Q: heroku logs --tail error status 404 on get/post request Whenever I make a post request on my heroku app it responds with a 404 status. What am i am missing in my code to get it to post/get sucessfully? here is the error when i enter heroku logs -tail:
2021-04-14T03:50:52.076702+00:00 heroku[router]: at=info method=GET path="/images/thumbnail_image0.jpg" host=thawing-bastion-89215.herokuapp.com request_id=9bdfae76-50dc-4221-8567-2bfa2f714ab0 fwd="73.189.169.17" dyno=web.1 connect=0ms service=5ms status=404 bytes=442 protocol=https

on my browser i get an error which says
Failed to load resource: the server responded with a status of 404 (Not Found)

locally my post request responds sucessfully with a status 200. and here is my post request on the front end onclick.
handleRequest = (event) => {
    event.preventDefault()
    const data = new FormData();
    const {file} = this.state
     data.append('file', file)

    axios.post('/api/user/myimages',data,{ 'Content-Type':'multipart/form-data',headers: { 'authorization': localStorage.getItem('token')}})
    .then((response)=>{
        const {fileName,filePath} = response.data
        this.setState({uploadedFile:response.data})
        this.getMyImage()
        console.log(response,'postfdsv')
    })

}

for the backend i use express and multer.
const multer = require('multer')

const upload = multer({dest:''})

  router.route('/myimages')
 .get(requireAuth,getMyImages)
 .post(requireAuth,upload.single('file'),postMyImages)

 postMyImages: async (req, res) => {
    const { fileName,filePath } = req.body;
    console.log(req.files,'req files data postMyImages')

    if(req.files === null) {
      return res.status(400).json({msf:'no file uploaded'})
    }

    try {
      const file = req.files.file

      file.mv(`${__dirname}/../client/public/images/${file.name}`,async (err)=>{
        if(err){
          console.error(err)
          return res.status(500).send(err)
        }

        const newImage = await new Image({fileName:file.name,filePath:`/images/${file.name}`, user: req.user._id}).save();
        req.user.myImages.push(newImage);
        await req.user.save();
        return res.status(200).json(newImage);

        // res.json({fileName:file.name,filePath:`./images/${file.name}`})
      })}catch (e) {
      return res.status(403).json({ e });
    }

      // const newImage = await new Image({ fileName, user: req.user._id }).save();
      // const newStock = await Stock.create({ text, user: req.user._id });
      // req.user.myImages.push(newImage);

  }


text:
Q: Symlinks to executables in `/Applications` cannot run I'm trying to create a symlink to emacs, in order to let git use it as default editor.
ln -s /Applications/Emacs.app/Contents/MacOS/Emacs emacs

Calling /Applications/Emacs.app/Contents/MacOS/Emacs directly from terminal works.
Calling ./emacs in that folder gives a pop-up that says:

"This application will not run on your computer. Sorry!"

The symlink has permissions rwxr-xr-x.
I don't feel this is related to emacs, I've tried other applications. For example chess:
$ /Applications/Chess.app/Contents/MacOS/Chess # working
$ ln -s /Applications/Chess.app/Contents/MacOS/Chess chess
$ ./chess
2017-04-19 14:39:05.479 chess[16972:4178764] No Info.plist file in application bundle or no NSPrincipalClass in the Info.plist file, exiting

How can I make a working executable symlink to an application in /Applications?
(next step is to go through a script instead of a symlink, but I'd rather use a symlink.)


text:
Q: Best way to obtain frame value after transform? I have an imageview that has a pinchgesturerecognizer attached to it. In the pinchgesturerecognizer delegate method, I need to calculate the frame value of the transformation before it occurs in order to see if the scaling has pushed the imageview out of the bounds of the window. I know I need to use CGRectApplyAffineTransform to calculate the frame value each time, but since the imageview frame value will be invalid after the first transformation gets performed, do I need to now store the update frame value in an instance variable and keep updating it everytime a transform occurs, or is there someway I can obtain this value from the imageview itself?

A: So you want to check if a UIImageView is inside its window?
I think you can ignore the view frame and instead start your calculations
from the view bounds. This will include the transformation you have applied to the view.
Apple has a section named The Relationship of the Frame, Bounds, and Center Properties in the View Programming Guide for iOS.
CGRect imageViewBounds = imageView.bounds;
CGRect imageViewBoundsInWindow = [imageView convertRect:imageViewBounds
                                                 toView:nil];
CGRect windowBounds = imageView.window.bounds;
if ( CGRectIntersectsRect( windowBounds, imageViewBoundsInWindow ) ) {
     // imageView is visible in its window
}


text:
Q: Huffman Codes Logic Error Inside One of the Functions I wrote my version of Huffman Codes and it does not have any syntax errors. It compiles, but the output is not displaying the correct values. I have a logic error in some of my functions and I cannot find where I am making that mistake.
I have tried to debug it with MS Visual Studio debugger but it was not successful.
This is my version of the Huffman Codes.
I am posting the whole program because I am not certain where is my error located.
/*
    Author: Stevan Milic
    Date: 05.05.2018.
    Course: Data Structures II
    Professor: Dr. Claude Chaudet
    Description: Huffman Codes
*/
#include <iostream>
#include <cstdlib>
using std::cout;
#define MAX_TREE_HEIGHT 1000

// A Huffman tree node
struct MinHeapNode
{
    char codeword; // I chose char because we are inputing alphabetic       letters

    // The reason why I chose unsigned data type is because an unsigned  integer can never be negative.
    // In this case the frequency and the capacity of a character cannot be negative.
    unsigned freq; // Frequency of the character - how many times does it occur

    struct MinHeapNode *left, *right; // Left and Right children
};

struct MinHeap // Collection of nodes
{
    unsigned size; // Size of the heap
    unsigned capacity; // Capacity of the heap
    struct MinHeapNode** array; // Heap node pointers array
};

// Function to dynamically alocate a new heap node with provided character   (codeword) and its frequency
struct MinHeapNode* newHeapNode(char codeword, unsigned freq)
{
    struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct   MinHeapNode));

    temp->left = temp->right = NULL;
    temp->codeword = codeword;
    temp->freq = freq;

    return temp;
}

// Creating a new dynamically allocated min heap with given capacity
struct MinHeap* createMinHeap(unsigned capacity)
{
    struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
    minHeap->size = 0; // Setting the size to 0
    minHeap->capacity = capacity; // Inserting the given capacity
    // Inserting into the heap node pointers array
    minHeap->array= (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*));
    return minHeap;
}

// Swap function to swap two min heap nodes
void swap(struct MinHeapNode** a, struct MinHeapNode** b)
{
    struct MinHeapNode* temp2 = *a;
    *a = *b;
    *b = temp2;
}
// minHeapify function
void minHeapify(struct MinHeap* minHeap, int index)
{
    int smallest = index;
    int leftSon = 2 * index + 1;
    int rightSon = 2 * index + 2;

    if (leftSon < minHeap->size && minHeap->array[leftSon]->freq <      minHeap->array[smallest]->freq)
        smallest = leftSon;

    if (rightSon < minHeap->size && minHeap->array[rightSon]-> freq < minHeap->array[smallest]->freq)
        smallest = rightSon;

    if (smallest != index)
    {
        swap(&minHeap->array[smallest], &minHeap->array[index]);
        minHeapify(minHeap, smallest);
    }
}

// Checking if the size of the heap is 1
int heapSizeOne(struct MinHeap* minHeap)
{
    return (minHeap->size == 1);
}

// Extracting minimum value node from the heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)
{
    struct MinHeapNode* temp = minHeap->array[0];
    minHeap->array[0] = minHeap->array[minHeap->size - 1];
    --minHeap->size;
    minHeapify(minHeap, 0);
    return temp;
}

// Inserting a new node into min heap
void insert(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)
{
    ++minHeap->size;
    int i = minHeap->size - 1;
    while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq)
    {
        minHeap->array[i] = minHeap->array[(i - 1) / 2];
        i = (i - 1) / 2;
    }
    minHeap->array[i] = minHeapNode;
}

// Build function to build min heap
void build(struct MinHeap* minHeap)
{
    int n = minHeap->size - 1;
    for (int i = (n - 1) / 2; i >= 0; --i)
        minHeapify(minHeap, i);
}

// Display function to print an array
void display(int arr[], int n)
{
    int i;
    for (i = 0; i < n; ++i)
        std::cout << arr[i];
    std::cout << "\n";
}

// Function to check if the node is a leaf
int isLeaf(struct MinHeapNode* root)
{
    return !(root->left) && !(root->right);
}

// Creating a min heap with given capacity equivalent to size and inserts all    the codewords and their frequency.
struct MinHeap* create(char codeword[], int freq[], int size)
{
    struct MinHeap* minHeap = createMinHeap(size);
    for (int i = 0; i < size; ++i)
        minHeap->array[i] = newHeapNode(codeword[i], freq[i]);
    minHeap->size = size;
    build(minHeap);
    return minHeap;
}

// Function that builds the Huffman tree
struct MinHeapNode* buildHT(char codeword[], int freq[], int size)
{
    struct MinHeapNode *left, *right, *top;

    // Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency.
    struct MinHeap* minHeap = create(codeword, freq, size);

    // while loop runs as long as the size of heap doesn't reach 1
    while (!heapSizeOne(minHeap))
    {
        // Getting the two minimums from min heap
        left = extractMin(minHeap);
        right = extractMin(minHeap);

        // The frequency of top is computed as the sum of the frequencies of left and right nodes.
        top = newHeapNode('_', left->freq + right->freq);
        top->left = left;
        top->right = right;
        insert(minHeap, top);
    }
    // The remaining value is the root node which completes the tree
    return extractMin(minHeap);
}

// Prints huffman codes from the root of
// Displaying Huffman codes
void displayHC(struct MinHeapNode* root, int arr[], int top)
{

    // Left side is given the value 0
    if (root->left)
    {
        arr[top] = 0;
        displayHC(root->left, arr, top + 1);
    }
    // Right side is given the value 1
    if (root->right)
    {
        arr[top] = 1;
        displayHC(root->right, arr, top + 1);
    }
    // If this is a leaf node, print the character and its code.
    if (isLeaf(root))
    {
        std::cout << root->codeword << ": ";
        display(arr, top);
    }
}

// Building a Huffman Tree and displaying the codes
void HuffmanCodes(char codeword[], int freq[], int size)

{
    // Building a HT
    struct MinHeapNode* root = buildHT(codeword, freq, size);

    // Displaying the HT we built
    int arr[MAX_TREE_HEIGHT], top = 0;

    displayHC(root, arr, top);
}

// I used the example from the PP presentation in the Files section - The Hoffman Coding
int main()
{
    std::cout << "A|4\t B|0\t C|2\t D|1\t C|5\t E|1\t F|0\t G|1\t H|1\t I|0\t J|0\t K|3\t L|2\t M|0\t N|1\t\nO|2\t P|0\t Q|3\t R|5\t S|4\t T|2\t U|0\t V|0\t W|1\t X|0\t Y|0\t Z|0\t _|6\n" << endl;
    char arr[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_' };
    int freq[] = { 4, 0, 2, 1, 5, 1, 0, 1, 1, 0, 0, 3, 2, 0, 1, 2, 0, 3, 5, 4, 2, 0, 0, 1, 0, 0, 6};

    int size = sizeof(arr) / sizeof(arr[0]);

    HuffmanCodes(arr, freq, size);

    std::cout << "\n\n";
    return 0;
}

For example, I expect the code to output A: 0101 but it outputs A: 001
Another example, I expect C to be C: 1111 but it outputs C: 11111

A: I don't think that you have any problem in your code. In fact the problem is in your question, since you are assuming that there is a single correct Huffman code for a given distribution. This is never true. You have many possible Huffman codes even when lengths are not interchangeable, just by changing 0 and 1 at any node. In your specific case you have C which belongs to the group CMPU of letters with frequency 2. You can exchange their lengths and codes as you wish without impacting the average code length. In particular two should have a length of 5 and two should have a length of 4. Check if this is true in your manually built output. The same holds for A, which has a frequency of 4 as T. So you should check if A and T have a code length of 3 and 4 or viceversa.
An easy check is to compute the average code length of your distribution, which should be   3.886, pretty near to the Entropy which is 3.818.
I don't think you checked the order in which the data is returned after being placed in the heap, so weird things may happen.


text:
Q: Teamcity - manually restart a test through web interface In a project with multiple sub components(workflows), I was hoping to just restart a single workflow. Previously in Github actions you could just click into the failed test and there was a button to just click restart workflow, is there something similar in Teamcity, if it exists a screenshot of this would be greatly appreciated.
Edit:
In the end the solution was because I was part of an organisation, and at the time not given the correct permissions in Teamcity, so the blue run button on the top right was not showing. Once permissions were fixed it became easy to re run the tests.

A: You can manually re-run a job.  Like this Experimental UI or like this Classic UI.
If you want to have a job retry on failure, then you can add a Retry Trigger