text:
Q: Managing Maven dependencies between multiple components with multiple teams making changes In a situation where there are multiple teams making changes to some Maven projects with dependencies between them (otherwise unrelated projects i.e. no super POM or anything like that), with each team working in a separate working branch on all of these projects and merging them back to trunk only after a story is complete and tested, how should one handle the dependencies between snapshot builds that each team produces?
Note that any of the teams could be making changes in any of the projects: they work on different pieces of functionality of the same system, and the projects are more like different layers.
Before the split into multiple teams, artifacts were deployed to a central Nexus repository.  Of course, it would be possible to set up separate Nexus repositories for each team, and an additional one for trunk, but I'm hoping there would be a better way to deal with this.

A: TL;DR: Use release dependencies instead of snapshot ones.

Case to consider when choosing between snapshot and release dependencies is when changes in some component (A) break a dependent component (B).
When this happens, you need to fix it, but there are two options, one of which might turn out preferable depending on your project specifics.
One option is when you prefer to fix the issue immediately, even though it may come at cost of distracting developer working on component A. Benefit of this approach is its conceptual simplicity - it relieves developers from the need to memorize, maintain and update dependencies between components, because instead their efforts are focused on simply keeping all the most recent versions of components in sync.
In this case, release dependencies don't offer anything appealing compared to snapshot ones; rather the opposite - these would introduce an extra step / effort to release updated component A to be able to test whether dependent component doesn't break anymore.

*

*By the way, Maven provides support for a simplest form of snapshot dependency preference: multi-module projects, where handling snapshot dependencies between modules is made as easy as it gets (though this comes at the expense of simultaneous releases, which is sometimes undesirable - eg when components / modules tend to change at very different pace).
An opposite option is when you would prefer to postpone integration fixes in the component A, for example when you believe that in your project it is more important for developer to strongly focus on the changes made in it and switch their efforts to integration later. This could be the case when dependencies between components are "loose", small, carefully designed and slowly changing interfaces.

*

*For example, if you already have carefully crafted, thoroughly tested, clean and convenient interface between components A and B, you may prefer to postpone messing in B while you're polishing changes roughly drafted in A, expecting that it will take less effort to integrate after interface at A side gets clean back again.
In cases like this release dependencies allow you to totally isolate dependent component. You don't need to worry about component B at all, until you are done with A and modify dependency in B to refer desired release. Snapshot dependencies can not offer anything like this: if changes made in A break dependent component, you'll have to put an effort into bringing things back to shape.

Now, let's see how above applies in your case,

*

*unrelated projects

*each team working in a separate working branch

*split into multiple teams

All of the above whispers, says, cries that team is moving in a direction allowing more independent, more isolated work on the components of the system. So that John working on a project A, Paul working on B, George working on C and Ringo working on D have a leeway in planning and implementing changes within these components without permanently having to look at what happens in other components.
Now, let's look from above perspective at "dependencies between snapshot builds that each team produces". The way how Maven works, this would mean a huge step back into what team is supposed to move away from. the very moment John makes an intermittent change in A and builds a snapshot, Maven immediately picks that snapshot and "broadcasts" it into projects of Paul, George and Ringo!
Now, three guys working in other projects have to adapt to changes made by John and, if these changes cause some serious trouble in other projects, most likely John will have to break his flow and urgently adapt their project to... oh by the way to what is he going to adapt? Paul, George and Ringo, they all work like John, their projects are permanently changing, are they supposed to explain to John what exactly he needs to take into account for today, and what he possibly will have to account for tomorrow?
You see, if team is supposed to move to more independent development of different components / projects, using snapshot dependencies essentially totally breaks this movement and returns you back to the days of monolithic approach.
If you want to keep moving to stronger separated components / projects, you better have to define "communication points" at which these projects would "declare" their readiness / obligation to integrate with others. In Maven, releases naturally serve this purpose.
Maven releases provide stable, fixed "checkpoints" allowing project developer to safely communicate with outer world.

*

*Release 2.15.23 is most recent one ready to be integrated; we no longer support / accept bug reports against releases earlier than 2.14.999; releases 2.15.24 and later ones currently suffer from a critical issue and are by no means intended for integration until further notice.

Worth stressing that release dependencies denote stable "checkpoints" between components, not between people. Whether components are maintained by separate developers or not isn't really relevant.
Even if you have, say, John working in both components A and B or maybe John and Paul together working on these two components, it still makes sense to have release dependencies, to allow programmer focus on work in currently chosen component, without being permanently distracted with worries about how this could impact another.
Given above, you also need to decide between teams how exactly are you going to schedule releases to make integration as smooth as possible. Here your options are really broad. A natural "schedule" that comes to mind is that each team decides when they're ready to offer a "checkpoint" of their work for other teams to integrate.
However natural ad-hoc releases sound "from within" a single team, if you look at it from the perspective of other teams, you may find that they would prefer to have a more regular way to get to "integration checkpoints" - from this perspective, you may wish to consider some predictable ways to "promote" component updates for other teams attention - monthly, or weekly, or maybe daily releases.

Now that your system became more complicated, specifics and purpose of snapshot dependencies are worth taking a closer look at. You can find a pretty decent explanation of this in Maven: The Complete Reference at Sonatype (bold font in below quote is mine):

...when you deploy a snapshot, you are not making a release of a software component; you are releasing a snapshot of a component at a specific time.
Why would you use this? SNAPSHOT versions are used for projects under active development. If your project depends on a software component that is under active development, you can depend on a SNAPSHOT release, and Maven will periodically attempt to download the latest snapshot from a repository when you run a build. Similarly, if the next release of your system is going to have a version "1.4", your project would have a version "1.4-SNAPSHOT" until it was formally released...
If a project depends on a SNAPSHOT, it is not stable as the dependencies may change over time... SNAPSHOT versions are for development only...

As you can see, above stresses temporary, intermittent, unstable nature of snapshot dependencies and limits their applicability to times of "active development". In your case, you can think of temporarily switching to snapshot dependency when you need to do series of closely correlated, synchronized, tightly coupled changes in different components. After this "active" phase is over, you can do "checkpoint" releases of involved components and switch back to release dependencies.
Note by the way that if you discover that switching to snapshot dependency happens too often, this might indicate a need to rethink your design. You may think of ways to better isolate components, or of opposite, that is, of "merging" previously separate components back into monolithic, synchronously developed and released module.

A: Source code repositories have branches, binary ones don't. So any part of your development plan that relies on branching can't rely on binary repositores for things that are in the scope of branches.
(One exception to the above is ClearCase, which does do both, and is best not spoken of.)
If the teams are to be independant, you really do need to manage the dependencies in terms of released versions. This will be painful; what you are doing is hard. Probably have to get used to planning and discussing changes in advance, abandoning ad-hoc refactoring.
On the other hand, perhaps the teams are really only nominal, e.g. everyone is all working together to a single overall product release/delivery schedule. Then just keep to a single overall version number that gets bumped any time a feature branch is merged back to master. All local dependencies then simply use {project.version}.
Note that this is still not a snapshot, as you never update it without changing the number.
And then within a team share code not binaries. Some extra recompilation, but if that takes more than 15 seconds, get faster PCs. And anyone not using a multi-module IDE like eclipse will have to write a trivial reactor-build POM to cover the set of modules they are currently working on.
See:
http://books.sonatype.com/m2eclipse-book/reference/eclipse.html
http://axelfontaine.com/blog/final-nail.html
http://ahoehma.wordpress.com/2010/12/22/intermodule-dependencies-now-better-working-with-maven-3/
For how to set up an IDE, CI build server and reactor build for this kind of situation.
Or, you could try reimplementing ClearCase with some scripting on top of git+Nexus (don't do this).


text:
Q: Difference String on Postgres I have two string that contain one and zeros. I want to determine how many chars are different the same position.
For example:
"0000111000000000000000000000000000000000000000000000000000000000"
AND
"0000000000000010000110000111100000000000000000000000000000000000"
The result is: 10
These strings' length are 64 always;
I can do it with loop which iterate over the string and count difference. but i want to do it with reg exp or another tool. The speed is important me. Because i have a lot of data to compare.

A: Cast the strings to bit(64), use bitwise XOR, cast the result to text and count the 1 chars:
select length(replace(
    ( '0000111000000000000000000000000000000000000000000000000000000000'::bit(64)
    # '0000000000000010000110000111100000000000000000000000000000000000'::bit(64))::text,
    '0', ''))

 length
--------
     10
(1 row)

A: klin's solution works for this particular problem.  A more general approach is to separate the values, one character per row, and count them:
select count(*)
from unnest(regexp_split_to_array('0000111000000000000000000000000000000000000000000000000000000000', ''),
            regexp_split_to_array('0000000000000010000110000111100000000000000000000000000000000000', '')
           ) u(a, b)
where a <> b;

I'm pretty sure klin's answer will be faster (although it is always worth testing such things).  But this is more general, in terms of the length of the strings and the values being compared.

A: You shouldn't store the data as strings, but as bit strings in postgres. This will enable you to call xor for the two strings and then you can can count the number of ones set.
The following page describes bit strings
To count the bits sets you can write your own function or use the pg_bitcount extension

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the goal to contains the information about static variables in the symbols table? I'm trying to understand .symtab setcion type for the relocatable object files. And I know, that it contains information about static variables. But why?
All we need to do for linking relocatable object files with some other is relocate adresess of this static variable (And some others, of course, but it's don't matter for static variables). So all that we need to have -- is relocation table that stored in .rel.data and contains all information to relocate static variable, isn't it?

A: But for debugging it can be quite useful to know where the variables are.

A: Not sure on your compiler, but for the IBM AIX Compiler, the default is to not add static variables to the symbol table.
However, for debugging it is quite useful for say, gdb, to know what the static variables contain and the related symbols so it would make sense for them to appear there.


text:
Q: Как в laravel+ajax прописать путь на запрос, чтобы не было ошибок? Сегодня я залил проект на хостинг- поддомен https://tst.uz/medreports/public.
У меня проект на laravel, где я использую ajax запрос:
const containerAdd = $('#tbody')
    $.ajax({
        type: 'GET',
        url: '/patients',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            containerAdd.html('');

Выходит ошибка, но это понятно-т.к мне нужен сделать так:url: 'medreports/public/patients'.Но в этом случае у меня выходит ошибка и почему то запрос на url выглядит так:
https://tst.uz/medreports/public/medreports/public/patients

Помогите,пожалуйста, решить эту проблему.


text:
Q: Entity Data Filtering - payara41-web-4.1.1.164 with Jersey - How to ObjectProvider I am trying to obtain the ObjectProvider in a MessageBodyReader. But it ends up with the and CDI-Error: "WELD-001334: Unsatisfied dependencies for type ObjectProvider with qualifiers @Default". The idea is to map the ObjectProvider from Jersey to a EntityGraph from JPA. Below the code:
import org.glassfish.jersey.message.filtering.spi.FilteringHelper;
import org.glassfish.jersey.message.filtering.spi.ObjectGraph;
import org.glassfish.jersey.message.filtering.spi.ObjectProvider;

@ApplicationScoped
@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class ObjectGraphMessageBodyReader extends JacksonJsonProvider {

  @Inject
  private javax.inject.Provider<ObjectProvider<ObjectGraph>> provider;

I gabbed the code from: https://github.com/jersey/jersey/blob/master/tests/e2e/src/test/java/org/glassfish/jersey/tests/e2e/entity/filtering/FilteringMessageBodyProvider.java


text:
Q: The period of $\sin(nx)$ How can I prove with induction that period of $\sin(nx)$ is $\frac{2\pi}{n}$? I know how to prove this using a different method, but I need to prove it with induction.

A: Note that $$f(x)$$ hase nthe period $T$ if $$f(x+T)=f(x)$$ for all $$x$$ in the domain of $$f(x)$$


text:
Q: Can I solve an Euler differential equation by using the Frobenius method? I'm having some trouble by trying to solve Euler equations by using the Frobenius method. For example, I'm asked to solve the Euler differential equation
$$ x^2y'' + xy' - y = 0 $$
using a power series solution.
I start by assuming there is at least one solution with the form $ y = x^\sigma\sum{a_nx^n} $.
First, I divide the whole differential equation by $x^2$. Then I substitute the expression above so I get
$$\sum{(n+\sigma)(n+\sigma-1)a_nx^{n+\sigma-2}} + \frac{1}{x}\sum{(n+\sigma)a_nx^{n+\sigma-1}}-\frac{1}{x^2}\sum{a_nx^{n+\sigma}}$$
And now, dividing by $ x^{\sigma-2}$, I get
$$\sum{((n+\sigma)(n+\sigma-1)+(n+\sigma) - 1})a_nx^n $$
Now I don't know how to find the recurrence relation I'm looking for in order to find the form of $a_n$. In all the examples I've been able to find, in the last expression one always finds terms of $a_{n-1}$, for example, but here I don't know how to continue.
Did I do something wrong? I'm confused because I believe the equation given fits the requeriments needed in order to the Frobenius method to be applicable, but this happens to me every time I try to solve an Euler equation using it.
Thank you very much in advance.

A: First you need the indicial equation: we have
$$((n+\sigma)(n+\sigma-1)+(n+\sigma)-1)a_n=0\tag{$*$}$$
for all $n$, and you can assume that $a_0\ne0$, otherwise take a different value of $\sigma$.  So taking $n=0$ gives
$$\sigma(\sigma-1)+\sigma-1=0$$
and hence $\sigma=\pm1$.  Considering $\sigma=-1$, equation $(*)$ becomes
$$(n^2-2n)a_n=0$$
for all $n$; therefore $a_0$ and $a_2$ are arbitrary, all others must be zero.  So your solution is
$$y=x^{-1}(a_0+a_2x^2)=a_0x^{-1}+a_2x\ .$$
It is easy to check that this is a solution of your DE, and it has two arbitrary constants, as expected.

If you take $\sigma=1$, a similar process gives only $a_0$ non-zero, so $y=a_0x$, which is already included in the above solution.  When the roots of the indicial equation differ by an integer, sometimes (though not here) it is necessary to seek an alternative form of solution.  Try searching for "frobenius method solutions differ by an integer".


text:
Q: Unity - Animation Loops? I am using an FBX 3D object file as a game object in my project which have further sub assemblies. Now i want to animate a part of the assembly.
I followed this process:

*

*Select the part which I want to animate.

*In the animation panel create one animation.

*Add property > transform > position

*Using pivot, i move that part to the location where I want to animate.

Challenges

*

*Animate in loop. Moreover if I Select animation file, it does not show Wrap mode
(   1. I don't want any loops in my animation, even after deselecting loop-time it does loop. - I dont know why?

*It is animating in reverse. suppose if the object needs to go from           position x:3 to position x:8 but it goes from position x:8 to position x:3

*the above point happens in loop. just like a ping pong)

*Animates in reverse.

*I take the whole animation as one loop i.e Part comes out of assembly and goes back and repeating for infinite time.

I want to stop the animation till the point it comes out.
Any help will be appreciated


text:
Q: How to avoid background color opactity issue when I animate an image or smth else? This screenshot and code snippet will show you my trouble. How to avoid this? May be I do this in wrong way? I would like to see some code example, if possible.

let canvas = document.querySelector("canvas");
 let ctx = canvas.getContext("2d");

 canvas.width = 500;
 canvas.height = 500;

 let image = new Image();

 image.src= "https://www.html5rocks.com/static/images/identity/HTML5_Badge_256.png";

 function rand(min, max)
 {
  return Math.floor(Math.random() * (max - min + 1)) + min;
 }

 image.addEventListener("load", function()
 {

  let top = canvas.width / 2 - image.width / 2;
  let left = canvas.height / 2 - image.height / 2;

  function render()
  {

   top += rand(-2, 2);
   left += rand(-2, 2);

   ctx.save();
   ctx.globalAlpha = 0.05;
   ctx.fillStyle = "#9ea7b8";
   ctx.fillRect(0, 0, canvas.width, canvas.height);
   ctx.restore();
   ctx.drawImage(image, top, left, image.width, image.height);
   requestAnimationFrame(render);
  }

  render();
 });
<canvas></canvas>

A: Ok, after a lot of tries, job is done. Every frame I draw full path.

let canvas = document.querySelector("canvas");
 let ctx = canvas.getContext("2d");
 let tail = 20;

 canvas.width = 800;
 canvas.height = 600;

 let image = new Image();

 let opacity = [];

 image.src= "https://www.html5rocks.com/static/images/identity/HTML5_Badge_256.png";

 for(let i = 1; i <= tail; i++)
 {
  opacity.push(i / tail);
 }

 function rand(min, max)
 {
  return Math.floor(Math.random() * (max - min + 1)) + min;
 }

 image.addEventListener("load", function()
 {

  let frames = [];

  frames.push({
   x: canvas.width / 2 - image.width / 2,
   y: canvas.height / 2 - image.height / 2
  });

  for (let i = 1; i < tail; i++)
  {
   frames.push({
    x: frames[i - 1].x + rand(-2, 2),
    y: frames[i - 1].y + rand(-2, 2)
   });
  }

  function render()
  {

   frames.shift();
   frames.push({
    x: frames[frames.length - 1].x + rand(-2, 2),
    y: frames[frames.length - 1].y + rand(-2, 2)
   });

   ctx.globalAlpha = 1;
   ctx.fillStyle = "#9ea7b8";
   ctx.fillRect(0, 0, canvas.width, canvas.height);

   for(let i = 0; i < tail; i++)
   {
    ctx.save();
    ctx.drawImage(image, frames[i].x, frames[i].y, image.width, image.height);
    ctx.globalAlpha = opacity[tail - 1 - i];
    ctx.fillRect(frames[i].x - tail, frames[i].y - tail, image.width + tail + tail, image.height + tail + tail);
    ctx.restore();
   }

   requestAnimationFrame(render);
  }

  render();
 });
<canvas></canvas>

A: The problem
The best way I can think of to describe this artifact is to call it a rounding error. One thing that people tend to forget, is that when you draw to a canvas, you are actually writing to a bitmap. Effectively an image. The alpha value per pixel is an integer, x, where 0 <= x <= 255.
So, when you say:
ctx.save();
ctx.globalAlpha = 0.05;
ctx.fillStyle = "#9ea7b8";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ctx.drawImage(image, top, left, image.width, image.height);

You are drawing a mostly transparent square which won't make anything disappear fully. For instance, if a pixel has a color of rgba(254,255,255,255) and you draw over it with a white square at 0.05 opacity, rgba(255,255,255,12), it will pull the red from 254 up to 254.05. This needs to be an integer, though, so it gets rounded down, and will never fully become the color it is approaching.
Now how to fix it

*

*One way I can think to fix this is to basically make a snake. You can use a circular array to store the positions of each, progressively more transparent image, and then draw them once you clear the screen. There is a problem with this though, it takes up a bit more room, and takes a bit longer to draw.

*You can go through the image data and if a pixel is close enough, you make it what you want. I won't provide finished code for you, but you can use ctx.getImageData().

Pixel comparisons should be similar to
if(abs(actualRed-targetRed) < tolerance && abs(actualGreen-targetGreen) < tolerance....){
    actualRed=targetRed;
    actualGreen=targetGreen...
}

*This page has a very interesting approach. Basically, it manipulates the alpha values of the picture directly, instead of drawing a transparent picture over it. You want a background color, apparently. This starts to complicate things, but not too badly. I would suggest separating the dynamic images from the static images. You can have two canvases that are stacked on top of one another (this is best practice, actually). Or you can just set the background of the canvas.

Hopefully this helped.


text:
Q: Fast way to import 24000 single variation products to Shopify I want to import ~24000 (single variation) products to Shopify every night at 04:00.
The problem with the default Admin > Products > Import > CSV method is that it takes an unacceptably long time to finish. So I started working with the Shopify API using their Ruby gem.
The Shopify API has an API call limit of 2 calls per second, with room for a burst of 40 calls at once. You can read more about the API call limit here. I don't understand the "room for a burst of 40 calls at once" part.
A Shopify Employee told me the following about importing products via the API:

If you were to make Product creation API requests that includes the
  variant information in them (assuming 3 variants per product) and
  using a default API limit (refresh of 2 requests per second, or 2
  concurrent requests) you could probably finish creating all those
  products in about 67 minutes.

I wrote the following Ruby script to import all products to Shopify:
require 'shopify_api'
require 'open-uri'
require 'json'

begin_time = Time.now

shop_url  = "https://<API_KEY>:<PASSWORD>@<SHOPNAME>.myshopify.com/admin"

ShopifyAPI::Base.site = shop_url

raw_product_data = JSON.parse(open('<LINK>') {|f| f.read }.force_encoding('UTF-8'))
raw_product_data_size = raw_product_data.size

puts '========================================================================='
puts "#{raw_product_data_size} products loaded. Starting import now..."
puts '-------------------------------------------------------------------------'

raw_product_data.each_with_index do |item, index|
  single_product_begin_time = Time.now

  # Store item data in variables
  <DATA>

  # Create new product
  new_product = ShopifyAPI::Product.new
  new_product.title = title
  new_product.body_html = body
  new_product.product_type = type
  new_product.vendor = vendor
  new_product.tags = tags

  new_product.variants = [
    {
      "option_1" => "First",
      "price" => variant_price,
      "sku" => variant_sku
    }
  ]

  new_product.images = [
    {
      src: image_src
    }
  ]

  new_product.save

  creation_time = Time.now - single_product_begin_time

  puts "#{((index / raw_product_data_size.to_f) * 100).round(2)}% - #{index} - #{variant_sku} added in #{creation_time.round(2)} seconds"
end

puts '-------------------------------------------------------------------------'
puts "Done. It took #{begin_time - Time.now} minutes."
puts '========================================================================='

But I'm not getting anywhere near the 67 minutes.
It currently takes around 3 seconds to add a single product. At this rate it would take 20 hours to add 24000 products. That's unacceptable. Everything under 2 hours is acceptable.
What could I try to speed things up?

A: Short and sweet answer, use multithreading.
Since a single product took ~3 seconds to import, my solution is having 5 workers (threads) running the product import and checking for 429 errors. If they hit a 429, they pause for 10 seconds and then retry. It currently takes ~3,6 hours to import ~26000 product.

A: Another option here is avoiding throttling requests until you start hitting rate limit errors from shopify. This ensures that you are taking advantage of the burst limits and only pausing when the Shopify API is rate limiting you.
I wrote a gem which handles detecting the 429 error (and other network errors) and automatically retrying based on an exponential backoff schedule.
https://github.com/iloveitaly/shopify_api_extensions/
I believe Shopify also has the option of increasing your rate limit. Contact their support to see if they can raise the limits on your account.


text:
Q: How to Keep element absolute at their location bootstrap 3 I have some problem with position element can not keep absolute position in resize window (in responsive)
after resposive absolute element shift the ratio parent
How i can keep it ?
In bootplay my code (if resized absolute element to the right) :
Bootplay

          right

Element

Element

Element

Element

CSS :
/* CSS used here will be applied after bootstrap.css */

.right-section {
  background-color: #e3e3e3;
}

.image {
  width: 200px;
  height: 200px;
  background-color: #9EC7E3;
  border-radius: 50%;
}

.type {
  background-color: red;
  position: absolute;
  top: 120px;
  right: 5px;
  padding: 10px;
}

A: The problem is that the absolutely positioned
Element
 elements are positioned relative to the column divs, not the

 circles.
If you move the absolutely positioned element inside the circle image divs, and then make those position: relative;, you should get what you're after:
HTML:

Element

CSS:
.image {
  width: 200px;
  height: 200px;
  background-color: #9EC7E3;
  border-radius: 50%;
  position: relative;
}


text:
Q: How to skip hook configurations for control sequences that don't exist? How can we make tex4ht skip a configuration for a hook if the corresponding control sequence doesn't exist?
Suppose we have a 4ht file that contains a configuration for \chapter.
\Configure{chapter}
  {<beginning of chapter>}   {<end of the chapter>}
  {<before chapter heading>} {<after chapter heading>}

but we are using our 4ht file with a document class, such as article, which lacks \chapter. Then we get the following warning:
l.10 --- TeX4ht warning --- \Configure{chapter}? ---

A: This is the default definition of \Configure command:
 \def\Configure#1{%
  \expandafter\ifx \csname c:#1:\endcsname\relax
     \:warning{\string\Configure{#1}?}
  \fi
  \csname c:#1:\endcsname}

the c:#1: command is defined by \NewConfigure for particular particular configuration and takes care of \Configure's parameters. The problem is, if the configuration isn't defined, the parameters aren't handled and they end in the document:
...
<html xmlns="http://www.w3.org/1999/xhtml"
>
<head>  ¡beginning of chapter¿ ¡end of the chapter¿ ¡before chapter heading¿ ¡after
chapter heading¿ <title></title>
...

As the number of parameters for \Configure isn't fixed, but depends on declaration by \NewConfigure, it is not easy to handle this situation automatically.
Possible solution would be to declare the configuration in the config file in the case it doesn't exist yet:
\newcommand\DeclareConfigure[2]{%
  \expandafter\ifx \csname c:#1:\endcsname\relax%
    \NewConfigure{#1}{#2}%
  \fi%
}

this command uses the trick for checking configuration existence and declares the configuration if it doesn't exist. First parameter is configuration name, second is number of arguments. Full example:
\newcommand\DeclareConfigure[2]{%
  \expandafter\ifx \csname c:#1:\endcsname\relax%
    \NewConfigure{#1}{#2}%
  \fi%
}

\Preamble{xhtml}
\DeclareConfigure{chapter}{4}
\begin{document}
\Configure{chapter}
  {<beginning of chapter>}   {<end of the chapter>}
    {<before chapter heading>} {<after chapter heading>}
\EndPreamble

\Configure{chapter} takes four parameters, so we need to use \DeclareConfigure{chapter}{4}


text:
Q: Identify which country won the most gold, in each olympic games When I write the below codes in pandas
gold.groupby(['Games','country'])['Medal'].value_counts()

I get the below result, how to extract the top medal winner for each Games,The result should be all the games,country with most medal,medal tally
Games        country     Medal
1896 Summer  Australia   Gold       2
             Austria     Gold       2
             Denmark     Gold       1
             France      Gold       5
             Germany     Gold      25
                                 ...
2016 Summer  UK          Gold      64
             USA         Gold     139
             Ukraine     Gold       2
             Uzbekistan  Gold       4
             Vietnam     Gold       1
Name: Medal, Length: 1101, dtype: int64

    ID  Name    Sex Age Height  Weight  Team    NOC Games   Year    Season  City    Sport   Event   Medal   country notes
68  17294   Cai Yalin   M   23.0    174.0   60.0    China   CHN 2000 Summer 2000    Summer  Sydney  Shooting    Shooting Men's Air Rifle, 10 metres Gold    China   NaN
77  17299   Cai Yun M   32.0    181.0   68.0    China-1 CHN 2012 Summer 2012    Summer  London  Badminton   Badminton Men's Doubles Gold    China   NaN
87  17995   Cao Lei F   24.0    168.0   75.0    China   CHN 2008 Summer 2008    Summer  Beijing Weightlifting   Weightlifting Women's Heavyweight   Gold    China   NaN
104 18005   Cao Yuan    M   17.0    160.0   42.0    China   CHN 2012 Summer 2012    Summer  London  Diving  Diving Men's Synchronized Platform  Gold    China   NaN
105 18005   Cao Yuan    M   21.0    160.0   42.0    China   CHN 2016 Summer 2016    Summer  Rio de Janeiro  Diving  Diving Men's Springboard    Gold    China   NaN

A: The data Your data only included Chinese gold medal winners so I added a row:
  ID             Name Sex   Age  Height  Weight     Team  NOC  \
0   17294        Cai Yalin   M  23.0   174.0    60.0    China  CHN
1   17299          Cai Yun   M  32.0   181.0    68.0  China-1  CHN
2   17995          Cao Lei   F  24.0   168.0    75.0    China  CHN
3   18005         Cao Yuan   M  17.0   160.0    42.0    China  CHN
4   18005         Cao Yuan   M  21.0   160.0    42.0    China  CHN
5  292929  Serge de Gosson   M  52.0   178.0    69.0   France   FR

         Games  Year  Season            City          Sport  \
0  2000 Summer  2000  Summer          Sydney       Shooting
1  2012 Summer  2012  Summer          London      Badminton
2  2008 Summer  2008  Summer         Beijing  Weightlifting
3  2012 Summer  2012  Summer          London         Diving
4  2016 Summer  2016  Summer  Rio de Janeiro         Diving
5  2022 Summer  2022  Summer       Stockholm   Calisthenics

                                 Event Medal country  notes
0  Shooting Men's Air Rifle, 10 metres  Gold   China    NaN
1              Badminton Men's Doubles  Gold   China    NaN
2    Weightlifting Women's Heavyweight  Gold   China    NaN
3   Diving Men's Synchronized Platform  Gold   China    NaN
4             Diving Men's Springboard  Gold   China    NaN
5                              Planche  Gold  France    NaN

YOu want to de exactly what you did but sort the data and keep the top row:
gold.groupby(['Games','country'])['Medal'].value_counts().groupby(level=0, group_keys=False).head(1)

Which returns:
Games        country  Medal
2000 Summer  China    Gold     1
2008 Summer  China    Gold     1
2012 Summer  China    Gold     2
2016 Summer  China    Gold     1
2022 Summer  France   Gold     1
Name: Medal, dtype: int64

or as a dataframe:
GOLD_TOP = pd.DataFrame(gold.groupby(['Games','country'])['Medal'].value_counts().groupby(level=0, group_keys=False).head(1))

A: df_gold = df[df["Medal"]=="Gold"].groupby("Team").Medal.count().reset_index()
df_gold = df_gold.sort_values(by="Medal",ascending=False)[:8]
df_gold


text:
Q: How to rename Pandas dataframe to the value of a variable name I am trying to create a stock trading algorithm with python and pandas, in which I am making a function that I can pass a list of tickers and it will calculate a dataframe for each of the tickers passed. I want the name of each dataframe to be like df_ + "ticker name". So if I pass aapl and msft it will create two dataframes one called df_aapl and one called df_msft. In the function I have a variable called df_name which holds the value of 'df'+ tickername concatenated together. How do I rename the dataframe once it is created to the value of the df_name variable i.e. "df_appl" instead of "df_name". The line that says df_name = df is what needs fixed.
As a side note, call me dumb, but I cannot figure out how to rename a dataframe without making a copy. So help with that would be appreciated too.
def calcTickerData(ticker):
    df_name = 'df' + ticker

#get dataframe for ticker from alphavantage
    ts = TimeSeries(key = av_api_key, output_format ='pandas')
    df, meta_data = ts.get_daily(symbol = ticker, outputsize = 'compact')

#rename dataframe
    df_name = df
    return df_name
calcTickerData('AAPL')

A: You can use 'exec'
x='Foo'
exec("%s = %s" % (x,'Bar'))

This will return
Foo = 'Bar'

This same concept can be extrapolated into your case.
However, there might be better ways than to dynamically create variables, and this should only be used if you're sure this is the best option.


text:
Q: Insert data to sqlite android I have following query to insert values in sqlite table,
Insert Into T (Test) Values (' 42'SIZE ')

But it give me an error for inserting such data.
This is valid SQL syntax.
I am just in problem with 42 Inches = ' 42'LED TV Size ' should be inserting into the db.

A: It should be:
INSERT INTO T (Test) VALUES ('42', SIZE)

(assuming 'T' is your table).

A: Invalid sql...
INSERT INTO table_name
VALUES (value1, value2, value3,...)

Or if you only want specific parts of the table filled:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

A: You're trying to insert the value 42' SIZE and since this is a string, you're enclosing it within quotes... the problem you're facing is there is a quote within it which is disrupting your string and SQL doesn't know how to reconcile it. You must "escape" the quote that will be part of your string (so that it is not part of the full SQL statement).
The SQLite method is to simply place a second quote, which would give you:
Insert Into T (Test) Values (' 42''SIZE ').
The standard method is to use a backslash however I don't think SQLite allows that. I tried it just to check, using the sqlite3 command line tool, and it wasn't happy with my using backslash as an escape method.


text:
Q: Calculating the first zero of Riemann Zeta Function by hand There are lots of pages on MSE and other websites regarding few first zeros of The Riemann Zeta Function. On MSE [this] is by far the closest (or the only one I've found) explanation for finding the first zero, but again it doesn't explain how to calculate $t \approx 14.134725$ numerically in details. And, I don't think solving $\zeta(z)=\frac 1{1-2^{1-z}}\sum_{n=1}^\infty \frac {(-1)^{n-1}}{n^z}=0$ would be a plausible approach(?)
I have heard that Riemann computed the first three zeros himself and I suppose he didn't have an access a computer so what are the numerical methods/formulas/algorithms to arrive at $t \approx 14.134725$ through calculation by hands?

A: A formula Riemann derived, now called the Riemann Siegel Formula, gives a way to compute the zeta function on the critical line with extreme accuracy. He used the contour integral representation of the Zeta function that was slightly modified (more similar to the hurwitz zeta function but it doesn't really matter) and expanded the contour to give some easily computable terms, then redrew another contour to "concentrate" the value of the rest of the integral and was able to give some asymptotic remainder terms, all of which give a surprisingly accurate (and fairly simple) way to calculate the value of the zeta function on the critical strip. You can see the formula on Wikipedia
(Specifically for the critical strip) and the generalized formula here Using Desmos I was able to insert the formula and I tested out the accuracy and was surprised-- the first few zeroes of the zeta function on the critical strip lie around:
t=14.134725...
t=21.02203...
t=25.0108...
And here is a picture of a graph of the formula:
https://i.stack.imgur.com/3kQNz.jpg
And it's accuracy maintains for large values as well--two zeroes that lie incredibly close to each other and describe "Lehmer's Phenomenon"
, both lying at around t=7005 are shown with the formula aswell:
https://i.stack.imgur.com/yGxSg.jpg
If you're interested in a thourough derivation of the formula here is a pretty good explanation--there's several versions of the formula that are far more complex and have a much more complex derivation but this one is still suitable.
I cant upload photos on here yet and I'm on mobile so I'm sorry if this is messy--hope this helps.


text:
Q: Can't unlock MacBook Air with PIN from Find my iPhone I locked my MacBook Air through Find My iPhone app because I thought I had lost it. One day later I found it. I tried to unlock it with the PIN I had set and apparently I remembered the PIN wrong.
I logged into iCloud from another PC and got my PIN right. When I tried to insert it again it wasn't possible. In the screen I could only see Wrong Passcode. Try Again. There is no place where I can insert the passcode. If I restart it, it says that my device is disabled and I have to wait 60 min. After 60 min, same message Wrong Passcode. Try Again. and no place where to insert passcode.
I tried what other people suggested in similar posts (option+cmd+R) and it didn't work for me.
How do I resolve the issue?


text:
Q: SQL: группировка данных Есть табличка
code  idArt idManufact
0001  222   1
0002  223   1
0003  222   1
0001  333   2
0002  334   2
0003  335   2
0004  333   2

Нужно получить все значения  в рамках idManufact
где idArt <> idArt  c code = 0001, а так же исключить все  idArt  c code = 0001
т.е. получить нужно:
code  idArt idManufact
0002  223   1
0002  334   2
0003  335   2

A: что-то вроде такого видимо должно быть?
SELECT a.*
FROM data AS a
LEFT JOIN (
     SELECT idArt, idMan
     FROM data
     WHERE code = '0001'
  ) AS b ON (a.idMan = b.idMan and a.idArt  = b.idArt)
WHERE b.idArt is null

A:
Не уверен, что понял ваш запрос целиком, но как-то так работает:

SELECT *
  FROM s
 WHERE idart NOT IN (
  SELECT idart
    FROM s
   WHERE code = '0001'
)
;

DB Fiddle:
https://www.db-fiddle.com/f/pXPcMHcSYxSnZYKp28qxng/0.


text:
Q: Unity WebGL UnityWebRequest not working when uploading and downloading data I can neither upload data nor download data by communicating with a web server using UnityWebRequest. In my case I am trying to upload and download user high scores (I am using the dreamlo service). Both of the Coroutines below do not work as the Upload Coroutine simply does not upload the desired score, and the Download Coroutine does not return text.
IEnumerator UploadHighscore(string name, int score, int gameMode){
        UnityWebRequest www = new UnityWebRequest (webURL + privateCode + "/add/" + UnityWebRequest.EscapeURL(name + "+" + score.ToString()) + "/" + score + "/" + gameMode);
        yield return www;

    if (string.IsNullOrEmpty(www.error))
    {
        print("Uploaded");
        uIManager.RegisterCallBack(true);
    }
    else {
        print ("Failed to Upload: " + www.error);
        uIManager.RegisterCallBack(false);
    }
}

IEnumerator DownloadHighscores(){
    UnityWebRequest www = UnityWebRequest.Get (webURL + publicCode + "/pipe/");
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
    }
    else
    {
        FormatHighScores(www.downloadHandler.text);
    }
}

Thank you for any help in advance!
Edit: The code works in the Unity Editor. For some reason it only stops working once embedding my WebGL build into my Website.

A: Try to use The WWW class.
If the game doesn't work when compiled,
send the errors from the console of the browser.


text:
Q: Error: cannot convert 'std::string (*)[3]' to 'std::string** in return Working to get my code to compile, and I ran into a weird error that I haven't seen on here before. I'm trying to get Board::getAr() to return ar, but I'm getting this error. Line 120.
  1 #include <iostream>
  2 #include "Board.hpp"
  3 #include <string>
  4 #include <cstring>
  5
  6 Board::Board()
  7 {
  8         for(int j = 0;j < 1;j++)
  9         {
 10                 for(int i = 0;i < 4;i++)
 11                 {
 12                         ar[i][j] = i;
 13                 }
 14         }
 15         for(int j = 0;j < 4;j++)
 16         {
 17                 for(int i = 0;i < 1;i++)
 18                 {
 19                         ar[i][j] = j;
 20                 }
 21         }
 22         for(int j = 1;j < 4;j++)
 23         {
 24                 for(int i = 1;i < 4;i++)
 25                 {
 26                         ar[i][j] = ".";
 27                 }
 28         }
 29 }
 30 bool Board::makeMove()
 31 {
 32         if(ar[x][y] == ".")
 33         {
 34                 return true;
 35         }
 36         else
 37         {
 38                 std::cout << "That square is already taken." << std::endl;
 39                 return false;
 40         }
 41 }
 42 boardState Board::gameState()
 43 {
 44         bool temp = gameCheck();
 45         if(temp == true)
 46         {
 47                 if(player == 'x')
 48                 {
 49                         return X_WON;
 50                 }
 51                 else if(player == 'o')
 52                 {
 53                         return O_WON;
 54                 }
 55         }
 56         else
 57         {
 58                 return UNFINISHED;
 59         }
 60 }
 61 bool Board::gameCheck()
 62 {
 63         bool row = true;
 64         bool col = true;
 64         bool col = true;
 65         bool diag = true;
 66         bool altDiag = true;
 67
 68         for(int j = 1;j < 4;j++)
 69         {
 70                 for(int i = 1;i < 4;i++)
 71                 {
 72                         const char* temp1 = ar[i][j].c_str();
 73                         const char* temp2 = ar[j][i].c_str();
 74                         const char* temp3 = ar[i][i].c_str();
 75                         const char* temp4 = ar[i][4-1].c_str();
 76                         if(*temp1 != player)
 77                         {
 78                                 row = false;
 79                         }
 80                         if(*temp2 != player)
 81                         {
 82                                 col = false;
 83                         }
 84                         if(*temp3 != player)
 85                         {
 86                                 diag = false;
 87                         }
 88                         if(*temp4 != player)
 89                         {
 90                                 altDiag = false;
 91                         }
 92                 }
 93         }
 94         if(row == true || col == true || diag == true || altDiag == true)
 95         {
 96                 return true;
 97         }
 98         else
 99         {
100                 return false;
101         }
102 }
103 void Board::print()
104 {
105         for(int j = 0;j < 4;j++)
106         {
107                 for(int i = 0;i < 4;i++)
108                 {
109                         std::cout << ar[i][j] << " ";
110                 }
111                 std::cout << "\n";
112         }
113 }
114 char Board::getPlayer()
115 {
116         return player;
117 }
118 std::string** Board::getAr()
119 {
120         return ar;
121 }
122 void Board::setX(int a)
123 {
124         x = a;
125 }
126 void Board::setY(int b)
127 {
128         y = b;
129 }

Any ideas? I can't start the logic troubleshooting until I get this problem fixed. Here's my hpp file:
  1 #ifndef BOARD_HPP
  2 #define BOARD_HPP
  3
  4 #include <string>
  5
  6 enum boardState {X_WON, O_WON, DRAW, UNFINISHED};
  7
  8 class Board
  9 {
 10 public:
 11         int x, y;
 12
 13         Board();
 14         bool makeMove();
 15         boardState gameState();
 16         void print();
 17         char getPlayer();
 18         std::string** getAr();
 19         void setX(int);
 20         void setY(int);
 21         bool gameCheck();
 22 private:
 23         std::string ar[3][3];
 24         char player;
 25 };
 26 #endif

I'm pretty lost and any other similar threads aren't really helping me solve the problem.


text:
Q: Django tags for templates in Eclipse I'm wondering if is it possible to have autocompletion, autoformatting, and those beautiful things working in Eclipse IDE for Django based templates.
Mainly for these things:  {% ... %} {{ ... }}
Thanks in advance

A: Check this page for Django Eclipse plugin: http://eclipse.kacprzak.org/

A: I have started creating my own template in Windows > Preferences > Editors > HTML > Templates, for example for  the {% code %} and {% endcomment %} tag. Of course, this is not exactly what you want, because it is not dynamically, and that is exactly where it would help most.

A: By default PyDev has "Templates" which makes this very easy. I created templates for all the Django template tags and shared them on Bitbucket. Just download them and import it in Eclipse.

A: I really don't know of anything.  A priori, it sounds possible that a project might get the {% ... %} working properly, but the {{ ... }} could be quite a stretch.  Consider that the django templates don't know anything about code that will be filling them in, so there's no real way to look at headers or a symbol table and guess that when you start typing fo that foobar might be a valid variable name.

A: Looks like the PyDev 2.0 has integration with Django Templates Editor that works with Aptana Studio 3 from 2010-08-18. This may be a little dated. I'm trying to get the same thing done today. There are instructions from Fabio Zadrozny


text:
Q: java.lang.VerifyError: com/crashlytics/android/core/CrashlyticsCore I'm getting weird crash when few of my customer are opening my app that is using Crashlytics:
Android version: Android 4.4
Device: Xperia Z3v (D6708)
java.lang.VerifyError: com/crashlytics/android/core/CrashlyticsCore
    at com.crashlytics.android.core.CrashlyticsCore$Builder.build(CrashlyticsCore.java:186)
    at com.my.MyApplication.onCreate(MyApplication.java:74)
    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4464)
    at android.app.ActivityThread.access$1500(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:212)
    at android.app.ActivityThread.main(ActivityThread.java:5137)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:718)
    at dalvik.system.NativeStart.main(Native Method)

Also happens on Samsung Galaxy S4 and Samsung Galaxy Note ||
This is my code:
public class GlobeKeeperApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        try {
            CrashlyticsCore core = new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build();
            Fabric.with(this, new Crashlytics.Builder().core(core).build(), new Crashlytics());
        } catch (Exception e) {
            Log.e(TAG, "Failed to initialize Crashlytics.");
        }
    }
}

After contacting Fabric support team, they told me to try and move the initialization to my Main Activity, so I also tried that without success..
Fabric team still didn't get back to me with a solution.


text:
Q: From list shown below - highlight in BOLD the pair with the highest value I have been trying for sometime to achieve the following:-
Given the list - {{"E", 3}, {"D", 2}, {"S", 2}, {"M", 2}} a list of pairs which maybe 4 pairs - more or less... This list is an output of a previous calculation - so the result can be different every calculation.
I need the output list shown above to highlight in BOLD the pair with the highest value.
Thus the result would look like  -  {{"E", 3}, {"D", 2}, {"S", 2}, {"M", 2}} in this case.
I am sure the answer is so simple, but I can't find it.
Please could anyone advise how to do this with coding.
Many thanks for your help & suggestions.

A: You can highlight the largest case with MapAt:
MapAt[Style[#, Bold] &, list, OrderingBy[list, Last, -1]]

In the last argument, I used OrderingBy to find the index of the largest element.


text:
Q: Proof that Quaternion Algebras are simple I have a proof that every quaternion algebra over a field $A=\left(\frac{a,b}{F}\right)$ is simple, i.e. has no nontrivial two-sided ideals, which appeals to the algebraic closure of $F$ and the elevation of ideals $I\subset A$ to ideals $\overline I\subset\left(\frac{a,b}{\overline F}\right)=M_2(\overline F)$ and uses properties of this latter space.
EDIT: Sorry, I didn't realise this notation wasn't common.  $A$ is a four-dimensional algebra over a field $F$, which we assume has characteristic $\neq 2$, spanned by $\{1,i,j,k\}$ thus:
$$
i^2=a\,1\quad j^2=b\,1\quad ij=-ji=k.
$$
where $a,b\in F^\ast$.
However, I'd like to be able to accomplish this proof without using the algebraic closure, but I'm not sure what the most appropriate method is. Here's my proof:

Take some nonzero $I\subset A$ and examine an arbitrary element $x_0+ix_1+jx_2+kx_3=x\in I\subset A$. Then we know
$$
(x_0+ix_1+jx_2+kx_3)(x_0-ix_1-jx_2-kx_3)=x_0^2-ax_1^2-bx_2^2+abx_3^2\in I
$$
since $I$ is closed under right (and left) multiplication.
Now it would be great to suggest that this element is nonzero. If that were true, then we'd be done. If it's zero, then we have
$$
x_0^2+abx_3^2=ax_1^2+bx_2^2.
$$
Is this possible?
LAST EDIT: I found a good proof of what I wanted to do here. Thanks everyone for your help!

A: I'll retract this if whatever $A=\left(\frac{a,b}{F}\right)$ means prohibits my example :)
I decided to run fast with my "what if $F$ has characteristic two" comment fast and mention why the quaternions over a field of characteristic 2 are never a simple ring.
Since $-1=1$ in such a ring, the generators wind up commuting instead of anticommuting, so the whole thing winds up commutative. Thus the ring would be simple iff it is a field. However, as mentioned, $(1+i+j+k)\cdot(1-i-j-k)=0$ in that characteristic, and so it is clearly not a field.

Thanks for clarifying the original post. That construction is just the Clifford algebra of a two dimensional space with the symmetric bilinear form $\begin{bmatrix}a&0\\0&b\end{bmatrix}$. You will find a lot said about this when the form is nondegenerate (that is, $a,b$ are both nonzero.) If you check out the link, you can see that for real algebras, an even dimensional vector space with a nondegenerate form is isomorphic to a full matrix ring over a division ring (which is necessarily simple).
I wish I could instantly recall if the same is true for rings of characteristic other than 2. My memory is telling me something like that appears (or at least, the proof for "quaternion algebras") in Jacobson's Basic Algebra I in the section on the Hurwitz problem (7.6, I see from the googlebooks preview).

A: The algebra $A=\left(\dfrac{a,b}{F}\right)$ is simple when $ab\neq0$, and $2\neq0$ in $F$.
You haven't used the fact that an ideal must be 2-sided. Let's see how that helps.
Let $I$ be any non-zero ideal, and let $q=x_0+x_1i+x_2j+x_3k$ be an arbitrary element non-zero element of $I$. Then using the multiplication rules (and their consequence $ki=-jii=-aj, ik=iij=aj$) we see that both
$$
qi=-ax_1+x_0i-ax_3j-x_2k
$$
and
$$
iq=-ax_1+x_0i+ax_3j+x_2k
$$
are in $I$. As $2$ is invertible in $F$ we have that both
$$
\frac{iq-qi}2=ax_3j+x_2k\in I
$$
and
$$
\frac{iq+qi}2=-ax_1+x_0i\in I.
$$
Furthermore, one of them is non-zero. Because $j$ is invertible $ax_3j+x_2k=(ax_3+x_2i)j$ and $ax_3+x_2i$ generate the same ideal, so we can deduce in either case that the ideal $I$ contains a non-zero element of the form
$z=y_0+y_1i$.
Then also the following elements are in $I$:
$$
zj=y_0j+y_1k\in I\qquad\text{and}\qquad jz=y_0j-y_1k\in I.
$$
Repeating the above trick this implies that
$$
\frac{zj-jz}2=y_1k\in I\qquad\text{and}\qquad\frac{zj+jz}2=y_0j\in I.
$$
At least one these non-zero. But any non-zero $F$-multiple of any of the basis elements is a unit in $A$, so we can conclude that $I$ contains a unit of $A$ and is thus all of $A$.

Compare this with the exercise you have probably had earlier. The algebra of 2x2-matrices over any field has no non-zero ideals (i.e. it is simple - the same applies to matrix algebras of all sizes). That algebra does have non-trivial left (resp. right) ideals. Consider the sets of matrices where a fixed column (resp. row) is constrained to be all zeros. The upshot here is that in non-commutative algebra 2-sidedness of an ideal is a much stronger requirement. The early examples of ideals a student sees are more often than not in commutative rings, and things are simpler there.


text:
Q: Spark ml: Is it possible to save trained model in PySpark and read from Java Spark code? I have a PySpark job which processes input data and trains a logistic regression model. I need to somehow transfer this trained model to a production code which is written in Java Spark. After loading this trained model from Java code, it will pass features to get prediction from the model.
From PySpark side, I'm using the dataframe API (spark.ml), not mllib.
Is it possible to save the trained (fitted) model to a file and read it back from the Java Spark code? If there's a better way, please let me know.

A: Yes it is possible. With a single exception of SparkR, which requires additional metadata for model loading, all native ML models (custom guest language extensions notwithstanding) can be saved and loaded with arbitrary backend.
Just save MLWritable object on one side, using its save method or its writer (write) and load back with compatible Readable on the other side. Let's say in Python:
from pyspark.ml.feature import StringIndexer

StringIndexer(inputCol="foo", outputCol="bar").write().save("/tmp/indexer")

and in Scala
import org.apache.spark.ml.feature.StringIndexer

val indexer = StringIndexer.load("/tmp/indexer")
indexer.getInputCol
// String = foo

That being said ML models are typically bad choices for production use, and more suitable options exist - How to serve a Spark MLlib model?.

A: Welcome to SO. Have you tried doing this? In general, it must be working - if you save spark.ml model, then you could load it with spark from any language supporting spark. Anyway, Logistic regression is a simple model so you can just save its weights as an array and recreate it in your code.


text:
Q: How can I force dependent project to install nuget package used in dependency? I developed a nuget package "nuget_X" installed on a project "project_1".
I have a second project "project_2" that reference "project_1".
If "project_1" is published as nuget package "nuget_1", I can force "project_2" to reference "nuget_X" by declaring "nuget_X" as dependency of "nuget_1"
But "project_1" is referenced as "ProjectReference". So, how can I configure "nuget_X" or "project_1" to force "project_2" to install "nuget_X"?

A: PackageReference on Visual Studio 2017 don't allow to force nuget of dependency to be installed when using ProjectReference. But it allow to produce an acceptable equivalent result. for more details, see comments.


text:
Q: JQuery onclick function to call a function in PHP via AJAX Creating function increment the session value called clicks every time someone clicks a button, the php works perfectly fine, but failing to call it via AJAX.
JQuery:
$("button").click(function() {
    $.ajax({
        url: 'resources/ajax/addclick.php',
        success: function(output) {
            alert(output);
        }
    });
});

php: addclicks.php
<?php
require_once("../config.php");

function click(){
    $_SESSION['clicks'] ++;
}
?>

php: config.php
session_id();
session_start();

$id = session_id();

if (!isset($_SESSION['started'])) {
    date_default_timezone_set("Asia/Tokyo");
    $_SESSION['started'] = date("h:i:s a");
    $_SESSION['date'] = date("Y/m/d");
}

if (!isset($_SESSION['clicks'])) {
    $_SESSION['clicks'] = 0;
}

html button:
<form class="button" method="post">
  <button class="button" id="button" type="submit">Click
   me</button>
  </form>

A: $("button").click(function(){
  $.ajax({
  method: "POST",
  url: "addclick.php",
  data: { add: 1 }
})
  .done(function( msg ) {
    alert( msg );
  });
});

And your php most be like this
<?php
$_SESSION['clicks'] = $_SESSION['clicks'] + $_POST['add'];

echo $_SESSION['clicks'];
?>

Your html doesn't need form tag, al least you want to prevent submit
<button class="button" id="button" type="submit">Click
   me</button>


text:
Q: Use a single while loop to calculate various means I am to calculate the arithmetic mean, the geometric mean, and the harmonic mean for five numbers using a single while loop.
Here is what I have so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>

float a;
float g;
float h;
sum1 = 0;
sum2 = 0;
sum3 = 0;
n = 5;
int k;

int main()
{

    printf("Please Enter Five Integers:\n");

    while (k = 0 && k < n && ++k);
    {
        scanf("%lf", &k);
        sum1 = sum1 + k;
        sum2 = sum2 * k;
        sum3 = sum3 + (1.0 / k);
    }

    a = sum1 / n;
    g = pow(sum2, 1 / n);
    h = n / sum3;

    printf("Arithmetic mean: %.3f\n", a);
    printf("Geometric mean: %.3f\n", g);
    printf("Harmonic mean: %.3f\n", h);

    return 0;

A: Your C program has several issues.
You don't declare all the variables you are using, for example, and there's no need for them to be global.
Your initial value for sum2 (0) is wrong, it will never update because you repetedly multiply k times 0.
Then in pow(..., 1 / n) the 1/n is an integer division, so you are elevating to 0.
Your loop and its condition must be modified. Try this, I used double, instead of integers and float, but it depends on your assignment:
#include <stdio.h>
#include <math.h>

#define MAX 80

int main()
{
    double a, g, h, k;
    double sum = 0, prod = 1, sum_inv = 0;
    const int n = 5;
    int i = 0;

    printf("Please, enter five numbers:\n");

    char buffer[MAX];
    while ( i < n ) {
        fgets(buffer, MAX, stdin);
        if ( sscanf(buffer, "%lf", &k) != 1 ) {
            printf("Wrong format, floating point number expected\n");
            continue;
        }
        if ( k == 0.0 ) {
            printf("You should enter non zero numbers\n");
            continue;
        }
        ++i;
        sum += k;
        prod *= k;
        sum_inv += (1.0 / k);
    }

    a = sum / n;
    g = pow(prod, 1.0 / n);
    h = n / sum_inv;

    printf("Arithmetic mean: %.3f\n", a);
    printf("Geometric mean: %.3f\n", g);
    printf("Harmonic mean: %.3f\n", h);

    return 0;
}

A: Apologies if this is brutal, but simply saying there are multiple issues and proceeding to correct them without explaining why they are issues or what was done to correct them doesn't make for a very good answer. It makes for homework cut-and-paste.
#define _CRT_SECURE_NO_WARNINGS

This is actually a bad idea. Those security warnings often tell you you're taking unnecessary risks. They are annoying, but often they are right.
#include <stdio.h>
#include <math.h>

These should be <cstdio> and <cmath>. Better still, don't use cstdio. Use the C++ equivalents.
float a;
float g;
float h;
sum1 = 0;
sum2 = 0;
sum3 = 0;
n = 5;

The preceding 4 variables do not have data types. All variables must have a type.
Further initializing sum2 to zero when it will be used to gather a product is a bad idea. 0 will result.
int k;

None of these variables need to be global and all of the variable names are non-descriptive. In a program this size, that's not horrible, but in a large program with dozens or thousands of variables, being able to read from the variable name what it does and what it contains is worth it's weight in gold.
int main()
{

    printf("Please Enter Five Integers:\n");

    while (k = 0 && k < n && ++k);

The ; is a bad mistake here. ; ends the instruction. It separates the loop from it's body, so you get a while the loops but does nothing else.
But let's look at the loop conditions shall we?
k = 0

this is the same as
k = 0
if (k)

Which is always false since k is 0.  This exits the loop right here.
k < n

Which it always is because of k = 0. k is 0. A moot point because this never gets tested.
++k

is always true because at this point k will always be 1.
This screams read the textbook more closely because you missed quite a bit.
    {
        scanf("%lf", &k);

This line reads a floating point number into an integer. Not a good idea. The results will be bizarre at best.
In addition, the return code from scanf is untested so you have no way to tell whether or not scanf successfully read a value.
And this question is tagged C++. Why use C?
        sum1 = sum1 + k;
        sum2 = sum2 * k;
        sum3 = sum3 + (1.0 / k);

That all looks good to me, other than being really bad, non-descriptive names.
    }

    a = sum1 / n;

Syntactically and logically sound.
    g = pow(sum2, 1 / n);

1 / n will be performed entirely in integer arithmetic and certainly result in a fraction. Integers can't do fractions, so this will result in 0. Any number to the power of 0 is one.
    h = n / sum3;

Looks good.
    printf("Arithmetic mean: %.3f\n", a);
    printf("Geometric mean: %.3f\n", g);
    printf("Harmonic mean: %.3f\n", h);

Again, using C in C++. printf has it's uses, even in C++, and frankly this is one of those cases where I might use it (but with caution because there is a performance hit) because the C++ equivalent std::cout << "Arithmetic mean: " << std::fixed << std::setprecision(3) << a << '\n'; is brutally verbose.
    return 0;
}

Revising this for C++
#include <cmath>
#include <iostream>
#include <iomanip>
#include <limits>

int main()
{
    // discarded a, g, and h. Renamed the rest for easier reading
    float sum = 0;
    float product = 1;
    float invSum = 0;
    constexpr int MAX = 5;
    int input;

    std::cout <<"Please Enter Five Integers:" << std::endl;
    int count = 0;
    while (count < MAX)
    {
        if (std::cin >> input)
        { // read a good, or at least not horrible, number
          // this will not handle the problem of "123abc" as input. "123" will be
          // accepted and "abc" will be seen as a second token and rejected.
          // proper handling of this is a question unto itself and has been asked
          // hundreds of times.
            sum += input;
            product *= input;
            invSum += (1.0 / input);
            count++;
        }
        else
        { // clean up and ask for new input
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout <<"Bogus integer. Input again: " << std::endl;
        }
    }

    std::cout << "Arithmetic mean: " << std::fixed << std::setprecision(3) << sum / MAX << '\n';
    std::cout << "Geometric mean: " << std::fixed << std::setprecision(3) << pow(product, (1.0 / MAX))  << '\n';
    std::cout << "Harmonic mean: " << std::fixed << std::setprecision(3) << MAX / invSum << '\n';
    return 0;
}


text:
Q: Precision of Multiplying Floats Does performing operations (like multiplication, division, addition, and subtraction) on floats and doubles maintain their degree of precision?
For example, if I multiplied (or divided, added, subtracted) 1000 floats together, would I still maintain 7 digits of precision?
I have read on this website here that the precision is maintained (http://floating-point-gui.de/formats/fp/), but I wanted to double check.

A: There's precision and there's accuracy. The precision of a float is always the same. But the accuracy of your calculations depends on a variety of implementation-specific details.
For example, if each calculation introduces a half-LSB of error, then after 1000 calculations the result could be off by 500 LSBs. Hence, although the answer would be precise to 7 digits, it would only be accurate to 4 digits.

A: The answer depends on what you mean by "maintaining precision". A single floating point always has the same "precision" of about 7 digits (it's not exactly 7 digits due to binary storage).
Some calculations may introduce rounding error, which can make the least significant bit incorrect, but those errors can add up (like user3386109 explained in their answer) or they can be amplified. An example of an amplification would be if I was calculating a calculus limit of the form (f(x+h)-f(x))/h as h goes to zero. If f(x+0.0000001) should be 3.1234567, but I get 3.1234566 and f(x) gives the correct 3.1234568. Now, the formula should be (3.1234567-3.1234568)/0.0000001, which is -1, but I got (3.1234566-3.1234568)/0.0000001, which is -2.
Suddenly, my least significant digit is my most significant digit. There are other ways to amplify rounding errors and techniques for avoiding it.
Always be aware of rounding error when dealing with non-integer types. Some examples of rounding error failures


text:
Q: How to interface a thermal printer to an Arduino I've a thermal printer which has TTL, RS232 & a four pin interface. I want to connect it to an Arduino and take printouts with it. It has the following pinouts:
RS232 & TTL

*

*GND

*TXD

*RXD

*DSR

*DTR

Another Four Pins Interface

*

*LED

*FEED

*ONLINE

*GND

I've tried printing using the serial communication by sending serial print commands from the TX of the Arduino to the RXD of the printer but for some reason it did not work.
How can I connect it to an Arduino and write a program for it?
Datasheet Links
https://drive.google.com/file/d/1F7it7uGA20YBPsqsTllIjLz1V8hDCv9Y/view?usp=drivesdk
https://drive.google.com/file/d/1FKDVJOw3tqIYPo8PN1DfwKDOgMbw3mg6/view?usp=drivesdk

A: You might want to take a look at this library. The command set seems similar (for example Init is ESC + @). If anything, you can try to copy fragments of code for a simple printout.
Couple of things to consider:

*

*Thermal printers need a stronger power supply. Get an external 9V power supply and connect it to the printer (not the Arduino!) - Seems like you did that.

*Make sure GND on both the printer and board are connected.

*Make sure the baudrate of the Arduino is compatible with the printer (e.g. Serial1.begin(19200);

*Be patient. Hardware development is an art that fights back. Good luck!


text:
Q: Changing cell background in jtable, according to expiry dates Currently I am trying to make an Expiry Date checker, whereby the user enters a Best Before Date of an item into a jtable. The program will output a red or green colored cell, according to whether it is expired by comparing it to the current date.
Here is the code im working with: (for some reason no color changes occur)
    public void dateComparer(TableCellRenderer renderer, int row, int column){
     SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
     Calendar cal  = Calendar.getInstance();
     String expDateString = sdf.format(cal.getTime());

     Date current = new Date(expDateString);
     Date BBD = new Date(jtableMain.getModel().getValueAt(row,3).toString());

     for(int i=0; i<=jtableMain.getRowCount()-1; i++){
         if(BBD.before(current))
            setBackground(Color.GREEN);
         if(BBD.after(current))
             setBackground(Color.RED);

   }

Here is what the current setup looks like jtable


text:
Q: Counting occurrences in an array that has more than 1 key I'm trying to get the occurrences of an array taking in count 1 key value, for example:
 $newarray[0] = [
                    'id' => '2',
                    'date' => '2016-04-22'
                    ];
 $newarray[1] = [
                    'id' => '2',
                    'date' => '2016-04-13'
                    ];
 $newarray[2] = [
                    'id' => '2',
                    'date' => '2016-04-12'
                    ];
 $newarray[3] = [
                    'id' => '1',
                    'date' => '2016-03-11'
                    ];
 $newarray[4] = [
                    'id' => '2',
                    'date' => '2016-03-05'
                    ];
 $newarray[5] = [
                    'id' => '1',
                    'date' => '2016-03-01'
                    ];

I want to transform this, to something like this:
Array ( [0] => Array ( [id] => 1 [date] => 2016-03-11 [occurences] => 2 ) [1] => Array ( [id] => 2 [date] => 2016-04-22 [occurences] => 4 )  )

I tried doing this:
$cleanarray;
$newarray2=$newarray;
$newarray;
$k=0;
$num=1;

for($i=0; $i<count($newarray); $i++){
    for($j=1; $j<count($newarray2); $j++){
        if($newarray2[$j]["id"]==$newarray[$i]["id"]){
          $num++;
        }

    }
    $cleanarray[$k] = [
                    'id' => $newarray[$i]["id"],
                    'date' => $newarray[$i]["date"],
                    'occurences' => $num
                ];
    $k++;
  $num=0;
}

But a lot of items repeat, with the same occurrences but several times, and in other cases the repeated items (with same id) would have different occurrences, so I don't know what can I do, I know that there is a function of:
$occurences = array_count_values($array);

But it doesn't work in this case, how can I approach to the solution?

A: I know what are you looking for, but I think this could solve your problems:
$newarray[0] = [
                'id' => '2',
                'date' => '2016-04-22'
                ];
$newarray[1] = [
                'id' => '2',
                'date' => '2016-04-12'
                ];
$newarray[2] = [
                'id' => '2',
                'date' => '2016-04-12'
                ];
$newarray[3] = [
                'id' => '1',
                'date' => '2016-03-11'
                ];
$newarray[4] = [
                'id' => '2',
                'date' => '2016-03-05'
                ];
$newarray[5] = [
                'id' => '1',
                'date' => '2016-03-01'
                ];

foreach($newarray as $key => $value){
    if(isset($found[$value['id']][$value['date']])) {
        $found[$value['id']][$value['date']]++;
    } else {
        $found[$value['id']][$value['date']] = 1;
    }
}
print_r($found);

this will return something like:-
Array
(
    [2] => Array
        (
            [2016-04-22] => 1
            [2016-04-12] => 2
            [2016-03-05] => 1
        )

    [1] => Array
        (
            [2016-03-11] => 1
            [2016-03-01] => 1
        )

)

A: Using temporary keys for this process will be the most performant way.  Temporary keys simplify the output array task, requiring less and faster checking.  If you wish to sort on id after the result array is generated, the temporary keys allow a simple ksort() call.
Code: (Demo)
$newarray=[
        ['id' => '2','date' => '2016-04-22'],
        ['id' => '2','date' => '2016-04-13'],
        ['id' => '2','date' => '2016-04-12'],
        ['id' => '1','date' => '2016-03-11'],
        ['id' => '2','date' => '2016-03-05'],
        ['id' => '1','date' => '2016-03-01']
];

foreach($newarray as $a){
    if(!isset($result[$a['id']])){
        $result[$a['id']]=array_merge($a,['occurrences'=>1]);  // use id as temp key, preserve first found date
    }else{
        ++$result[$a['id']]['occurrences'];  // only update occurrences to preserve date
    }
}
ksort($result);  // optionally sort on id ASC
var_export(array_values($result));  // remove temporary keys from first level and print to screen

Output:
array (
  0 =>
  array (
    'id' => '1',
    'date' => '2016-03-11',
    'occurrences' => 2,
  ),
  1 =>
  array (
    'id' => '2',
    'date' => '2016-04-22',
    'occurrences' => 4,
  ),
)

A: You can do it like below:-
$final_array = array();

foreach($newarray as $arr){
   if(!in_array($arr['id'],array_keys($final_array))){
      $final_array[$arr['id']] = $arr;
      $final_array[$arr['id']]['occurences'] = 1;
   }else{
     $final_array[$arr['id']]['occurences'] += 1;
   }
}
$final_array= array_values($final_array);
print_r($final_array);

Output:- https://eval.in/847242
Note:- if you want final array to be ascending order of id then use usort() function like below:-
function cmpId($a, $b) {
    return ($a['id'] - $b['id']);
}

usort($final_array, "cmpId");
print_r($final_array);

Output:- https://eval.in/847245


text:
Q: Can multiple thread perform Single task, So that task gets done quickly ? in Java I have a task, it consumes lots of seconds to complete. So I want to know whether using the multithreading concept in Java, can I use multiple threads to perform that single task, so that my task would get done quickly.
Here is my Example. Thread Class:
public class ThreadImpl implements Runnable {
    @Override
    public void run() {
        String value="a";

        for (int i = 0; i < 2147483646; i++) {
            value = value + "b";
        }
        System.out.println("thread task completed " + value);
    }
}

Main Class
public class Main {

public static void main(String[] args) {

    Thread t = new Thread(new ThreadImpl());
        t.start();
    }
}

I want to understand, is it really possible to create multiple threads and execute that task public void run() alone simultaneously? If yes, how to achieve this?

A:
Can I use multiple thread to perform [a] single task.

That depends on what you mean by "task." Your example shows a single function that performs a single computation when it is called by a thread. (Note: It's not a very interesting computation, but it's a computation none the less.)  If that same function is called by more than one thread, then all that will happen is, each thread will perform the identical computation because that's the only thing that your function was written to do. No time will be saved.
In order for multiple threads to cooperate on solving some problem, You have to write the code that instructs them to cooperate. You have to write one or more functions that can perform parts of the computation; You have to write code that assigns the different parts to the different threads; and You likely will need to write code that combines the partial results into a single, final result. There is no magic in Java that will automatically re-write your single-threaded code to do those things for you. You have to write it yourself.

A: A sample snippet using parallel streams
final String[] value = {"a"};
    Stream.iterate(1,x -> x+1 )
            .limit(10)
            .parallel()
            .forEach(y -> value[0] = value[0] + "b"  );

You can change the limit value to the number you require. On my machine with parallel i see 5x performance gain with parallel when limit is 100000.


text:
Q: How to pass the parameter to a method when calling in MVC5? I have a method defined like this:
public ActionResult MatchedBusinesses(List<Business> businesses)
    {
        if (businesses != null)
        {
            return View(businesses);
        }

        return View("NoMatchFound");
    }

Then, in my other method I have something similar to this one:
var list = results.AsEnumerable().OrderBy(b => Math.Abs(Convert.ToInt32(temp) - Convert.ToInt32(b.Zip))).Take(5).ToList();

return RedirectToAction("MatchedBusinesses", "Home", list);

The point is that, for the list variable I get the 5 entries that I select using the query. But, then I want to pass that result to my other method, which will be used in other method's view. The problem is, when I call the other method, the businesses parameter is always null. How can I solve the problem? Clearly, I'm not passing the parameter to my MatchedBusinesses method correctly. Any idea, how to solve the problem?

A: You are using the overload of RedirectToAction where the 3rd parameter is object routeValues. Internally the method uses reflection to build the route values based on the names and the ToString() values of the objects properties.
It works only for properties that are value types, but for properties that are complex types, including collections, it will not bind because (in your case) the value is a string "List<YourAssembly.Business>" and a string cannot be bound to a collection.
You need to persist the collection before redirecting (e.g. database, session, TempData) and then retrieve the collection in the action result.
For example
var list = results.AsEnumerable()....
TempData["results"] = list;
return RedirectToAction("MatchedBusinesses", "Home");

public ActionResult MatchedBusinesses()
{
  List<Business> businesses = (List<Business>)TempData["results"];
}

but use TempData with caution (if the user refreshes the browser, the data will be lost). Its better to persist the information to the database with some key, and then pass the key as a route parameter to the MatchedBusinesses() method so that you can retrieve the data from the database.

A: Edit
What you're trying to do doesn't make much sense. You cannot, and should not, attempt to send large and/or complex objects, like a List, using Route. Instead you should use POST, or follow Stephen Muecke's suggestion in using TempData
However, here's how you can correctly send simple values using RouteValue
You pass parameters by using
return RedirectToAction("ActionName", "ControllerName",
    new { paramName = paramValue });

Or if the target Action it's in the same controller
return RedirectToAction("ActionName", new { paramName = paramValue });

The parameter name, is optional. But using
return RedirectToAction("ActionName", new { paramName = paramValue });

Implies that the target action accepts a parameter with the name paramValue.
Here are all the overloads for RedirectToAction
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction%28v=vs.118%29.aspx

A: Try wrapping your parameter in your return statement in a blank object variable like so:
return RedirectToAction("MatchedBusinesses", "Home", new { businesses = list });

All of the route values for an action have to be one parameter, so it's passed as an object, and then split into the various parameters of the receiving action. Even if you have only one param, it's still looking for an object to split.


text:
Q: Magento 2: Which pages are cached via FPC? I'm having issues with cache and I would like to know which pages are natively cached and uncached by Magento 2?

A: Cacheable
There is a list of default pages which are cacheable:

*

*Home page

*Category page

*Products list page

*Product page

*CMS page

Uncacheable
And there is a list of pages defined as uncacheable:

*

*Cart page

*Checkout page

*All pages of customer account

Reference here


text:
Q: Using JayData with dynamic init i am new with JayData, i have an OData service which i want to consume with JayData
i have this function
$data.initService('/odata')
            .then(function (context) {
                // manage your data through context with JSLQ

                context.Store.forEach(function (s) {
                    alert(s.Name);
                    })

            });

but the i never get to the foreach
my model is
public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Store
{
    public int ID { get; set; }
    public string Name { get; set; }

    public List<Product> Products { get; set; }
}

i have changed to use JaySvcUtil - and generated entity model, how ever i got strange request, when it goes to the server i get error 500 cause it use text/plain
 var oProviderConfig = {
                name: 'oData',
                oDataServiceHost: 'http://localhost:16894/odata'
            };

            var c = new $data.generatedContexts[0](oProviderConfig);
            c.onReady(function () {
                c._Store.forEach(function (s) {
                    alert(s.Name);
                });
            });

GET
500
Internal Server Error
text/plain
datajs-1.1.0.js:2484
Script
358 B
0 B

A:  var oProviderConfig = {
                name: 'oData',
                oDataServiceHost: 'http://localhost:16894/odata',
                maxDataServiceVersion: '3.0'
            };

that fixed it


text:
Q: WildFly 8.2.1 and nGinX I have 2 servers(CentOS7) in LAN WildflyAPP and nGinX.
nGinX is having 2 eth cards. One connected with LAN(192.X.X.X network) and second up to the wild world (external static IP).
I'm trying to use nGinX as Proxy to Wildfly 8.2.1(as a service) using subdomains:
app.mydomain.com to be used as proxy to Wildfly application (8080 port)
wildfly.mydomain.com for management to wildfly (9000 port)
In both cases im receiving 502 error
I used default configuration for nGinx:
server {
    listen  80;
    server_name app.mydomain.com;

    error_log /var/log/nginx/app-error.log;
    access_log /var/log/nginx/app-access.log;

    location / {
            proxy_pass http://192.X.X.X:8080/;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host $host;
            add_header Cache-Control "no-cache, no-store";
    }
 }

I also tried versions with:
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;

Nothing i found anywhere in net helped (standalone file checked and looks ok, APP accessible from LAN at 8080 without any problems).
Please help me what i am doing wrong here.


text:
Q: Expose pod to a particular pre-determined IP address I'm looking to expose individual pods HTTP.  The trick here is that the pod in question needs to know its externally valid IP address, and so in order to configure that ahead of time, I have to have certainty on the external IP address that I'm exposing it by.
Currently I'm trying to expose in this way:
kubectl expose pod my-pod --type=LoadBalancer --name=lb-http --external-ip=$IP --port=80 --target-port=30000

But I'm thinking that the --external-ip flag isn't operating as I intend, as my GKE cluster ends up with a different endpoint IP address.
Is there a way to expose an individual pod to a particular pre-determined IP address?

A: Not possible via LoadBalancer type service. However you can use nginx ingress controller to expose all of your pods on same static IP and apply ingress rules for path and host based routing.This doc demonstrates how to assign a static-ip to an Ingress on through the Nginx controller.
You can achieve the same with GKE ingress as well. Here is the doc on how to do that.

A: You can't pre-assign an IP. It will go create a new GCP LB and then stash the IP/hostname in the Status substruct. Then you take that and put it in your config file or whatever.


text:
Q: Stanfordnlp python - sentence split and other simple functionality I'm trying to split a string into sentences using Stanford NLP parser, I used the sample code provided by Stanford NLP but it gave me words instead of sentences.
here's the sample input:
"this is sample input. I want to split this text into a list of sentences. Please help"

here's my desired output:
["this is sample input.", "I want to split this text into a list of sentences.", "Please help"]

What I've done:

*

*NLTK sent_tokenizer(); does not split newlines, and seems less accurate than stanfordnlp

*stanfordnlp split is great but the sample output isn't in the list of sentences

I heard there's a nltk parser that uses stanfordnlp library, but I was unable to get any sample guide for it.
At this point, I'm quite confused as there's almost no exhaustive python guide for Stanford NLP. It's mandatory to use python for this task, as other components in my research use python to process the data. Please help! thank you.
sample code:
import stanfordnlp

nlp = stanfordnlp.Pipeline(processors='tokenize', lang='en')
doc = nlp(a)
for i, sentence in enumerate(doc.sentences):
    print(f"====== Sentence {i+1} tokens =======")
    print(*[f"index: {token.index.rjust(3)}\ttoken: {token.text}" for token in sentence.tokens], sep='\n')
print(doc.sentences.tokens.text[2])

output:
====== Sentence 84 tokens =======
index:   1  token: Retweet
index:   2  token: 10
index:   3  token: Like
index:   4  token: 83
index:   5  token: End
index:   6  token: of
index:   7  token: conversation
index:   8  token: ©
index:   9  token: 2019
index:  10  token: Twitter
index:  11  token: About
index:  12  token: Help
index:  13  token: Center
index:  14  token: Terms
index:  15  token: Privacy
index:  16  token: policy
====== Sentence 85 tokens =======
index:   1  token: Cookies
index:   2  token: Ads
index:   3  token: info

source : https://stanfordnlp.github.io/stanfordnlp/pipeline.html

A: I would use normal split('.') but it will not work if sentence ends on ? or !, etc.
It would need regex but it still may treats ... inside sentence as ends of three sentences.

With stanfordnlp I can only concatenate words in sentence so it gives sentence as one strings but this simple method adds spaces before ,.?!, etc.
import stanfordnlp

text = "this is ... sample input. I want to split this text into a list of sentences. Can you? Please help"

nlp = stanfordnlp.Pipeline(processors='tokenize', lang='en')
doc = nlp(text)

for i, sentence in enumerate(doc.sentences):
    sent = ' '.join(word.text for word in sentence.words)
    print(sent)

Result
this is ... sample input .
I want to split this text into a list of sentences .
Can you ?
Please help

Maybe in source code it could find how it splits text to sentences and use it.


text:
Q: How to test login from multiple IP addresses in Rails At the request of a customer, I had to implement sending a notification email every time the application detects two active sessions for the same user from different IP addresses. How do you test this?

A: Created integration test test/integration/multiple_ip_test.rb
require 'test_helper'

@@default_ip = "127.0.0.1"

class ActionController::Request
  def remote_ip
    @@default_ip
  end
end

class MultipleIpTest < ActionDispatch::IntegrationTest
  fixtures :all

  test "send email notification if login from different ip address" do
    post_via_redirect login_path,
                      :user => {:username => "john", :password => "test"}
    assert_equal "/users/john", path

    reset!
    @@default_ip = "200.1.1.1"
    post_via_redirect login_path,
                      :user => {:username => "john", :password => "test"}
    assert_equal "/users/john", path
    assert_equal 1, ActionMailer::Base.deliveries.size
  end
end

Integration tests look a lot like functional tests, but there are some differences. You cannot use @request to change the origin IP address. This is why I had to open the ActionController::Request class and redefine the remote_ip method.
Because the response to post_via_redirect is always 200, instead of using assert_response :redirect I use the URL to verify the user has logged in successfully.
The call to reset! is necessary to start a new session.
For an introduction on integration tests, check the Rails Guides on testing, unfortunately they do not mention the reset! method.

A: Assuming you are using some framework for logging in such as devise, the following command will get the IP of a machine remotely accessing your app:
request.remote_ip

You will need to store their used IPs in the model then you should easily be able to tell if they access with differing IPs.


text:
Q: Contact form - success message I am using a contact form and at the moment when you submit your details you are brought to a new page with a "thank you" message. I don't want users to be re-directed to a new page and instead I would like the "thank you" message to be displayed on the same page as the form. The code I am using is below.
Contact form code:
  <form name="htmlform" method="post" action="html_form_send.php">

  First Name *

  <input  type="text" name="first_name" maxlength="50" size="30">

  Last Name *

  <input  type="text" name="last_name" maxlength="50" size="30">

  Email Address *

  <input  type="text" name="email" maxlength="80" size="30">

  Telephone Number

  <input  type="text" name="telephone" maxlength="30" size="30">

  Comments *

  <textarea  name="comments" maxlength="1000" cols="25" rows="6"></textarea>

  <input type="submit" value="Submit">

</form>

PHP code to send form:
<?php
if(isset($_POST['email'])) {

    // CHANGE THE TWO LINES BELOW
    $email_to = "you@yourdomain.com";

    $email_subject = "website html form submissions";

    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.

";
        echo $error."

";
        echo "Please go back and fix these errors.

";
        die();
    }

    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');
    }

    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required

    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.
';
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.
';
  }
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.
';
  }
  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.
';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below.\n\n";

    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }

    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting us. We will be in touch with you very soon.

<?php
}
die();
?>

A: If you're wanting to refresh the page to the same location on which the form is located and display the results on the same page, then you could try this:
replace
    <form name="htmlform" method="post" action="html_form_send.php">

with the following (so that you refresh the same page as the form).
    <form name="htmlform" action="" method="post">

Adjust your submit button by giving it a name:
    <input type="submit" name="submit" value="Submit">

and then validate whether the post has been submitted by checking if 'submit is set, rather than email...
    if(isset($_POST['submit'])) { rather than if(isset($_POST['email'])) {

Then move the thankyou message code from the file 'html_form_send.php' to above your form code in the original file.
This should POST the data from the form to the same page on which the form is located, and only display the thank you message if the page detects that the form has been submitted... So long as you enclose any printed/echo'd thank you message inside the if(isset($_POST['submit'])) {    brackets - i.e. in here   } then it should work.
If you want to check if the form has been submitted without refreshing the page you'll need to look in to AJAX, but that is a bit more complicated.


text:
Q: Is There An Equivalent Technique To Image Replacement For Use With Inline SVG There are a wealth of techniques for implementing image replacement with background images, but I find myself using inline SVG more and more (primarily because I can manipulate its components with CSS).
However in places (like links and headers) where text content is important for SEO, SVG alone doesn't cut it. Are there any equivalent techniques in the wild allowing text within a header or anchor to be visually hidden whilst leaving inline SVG unaffected.
Note: I know that Google does index SVG, but it seems quite arbitrary, even with liberal usage of <title> and <desc>.

A: I can only suggest the following based on this article by Chris Coyier at CSS-Tricks.com
Reference Article
First, define your SVG

<svg width="100px" height="100px" viewBox="0 0 100 100" class="hardcore-hide">
  <circle id="template" cx="50" cy="50" r="50">
    </svg>

..but the hide it with display:none;
Use a standard div (or element) with an absolutely positioned child of 100% size.
Then add a SVG use element inside the absolutely positioned child

Logo text

    <svg viewBox="0 0 100 100" class="circle circle-1">
      <use xlink:href="#template">
        </svg>

CSS (so far) would look something like this.
.hardcore-hide {
  display: none;
}

.circle {
  height: 100px;
  width: 100px;
}

body {
  padding: 1rem;
}

.logo {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
  border:1px solid grey;
  width:200px;
  height:100px;
  position: relative;
  display: inline-block;
}

.logo svg {
  position: absolute;
  height:100%;
  width:100%;
  top:0;
  left:0;
}

then you can add addtional styling as follows
.circle-1  svg {
  fill: red;
}
.circle-2 svg {
  fill: orange;
}
.circle-3  svg {
  fill: #f06d06;
}

Codepen Demo


text:
Q: real time online push button based counting system I am doing this project:
I have 4 inputs. These are push buttons, connected to a microcontroller.
Each time a push button is pressed, say for example pushbutton_1 is pressed, the press of a switch button should be recognised as a HIGH.
In its normal unpressed state it should be recognised as a LOW.
Then using serial communication i should transfer it to a computer.
Along with this, i need to implement a count for each button.
Each time a push button is pressed, the count that is assigned to that push button, should increment by 1.
The data arriving through serial communication should be transferred to an excel sheet/database.
The excel sheet/database should display a count for each pushbutton.
I have 4 important question areas:

*

*Which microcontroller should i use? (I have experience with arduino   development platform)

*How do i implement the transfer of data from microcontroller to computer via serial communication?

*Afterwards, how do i transfer the arriving data to MS excel/database?

*How do i run implement the system in realtime?
Please suggest me the best possible way to implement this system.

A: To solve this using an MPU like an RPi via the Internet, its pretty trivial. To do this:

*

*Wire your switches to the GPIO inputs on the Pi. This is a trivial example: http://razzpisampler.oreilly.com/ch07.html

*When the state changes, send a message via a realtime service such as PubNub (free for student and other uses: http://www.pubnub.com/free-evangelism-program/)

*On a remote "server-side", take the data received via the subscriber logic write to a CSV.

If you followed these directions, you would use the PubNub python client to publish the data from the Pi: https://github.com/pubnub/python/tree/master/python#publish
and then you would use python (PubNub supports over 70 languages, so you could use python or the language of your choice) to subscribe to the pushbutton data channel(s)
https://github.com/pubnub/python/tree/master/python#subscribe
You could even make a cool realtime updating web page in HTML/JS using the PubNub JS client
Source: https://github.com/pubnub/javascript/tree/master/web
Docs: http://www.pubnub.com/docs/javascript/api/reference.html#subscribe
to dynamically update a dashboard, with no file writing needed.