text:
Q: Midnight last Monday in Powershell I'm trying to hack up a script that returns the amount of email received to and sent from certain mailboxes today, this week and this month.  I wrote this and felt good about myself until I realised my logic was wrong and it was returning the last 24 hours (get-date.(adddays(-1)) and last 7 consecutive 24 hour periods (get-date.adddays(-7)) etc.
Figuring out the first day of the month to count from wasn't that hard, found a snippet to copy
$firstDayOfMonth = Get-Date ((("01/" + (Get-Date $today).Month).ToString() + "/" + ((Get-Date $today).Year).ToString() + " 00:00:00"))

which starts with 01/ and adds today's month and years as string then appends midnight time and bundles the whole thing into a system.time object, but I can't do that with the week.
System.time objects have a .DayOfWeek property and I can switch that to figure out how many days we are from last Monday, and I have a $Monday variable that contains this time last Monday, how do I modify that variable to refer to midnight last Monday?

A: maybe, this is your friend:
([int](Get-date).DayOfWeek)

This converts the DayOfWeek-property to the numeral-day of the week ...
For Example:
(Get-Date 0:00).AddDays(-([int](Get-date).DayOfWeek)+1)

A: First Monday of the Month
do {
    $n++
    $date = (date -Hour 0 -Minute 0 -Second 0).AddDays(-$n)
}
Until ( `
    $date.DayOfWeek -eq "Monday" -and `
    $date.Day -le 7 `
)

First Monday of the Week
$n = 0
do {
    $date = (date -Hour 0 -Minute 0 -Second 0).AddDays(-$n)
    $n++
}
Until ( $date.DayOfWeek -eq "Monday" )

A: You can calculate the date of last Monday like this:
$today = Get-Date
$delta = $today.DayOfWeek.value__ - 1

$today.AddDays(-$delta).Date

The Date property returns the date with the time set to 00:00:00, so you don't need to calculate the time.
Note that on Mondays the above code returns the current date. If you want the code to return the previous Monday you need to change the second line to this:
$delta = ($today.DayOfWeek.value__ + 5) % 7 + 1

The first day of the month can be calculated in a similar manner:
$today = Get-Date
$delta = $today.Day - 1

$today.AddDays(-$delta).Date

A: Sunday of this week (Assuming weeks start on Sunday):
$sunday = (Get-Date).AddDays(-1 * (Get-Date).DayOfWeek.Value__).Date

Monday of this week:
$monday = (Get-Date).AddDays((-1 * (Get-Date).DayOfWeek.Value__) + 1).Date

Tuesday of this week:
$tuesday = (Get-Date).AddDays((-1 * (Get-Date).DayOfWeek.Value__) + 2).Date

Etc. etc. for Wed - Sat

A: got this one working for any day:
((Get-Date).adddays(-(6+(Get-Date -UFormat %u)))).date

A: Try this:
$i=0
do { $LastMonday = (Get-Date).AddDays(--$i).Date }
until ( $LastMonday.DayofWeek -eq 'Monday' )

$LastMonday

Monday, February 03, 2014 12:00:00 AM

The Date proptery of a DateTime object is the datetime on Midnight of that day.


text:
Q: What conditions on the coefficients of $p(x) = ax^3 + bx^2 + cx + d$ guarantee that $p(x)\geq 0$ for some $x$? I am working on a research level problem and I am stuck up with a third degree polynomial inequality. So I would like to know:

Given the polynomial $p(x) = ax^3 + bx^2 + cx + d$, which conditions on the coeficients $a, b, c, d$ should we impose in order to have:
  $$p(x) \geq 0$$
  for some $x$?

A: Note that if $a$ is nonzero, then the cubic tends to $-\infty$ on one side and $\infty$ on the other and the condition is satisfied. Otherwise, we have a quadratic; if $b$ is positive then we tend to $\infty$ and the condition is satisfied. If $b$ is negative, we require at least one root to satisfy the condition, i.e. the discriminant is nonnegative. If $b=0$, then if $c$ is nonzero we clearly satisfy the condition with a linear function. Finally, if $a = b = c = 0$ then $d \ge 0$ trivially works.

A: This is always true. If $a>0$ then as $x$ tends to positive infinity, we're good. Otherwise, $a<0$ (as it's a third degree polynomial) so as $x$ tends to negative we're good.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a Visual Studio add-in to generate files? I would like to create a Visual Studio add-in to generate files.
For example, I would like to create something similar to the "Add Controller" dialog in ASP.NET MVC. This appears when you right-click on the "Controller" folder in an MVC project in Visual Studio.
However, instead of creating a controller file, I would like to create "Handler", "Request", and "Reply" classes within a folder, for my implementation of a service bus.
Creating these classes over and over again is becoming a bit of a chore, so I'd like to automate it. Is an add-in the way to go here? Do I also need to use macros and/or T4 templates?
It would be nice I could run the add-in by right-clicking on a folder and then choosing Add->Handler or something similar. I'm sure there must be a way to do something like that, but I haven't found a good resource yet through Google.
For reference, I've already looked at these web pages for info:

*

*http://msdn.microsoft.com/en-us/vstudio/bb968855.aspx

*http://msdn.microsoft.com/en-us/library/80493a3w.aspx

*http://msdn.microsoft.com/en-us/library/7k3w6w59.aspx

*http://www.c-sharpcorner.com/UploadFile/mgold/AddIns11292005015631AM/AddIns.aspx

*http://www.codeproject.com/Articles/16515/Creating-a-Custom-Tool-to-Generate-Multiple-Files

*http://www.olegsych.com/2010/03/t4-tutorial-integrating-generated-files-in-visual-studio-projects/

A: You can create templates which could make you nearly everithing you would like to do.

*

*Creating Vs-Templates

*Item templates
You can use your custom templates with the built in way easily and you can extract them from
...\Documents\Visual Studio 20[XY]\Templates\

folder to migrate them by copying.


text:
Q: Positioning and grouping SVG D3/SVG/ionic A D3 bubblechart. Group and position svg:circles and svg:text elements

*

*the function render() creates an svg element, circle and text as usual. This function includes .exit.remove update patterns.

*runSimulation() is executed after page opening and a createChart() function.

*click on a circle executes runSimulation() again, removing the circle
with .exit().remove() etc.

Simplified code:
fundtion render (){

  const nodeEnter = this.nodeElements
  .enter()
  .append('svg:svg');

   nodeEnter
  .append('circle')
  .on('click',runSimulation);

  const textEnter = this.textElements
  .enter()
  .append('svg:text');
  }

this.runSimulation(){

    this.render();

    function ticked(){
    this.nodeElements
    .attr('cx', cxValue)
    .attr('cy', cyValue):
    }

   this.simulation.nodes.on.('tick',ticked);

   }

*

*On the first run the cx and cy attributes are appended to the svg:svg while the circles do not have the attributes and everything is rendered in the top left corner ( also with using svg:g)

*on the click action the runSimulation is executed a second time; now the circle gets the cx and cy attributes attached and all elements move into the expected position.

-I am looking for a way to get the cx cy attributes to the circle on the first rendering so that the parent elements do not cluster at x=0 y =0, or to get x and y to svg:svg; the shown pattern is not working and I appreciate your help.

A:  this.nodeElements = this.nodeGroup.selectAll('g')
  .data(this.data, node => node.nodeName);

 this.nodeElements.exit().remove();

 const nodeEnter = this.nodeElements
  .enter()
  .append('g');

nodeEnter
  .append('circle')
  .attr('fill', node => this.color(node.familyType))
  .attr('r', function (node) {
    return (node.nodeName.length > 10) ? "75" : node.nodeName.length*6;
  })
  .on('click', this.runSimulation);

let wrap = (text) => {
  text.each(function() {
    let text = d3.select(this),

const textnode = nodeEnter
  .append('text')
  .attr('id', 'text')
  .attr('text-anchor', 'middle')
  .attr('alignment-baseline', 'middle')
  .attr('dy', '0.1em')
  .attr('font-size', '1.2em');

this.settings.getValue('option1').then((option) => {
  if (option === true) {
    let type = node => node.nodeName;
    textnode
      .text(type);
  }
  if (option === false) {
    let type = node => node.otherName;
    textnode
      .text(type);
  }
})

Thank you for your answer, Steven. runSimulation executes a tick function that does add the proper d.x and d.y now. I am not sure why it did not work - ionic lifecycle events ?


text:
Q: Error only with firefox on deployed version on heroku This problem made me crazy, and it's stealing me a lot of time.
My Meteor application work good on my local dev machine, but when I deploy it with BUILD_PACK=https://github.com/oortcloud/heroku-buildpack-meteorite.git I have a problem ONLY with Firefox, that give me a generic error
"Exception from Deps afterFlush function function: "

...but I can't view call stack or where is generated.
I check that build pack and local dev machine use the same node.js version (v0.10.26), obviously on local use Meteor integrated MongoDB and on heroku use Mongolab service.
I don't know how find the problem.
On heroku build version Chrome work like a charm, Firefox have that the problem.
On local machine both Chrome and Firefox work good.
I have also tried with demeteorize, but the problem is the same...
edit:
On Firefox debug console error is on row 1 (43c9ee3da328e93321624a3179d27858c654879d.js:1)
How can I deploy on heroku without js minify?
edit2:
I have deployed on *.metor.com and WORK GOOD! (with and without --debug flag)
The problem/error is heroku and/or build pack...but where?!?
SOLUTION FINDED:
I have made a big mistake. The error throw from an external library. This library give this problem only on firefox.
Firefox console debug log don't reports the library error, because the call to this API library it is done into observer method.
The problem exist on both heroku and local dev machine...I'm feeling very silly
thanks guy for your support ad time!

A: This error is from your client side code, the way its deployed isn't likely to change it (Demeteorizer, using meteor deploy instead, etc)
These errors usually come from you reading data without it being ready yet. On your localhost the latency is so low usually data is immediately ready and you wouldn't notice the problem.
This is an example of code that can cause such an issue:
var firstname = People.findOne().name;

Here the assumption is that the people collection is ready. If its not ready People.findOne() returns null and looking for .name is going to throw an Error while loading a page.
To fix this you have to find where you have used code like the above (obviously yours will have different names and structure) and check that the collection is ready first, or that the result being searched for actually exists.
Again this is just the most likely place the error comes from. There are plenty of other reasons that can cause the error. Firefox's debug console isn't very descriptive as Chrome's is so its quite difficult to debug.
It could even be a 3rd party dependency didn't load and you tried to use it somewhere like a template helper.


text:
Q: Error with my contact form, NoMethodError in Contacts#new I get this error when I try the create a new email. What's happening?
NoMethodError in Contacts#new

blog/app/views/contacts/new.html.erb where line #4 raised:

undefined method `contacts_path' for #<#<Class:0x007fab694b2320>:0x007fab6bdde2a8>
Did you mean?  controller_path

Here is my code:

<%= form_for @contact do |f| %>
    <%= f.label :name %>

    <%= f.text_field :name, required: true %>

Here is my project

A: OK, quickly looked at your routes.rb,
resources :contacts, only: [:new, :created]

is not well formed it should be:
resources :contacts, only: [:new, :create]

That's probably it. To see what's happening you can run rake routes and you'll see the list of your routes. Then you can fix the route file to have appropriate route path


text:
Q: Group action and invariant measures Let's first start with the example from where this question arose. I consider the metric space $\mathbb{R}$ and the Lebesgue-measure $\lambda$ on $\mathbb{R}$ as well as the transitive group action $+\colon (\mathbb{R},+)\times \mathbb{R}\to\mathbb{R}$, for which the measure and the metric are both invariant. When integrating over a set $M$ with respect to $\lambda$ I can fix a point $x\in\mathbb{R}$ (the metric space rather than the group) and, since the action is transitive, integrate over a set $M'$ with respect to some measure $\mu$ on the additive group $(\mathbb{R},+)$, such that $M'+x=M$ and $\mu(M')=\lambda(M)$. This is possible as well as completely independent of the choice of $x$ by choosing $\mu$ to be the Lebesgue-measure on $(\mathbb{R},+)$.
Now I want to generalise this statement to arbitrary metric spaces and groups. I have a metric space $X$ with a radon-measure $\mu$ as well as a transitive group action from a topological group $\cdot\colon G\times X\to X$ which leaves the metric and the measure invariant. Analogous to $\mathbb{R}$ I chose another condition that for any $\varepsilon>0$ there exists a neighbourhood $U$ of $1\in G$ such that the metric is left small when translating with elements from $U$, i.e. $\forall x\in X,g\in U\colon d(gx,x)<\varepsilon$. This so far were reasonable assumptions since they give me the required continuity of the group action. Trying to find a suitable measure on $G$ just like above I came to 3 distinct conditions, that could give me what I require.

*

*Assume that $G$ is commutative. This will make sure that $\mu(Ux)=\mu(Uy)$ for every $x,y\in X,U\subseteq G$ since $y=gx$ for some $g$ since I can simply commute the $g$ to the front and disregard it due to invariance.

*Assume that the action is free, i.e. $G$ and $X$ are basically the same since for any $x\in X$ the function $f\colon G\to X,g\mapsto gx$ would be a bijection, giving me a very natural choice for the measure on $G$.

*Assume that not only above condition, $\forall\varepsilon>0 \exists U \text{ negihbourhood of }1\in G\forall x\in X,g\in U\colon d(gx,x)<\varepsilon$ but even more: $\forall\varepsilon>0 \exists U \text{ negihbourhood of }1\in G\forall x\in X\colon g\in U \iff d(gx,x)<\varepsilon$, which would also solve some problems.

The questions now is: Which of these 3 conditions is most natural/weakest? Which would you go for in the most general case? Do I even need any of them or would this work with the above statements, without 1,2 or 3? Thanks for any help!


text:
Q: High school implicit differentiation question A particle follows a path determined by the equation $x^2 + x = y^3 + 3y^2 + 2y + 2$. The x-coordinate
of the particle changes at a constant rate given by $dx/dt$ =$4$
Determine the rate at which the y-coordinates are changing when y = 0.
I've implicitly differentiated the above equation to get $dy/dx=(2x+1)/(3y^2+6y+2)$ but not sure where to go from there.


text:
Q: How can I fix a USG_AUTHORIZATION_FAILED error using SOAP? I'm trying to call an API using C# code samples downloaded from https://github.com/SabreDevStudio/SACS-DotNet. I'm using SOAP.
After registration, I received the following authentication info:

Key: V1:xxxxxxxxxxxxxxxx:PUBLIC:EXT
  Shared Secret: yyyyyyyy

Therefore, I have configured my SACSConfig.properties as follows:
userId=xxxxxxxxxxxxxxxx
group=PUBLIC
domain=EXT
clientSecret=yyyyyyyy
environment=https://sws3-crt.cert.sabre.com

Then I ran the sample application as follows:

*

*Run

*Click on "SOAP Workflow"

*Click on "submit"

The call to the SessionCreateRQAsync API is successful, but in the method PassengerDetailsContactActivity.RunAsync an error occurs when the following statement is executed:
PassengerDetailsRS response = service.PassengerDetailsRQ(request);

The error is:

com.sabre.universalservices.base.security.AuthorizationException:
  errors.authorization.USG_AUTHORIZATION_FAILED

Why does this error occur and how can I fix it?


text:
Q: Query optimisation for FK association on inherited model from the base model I have users who create (or receive) transactions. The transaction hierarchy I have is a multi-table inheritance, with Transaction as the base model containing the common fields between all transaction types, such as User (FK), amount, etc. I have several transaction types, which extend the Transaction model with type specific data.
For the sake of this example, a simplified structure illustrating my problem can be found below.
from model_utils.managers import InheritanceManager

class User(models.Model):
    pass

class Transaction(models.Model):
    DEPOSIT = 'deposit'
    WITHDRAWAL = 'withdrawal'
    TRANSFER = 'transfer'

    TYPES = (
        (DEPOSIT, DEPOSIT),
        (WITHDRAWAL, WITHDRAWAL),
        (TRANSFER, TRANSFER),
    )

    type = models.CharField(max_length=24, choices=TYPES)
    user = models.ForeignKey(User)
    amount = models.PositiveIntegerField()

    objects = InheritanceManager()

    class Meta:
        indexes = [
            models.Index(fields=['user']),
            models.Index(fields=['type'])
        ]

class Withdrawal(Transaction):
    TYPE = Transaction.WITHDRAWAL
    bank_account = models.ForeignKey(BankAccount)

class Deposit(Transaction):
    TYPE = Transaction.DEPOSIT
    card = models.ForeignKey(Card)

class Transfer(Transaction):
    TYPE = Transaction.Transfer
    recipient = models.ForeignKey(User)

    class Meta:
        indexes = [
            models.Index(fields=['recipient'])
        ]

I then set each transaction's type in the inherited model's .save() method. This is all fine and well.
The problem comes in when I would like to fetch the a user's transactions. Specifically, I require the sub-model instances (deposits, transfers and withdrawals), rather than the base model (transactions). I also require transactions that the user both created themselves AND transfers they have received. For the former I use django-model-utils's fantastic IneritanceManager, which works great. Except that when I include the filtering on the transfer submodel's recipient FK field the DB query increases by an order of magnitude.
As illustrated above I have placed indexes on the Transaction user column and the Transfer recipient column. But it appeared to me that what I may need is an index on the Transaction subtype, if that is at all possible. I have attempted to achieve this effect by putting an index on the Transaction type field and including it in the query, as you will see below, but this appears to have no effect. Furthermore, I use .select_related() for the user objects since they are required in the serializations.
The query is structured as such:
from django.db.models import Q

    queryset = Transaction.objects.select_related(
         'user',
         'transfer__recipient'
    ).select_subclasses().filter(
         Q(user=request.user) |
         Q(type=Transaction.TRANSFER, transfer__recipient=request.user)
    ).order_by('-id')

So my question is, why is there an order of magnitude difference on the DB query when including the Transfer.recipient in the query? Have I missed something? Am I doing something silly? Or is there a way I can optimise this further?


text:
Q: How do i insert a line in front of a previous line using regex on notepad++? For example, I would like to following list:
E|MG000|HIST|062575|08012019|062575|MG003
L|22WBM3|1|1871.1
E|MG000|HIST|020590|31012019|020590|MG003
L|10B771D015|-4|8.488
E|MG000|HIST|062575|21022019|062575|MG003
L|22WBM3|-1|1871.1

to look like this:
E|MG000|HIST|062575|08012019|062575|MG003 - L|22WBM3|1|1871.1
E|MG000|HIST|020590|31012019|020590|MG003 - L|10B771D015|-4|8.488
E|MG000|HIST|062575|21022019|062575|MG003 - L|22WBM3|-1|1871.1

A: Try (?m)^(E\|(?:(?!L\|).)+)\s+^(L\|.*(?:\r?\n)?)
Replace $1 - $2
demo

A: *

*Ctrl+H

*Find what: \R(?=L)

*Replace with: -  (space hyphen space)

*CHECK Match case

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
\R          # any kind of linebreak
(?=         # positive lookahead, make sure we have after:
    L         # letter L
)           # end lookahead

Screenshot (before):

Screenshot (after):


text:
Q: $A$ is a symmetric matrix such that $A^4=A$. Prove that $A$ is idempotent
Let $A$ be a real symmetric matrix such that $A^4=A$. Prove that $A$ is idempotent.

I have tried using eigenvalues and only inferred that the eigen values may be $0,1$. But I cannot proceed with this.

A: Let $A=PDP^{-1}$ be the eigendecomposition of the given matrix. Then, since the diagonal matrix of eigenvalues $D$ contains only 0s and 1s, $D^2=D$ and
$$A^2=PDP^{-1}PDP^{-1}=PD^2P^{-1}=PDP^{-1}=A$$

A: Here's a proof which doesn't invoke Cayley Hamilton or eigenstructures:
We have $A^4 - A = 0$.  Factoring this yields
$$
(A^2 + A + I)(A^2 - A) = 0
$$
However, we may write
$$
A^2 + A + I = \left(A + \frac 12 I\right)^T\left(A + \frac 12 I\right) + \frac 34 I
$$
Since $A^2 + A + I$ can be written as the sum of a positive semidefinite and positive definite matrix, it must be positive definite (and hence invertible).  Thus, we have
$$
(A^2 + A + I)(A^2 - A) = 0 \implies A^2 - A = 0 \implies A^2 = A
$$
Thus, $A$ is idempotent.

A: I tried to cook up a basic proof which doesn't directly invoke the eigenstructure of $A$ or Cayley-Hamilton, etc.; here's what I've got:
if
$A^4 = A, \tag 1$
then
$A(A - I)(A^2 + A + I) = A(A^3 - I) = A^4 - A = 0; \tag 2$
since
$A^T = A, \tag 3$
we have for any vector $x$
$\langle x, Ax \rangle = \langle x, A^4 x \rangle = \langle (A^T)^2 x, A^2 x \rangle = \langle A^2 x, A^2 x \rangle \ge 0; \tag 4$
$\langle x, A^2 x \rangle = \langle A^T x, Ax \rangle = \langle Ax, Ax \rangle \ge 0; \tag 5$
thus
$\langle x, (A^2 + A + I)x \rangle = \langle x, A^2 x \rangle + \langle x, Ax \rangle + \langle x, x \rangle > 0, \tag 6$
by (4), (5) and the fact that $\langle x, x \rangle > 0$; now if any matrix $B$ satisfies
$\langle x, Bx \rangle \ne 0, \forall x, \tag 7$
then $B$ is invertible; if not,
$\exists y \ne 0, \; By = 0 \Longrightarrow \langle y, By \rangle = 0, \tag 8$
which contradicts (7); applying this conclusion to $A^2 + A + I$ we see that it must be invertible; then by (2) we see that
$A^2 - A = A(A - I) = 0, \tag 9$
or
$A^2 = A. \tag{10}$

A: You are given that
$$
          0 = A^4-A=(A^2-A)(A^2+A+I)
$$
Because $A$ is assumed to be real and symmetric, then the matrix $A^2+A+I$ is real and symmetric, and its eigenvalues have the form
$$
             \lambda^2+\lambda +1 = (\lambda+1/2)^2+3/4 \ge 3/4.
$$
So $A^2+A+I$ is invertible, which forces $A^2-A=0$, or $A^2=A$.

A: If A=0 or A=$I_n$ ok, you can use the Spectral theorem or eingvalues, $A^4=A$ implies that $p(x)=x^4-x$ is a multiple of Characteristic polynomial of A note that $p(x)=x(x-1)(x^2+x+1)$ every ortogonal operator have real eingvalue, thus the characteristic polynomial is x or x-1 or x(x-1), but by Cayley Theorem the characteristic polynomial(A)=0 thus x(x-1) again Cayley Theorem $A^2-A=0$.


text:
Q: Реализация цифровой подписи ГОСТ Начал реализацию цифровой подписи ГОСТ. Нужно сделать так: Прежде всего необходимо найти два простых числа, q длиной 256 бит и p длиной 1024 бита, между которыми выполняется соотношение
p = bq + 1

для некоторого целого b. Старшие биты в p и q должны быть равны единице. Затем выбирается число a > 1, такое, что
a^q mod p = 1

У меня не получается сгенерировать число a, попробовал вот так:
    BigInteger q = BigInteger.probablePrime(256, random);
    BigInteger p = BigInteger.probablePrime(1024, random);
    BigInteger b = (p.subtract(BigInteger.ONE)).divide(q);
    BigInteger a = null;

    do {
        a = new BigInteger(256, random);
        System.out.println(cryptoLab1.ModPow(a,q,p));
    } while (cryptoLab1.ModPow(a,q,p).intValue() != 1);

Как можно сгенерировать число a согласно условию выше?


text:
Q: How to stop a div from automatically scrolling to bottom Hello everyone i have been looking for a code to stop a section in a P.O.S from jumping to the bottom when i scroll up to the top. I have tried a few variations of a Javascript code but most i can get it to do is jump back down but a few lines from the end of the divider. Here is the code i started with that goes right to the bottom. This does it when it refeshes the div every 2 seconds.
function at_Ticket_ScrollBottom()
{
  var objDiv = document.getElementById("cartTicket");
  objDiv.scrollTop = objDiv.scrollHeight;
}

The second code I used is:
function at_Ticket_ScrollBottom()
{
   var objDiv = document.getElementById("cartTicket");
   objDiv.scrollTop = objDiv.offsetHeight;
}

This second code jumps down but is a few lines from the bottom. I am trying to make it so it will remain on the line you highlight no matter what one in the div it is.
I am using PHP, Javascript, and ajax for this web based point of sales system. if you have any ideas that would be great been struggling for about a week and the closest I got is the second code I posted. Most people ask how to auto scroll to the bottom so I haven't find a lot so far


text:
Q: sudo apt-get install package with python processing error So, I have tried to install tor and ffmpeg on my ubuntu 16.04 LTS with the step on: https://www.torproject.org/docs/debian
but after I run the line : apt-get install tor deb.torproject.org-keyring
It produce this log of error:
Setting up python3.5-minimal (3.5.2-2ubuntu0~16.04.1) ...
Traceback (most recent call last):
  File "/usr/lib/python3.5/py_compile.py", line 186, in <module>
    sys.exit(main())
  File "/usr/lib/python3.5/py_compile.py", line 178, in main
    compile(filename, doraise=True)
  File "/usr/lib/python3.5/py_compile.py", line 136, in compile
    os.makedirs(dirname)
  File "/usr/lib/python3.5/os.py", line 241, in makedirs
    mkdir(name, mode)
OSError: [Errno 117] Structure needs cleaning: '/usr/lib/python3.5/importlib/__pycache__'
dpkg: error processing package python3.5-minimal (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of python3.5:
 python3.5 depends on python3.5-minimal (= 3.5.2-2ubuntu0~16.04.1); however:
  Package python3.5-minimal is not configured yet.

dpkg: error processing package python3.5 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of python3.5-dev:
 python3.5-dev depends on python3.5 (= 3.5.2-2ubuntu0~16.04.1); however:
  Package python3.5 is not configured yet.

dpkg: error processing package python3.5-dev (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of python3-dev:
 python3-dev depends on python3.5-dev (>= 3.5.1-2~); however:
  Package python3.5-dev is not configured yet.

dpkg: error processing package python3-dev (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                No apport report written because the error message indicates its a followup error from a previous failure.
        No apport report written because MaxReports is reached already
                                                                      Errors were encountered while processing:
 python3.5-minimal
 python3.5
 python3.5-dev
 python3-dev
E: Sub-process /usr/bin/dpkg returned an error code (1)

Do anyone know how to solve this? Thank You


text:
Q: Pulling data from a file to use as a payload How can I have Scapy pull a file and send it within an ICMP packet?
I am using Scapy to create an ICMP packet and want it to pull a file and include it in the payload.  I have been messing with the basic send command and cant figure out the next step.
send(IP(dst="1.1.1.1")/ICMP()/{file.txt}

A: Simplest way is to read the file into a string (or bytes) with open and read, then add it as Raw.
with open('file.txt') as f:
    s = f.read()
send(IP(dst = '1.1.1.1') / ICMP() / Raw(load = s)) # you can, also, omit Raw(load = s) and just add it as ... / string_variable

Depending on the file length and content type slight modifications may be needed. This example works with a small text file.
Answer tested with scapy3k (http://github.com/phaethon/scapy) and python3, but it should work with scapy, too.


text:
Q: What are the steps for migrating from Play! 1.1 to 2.0? Is there any documentation on how to migrate from Play! 1.1 to Play! 2.0? I understand that I would need to rewrite the templates, but what additional steps would I need to perform to be up to date?
The app is written in Java with some jQuery with AJAX. I'm not using any NHibernate in it.
On a similar note, is the effort actually worth it? Or should I upgrade to 1.2 and not worry about 2.0?

A: play 2 is not play1.2.5+, which means you don't get all the features you get in play1.2.4 and some new ones.
there are some important fundamental changes (from 1.2.x to 2.0) I am still trying to wrap my head around. I would suggest to head over the mailing list for detailed questions if docs are unclear.
now to address your specifics.

rewrite the templates

yes, you will need to do that. though, there are plans to support compatibility. no idea when it will be done though.

additional steps would I need to perform to be up to date?

*

*firstly, the project structure/setup/tools are different.

*secondly, serving requests is different. For isntance in play2, you return RESULT object. Have a look at the docs to get an idea.

*thirdly, alot of modules are not available for 2.0. So if you rely on them, you will have to wait/write them yourself.

based on what I have seen, you would basically have to rewrite significant portions from 1.1 to 2.0.
You are better off upgrading to 1.2.4.


text:
Q: Can someone explain SUM Function task? Create a function sum that will work like that: sum(a)(b) = a+b and accepts any number of brackets.
Task is taken from this learning source.

function sum(a) {

  var sum = a

  function f(b) {
    sum += b
    return f
  }

  f.toString = function() { return sum }

  return f
}

alert( sum(1)(2) )  // 3
alert( sum(5)(-1)(2) )  // 6
alert( sum(6)(-1)(-2)(-3) )  // 0
alert( sum(0)(1)(2)(3)(4)(5) )  // 15

Can anyone explain actually how it works? A and B arguements are fine, but where in the code do we use other arguements (in cases when more than two of them)?
Why do we need to use toString method here? Is it related to problem or just for alert.
Also, I tried the same code with console.log instead of alert, and it didn't worked. What's the problem here?

A: Take a the alert out of the picture, and you have this code being invoked:
sum(1)(2)

You are probably confused about the double parenthesis - what's happening here is you are first invoking the sum function, and passing it the argument of 1. When you pass 1 to sum, you are setting 1 to a local variable named sum, then a function is declared f and used as the return value from the sum function.
As a result, since you invoked sum and got back a function (f), you can then call that function with parameter 2.
So in essence, you're really doing this:
var someFunc= sum(1);
someFunc(2);

Which can be re-written like this:
sum(1)(2);

A: function sum(a) {
var sum = a
//return function f;
function f(b) {
sum += b
return f
}
//override of toString to print sum
f.toString = function() { return sum }
return f;
}
alert(sum(1)(2));

Explanation for alert(sum(1)(2))
1.sum(1) gets executed first returning a closure with sum value 1
f(b){
    sum=sum+b; //sum=1 here from sum(1)
}

2.Next f(2) gets called
sum=sum+b// sum=1,b=2 so sum=3

and f gets returned.since f is overridden it prints sum value which is 3


text:
Q: Spectrum of the derivative operator: What's wrong in my argument? Consider the Banach space $X=C[0,1]$ of continuous functions $f:[0,1]\to\mathbb{R}$ equipped with the supremum norm. If we consider the following unbounded operator $A$ defined on its domain $D(A)=\{f\in C^1[0,1]:f(0)=1\}$ by $Af=f'$. I am interested in finding its spectrum. So if $g\in X$, then $g$ has a unique antecedent $f$ by the application $\lambda-A$ which is given by the formula $$f(x)=e^{\lambda x}-\int_0^xe^{\lambda(x-y)}g(y)dy.$$
That is $\lambda-A$ is invertible for every $\lambda\in \mathbb{C}$. Which means that the spectrum of $A$ is empty.
Now in the other hand, for each $\lambda\in \mathbb{C}$, if we consider the function $f_\lambda$ defined by $f_\lambda(x)=e^{\lambda x}$, then $f_\lambda\neq0$, $f_\lambda\in D(A)$ and $Af_\lambda=\lambda f_\lambda$, which means that the point spectrum is the whole complex plane. But this contradicts the fact that the whole spectrum is empty !!?


text:
Q: Get count of array and then average in a for each loop This should be easy but for some reason it's escaping me. I have a very simple query and loop here. I didn't add the actual query...but the array of objects in $results. The $totalHits addition works fine. Totaling up the number in $iratings works fine as well. What I am also trying to do is get the count of records in $iratings and print out an average...I just can't seem to get the count part working. How can I modify this to grab the count of $iratings then divide the TotalRating by the count of the number of "$iratings" in the array? if that makes sense?
$result = $db->loadObjectList();

// Tally Up the Stats

    $totalHits = 0;
    $totalRating = 0;

    foreach ($result as $item) {
    $ihits = $item->ihits;
    $totalHits = $totalHits + $ihits;
    $iratings = $item->iratings;
    $totalRating = $totalRating + $iratings;
    }

echo ('
Total Hits: '.$totalHits);
 echo ('
Total Rating: '.$totalRating);

A: $result = $db->loadObjectList();

// Tally Up the Stats
$totalHits = 0;
$totalRating = 0;
$numIterations = 0;

foreach ($result as $item) {
    $ihits = $item->ihits;
    $totalHits = $totalHits + $ihits;
    $iratings = $item->iratings;
    $totalRating = $totalRating + $iratings;
    $numIterations++;
}

echo ('
Total Hits: '.$totalHits);
echo ('
Total Rating: '.$totalRating);
echo ('
Average Rating: ' . ($totalRating/$numIterations));


text:
Q: Why is the printf statement in the code below printing a value rather than a garbage value? int main(){
    int array[] = [10,20,30,40,50] ;
    printf("%d\n",-2[array -2]);
    return 0 ;
}

Can anyone explain how -2[array-2] is working and Why are [ ] used here?
This was a question in my assignment it gives the output " -10  " but I don't understand why?

A: Technically speaking, this invokes undefined behaviour. Quoting C11, chapter §6.5.6

If both the pointer
  operand and the result point to elements of the same array object, or one past the last
  element of the array object, the evaluation shall not produce an overflow; otherwise, the
  behavior is undefined. [....]

So, (array-2) is undefined behavior.
However, most compilers will read the indexing, and it will likely be able to nullify the +2 and -2 indexing, [2[a] is same as a[2] which is same as *(a+2), thus, 2[a-2] is *((2)+(a-2))], and only consider the remaining expression to be evaluated, which is *(a) or, a[0].
Then, check the operator precedence
-2[array -2] is effectively the same as -(array[0]). So, the result is the value array[0], and -ved.

A: This is an unfortunate example for instruction, because it implies it's okay to do some incorrect things that often work in practice.
The technically correct answer is that the program has Undefined Behavior, so any result is possible, including printing -10, printing a different number, printing something different or nothing at all, failing to run, crashing, and/or doing something entirely unrelated.
The undefined behavior comes up from evaluating the subexpression array -2.  array decays from its array type to a pointer to the first element.  array -2 would point at the element which comes two positions before that, but there is no such element (and it's not the "one-past-the-end" special rule), so evaluating that is a problem no matter what context it appears in.
(C11 6.5.6/8 says)

When an expression that has integer type is added to or subtracted from a pointer, ....  If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

Now the technically incorrect answer the instructor is probably looking for is what actually happens on most implementations:
Even though array -2 is outside the actual array, it evaluates to some address which is 2*sizeof(int) bytes before the address where the array's data starts.  It's invalid to dereference that address since we don't know that there actually is any int there, but we're not going to.
Looking at the larger expression -2[array -2], the [] operator has higher precedence than the unary - operator, so it means -(2[array -2]) and not (-2)[array -2].  A[B] is defined to mean the same as *((A)+(B)).  It's customary to have A be a pointer value and B be an integer value, but it's also legal to use them reversed like we're doing here.  So these are equivalent:
-2[array -2]
-(2[array -2])
-(*(2 + (array - 2)))
-(*(array))

The last step acts like we would expect: Adding two to the address value of array - 2 is 2*sizeof(int) bytes after that value, which gets us back to the address of the first array element.  So *(array) dereferences that address, giving 10, and -(*(array)) negates that value, giving -10.  The program prints -10.

You should never count on things like this, even if you observe it "works" on your system and compiler.  Since the language guarantees nothing about what will happen, the code might not work if you make slight changes which seem they shouldn't be related, or on a different system, a different compiler, a different version of the same compiler, or using the same system and compiler on a different day.

A: Here is how -2[array-2] is evaluated:
First, note that -2[array-2] is parsed as - (2[array-2]). The subscript operator, [...] has higher precedence than the unary - operator. We often think of constants like -2 as single numbers, but it is in fact a - operator applied to a 2.
In array-2, array is automatically converted to a pointer to its first element, so it points to array[0].
Then array-2 attempts to calculate a pointer to two elements before the first element of the array. The resulting behavior is not defined by the C standard because C 2018 6.5.6 8 says that only arithmetic that points to array members and the end of the array is defined.
For illustration only, suppose we are using a C implementation that extends the C standard by defining pointers to use a flat address space and permit arbitrary pointer arithmetic. Then array-2 points two elements before the array.
Then 2[array-2] uses the fact that the C standard defines E1[E2] to be *((E1)+(E2)). That is, the subscript operator is implemented by adding the two things and applying *. Thus, it does not matter which expression is E1 and which is E2. E1+E2 is the same as E2+E1. So 2[array-2] is *(2 + (array-2)). Adding 2 moves the pointer from two elements before the array back to the start of the array. Then applying * produces the element at that location, which is 10.
Finally, applying - gives −10. (Recall that this conclusion is only achieved using our supposition that the C implementation supports a flat address space. You cannot use this in general C code.)

A: This code invokes undefined behavior and can print anything, including -10.
C17 6.5.2.1 Array subscripting states:

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))

Meaning array[n] is equivalent to *((array) + (n)) and that's how the compiler evaluates subscripting. This allows us to write silly obfuscation like n[array] as 100% equivalent to array[n]. Because *((n) + (array)) is equivalent to *((array) + (n)). As explained here:
With arrays, why is it the case that a[5] == 5[a]?
Looking at the expression -2[array -2] specifically:

*

*[array -2] and [array - 2] are naturally equivalent. In this case the former is just sloppy style purposely used for the sake of obfuscating the code.

*Operator precedence tells us to first consider [].

*Thus the expression is equivalent to -*( (2) + (array - 2) )

*Note that the first - is not part of the integer constant 2. C does not support negative integer constants1), the - is actually the unary minus operator.

*Unary minus has lower presedence than [], so the 2 in -2[ "binds" to the [.

*The sub-expression (array - 2) is evaluated individually and invokes undefined behavior, as per C17 6.5.6/8:

When an expression that has integer type is added to or subtracted from a pointer, the
  result has the type of the pointer operand. /--/ If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

*Speculatively, one potential form of undefined behavior could be that a compiler decides to replace the whole expression (2) + (array - 2) with array, in which case the whole expression would end up as -*array and prints -10.
There's no guarantees of this and therefore the code is bad. If you were given the assignment to explain why the code prints -10, your teacher is incompetent. Not only is it meaningless/harmful to study obfuscation as part of C studies, it is harmful to rely on undefined behavior or expect it to give a certain result.

1) C rather supports negative integer constant expressions. -2 is an integer constant expression, where 2 is an integer constant of type int.


text:
Q: File Transfer android I'm working on an android application that founds all the devices connected to the same network via WiFi, now i want to send files from my android application, the receiver device may be an android device or anything else(windows or mac etc).
I'm new to android programming and i don't know how it will be done, only i want to do is to send and receive files from my application,
Is it possible if yes then how??
Thanks in advance and sorry for poor english

A: If you want to send a file from your app to another device, you need to have a receiving app in the receiver device, otherwise it won't be possible,
There is a possibility is to use built-in NFC check here NFC
EDIT
you mentionned sending from your app to another this can be done by uploading your file to a remote server then downloading it from that remote server again
here is a snippet on how to upload it
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}

and here is a tutorial on how to download it from the receiving app Download from remote server


text:
Q: Java applet don't work in browser People i make a java applet:
    import java.net.InetAddress;
public class PegaIP {
    public static void main(String[] args) {
        try {
            getAppletContext().showDocument
                    (new URL("javascript:UpdateIP(\"" + InetAddress.getLocalHost().getHostAddress() + "\")"));
        } catch (Exception e) { }
    }
}

and i received some error:
Plug-in 10.9.2.05 do Java
Usando versão JRE 1.7.0_09-b05 Java HotSpot(TM) Client VM
Diretório home do usuário = C:\Users\Edilsom

c:   limpar janela da console
f:   concluir objetos da fila de finalização
g:   coleta de lixo
h:   exibir esta mensagem de ajuda
l:   descartar lista de carregadores de classes
m:   imprimir uso de memória
o:   log do trigger
q:   ocultar console
r:   recarregar configuração da política
s:   descartar propriedades do sistema e de implantação
t:   descartar lista de threads
v:   descartar pilha de threads
x:   limpar cache do carregador de classes
0-5: definir nível de rastreamento como <n>

Match: beginTraversal
Match: digest selected JREDesc: JREDesc[version 1.6+, heap=-1--1, args=null, ref=http://java.sun.com/products/autodl/j2se, sel=false, null, null], JREInfo: JREInfo for index 0:
platform is: 1.7
product is: 1.7.0_09
location is: http://java.sun.com/products/autodl/j2se
path is: C:\Program Files (x86)\Java\jre7\bin\javaw.exe
args is: null
native platform is: Windows, x86 [ x86, 32bit ]
JavaFX runtime is: JavaFX 2.2.3 found at C:\Program Files (x86)\Java\jre7\
enabled is: true
registered is: true
system is: true

Match: ignoring maxHeap: -1
Match: ignoring InitHeap: -1
Match: digesting vmargs: null
Match: digested vmargs: [JVMParameters: isSecure: true, args: ]
Match: JVM args after accumulation: [JVMParameters: isSecure: true, args: ]
Match: digest LaunchDesc: null
Match: digest properties: []
Match: JVM args: [JVMParameters: isSecure: true, args: ]
Match: endTraversal ..
Match: JVM args final:
Match: Running JREInfo Version    match: 1.7.0.09 == 1.7.0.09
Match: Running JVM args match: have:<>  satisfy want:<>
CacheEntry[http://localhost/3gloja/pegaip.class]: updateAvailable=true,lastModified=Tue Nov 20 22:46:40 GMT-03:00 2012,length=780

what i do wrong??

A: Java applets do not run with the main, you need init. Must also extend JApplet.
import javax.swing.JApplet;
public class PegaIP extends Applet
public void init() replaces public static void main(String[] args)
A resource can be found here: http://docs.oracle.com/javase/tutorial/deployment/applet/getStarted.html

A: People this is code works fine for me:
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import javax.swing.JApplet;
public class PegaIP extends JApplet {
    @Override
    public void init() {
        try {
            getAppletContext().showDocument (new URL("javascript:UpdateIP(\"" + InetAddress.getLocalHost().getHostAddress() + "\")"));
        } catch (UnknownHostException | MalformedURLException e) {
            System.err.println("Ocorreu erro na criação da GUI");
        }
    }
}

Thanks everyone help me...


text:
Q: react-navigation more than one nesting I have this structure:

*

*Main

*

*Child 1

*Child 2

*

*Grandchild 1

*Other

The problem that I'm having is that I can't navigate from Child 2 to Grandchild 1. It throws
TypeError: navigation.navigate is not a function
or
undefined is not an object (evaluating 'props.navigation.navigate')
I have a stack navigator like this:
<Stack.Navigator>
    <Stack.Screen name="Main" />
    <Stack.Screen name="Child2" />
    <Stack.Screen name="Grandchild" />
</Stack.Navigator>

I can go from Main to Child2, do I have to make a new Stack for deeper nesting?

A: I was using the navigation.navigate in the wrong place
It should be used in Component
<Child onPress={() => navigation.navigate('Grandchild');} />

And then inside the component Touchable do:
<Touchable onPress={props.onPress}>
...
</Touchable>


text:
Q: Proving that $ (A \triangle B) - C= (A - C) \triangle (B -C)$ Let A,B,C be subsets of a universe V.
I need to prove  $ (A \triangle B) - C= (A - C) \triangle (B -C)$
Here is my attempt. Could someone please verify it?
I used 2 auxiliary results for the proof:
Lemma 1:

$((A-C) \cap B^c) \subset (A - C) \triangle (B -C)$

Proof:
$(A - C) \triangle (B -C) =\mathbf{[(A-C ) - (B-C)]}\cup[(B-C)-(A-C)]$
$\implies (A - C) \triangle (B -C) = \mathbf{[(A-C)\cap(B\cap C^c)^c]}\cup[(B-C)-(A-C)]$
$\implies (A - C) \triangle (B -C) = \mathbf{[(A-C)\cap(B^c\cup C)]}\cup[(B-C)-(A-C)]$
$\implies (A - C) \triangle (B -C) = \mathbf{[((A-C)\cap B^c)\cup((A-C)\cap C))]}\cup[(B-C)-(A-C)]$
$\square$
Lemma 2:

$((B-C)\cap A^c) \subset (A - C) \triangle (B -C)$

Proof:
$(A - C) \triangle (B -C) =[(A-C ) - (B-C)]\cup\mathbf{[(B-C)-(A-C)]}$
$\implies (A - C) \triangle (B -C) =[(A-C ) - (B-C)]\cup\mathbf{[(B\cap C^c)\cap(A\cap C^c)^c]} $
$\implies (A - C) \triangle (B -C) =[(A-C ) - (B-C)]\cup\mathbf{[(B\cap C^c)\cap(A^c \cup C)]} $
$\implies (A - C) \triangle (B -C) =[(A-C ) - (B-C)]\cup\mathbf{[(B\cap C^c \cap A^c )\cup( B\cap C^c \cap C)]} $
$\implies (A - C) \triangle (B -C) =[(A-C ) - (B-C)]\cup\mathbf{[((B - C) \cap A^c )\cup( B\cap C^c \cap C)]} $
$\square$
Proof of the equality:
Let $x \in ((A \triangle B) - C)$
$x \in ((A \triangle B )- C) \iff [x \in (A \triangle B) ] \land [x\in C^c]$
$\iff [x \in (A - B) \lor x\in (B-A)] \land [x \in C^c] $
$\iff [x \in (A-B) \land x \in C^c] \lor [x \in (B-A) \land x \in C^c]$ (1)
By (1) $x \in (A \triangle B - C)$ if and only if one of the following conditions hold:
(i). $x \in (A-B) \land x \in C^c$
(ii). $x \in (B-A) \land x \in C^c$
Assuming (i):
$x \in (A-B) \land x \in C^c \iff [x \in A \land x\in B^c] \land x \in C^c$
$\iff x \in A \land x\in C^c \land x \in B^c$
$\iff x \in (A-C) \land x \in B^c$
$\iff x \in ((A-C) \cap B^c)$
So, by Lemma 1 we have $x \in ((A - C) \triangle (B -C))$
Assuming (ii):
$x \in (B-A) \land x \in C^c \iff x \in B \land x \in A^c \land x \in C^c$
$\iff x \in B \land x \in C^c \land x \in A^c$
$\iff x \in (B-C) \land x \in A^c$
$\iff x \in ((B-C) \cap A^c)$
By Lemma 2, $x \in ((A - C) \triangle (B -C))$
$\blacksquare$
Is this correct? If it is not, what are my mistakes? And if it is, is there a simpler or clearer proof?

A: As far as i can tell your solution has no mistakes, however it can be done shorter. You can do set algebra and try to meet the equality by showing that one side can be written as the other side, my advice is to always work from the biggest side and reduce it to the smallest side, here is my proof
$$(A \triangle B) - C= (A - C) \triangle (B -C)$$
Start:
$$(A - C) \triangle (B -C)$$
Def Triangle operator
$$(A-C)-(B-C)\cup (B-C)-(A-C)$$
Def -operator
$$((A\cap C^c)\cap(B\cap C^c)^c)\cup ((B\cap C^c)\cap(A\cap C^c)^c)$$
DeMorgan
$$((A\cap C^c)\cap(B^c\cup C))\cup ((B\cap C^c)\cap(A^c\cup C))$$
Distribution and absorption one step
$$(A\cap (B^c\cup C)\cap C^c\cap B^c)\cup (B\cap (A^c\cup C)\cap A^c\cap C^c))$$
absorption
$$(A\cap C^c\cap B^c)\cup (B\cap A^c\cap C^c))$$
commutative property and def -
$$(A-B)-C\cup(B-A)-C$$
Def triangle/ distribution or/-
$$(A \triangle B) - C$$


text:
Q: Is this set relatively open or closed? Take the set  $\{(x,y) : (x-2)^2 + y^2 < 2\}$ .  Is this set relatively open or relatively closed in the subspace $B(2,0)$ radius $\sqrt2$.  (The open ball centered at $(2,0)$ with radius $\sqrt2$) ?
I want to say it is both relatively open and relatively closed although I've been told it is just relatively closed.  I don't understand how it is one and not the other.  You can get an open ball around every point in the set and it is still in the subspace.  Since the subspace is equal to the set, you can find any closed or open set in $\mathbb R^2$ s.t. the set is equal to the intersection.
Thanks!

A: Given a topological space, a subset $A \subset X$ becomes a topological space of its own by defining the open sets in $A$ to all sets of the form $U \cap A$ where $U \subset X$ is open (same for closed sets). So $A$ is open and closed in $A$.


text:
Q: What is the meaning of "pump" I'm reading (Cambridge Collocation in use) and find this sentence and I don't fully understand it.

There was good news for motorists today as pump prices were lowered by the major oil companies.

So pump here motor or what?

A: In the context of prices to motorists and oil companies, "pump prices" means the prices of gasoline or petrol or similar liquid fuel sold in a retail station serving automobiles. The stations typically have multiple free-standing machines that pump the fuel from an underground tank into a hose having a nozzle that inserts into a vehicle's fuel tank fill pipe. Such machines are often called "pumps," and typically have the price of the product per unit volume (gallon, liter) on them in a display window.
So "pump prices" means the prices of automobile fuel per unit volume.


text:
Q: Jetpack compose and AuthStatelistener firebase Hi i am trying to create an app in jetpack compose with MVVM architechture and with firebase.
I am now wondering where you would go about placing the AuthStatelistener in this case. I cant find anything about it on the web. The thing is that implementing that statelistnener does not work quz you do not use classes in Jetpack compose you use functions. and you cant call screens in the MainActivity. So how would you then check if the user is still signed in??? There is nothing about it on the web. There is a bunch of tutorials on the web about MVVM structure and ordinary xml layouts but nothing what i can find about jetpack compose?????


text:
Q: TypeError: this.state.schedulelistnew.map is not a function Create class 'ScheduleList' and initalize array elements
class ScheduleList extends Component {
      state = {
        schedulelistnew: []
    };

Used to populate array elements from API using axios
 componentDidMount() {
        axios.get(`https://apiv2.apifootball.com/?action=get_H2H&firstTeam=Chelsea&secondTeam=Arsenal&APIkey=******`)
        .then(res => {
           const schedulelistnew = res.data;
          this.setState({ schedulelistnew });
        });
      }

Render the array elements to the Component 'ScheduleListItem '
 render() {
        return (

            <Row>
              <Col lg="9" md="8">
                {this.state.schedulelistnew.map(item => (

                    <ScheduleListItem item={item} />

                ))}

What am I missing?

A: when the map process you forget about return
{this.state.schedulelistnew.map( item => {
    return (

        <ScheduleListItem item={item} />

   );
  }
)}


text:
Q: TCP connection limit/timeout in virtual machine and native macOS/ARM-based Mac gRPC Go client? I am currently working on a gRPC microservice, which is deployed to a Kubernetes cluster. As usual, I am benchmarking and load-/stress-testing my service, testing different load balancing settings, impact of SSL and so forth.
Initially, I used my Macbook and my gRPC client written in Go and executed this setup either in Docker or directly in containerd with nerdctl. The framework I use for this is called Colima and basically builds on a lean Alpine VM to provide the container engine. Herein, I ran into issues with connection timeouts and refusals once I crossed a certain number of parallel sessions, which I guess is a result from the container engine.
Therefore, I went ahead and ran my Go client natively on macOS. This setup somehow runs into the default 20s keepalive timeout for gRPC (https://grpc.github.io/grpc/cpp/md_doc_keepalive.html) the moment my parallel connections exceed the number of traffic I can work out by some margin (#1).
When I run the very same Go client on an x86 Ubuntu 22 desktop, there are no such issues whatsoever and I can start way more sessions in parallel, which are then processed accordingly without any issues with the 20s keepalive timeout.
Any ideas how that comes to being and if I could make some changes to my setup to be able to run my stress-test benchmarks from macOS?
#1: Let's say I can process and reply 1 request per second with my service. For stress testing, I now start 20 parallel sessions and would expect them to be processed sequentially.


text:
Q: Block Internet Connection through Terminal on OSX Even though I don't have administrative privileges, can I block Internet connection on my Mac OS 10.8 machine, through the terminal?
I want to do this because I am too lazy to disconnect ethernet cable from my machine to check one of my apps in offline mode.
I have found that for Windows we have: ipconfig release and ipconfig renew commands for the same task.
Do we have any alternatives for those in Mac or any better solution to achieve it?

A: Since it won't be possible to do it as a normal user without special settings. (A normal user should not be able to break the system by default...) If you can convince the administrator that you need to do it, they can add the relevant command for your user to the sudoers file... (Looks like you basically want the DHCP client to restart). Seems like you'll need access to the ipconfig command. (sudo ipconfig set en0 NONE; sudo ipconfig set en0 DHCP (replace en0 with your ethernet interface as reported by ifconfig) should do it...)
You might also want to check if there is a group that you can be added to to allow you to access network settings...
Looks like another method is to set up multiple network "Locations" (admin will need to do it) and you can then switch between them using scselect, seemingly without admin rights...
The administrator should be able to limit you to only those commands in su.
(Some of this info comes from a superuser post I found (but can only access via Google cache where I am currently..))


text:
Q: How to subtract two dates in LINQ? I have a problem with subtracting two dates in the MySQL database and comparing them to int numbers. I tried to use dbfunctions.diffdays however it is a conflict of types.
When I start the application I get a message:

System.ArgumentException: 'DbArithmeticExpression arguments must have
  a numeric common type.'

Below is my code
    i
    int intervalDay = 25;
    var dateCount = (from Rezerwacje in db.Rezerwacje
                     join rooms in db.rooms on Rezerwacje.PokojID equals rooms.id
                     where (rooms.floor > 0 && rooms.floor <= 2) &&(Rezerwacje.DataDo == dateTime) && ((Rezerwacje.DataDo - Rezerwacje.DataOd).Days > intervalDay)
                     select Rezerwacje).Count();
                     return dateCount;

A: You could use
System.Data.Objects.EntityFucntions
and in the code:
where ... &&
      EntityFunctions.DiffDays(Rezerwacje.DataDo, Rezerwacje.DataOd) > intervalDay

A:  using System.Data.Entity;

 //code in LINQ
 ... DbFunctions.DiffDays(Rezerwacje.DataDo, Rezerwacje.DataOd) >= intervalDay

A: Ultimately I use List and foreach.
Downloading data from database:
public int DateCleanFloor1to2(DateTime dateTime)
{
            var dateList = (from Rezerwacje in db.Rezerwacje
                            join rooms in db.rooms on Rezerwacje.PokojID equals rooms.id
                            where (rooms.floor > 0 && rooms.floor <= 2) && (Rezerwacje.DataDo == dateTime)
                            select Rezerwacje).ToList();

            return SubtractDateToDateFrom(dateList, dateTime.AddDays(25));
 }

And method with foreach loop:
public int SubtractDateToDateFrom(List<Rezerwacje> dateList, DateTime dateTime)
{
            int count = 0;
            foreach (var item in dateList)
            {
                if (item.DataDo < dateTime)
                {
                    count++;
                }
            }

            return count;
}

@DevilSuichiro @Arulkumar @Seven


text:
Q: Erro CORS com SignalR usando UseCredentials() Como diz no título, estou com um problema de CORS com as Credentials usando o SignalR, o erro retornado é:

Access to fetch at https://localhost:54083/notification/negotiate?negotiateVersion=1 from origin http://localhost:3000 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

O meu problema é que eu já adicionei no meu Startup.cs, em services.AddCors, o método AllowCredentials(), e agora tenho ficado sem muitas opções de como resolver.
Segue meus métodos ConfigureServices e Configure de Startup.cs:
public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureCloudFoundryOptions(Configuration);
            services.AddSession();
            services.AddControllersWithViews();
            services.AddControllers();
            services.AddControllers().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);

            services.AddCors(options =>
{
    options.AddPolicy("ClientPermission", policy =>
    {
        policy.AllowAnyHeader()
            .AllowAnyMethod()
            .WithOrigins("http://localhost:3000")
            .AllowCredentials();
    });
});
            services.AddSignalR();

            var key = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("JWT:Key"));

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
                x.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/notification")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };
            });
            services.AddSingleton<IUserIdProvider, NameUserIdProvider>();

        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCors("ClientPermission");
            app.UseRouting();
            app.UseSession();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<NotificationHub>("/notification");

            });

        }
    }

O frontend é em React e é feito o consumo do serviço do SignalR desta forma aqui:
useEffect(() => {
    const newConnection = new HubConnectionBuilder()
      .withUrl("https://localhost:54083/notification")
      .withAutomaticReconnect()
      .build();

    setConnection(newConnection);
  }, []);

  useEffect(() => {
    if (connection) {
      console.log(connection)
      connection
        .start()
        .then((result) => {
          console.log("Connected!");

          connection.on("ReceiveMessage", (message) => {
            setNotifications(...notifications.push(message));
          });
        })
        .catch((e) => console.log("Connection failed: ", e));
    }
  }, [connection]);

A: Foram adicionadas novas politicas nos navegadores para acesso as redes privadas. Neste site https://developer.chrome.com/blog/private-network-access-preflight/ contém mais detalhes sobre essas mudanças.
Enfim, pelo que tudo indica será necessário informar nos cabeçalhos das requisições a política a seguir:

Access-Control-Allow-Private-Network

Para que a comunicação possa ser estabelecida.


text:
Q: How to enable a button if regex expression is valid I have a page on which there are two textboxes that have a regular expression on them.
ASPX Code TextBox 1
<asp:TextBox ID="txtCasesInsert" runat="server" Width="50px"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rfvCases" ControlToValidate="txtCasesInsert" ValidationGroup="InsertRecord"
                                runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
                            <asp:RegularExpressionValidator ID="regexCases" ControlToValidate="txtCasesInsert"
                                ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
                                runat="server" />

ASPX Code TextBox 2
<asp:TextBox ID="txtPremiumInsert" runat="server" Width="50px"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rfvPremium" ControlToValidate="txtPremiumInsert"
                                ValidationGroup="InsertRecord" runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
                            <asp:RegularExpressionValidator ID="regexPremium" ControlToValidate="txtPremiumInsert"
                                ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
                                runat="server" />

The regular expression works as intended for both text boxes.
What I need now is to be able to check the text being inputted into those text boxes and if the regular expression is valid, then enable my Insert button, otherwise, keep the button disabled.
Insert Button
<asp:Button ID="btnInsertRecord" Width="100px" Height="25px" runat="server" Text="Add Record"
                                CssClass="buttonBlue" ValidationGroup="InsertRecord" />

The reason I want to do this, is because when the regex has an error, the page still allows the user to insert data so I thought of disabling the button if the regex isn't successfull to prevent this.
I tried this C# If regex doesn't match then do something and I've also read up on Microsofts Regex documentation to learn more about what I can do with Regex's but I haven't found any information related to what I need.
I also tried creating a function with a TextChanged method hooked onto the textboxes but it didn't work. No error messages, just the button wasn't disabling when I inputted a wrong string. That's the problem I'm also having now with my current code. It's like nothing is happening. I've hooked the debugger on the _premiumMatch.Success line but again, nothing is happening, it just lets me proceed. When I created the TextChanged method for my button, I also tried adding it into my Page Load method but that disabled the button straight away.
Current VB Code (Example with one of the text boxes)
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
        Dim _premiumMatch = _regex.Match(txtPremiumInsert.Text)

        If _premiumMatch.Success Then

            Try
                Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
                                                                                _premium,
                                                                                _cases,
                                                                                _ddlMonths,
                                                                                _ddlYear)
            Catch ex As Exception
                InformationBox.ShowErrorMessage("Record not added. Please try again")
            End Try
            loadLimitInsurances()
            InformationBox.ShowSuccessMessage("New Record Inserted")
            txtBranchInsert.Text = ""
            txtPremiumInsert.Text = ""
            txtCasesInsert.Text = ""
        End If

Not sure what I'm doing wrong. Any suggestions? The above VB code, for now is in my buttons click event but even with an invalid regex, when I click the insert is still performed.
First Edit
Just tried calling the below function in my page load but the button disables straight away and does not become enabled if I input a valid regex. Again, example is for one textbox.
Protected Friend Sub CheckPremium() Handles txtPremiumInsert.TextChanged

    Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
    Dim _match As Match = _regex.Match(txtPremiumInsert.Text)

    If _match.Success Then
        btnInsertRecord.Enabled = True
    Else
        btnInsertRecord.Enabled = False
    End If

End Sub

Second Edit
I have tried the above code and I've activated AutoPostBack on the textbox and still when I type an invalid expression it postbacks and activates my button.

A: Try this code:
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
    Dim FoundMatch As Boolean = _regex.IsMatch(textPremiumInsert.Text)

    If FoundMatch = True Then

        Try
            Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
                                                                                _premium,
                                                                                _cases,
                                                                                _ddlMonths,
                                                                                _ddlYear)
        Catch ex As Exception
            InformationBox.ShowErrorMessage("Record not added. Please try again")
        End Try
        loadLimitInsurances()
        InformationBox.ShowSuccessMessage("New Record Inserted")
        txtBranchInsert.Text = ""
        txtPremiumInsert.Text = ""
        txtCasesInsert.Text = ""
    End If

The code above uses the Regex.IsMatch method to compare the string passed with the regex pattern. It returns true if the string matches the  Regex pattern.


text:
Q: How to set PAGES property in YAHOO.widget.CalendarGroup for different case? I meet a problem when doing the YAHOO.widget.CalendarGroup.
I want to do it like this, if the page widtha is less than 720px, the CalendarGroup PAGES property is 1 , if more than 720px, the CalendarGroup use the default PAGES property is 2.
I use
myCalendar.cfg.setProperty("PAGES",1);

but it doesn't work, I found in the document here:
http://developer.yahoo.com/yui/docs/YAHOO.widget.CalendarGroup.html#config_pages

pages - Number
  The number of pages to include in the CalendarGroup. This value can only be set once, in the CalendarGroup's constructor arguments.
  Default Value: 2

Seems we can't change the pages property after the initicalization. How could I change the pages based on the change of my browser width? THANKS.

A: As it says: "This value can only be set once, in the CalendarGroup's constructor arguments". Use the constructor, like this:
var myCalObject = new YAHOO.widget.CalendarGroup(
    calObject,
    calObject + "Container",
    { pages: 2, close: true, iframe: false }
);


text:
Q: Android: Asynctask without showing dialog I've searched in the web but I only find cases where the users want to show the dialog in the asynctask like this example: protected void onPreExecute().
{
                            super.onPreExecute();
                            pDialog = new ProgressDialog(NumericoComercial.this);
                            pDialog.setMessage("Actualizando ...");
                            pDialog.setIndeterminate(false);
                            pDialog.setCancelable(true);
                            pDialog.show();
                        }

What I would like to know is if it can be done an asynctask without showing any dialog in onPreExecute() and onPostExecute() as usually is done.
I have experienced some problems using asynctask with dialogs regarding Window Leaked Error. The thing I've tried is not adding any dialog to the Pre and Post Actions like the following example.
class UpdateCandidatos extends AsyncTask<String, String, String> {

                    @Override
                    protected void onPreExecute() {

                    }

protected void onPostExecute(String file_url) {

                    }
                }

Could be any errors using this method, for example when the activity is finished?
Thank you

A: I would recommend that you cancel your async task in you onPause() method. This way if your activity closes, the async task wont try to publish any data, and onPostExecute wont be called.
Hm, you shouldn't be having any errors with onPostExecute(), you can use async task without showing any data, its not mandatory. You dont even have to @override that function, just put Void i the declaration ( ...extends AsyncTask<...,...,Void> )

A: onPreExecute() and onPostExecute() are not required methods extending Aynctask then all the things you write in those methods (Dialog, ProgressDialog etc) are unnecessary for the correct working of your class.
class UpdateCandidatos extends AsyncTask<String, String, String> {

    protected Long doInBackground(String... urls) {
        //add here your background work
    }

}

this is a very simplified and fully forking AsyncTask that do "something" in background showing no dialog.
Note: you will have to handle the task according to the lifecycle of your app


text:
Q: Vigenere cipher-Cryptanalytic attack I implemented a program to break a Vigenere cipher. I've used the algorithm presented on this site.
Step 1- Finding the key length: I suppose that the key length is 2, 3, ..., max key length and I extract substrings for each key length(2 substrings for key length 2, 3 substrings for key length 3 and so on). Each of the extracted substring was ciphered using the Caesar's cipher. Then I compute the index of coincidence for each of the extracted substring for a certain period and then I take the average IC for each period. The period with the biggest average IC represents the Vigenere key length.
Step2- Finding the key: Knowing the key length(let us suppose it is n), I extract the n substrings(meaning n Caesar ciphers) from the Vigenere cipher and for each substring I apply a Caesar brute force attack. Then for each string generated by this attack, I compute the chi-squared statistic to find out the key for each Caesar cipher. In the end, the keys for Caesar ciphers will form the Vigenere key.
The problem is that on average only 2/3 of the letters from the Vigenere key are found properly. I want to know if there is something I'm doing wrong. Is there any chance I could get the correct key using this approach?
Any advice would be greatly appreciated.


text:
Q: Thrust/CUDA replicate an array multiple times combined with the values of another array Let's say I have two arrays
A = {1, 2, 3}
and
B = {10,20,30,40,50}
I want to generate a new array which would have a size of
sizeof(A) * sizeof(B)
I want to replicate B sizeof(A) times, and on each repetition i, the resultant array should have A[i] added to it. So the result would be something like
{11,21,31,41,51,12,22,32,42,52,13,23,33,43,53}

A: This task can be interpreted as a 2-dimensional problem where the output array can be treated as a matrix of dimensions sizeof(A) times sizeof(B). In this way, we can use 2D CUDA indexing to achieve the desired functionality. A sample CUDA C++ code of this 2D implementation is shown below:
#include <iostream>
#include <cuda_runtime.h>
#include <cassert>

using namespace std;

__global__ void kernel_replicate(int* a, int* b, int* c, int alen, int blen, int clen)
{
    const int ai = blockIdx.x * blockDim.x + threadIdx.x;
    const int bi = blockIdx.y * blockDim.y + threadIdx.y;

    if(ai<alen && bi<blen)
    {
        const int ci = ai * blen + bi;
        c[ci] = a[ai] + b[bi];
    }
}

void replicate_device(int* a, int* b, int* c, int alen, int blen, int clen)
{
    dim3 block(16,16);
    dim3 grid;
    grid.x = (alen + block.x - 1) / block.x;
    grid.y = (blen + block.y - 1) / block.y;

    kernel_replicate<<<grid, block>>>(a,b,c,alen,blen,clen);

    assert(cudaSuccess == cudaDeviceSynchronize());
}

void replicate(int* a, int* b, int* c, int alen, int blen, int clen)
{
    int *ad, *bd, *cd;

    size_t abytes = alen * sizeof(int);
    size_t bbytes = blen * sizeof(int);
    size_t cbytes = clen * sizeof(int);

    cudaMalloc(&ad, abytes);
    cudaMalloc(&bd, bbytes);
    cudaMalloc(&cd, cbytes);

    cudaMemcpy(ad,a, abytes, cudaMemcpyHostToDevice);
    cudaMemcpy(bd,b, bbytes, cudaMemcpyHostToDevice);

    replicate_device(ad,bd,cd, alen,blen,clen);

    cudaMemcpy(c,cd, cbytes, cudaMemcpyDeviceToHost);

    cudaFree(ad);
    cudaFree(bd);
    cudaFree(cd);
}

int main()
{
    const int alen = 3;
    const int blen = 5;
    const int clen = alen * blen;

    int A[alen] = {1,2,3};
    int B[blen] = {10,20,30,40,50};
    int C[clen] = {0};

    replicate(A,B,C,alen, blen, clen);

    for(int i=0; i<alen; i++)
    {
        cout<<A[i]<<" ";
    }
    cout<<endl;

    for(int i=0; i<blen; i++)
    {
        cout<<B[i]<<" ";
    }
    cout<<endl;

    for(int i=0; i<clen; i++)
    {
        cout<<C[i]<<" ";
    }
    cout<<endl;

    return 0;
}


text:
Q: Are ideals in rings and lattices related? There are (at least) two notions of ideals:

*

*An ideal in a ring is a set closed under addition and multiplication by arbitrary element.

*An ideal in a lattice is a set closed under taking smaller elements and suprema.
They coincide nicely on Boolean algebras/rings.
Is there a common generalization of them, or can one of them be represented as a special case of the other?

A: I believe that the notion of "ideal" for lattices came about later than the notion for rings, and that it originally arose in boolean algebras by analogy. It was later extended to lattices, and finally to partially ordered sets.
Kummer first introduced "ideal numbers" in his study of factorization in cyclotomic rings, $\mathbb{Z}[\zeta_p]$ where $\zeta_p$ is a primitive $p$th root of unity; some of these rings did not enjoy unique factorization, but Kummer used the notion of ideal number (with ideal being used in the sense of "existing in imagination or fancy only", and along the lines of an "imaginary embodiment of a quality"). These were "numbers" that did not actually exist in the rings, but which allowed for a kind of unique factorization (each element of $\mathbb{Z}[\zeta_p]$ could be written uniquely as a product of actual and ideal numbers). This was 1844.
Dedekind then took the notion of ideal number and replaced it with "ideal"; every "ideal number" of Kummer was identified with the set of all its "multiples", and this got extended to multiples of actual numbers. What we now call "principal ideals" corresponded to actual numbers, and nonprincipal ideals to ideal numbers. This allowed an extension from cyclotomic rings to arbitrary rings of integers in number fields. Dedekind gave several expositions of ideals, with the 1877 version probably being the most polished. You can find a very nice translation (with extended introductory remarks by John Stillwell) in Theory of Algebraic Integers by Richard Dedekind, Cambridge Mathematical Library , Cambridge University Press 1996, ISBN 0-521-56518-9.
Dedekind defines an ideal of the ring $R$ (always commutative) as a non-empty set $I$ such that

*

*The sum and difference of any two numbers in $I$ are also in $I$; and

*Each product of a number in $I$ by a numbers in $R$ is a number in $I$.

These notions were later extended by Artin and Noether in the 1920s to more general rings.
According to Orrin Frink (in this 1954 paper in the American Mathematical Monthly), it was M.H. Stone who investigated the notion in Boolean algebras (The theory of representations for Boolean algebras by M.H. Stone, Trans. Amer. Math. Soc. 40 (1936), 37-111). A quick perusal of the paper (found in JSTOR) suggests that this was indeed the first time that they were treated as "abstract rings".
This was then extended to other kinds of lattices. According to Frink, the definition of ideals in lattices proceeds by analogy to that of ideals in rings:

A collection $J$ of elements of a lattice $L$ is called an ideal if

*

*it contains all multiples $a\land x$ of any of its elements $a$; and

*it contains the lattice sum $a\lor b$ of any two of its elements.

(viewing $\land$ as multiplication and $\lor$ as sum). The point being that in addition to being analogous, in the case of boolean lattices the concept of "ideal" as a ring and "ideal" as a lattice coincide, as you note.
Frink then extended the definition to arbitrary partially ordered sets in the paper mentioned above. He writes:

The first problem here is to discover the proper definition. There are three properties that it would be desirable to have, however the definition is made. (1) if $a$ is any element of a partially ordered set $P$, then the set of all elements $x$ of $P$ such that $x\geq a$ should turn out to be an ideal, namely the principal ideal determined by the element $a$. (2) The intersection of any number of ideals should be an ideal, so that the set of all ideals will form a complete lattice relative to the subset relation taken as the order relation. (3) In a partially ordered set which is also a lattice, sets which are ideals in the sense of lattice theory should turn out to be ideals according to the definition to be given for partially ordered sets, and conversely.

He then bases his definition on the notion of normal ideal that was studied by Stone, MacNeille, and Garrett Birkhoff: given a subset $A$, we let $A^*$ be the set of all upper bounds of $A$, and $A^+$ the set of all lower bounds of $A$. A "normal ideal" was a set $A$ such that $A=A^{*+} = (A^*)^+$. Frink defines:

Definition. A set $J$ of elements of a partially ordered set $P$ is called an ideal of $P$ if, whenever $F$ is a finite subset of $J$, the set $F^{*+}$ is also a subset of $J$.

E.S. Wolk discussed the "fruitfulness of this definition" in a paper on representations of partially ordered sets. Here it is in JSTOR.
So here we see a process whereby the extension first occurred by considering a special kind of ring (Boolean rings), then extending the notion "by analogy" to lattices, and finally to partially ordered sets with a view towards extending lattice theorems, particularly representation theorems.
However, there is another sense in which ideals for lattices and ideals for rings are instances of a particular kind of more general construction, as noted by Alex Youcis: the notion of congruence of an algebra (in the sense of universal algebra).
Let $A$ be an algebra in the sense of universal algebra (a set together with a family of finitary operations); examples include semigroups (a single binary operation), monoids (a binary operation and a zeroary operation), groups (a binary, a unary, and a zeroary operation), rings, lattices, $R$-algebras, vector spaces, and many others. Say we have an equivalence relation $\sim$ on $A$, and we want to define an algebra structure on $A/\sim$ by "operating on representatives". E.g., in groups, we want to define the product of the equivalence classes $[a]$ and $[b]$ of $a,b\in A$ to be the equivalence class of the product. More generally, if $f\colon A^n\to A$ is an $n$-ary operation on $A$, we want to define an induced operation $\overline{f}\colon (A/\sim)^n\to (A/\sim)$ by
$$\overline{f}([a_1],\ldots,[a_n]) = [f(a_1,\ldots,a_n)].$$
Under what conditions will this be well-defined?
Theorem. The induced operation on equivalence classes is well-defined if and only if $\sim$, when viewed as a subset of $A\times A$, is a subalgebra of $A\times A$ (where the latter has the coordinatewise algebra structure).
This leads to:
Definition. Let $A$ be an algebra (in the sense of universal algebra). A congruence on $A$ is an equivalence relation that is a subalgebra of $A\times A$.
In the case of groups, congruences are in one-to-one correspondence with normal subgroups: given a normal subgroup $N$, we define the equivalence relation $\sim$ by $a\sim b$ if and only if $aN=bN$. Conversely, given a congruence $\Phi\subseteq A\times A$, we let $N=\{a\in A\mid (a,e)\in \Phi\}$; it is then not hard to show that $A$ is normal and that $(a,b)\in \Phi$ if and only if $aN=bN$.
Similarly, for rings, congruences are in one-to-one correspondence with ideals.
This does not hold for more general structures. We do have some connection: given a lattice $L$ and an ideal $J$ of $L$, we can define a relation $\Phi_J$ on $L$ by
$$ \Phi_J = \{ (a,b)\in L^2 \mid \exists c\in J (a\lor c = b\lor c)\}.$$
This is an equivalence relation on $L$. $(a,a)\in\Phi_J$ for all $a\in L$, since we can take any $c\in J$ to get $a\lor c = a\lor c$. It is also easy to verify that $(a,b)\in\Phi_J$ implies $(b,a)\in\Phi_J$. And if $(a,b),(b,c)\in \Phi_J$, with $x,y\in J$ such that $a\lor x = b\lor x$ and $b\lor y = c\lor y$, then
$$a\lor(x\lor y) = (a\lor x)\lor y = (b\lor x)\lor y = c\lor y\lor x = c\lor(x\lor y)$$
and $x\lor y\in J$ because $J$ is an ideal, so $(a,c)\in \Phi_J$.
For $\lor$-semilattices, $\Phi_J$ is a congruence on $L$: we need to verify that if $(a,b),(c,d)\in\Phi_J$, then $(a,b)\lor(c,d) = (a\lor b,c\lor d)$ is in $\Phi_J$. Indeed, if $a\lor x = b\lor x$ and $c\lor y=d\lor y$, then
$$(a\lor c)\lor(x\lor y) = (a\lor x)\lor(c\lor y) = (b\lor x)\lor(d\lor y) = (b\lor d)\lor(x\lor y),$$
and $x\lor y\in J$ because $J$ is an ideal.
If $L$ is a distributive lattice, then we also get that $\Phi_J$ is closed under meets, so that $J$ determines a congruence. In fact,

Proposition. The lattice $L$ is distributive if and only if for every ideal $J$ of $L$, the relation $\Phi_J$ is a congruence on $L$ and $J$ is an equivalence class of the corresponding partition.

In a Boolean algebra (and more generally, as noted by Martin Sleziak, in a generalized boolean lattice) every congruence is of the form $\Phi_J$ for some ideal $J$, but in an arbitrary distributive lattice, there may be congruences that are not induced by ideals.
(By the way, the same thing happens in semigroups, which also have a notion of "ideal"; see, e.g., Wikipedia; every ideal induces a congruence, but not every congruence is induced by an ideal. The notion of "ideal" in semigroups is also by analogy to "ideal" in rings, where an ideal of the ring forms an ideal of the multiplicative semigroup of the ring).

A: I believe what you are looking for is the notion of a "congruence" in universal algebra. See page 38 of this PDF.
EDIT: I was mistaken, please read boumol's comment below to see why.


text:
Q: SimpleAdapter - вместо последнего айтема отображается первый Народ, я уже не могу продвигаться дальше, мозги невыносимо болят. Помогите, ничего не получается у меня.
Вообшем, мне нужен свой адаптер для того, чтобы проверять данные на null и в случае совпадения скрывать TextView. А у меня пока даже не получается осуществить саму работу адаптера. Вот что я делаю:
Разметка

<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="GO"
    android:textColor="#FFFFFF"
    android:textSize="20sp"
    android:id="@+id/name_item"
    android:gravity="left"
    android:layout_margin="10dp"
    android:textStyle="bold"/>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="right"
    android:weightSum="7">

    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#F95D1C"
        android:textSize="19sp"
        android:id="@+id/vdohnovenie"
        android:textStyle="bold"
        android:gravity="center"/>

    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#FFA000"
        android:textSize="19sp"
        android:id="@+id/popular"
        android:textStyle="bold"
        android:gravity="center"/>

    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#F0FF00"
        android:textSize="19sp"
        android:id="@+id/money"
        android:textStyle="bold"
        android:gravity="center"/>

    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#00FF00"
        android:textSize="19sp"
        android:id="@+id/guitar"
        android:textStyle="bold"
        android:gravity="center"/>

    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#00AAFF"
        android:textSize="19sp"
        android:id="@+id/vokal"
        android:textStyle="bold"
        android:gravity="center"/>

    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#5F7FD0"
        android:textSize="19sp"
        android:id="@+id/harizma"
        android:textStyle="bold"
        android:gravity="center"/>

    <TextView
        android:layout_height="25dp"
        android:layout_width="wrap_content"
        android:text="+15"
        android:textColor="#AE51C7"
        android:textSize="19sp"
        android:id="@+id/style"
        android:textStyle="bold"
        android:gravity="center"/>

</LinearLayout>

</LinearLayout>

Подготовка данных и отправка в адаптер
lv1 = (ListView)findViewById(R.id.lv1)
String[] summary_lv2 = {"Слушать радио", "Выпить пива", "Общаться с крутыми музыкантами", "Выпить пива с музыкантами", "Слушать комп", "Слушать винил",  "Концерт местной группы", "Концерт отечественной группы", "Концерт зарубежной группы"};
String[] secondary_vdxnvn_lv2 = {"5", "15", "10", "15", "10", "15", "30", "50", "80"};
String[] secondary_popular_lv2 = {"", "", "", "", "", "", "", "", ""};
String[] secondary_money_lv2 = {"", "-60", "", "-120", "", "", "-400", "-600", "-1000"};
String[] secondary_guitar_lv2 = {"", "", "", "", "", "", "", "", ""};
String[] secondary_vokal_lv2 = {"", "", "", "", "", "", "", "", ""};
String[] secondary_harizma_lv2 = {"", "", "", "", "", "", "", "1", "1"};
String[] secondary_style_lv2 = {"", "", "", "", "", "", "", "", "1"};
String[] from = {"name_item", "vdoxnovenie", "popular", "money", "guitar", "vokal", "harizma", "style"};
int[] to = {R.id.name_item, R.id.vdohnovenie, R.id.popular, R.id.money, R.id.guitar, R.id.vokal, R.id.harizma, R.id.style};
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashmap;
for(int i = 0; i < summary_lv2.length; i++){
hashmap = new HashMap<String, String>();
hashmap.put("name_item", "" + summary_lv2[i]);
hashmap.put("vdoxnovenie", "+" + secondary_vdxnvn_lv2[i]);
hashmap.put("popular", "" + secondary_popular_lv2[i]);
hashmap.put("money", "" + secondary_money_lv2[i]);
hashmap.put("guitar", "" + secondary_guitar_lv2[i]);
hashmap.put("vokal", "" + secondary_vokal_lv2[i]);
hashmap.put("harizma", "" + secondary_harizma_lv2[i]);
hashmap.put("style", "" + secondary_style_lv2[i]);
arrayList.add(hashmap);
}
SimpleAdapter adapter = new CustomAdapter(this, arrayList, R.layout.item, from, to);
lv1.setAdapter(adapter);

Адаптер
public class CustomAdapter extends SimpleAdapter
{
    ArrayList<HashMap<String, String>> adapterList;
    Context adapterContext;
    int adapterLayout;
    String[] adapterFrom;
    int[] adapterTo;
    LayoutInflater lInflater;
    public CustomAdapter(Context context, List<? extends Map<String, String>> data, int layout, String[] from, int[] to) {
        super(context, data, layout, from, to);
        adapterContext = context;
        adapterList = (ArrayList<HashMap<String, String>>) data;
        adapterLayout = layout;
        adapterFrom = from;
        adapterTo = to;
        lInflater = (LayoutInflater)adapterContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return adapterList.size();
    }

    @Override
    public Object getItem(int position) {
        return adapterList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if(v == null) {
            v =  lInflater.inflate (R.layout.item, null);
 ((TextView)v.findViewById(R.id.name_item)).setText(adapterList.get(position).get("name_item"));
        }
        else {
            v = convertView;
        }
        return v;
    }
}

Пока что, тестирую отображение name_item. Текст в последнем айтеме содержит текст из первого айтема. Почему?


text:
Q: How to work with recyclerview item IDs in Adapter class I have tried to solve this issue for the past three days but to no avail. I am retrieving data from two database tables joined together (Table names are "classes" and "Sections"). The problem are described by the images below.

Each school class (Grade one, Grade two etc) should display sections(Grade1A for Grade one class, Grade2A for Grade two class, etc) for each class that was clicked. But from the Image all classes show the same (class sections) irrespective of the class that was clicked.
Question
How do I make each Section to display for their respective classes?
A sample code will be very much appreciated. If there is a way to get the Id of the recyclerViewItem and match it with the Id of the class name in the classes table, I will appreciate a code sample thanks.
Here is what I did in the onBindViewHolder() of my Adapter class. I think the error is from here
@Override
public void onBindViewHolder(final ClassSectionOnSetupRecyclerAdapter.ViewHolderCSOS holder, final int position) {
    holder.textView_classname_sections.setText(listClassesCSOS.get(position).getClasses_name());
    holder.layoutt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            // still thinking on how to apply this(this gets the ItemId of the recyclerview Items)
            long itemId = getRVItemId(position);
            Log.i("itemId", String.valueOf(itemId));
            if (holder.expandableCardView.isShown()) {
                holder.expandableCardView.setVisibility(View.GONE);
            } else {
                holder.expandableCardView.setVisibility(View.VISIBLE);
                if(itemId == listClassesCSOS.get(position).getId()) {
                    StringBuilder sb = new StringBuilder();
                    listClassesCSOS = demeaSQL.getAllSectionsByClassesID();
                    // not used yet
                    sectionsList = demeaSQL.getAllSections();
                     // getAllSections()
                    for (ClassesBean c : listClassesCSOS ){
                        sb.append(c.sectionBeanGetName() + "\n" + "\n");
                        // sets the textView with data from database after a class name has been clicked
                        holder.addedSectionTV.setText(sb.toString());
                    }
                }
            }
        }
    });
    holder.add_class_section.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showAddSectionsDialog();
        }
    });
}

A: in holder you calls demeaSQL.getAllSectionsByClassesID();. You don't set the id of class you have selected, therefore you receive same values by each class.
UPDATE
in your demeaSQL class you need new method getAllSectionsByClassesID(long id)
then change
listClassesCSOS = demeaSQL.getAllSectionsByClassesID();

to
listClassesCSOS = demeaSQL.getAllSectionsByClassesID(itemId);


text:
Q: Write test for accepting input from command line I am fairly new to rspec and want to write test in rspec for getting input from command line in Ruby. How do I go about it? Also, explain the test. Thanks

A: By using mocks:
STDIN.should_receive(:read).and_return("your string")

Also I like the approach which is described here. I think that the last one is more suitable for your case.

A: The general approach is to make such kind of objects swappable.
In your case, gets is implicitly called on $stdin. So you can make an optional
argument called "input" that defaults to $stdin and call gets on it.
Here is an simple example of Calculator that takes some input and gives the result back.
class Calculator
  def initialize input = $stdin
    @input = input
  end

  def process
    eval @input.gets
  end
end

Now you can run puts Calculator.new.process, type 1 + 2 and you will see 3.
You won't need any special tools for testing this because you can easily pass an IO object
and write to it right in your tests. IO.pipe is a good option for this:
describe "Calculator" do
  before do
    reader, @writer = IO.pipe
    @calc = Calculator.new(reader)
  end

  it "can sum up two numbers" do
    @writer.puts "1 + 2"
    result = @calc.process
    result.should eq(3)
  end
end

You can also use StringIO instead which is not a real IO and does not require a UNIX-like environment.
Although you will need to rewind the stream each time you write.
require "stringio"

describe "Calculator" do
  before do
    @input = StringIO.new
    @calc = Calculator.new(@input)
  end

  it "can sum up two numbers" do
    @input.puts "1 + 2"
    @input.rewind
    result = @calc.process
    result.should eq(3)
  end
end

The upside of this approach versus stubbing are less brittle tests and a better design.
The tests are less brittle because if you decide to change the implementation and use getc
instead of gets (read characters one by one) for example you won't need to change the tests.
And the design is better because now you can easily give commands from a different source
such as a file Calculator.new(File.open("calculated_list.txt")). Or a fake IO which you
can use in your tests!


text:
Q: Divi hook not working I'm using Divi and need to add content via a Divi hook, via code in functions.php in my child theme. I'm testing the basics, and this code puts things before the main content:
function bgt_add_conditional_code_to_event_pages () {

echo do_shortcode('[et_pb_section  _builder_version="4.9.3" _module_preset="default"][et_pb_row _builder_version="4.9.3" _module_preset="default"][et_pb_column _builder_version="4.9.3" _module_preset="default" type="4_4"][et_pb_text _builder_version="4.9.3" _module_preset="default"]');
echo "
This is a test
";
echo do_shortcode('[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]');

}

add_action( 'et_before_main_content', 'bgt_add_conditional_code_to_event_pages' );

But! I want it to display AFTER the main content. Yet when I change to 'et_after_main_content'... nothing.
I can't imagine what I'm doing wrong! Hope someone can advise.

A: I hope you're doing well! I wonder if adding a priority to your filter would fix the issue. In the past I've had filters not fire because the default priority was too high or low. Could you try something like this:
add_action( 'et_after_main_content', 'bgt_add_conditional_code_to_event_pages', 9999 );

And see if that resolves the issue? From what I read in the divi documentation the way you're going about it should work I think.