text:
Q: Logical Equivalences: $(P\wedge\neg Q)\vee P \equiv P$ How do I approach/ complete logical equivalency problems such as these?
I can see that the left hand side Should end up becoming Idempotent law $P \vee P \equiv P$.
And have to use implication within $(P\wedge\neg Q)\vee P$, though I'm not sure how to forge it together.
Any help would be great.

A: Observe that, if the RHS is true, it implies that the LHS is true, once the disjunction is true. On the other hand, if the RHS is false, the LHS is also false, since the conjunction (and consequently the disjunction) is false. Therefore both formulas are equivalent.

A: If you want to use implication, you can take   $P\wedge\neg Q \equiv\neg(\neg P \vee Q)$. Letting $U=(\neg P \vee Q)$, the LHS is $\neg U \vee P$, which is equivalent to $U \rightarrow P$. $U$ is equivalent to $P \rightarrow Q$, so the LHS is $(P \rightarrow Q)\rightarrow P$. We have that the RHS entails the LHS: if $P$ is true, then all implications with $P$ as the conclusion are true. We also have that the LHS entails the RHS: if $P$ is false, then $(P \rightarrow Q)$ is true, and $True\rightarrow False$ is false.


text:
Q: too few arguments in function call? too few arguments in function call? what's wrong with this code?
I want to output to std::cout day
#include <iostream>
#include <string>

class Date
{
public:
    Date(unsigned _day, unsigned _month, unsigned _year) : day(_day), month(_month), year(_year) {}
    int GetDate(Date& dt)
    {
        return dt.day;
    }
private:
    unsigned day, month, year;
};

int main()
{
    Date dt(07, 10, 2004);
    std::cout << dt.GetDate();

    return 0;
    std::cin.get();
}

i understand the principle but I don't know what to do
/*too few arguments in function call
    Error   C2660   'Date::GetDate': function does not take 0 arguments */

A: You have defined GetDate() as a non-static method of the Date class, and have it take in an explicit Date& object reference as a parameter.  But main() is not passing in a Date object into that parameter, hence the error.
There is no need to pass in the object explicitly.  As a non-static method, GetDate() has a hidden this parameter that refers to the Date object that GetDate() is called on.
Try this instead:
#include <iostream>
#include <string>

class Date
{
public:
    Date(unsigned _day, unsigned _month, unsigned _year) : day(_day), month(_month), year(_year) {}
    int GetDate() const
    {
        return day; // this->day
    }
private:
    unsigned day, month, year;
};

int main()
{
    Date dt(07, 10, 2004);
    std::cout << dt.GetDate();

    return 0;
    std::cin.get();
}

A: As this member function
int GetDate(Date& dt)
{
    return dt.day;
}

is a non-static member function then it is natural when it outputs the data member day of the object for which it is called. But it is defined with a parameter that accepts another object of the type Date.
Thus in this call of the function
std::cout << dt.GetDate();

you need to specify an argument of the type Date like for example
Date dt(07, 10, 2004);
std::cout << dt.GetDate( dt );

But this does not make a great sense.
The function should be defined in the class like
int & GetDate()
{
    return day;
}

with its overload
const int & GetDate() const
{
    return day;
}

In this case this code snippet
Date dt(07, 10, 2004);
std::cout << dt.GetDate();

will make a sense.
Though it would be better to name the function as GetDay.
Pay attention that this statement
std::cin.get();

does not have an effect because it is placed after the return statement. Maybe you mean
std::cin.get();
return 0;

A: Ideally, you should update the implementation of your GetDate function.
int GetDate()
{
   return day;
}

A: The function GetDate has a parameter, that you are not passing in the function main.
It should be
Date a(1,1,2001);

std::cout << dt.GetDate(a);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prevent a selected -tag from being overwritten by .html() I have a PHP file that fetches rows of car brands from a database, echoes these as "<option value=\"$brand\">" . $brand . "</option>"; and puts them inside pre-written <select>tags.
My issue is that the first item that appears in the select box is not passing its value onwards.
The value of the select box is changed by this event
$('select[name=model]').on('change', function() {
  selectedModel = $("#select-model").val()
});

The <option>-tags are generated by this loop in brands.php:
while ($row = mysqli_fetch_array($result)) {
  $brand = $row['brand'];
  echo "<option value=\"$brand\">" . $brand . "</option>";
}

The brands are fetched by this function:
function fetchBrands() {
  $.ajax({
    type: "POST",
    url: "script/rent/brands.php",
    data: {dateFrom: selectedDateFrom,
           dateTo: selectedDateTo,
           destination: selectedDestination},

    success: function(data) {
        $("#select-brand").html(data);
      }
  });
}

Because the data is posted to #select-brandwith .html() I can't set a default value for the select box because it gets overwritten. Appending the options will result in duplicates etc. as fetchBrands() is dependent on a previous set of radio buttons and select boxes.

A: What I'd now suggest is that in your success function, add some code that gets the first element in the select tag, updates the selectedBrand, and then triggers the code that's attached to the change event.
If you refactored your code so that you added a reference to the handler code, this would make it easier.
$('select[name=model]').on('change', someFunction());

function someFunction(){
    selectedModel = $("#select-model").val()
}

function fetchBrands() {
  $.ajax({
    type: "POST",
    url: "script/rent/brands.php",
    data: {dateFrom: selectedDateFrom,
           dateTo: selectedDateTo,
           destination: selectedDestination},

    success: function(data) {
        $("#select-brand").html(data);
        $("#select-brand").val($("#select-brand option:first").val());
        someFunction();
      }
  });
}

Before extra information was added:
To have an element of a <select>...</select> automatically selected on page render, you need to add the attribute selected="selected" to the <option /> you want to be selected.
Alternatively, add a hook for document load that sets the selected brand.
Or, have the first option as something like this:
<option disabled="disabled" selected="selected">Choose a Brand</option>


text:
Q: How draw box across multiple axes on matplotlib using ax position as reference I would like to draw a box across multiple axes, using one ax coordinates as reference. The simple code I have, that does not generate the box is
import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(15,9))

x = 2 * np.pi * np.arange(1000) / 1000
y1 = np.sin(x)
y2 = np.cos(x)

ax1.plot(x,y1)
ax2.plot(x,y2)
plt.show()

This generate the following figure:

What I would like to have is the following figure, using x cordinates from ax2 to specify the position:

A: The question is a bit what purpose the rectangle should serve. If it is simply a rectangle bound to ax2 but extending up to the upper edge of ax1 a rectangle can be created like
import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(15,9))

x = 2 * np.pi * np.arange(1000) / 1000
y1 = np.sin(x)
y2 = np.cos(x)

ax1.plot(x,y1)
ax2.plot(x,y2)

rect = plt.Rectangle((1,0), width=1, height=2+fig.subplotpars.wspace,
                     transform=ax2.get_xaxis_transform(), clip_on=False,
                     edgecolor="k", facecolor="none", linewidth=3)
ax2.add_patch(rect)

plt.show()

But that will of course stay where it is, even if the limits of ax1 change. Is that desired?
So maybe a more interesting solution is one where the rectangle follows the coordinates in both axes. The following would only work in matplotlib 3.1, which is as of today only available as prerelease
(pip install --pre --upgrade matplotlib)
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(15,9))

x = 2 * np.pi * np.arange(1000) / 1000
y1 = np.sin(x)
y2 = np.cos(x)

ax1.plot(x,y1)
ax2.plot(x,y2)

def rectspan(x1, x2, ax1, ax2, **kwargs):
    line1, = ax1.plot([x1, x1, x2, x2],[0,1,1,0],
                      transform=ax1.get_xaxis_transform(), **kwargs)
    line2, = ax2.plot([x1, x1, x2, x2],[1,0,0,1],
                      transform=ax2.get_xaxis_transform(), **kwargs)
    for x in (x1, x2):
        p = ConnectionPatch((x,1), (x,0),
                            coordsA=ax2.get_xaxis_transform(),
                            coordsB=ax1.get_xaxis_transform(), **kwargs)
        ax1.add_artist(p)

rectspan(1, 2, ax1, ax2, color="k", linewidth=3)
plt.show()

A: There is definitely a simpler way to do it using a Rectangle patch but this is a workaround solution for the time being. The idea is to have 4 lines: 2 horizontal which are restricted to ax1 and ax2 respectively, and 2 vertical which span both ax1 and ax2. For the latter two, you use ConnectionPatch covering both the axes. To have the upper and lower y-value for the horizontal and vertical lines, you use get_ylim() function. The idea to plot vertical lines came from this official example and this answer by ImportanceOfBeingErnest

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import ConnectionPatch

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(15,9))

x = 2 * np.pi * np.arange(1000) / 1000
y1 = np.sin(x)
y2 = np.cos(x)

ax1.plot(x,y1)
ax2.plot(x,y2)

y_up, y_down = ax1.get_ylim(), ax2.get_ylim()

ax1.hlines(max(y_up), 1, 2, linewidth=4)
ax2.hlines(min(y_down), 1, 2, linewidth=4)

line1 = ConnectionPatch(xyA=[1,min(y_down)], xyB=[1,max(y_up)], coordsA="data", coordsB="data",
                      axesA=ax2, axesB=ax1, color="k", lw=4)
line2 = ConnectionPatch(xyA=[2,min(y_down)], xyB=[2,max(y_up)], coordsA="data", coordsB="data",
                      axesA=ax2, axesB=ax1, color="k", lw=4)

ax2.add_artist(line1)
ax2.add_artist(line2)

plt.show()


text:
Q: How to create an array from hash replacing all of the keys and values with integers I have a hash:
a = {"0" => ["2", "3"], "1" => "4", "3" => "5"}

and I need a function to make an array from it:
a = [[2, 3], 4, nil, 5]

Is there any simple way to do this?

A: min, max = a.keys.minmax_by(&:to_i)

min.upto(max).map do |key|
  a[key].respond_to?(:map) ? a[key].map(&:to_i) : a[key].to_i if a[key]
end # => [[2, 3], 4, nil, 5]

A: First we make a range from 0 to the maximum key value (as an integer)
Then for each number we fetch the value in "a" at the corresponding key.
If the value is an array, we convert it into an array of integers
if not, convert it into an integer (unless it's false or nil).
a = {"0" => ["2", "3"], "1" => "4", "3" => "5"}
a = (0..(a.keys.map(&:to_i).max)).map do |v|
  x = a[v.to_s]
  x.is_a?(Array) ? x.map(&:to_i) : (x && x.to_i)
end

A better version that can handle a minimum key > "0"
a = a.values_at(*Range.new(*a.keys.minmax_by(&:to_i))).map do |v|
  v.is_a?(Array) ? v.map(&:to_i) : (v && v.to_i)
end

a
=> [[2, 3], 4, nil, 5]

minmax returns an array that we explode into arguments to Range.new
We then explode that range into arguments for values_at.
[*Range.new(*["2","8"])]
=> ["2", "3", "4", "5", "6", "7", "8"]

A: I'm not sure whether it really makes sense to have the array that you have as the final output given that now you don't know for sure which element corresponds to which question.
If we simplify the problem that you want to convert the hash keys and values to numeric and add the missing keys, then you can do the following with help of Rails' Active Support Hash extension:
# Below require needed only if code is not being used in Rails app
require "active_support/core_ext/hash"

a = {"0" => ["2", "3"], "1" => "4", "3" => "5"}

p a.deep_merge(a) {|_,v,_| v.to_i rescue v.map(&:to_i)}
   .transform_keys(&:to_i)
   .tap { |h| h.reverse_update (h.keys.min..h.keys.max).zip([nil]).to_h }
   .sort {|a,b| a <=> b}  # Not really needed
   .to_h                  # Not really needed

#=> {0=>[2, 3], 1=>4, 2=>nil, 3=>5}

A: You're looking for Hash.values though you won't get that nil there:
a = {"0" => ["2", "3"], "1" => "4", "3" => "5"}
def deep_map(h)
  h.map{|i| i.is_a?(String) ? i.to_i : deep_map(i)}
end
deep_map (a.values)

gives:
[[2, 3], 4, 5]

A: The results are OK with the sample input. I didn't test any other cases:
a = {"0" => ["2", "3"], "1" => "4", "3" => "5"}

('0'..a.size.to_s).map do |i|
  v = ([a[i]].flatten.map { |i| i && i.to_i })
  v.size == 1 ? v[0] : v
end
# => [[2, 3], 4, nil, 5]

A: I'v split out the conversion of strings to a separate method (fixnumify) because it does not seem to be an essential element of the question:
a = {"0" => ["2", "3"], "1" => "4", "3" => "5"}

def fixnumify(obj)
  case obj
  when Array then obj.map(&:to_i)
  when String then obj.to_i
  else obj
  end
end

from, to = a.keys.minmax_by(&:to_i)
  #=> [0, 3]
a.values_at(*from..to).map { |v| fixnumify(v) }
  #=> [[2, 3], 4, nil, 5]


text:
Q: Use items in two dimensional array to add records to a table The table has records already. All I am trying to do is append records to the table. I have a number of floors in a table named FLOORS. I am trying to insert additional floors to the table. In a field on the form the number of tables are entered. If the number entered on the form is > the Table.Count, the additional records are generated and added to the table. Exception message - "Update Failed"
 Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
      Try
           Dim FirstCharacter As String
           Dim LastCharacter As String
           Dim ExtraFloors As Integer

           Floor = Me.FloorDbDataSet.Tables("Floor").Rows.Count + 1
           If Floor <= CInt(TxtNoOfFloors.Text) Then
                ExtraFloors = (CInt(TxtNoOfFloors.Text) - Floor)
                MsgBox("Extra Floors - " & ExtraFloors)
           End If
           Floor = Floor + 1
           MsgBox("First floor to be added - " & Floor)
           'setup array
           Dim FloorDetail(ExtraFloors - 1, 1) As String '(row,col)
           For intRow As Integer = 0 To ExtraFloors - 1
                If Floor < 10 Then
                     strFloorNo = "0" & Floor
                Else
                     strFloorNo = Floor
                End If

                FirstCharacter = strFloorNo(0)
                LastCharacter = strFloorNo(strFloorNo.Length - 1)
                If LastCharacter = "1" Then
                     strDescription = FirstCharacter & "1st Floor"
                ElseIf LastCharacter = "2" Then
                     strDescription = FirstCharacter & "2nd Floor"
                ElseIf LastCharacter = "3" Then
                     strDescription = FirstCharacter & "3rd Floor"
                Else
                     strDescription = strFloorNo & "th Floor"
                End If
                FloorDetail(intRow, 0) = strFloorNo
                FloorDetail(intRow, 1) = strDescription
                MsgBox(strDescription & " ==> " & strFloorNo)
                Floor = Floor + 1
           Next intRow

           Dim NewFloorRow As DataRow = FloorDbDataSet.Floor.NewFloorRow
           For outerIndex As Integer = 0 To ExtraFloors - 1
                NewFloorRow("FloorNo") = FloorDetail(outerIndex, 0)
                NewFloorRow("Description") = FloorDetail(outerIndex, 1)
                FloorDbDataSet.Floor.Rows.Add(NewFloorRow)
           Next
           Me.FloorTableAdapter.Update(FloorDbDataSet.Floor)
           FloorTableAdapter.Fill(FloorDbDataSet.Floor)
           FloorBindingSource.MoveLast()
      Catch ex As Exception
           MsgBox(strDescription & " ==> Update failed")
      End Try
 End Sub

A: Plutonix is absolutely right about your error handling.
However, the original issue is:
Dim NewFloorRow As DataRow = FloorDbDataSet.Floor.NewFloorRow
This should be INSIDE the loop.  Otherwise, your code is trying to add the same row repeatedly, which will cause the error.
       For outerIndex As Integer = 0 To ExtraFloors - 1
            Dim NewFloorRow As DataRow = FloorDbDataSet.Floor.NewFloorRow
            NewFloorRow("FloorNo") = FloorDetail(outerIndex, 0)
            NewFloorRow("Description") = FloorDetail(outerIndex, 1)
            FloorDbDataSet.Floor.Rows.Add(NewFloorRow)
       Next

And a recommended change to the exception handling:
MsgBox(strDescription & " ==> Update failed" & Environment.NewLine & ex.Message)

ex.Message is the actual error message.  The exception has other properties too like stacktrace that in certain modes will give you the line number of the error.


text:
Q: Remove portion of string TSQL I have a string of numbers that I need to trim a portion from using TSQL.
The string of numbers will always start with a 101 then it will have a set of 0's and a set of random numbers.
Example: 1010000123456
I need to trim the 101 and the set of zeros. This is probably simple but I'm having all kinds of issues because I don't have a specific character to reference to using a CHARINDEX and the possible combination of a 001 when the random numbers start that I need to keep is giving me issues using a PATINDEX with a SUBSTRING.

A: Remove the 101 in the string, Cast to big integer and then cast back to string.
select cast(cast(right('1010000123456', len('1010000123456')-3) as bigint) as varchar(20))
select cast(cast(right('1010000103456', len('1010000103456')-3) as bigint) as varchar(20))


text:
Q: Global minimum of $g(x)=\sum_{v=1}^k c_v\|x-x_v\|_2^2, \ \ c_v>0 \in \mathbb{R};\ x,x_v \in \mathbb{R}^n$ $g(x)=\sum_{v=1}^k c_v\|x-x_v\|_2^2, \ \ c_v>0 \in \mathbb{R};\ x,x_v \in \mathbb{R}^n$.
I need to find the minimum of $g$ and reason why it is a global minimum.
I tried the following:
$g(x)=\sum_{v=1}^k c_v\|x-x_v\|_2^2=\sum_{v=1}^kc_v \Big((x_1-x_{v_1})^2+ \ldots+ (x_n-x_{v_n})^2\Big)= \sum_{v=1}^k c_v \sum_{i=1}^n(x_i-x_{v_i})^2$
So $\nabla g(x)=\Big(\frac{\partial g(x)}{\partial x_1}, \ldots,\frac{\partial g(x)}{\partial x_n}\Big)=\Big(\sum_{v=1}^k c_v \sum_{i=1}^n2(x_i-x_{v_i}), \ldots,\sum_{v=1}^k c_v \sum_{i=1}^n2(x_i-x_{v_i})\Big)$
So it is a row vector with $n$ columns and each of them is $\sum_{v=1}^k c_v \sum_{i=1}^n2(x_i-x_{v_i})$.
Is that notation with $\nabla g(x)$ correct? I still got some troubles with it.
So $\nabla g(x)=0 \Leftrightarrow \sum_{v=1}^k c_v \sum_{i=1}^n2(x_i-x_{v_i})=0 \Leftrightarrow \sum_{v=1}^k c_v 2(x-x_v)=0\Leftrightarrow x\sum_{v=1}^kc_v=\sum_{v=1}^kc_vx_v \Leftrightarrow x=\frac{\sum_{v=1}^k c_vx_v}{\sum_{v=1}^k c_v}=:\bar x$ which should be the weighted average.
In order to be a minimum the Hessian matrix at $\bar x$ has to be positiv definite. How does the hessian of $g(x)$ look like? And then how can I reason the $\bar x$ isn't only a local minimum and that it really is the global minimum? (Or are there other ways to argue that $\bar x$ is a local and global minimum?)


text:
Q: Unloading a View in Objective-C (iPhone) I have a View-based app. The first view that is loaded has a button which loads another view using this code:
AddPost *addView = [[AddPost alloc] initWithNibName:@"AddPost" bundle:nil];
addView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:addView animated:YES];

What I want to do is provide a button on the view (AddPost) that will let me close it and go back to the original view. How can I do this?

A: It seems a little strange, but you can actually have addView call:
[self dismissModalViewControllerAnimated:YES];

From the docs:
"The parent view controller is responsible for dismissing the modal view controller it presented using the presentModalViewController:animated: method. If you call this method on the modal view controller itself, however, the modal view controller automatically forwards the message to its parent view controller."

A: The answer Conrad gave will work perfectly well. In the name of slightly better encapsulation you could put a delegate protocol on addView and have your first view implement this.
So in the header file for your addView controller:
@protocol addViewDelegate <NSObject>
    - (void)addViewRequestDismissal;
@end

You will also need an external properly on the addView controller:
@property (assign) id<addViewDelegate> delegate;

Then make your first view controller implement this, so in it's .h file you should have
@interface firstView : NSObject <addViewDelegate> {
}

When you instantiate your addView remember to set the delegate:
addView.delegate = self;

In the addView controller when your button is pressed call back:
- (void)buttonPressed {
    [self.delegate addViewRequestDismissal];
}

Finally in your first view remember to implement this method
- (void)addViewRequestDismissal {
    [self dismissModalViewControllerAnimated:YES];
}

Hope all goes well with this. Post back if you have any further problems :)


text:
Q: Creating a new dataframe in python based on calculations of existing dataframe In Table given in the top, I have this data of around 50000 lines.

In the bottom table, my desired data output.

First, calculation is my FLOWRATE in which, I want to count the number of values contained in a given TIMESTEP. For eg. calculation at TIMESTEP = 5200 FLOWRATE = 100 (1 * 100) (as only one atom id '75' is present. 100 here is my constant multiplier factor for all FLOWRATE values)
Second, I want to calculate the my MASS FLOW RATE for a TIMESTEP which is the product of FLOW RATE calculated above and correspoding mass of the id. For eg. TIMESTEP 5200 FLOWRATE 100 MASS FLOWRATE = 100 * 0.895253 = 89.5253. If more than one 'id' is present in a given TIMESTEP, then MASS FLOW RATE = FLOW RATE * sum of MASS FLOW RATE of ids. For eg. for TIMESTEP 5500, FLOWRATE 200 (TWO ids are there 86 and 325), MASS FLOW RATE  306.4898 i.e FLOW RATE * (sum of masses of id 86 and 325) = 200 * (0.768832 + 0.763617)
I have tried it coding using the below approach:
tstep = 5200
for row in df_intermediate.iterrows():
    df_new = df_intermediate[df_intermediate['TIMESTEP'] == 'tstep']
    df_final["TIMESTEP"] = df_new["tstep"]
    df_final["FLOW RATE"] = df_new[len["id"] * 100
    df_final["MASS FLOW RATE"] =  df_final["FLOW RATE"] * df_new["mass"]
    tstep = tstep + 100

But not able to generate my desired output table

A: Try with groupby:
output = df.groupby("TIMESTEP").agg(FLOW_RATE=("id", "count"), MASS_FLOW_RATE=("mass", "sum"))
output["FLOW_RATE"] = output["FLOW_RATE"].mul(100)
output["MASS_FLOW_RATE"] = output["MASS_FLOW_RATE"].mul(output["FLOW_RATE"])

>>> output
          FLOW_RATE  MASS_FLOW_RATE
TIMESTEP
5200            100         89.5253
5400            100         68.3110
5500            200        306.4898
5600            100         93.1666
5700            100         79.4396
6100            100         78.2639


text:
Q: Tensorflow Object Detection API 2 I'm new to tf object detection api 2.
After training the model you can run an evaluation process to check the accuracy of the model.
But when I tried to run I got the below error. I'm using the backbone as an efficientDet.
I was able to run the evaluation for scaling resolution 512 but 640 is failing with the below error.
This is the python file I called and ended up with the below error.
enter code here /tensorflow/models/research/object_detection/model_main_tf2.py
`enter code here`enter code here`Call arguments received:
  • inputs=tf.Tensor(shape=(1, 480, 640, 3), dtype=float32)
  • kwargs={'training': 'False'}

exception.
INFO:tensorflow:A replica probably exhausted all examples. Skipping pending examples on other replicas.
I0719 06:49:27.115007 140042699994880 model_lib_v2.py:943] A replica probably exhausted all examples. Skipping pending e
xamples on other replicas.
Traceback (most recent call last):
  File "/home/pictcompute/effient_net_ve/tensorflow/models/research/object_detection/model_main_tf2.py", line 115, in <m
odule>
    tf.compat.v1.app.run()
  File "/home/pictcompute/effient_net_ve/lib/python3.8/site-packages/tensorflow/python/platform/app.py", line 36, in run
    _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
  File "/home/pictcompute/effient_net_ve/lib/python3.8/site-packages/absl/app.py", line 312, in run
    _run_main(main, args)
  File "/home/pictcompute/effient_net_ve/lib/python3.8/site-packages/absl/app.py", line 258, in _run_main
    sys.exit(main(argv))
  File "/home/pictcompute/effient_net_ve/tensorflow/models/research/object_detection/model_main_tf2.py", line 82, in mai
n
    model_lib_v2.eval_continuously(
  File "/home/pictcompute/effient_net_ve/lib/python3.8/site-packages/object_detection/model_lib_v2.py", line 1159, in ev
al_continuously
    eager_eval_loop(
  File "/home/pictcompute/effient_net_ve/lib/python3.8/site-packages/object_detection/model_lib_v2.py", line 1009, in ea
ger_eval_loop
    for evaluator in evaluators:
TypeError: 'NoneType' object is not iterable

Highly appreciate your help.
Thanks

A: The error occurs when you try to iterate over a None value. For example
mylist = None
for x in mylist:
    print(x)

TypeError                                 Traceback (most recent call last)
<ipython-input-2-a63d8b17c4a7> in <module>
      1 mylist = None
      2
----> 3 for x in mylist:
      4     print(x)

TypeError: 'NoneType' object is not iterable

The error can be avoided by checking if a value is None or not before iterating over it. Thank You.


text:
Q: ADMA0176E PrivilegedActionException: Application installation of {0} faild with PrivilegedActionException when trying to add a project to my WebSphere, I get the following error:

ADMA0176E: Application installation of {0} faild with PrivilegedActionException. Ear file path is {1}.

Any idea what I could do? According to a Google search, it could be some permission problem, but I don't know where to start at all...
Any info is really appreciated!
Thanks a lot!

A: The problem was a wrong/missing configuration in Websphere: application security wasn't checked in the administration console...

A: Following files were missing for my project. Copying these files from another project solved the problem.

*

*security.xml  at path: [ibmconfig/cells/defaultCell]

*deployment.xml, resources.xml and variables.xml at path: [ibmconfig/cells/defaultCell/applications/defaultApp/deployments/defaultApp]
This worked on IBM WAS 7.

A: For me worked after I run the Eclipse as administrator. Just that.

A: What happened to me was that somehow the EAR's /META-INF/application.xml changed from:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" version="5">
    <display-name>macc-ear</display-name>
    <module id="Module_1381754217072">
        <web>
            <web-uri>macc-frontend.war</web-uri>
            <context-root>/macc</context-root>
        </web>
    </module>
</application>

to:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" version="5">
    <display-name>macc-ear</display-name>
</application>

I have no idea what caused this, but it seems like IBM Rational Application Developer (RAD) sometimes does things on its own.


text:
Q: Writing parquet files from kinesis I need to save raw events from my server into a parquet file so I can query the data.
Is there an easy way to write parquet to s3 directly from kinesis using scala/java ?
Ideally I would like to use kinesis firehose to do the heavy lifting.
any idea ?


text:
Q: Getting an out of memory exception with System.Threading.ReaderWriterCount I've got an asp.net application, it's running on DotNetNuke, under load we get the occasional out of memory exception.
I've got a dump loaded it into windbg.
the end of !dumpheap -stat is
1192a588    88684      2128416 AutoMapper.MappingEngine
79333594     9482      2266348 System.Byte[]
134b0034    88695      2838240 System.EventHandler`1[[AutoMapper.TypeMapCreatedEventArgs, AutoMapper]]
13d8703c    88684      4611568 System.Collections.Generic.Dictionary`2[[Castle.DynamicProxy.Generators.CacheKey, AutoMapper],[System.Type, mscorlib]]
13d86dc8    88684      4611568 Castle.DynamicProxy.ModuleScope
13d865bc    88684      4611568 System.Collections.Generic.Dictionary`2[[AutoMapper.Internal.TypePair, AutoMapper],[AutoMapper.IObjectMapper, AutoMapper]]
79327434    88703      4612556 System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Int32, mscorlib]]
6c38e4e4    88684      5675776 System.Threading.ReaderWriterLockSlim
79330b24    87736      6458012 System.String
000d9c88      129     24186884      Free
793042f4   221202    101117016 System.Object[]
6c38e4a0 22703104    544874496 System.Threading.ReaderWriterCount

I can't find much information on the System.Threading.ReaderWriterCount, as it seems to be the problem.
What is the likely cause? Or failing that what's the best next step to work that out?
Based on the pointer from the given answer I had a look at ReaderWriterLockSlim. I wasn't using it directly, but I saw that it had 88684 instances, digging deeper I saw quite a few classes with that number of instances, pointing to AutoMapper.MappingEngine. This should be a singleton, so I've had a look at where it's being created. I suspect that it's the DI container and have made some changes around that to see if it helps

A: ReaderWriterLockSlim is not a cheap class in memory footprint - that could be why your ReaderWriterCount instances are proliferating.  See here for detailed info from Reflector.
Can you reduce usage of this class?  Maybe not all of them need to be Read/Write Locks, simple Mutex/lock() might work?
Note also that this class is IDisposable - perhaps you are not Dispose()-ing of them after you are through with them?


text:
Q: Blocking page from scrolling without Overflow method I'd like to create a function that block the scroll for a couple of seconds when I'm at certain points of the page or when a div become visible.
I'm using the .waypoint plugin to trigger the function, I've tried the css "overflow: hidden" method but doesn't work well: it isn't immediate (if I scroll fast it activates late) and It creates some issues with the layout because of the disappearing of the scrollbar.
Any suggestion?


text:
Q: Find the curvature and torsion of the curve x=acos2t, y=asin2t,z=2asint. I have tried to use the formula of curvature=|r'×r''|/|r'|^3 but the calculation is too long. Same for torsion too.
Then I tried another approach as calculating unit tangent vector by using dr/ds. Then curvature×n=dt/ds but it is also very long and calculative.
Provide the calculations too please

A: Given the curve $\gamma(t)=\left(\cos (2 t),\sin (2 t),2 \sin (t)\right)$, we have the derivatives.
$
\gamma'(t)=\left(-2 a \sin (2 t),2 a \cos (2 t),2 a \cos (t)\right)\\
\gamma''(t)=\left(-4 a \cos (2 t),-4 a \sin (2 t),-2 a \sin (t)\right)\\
\gamma'''(t)=\left(8 a \sin (2 t),-8 a \cos (2 t),-2 a \cos (t)\right)
$
$$\kappa(t) =\frac {\|{\boldsymbol {\gamma }}'\times {\boldsymbol {\gamma }}''\|}{\|{\boldsymbol {\gamma }}'\|^{3}}$$
$$\gamma '\times \gamma ''=\left(2 a^2 (3 \sin (t)+\sin (3 t)),-8 a^2 \cos ^3(t),8 a^2\right)$$
$$\|{\boldsymbol {\gamma }}'\times {\boldsymbol {\gamma }}''\|=2 \sqrt{2} a^2 \sqrt{3 \cos (2 t)+13}$$
$$\|{\boldsymbol {\gamma }}'\|^{3}=2 \sqrt{2} \left(a^2 (\cos (2 t)+3)\right)^{3/2}$$
$$\kappa=\frac{\sqrt{3 \cos (2 t)+13}}{a (\cos (2 t)+3)^{3/2}}$$
$$\tau ={\frac {\det \left(\gamma',\gamma'',\gamma'''\right)}{\left\|\gamma'\times\gamma''\right\|^{2}}}$$
$$\det\left(\gamma',\gamma'',\gamma'''\right)=\det\left|
\begin{array}{lll}
 -2 a \sin (2 t) & 2 a \cos (2 t) & 2 a \cos (t) \\
 -4 a \cos (2 t) & -4 a \sin (2 t) & -2 a \sin (t) \\
 8 a \sin (2 t) & -8 a \cos (2 t) & -2 a \cos (t) \\
\end{array}
\right| =48 a^3 \cos (t)$$
$$\left\|\gamma'\times\gamma''\right\|^{2}=8 a^4 (3 \cos (2 t)+13)$$
$$\tau=\frac{6 \cos (t)}{3 a \cos (2 t)+13 a}$$


text:
Q: Is variable declaration within a loop bad? I'm referring to the main static languages today (C, C++, java, C#,). I've heard some contradicting answers about this, so I wanted to know:
If I have some code such as:
loop(...) {
  type x = val;
  ...
}

('loop' is some type of loop, e.g. for, while)
Will it cause memory allocation in each iteration of the loop, or just once? Is it different from writing this:
type x;
loop(...) {
  x = val;
  ...
}

where memory is only allocated once for x?

A: The strictly correct answer is that it depends on the implementation, as both are semantically correct. No language specification would require or prohibit such implementation details.
That said, any implementation worth its salt will be able to reuse the same stack slot or even CPU register (with native compilation, especially likely in presence of a JIT). Even the bytecode will likely be completely identical.
And finally, there's that thing with premature optimization... Unless proven otherwise, you shouldn't even bother thinking about low-level details like this (if you think knowledge and control over such issues matters, perhaps you should just program in assembler), because:

*

*Unless you're doing a microbenchmark (or a really huge number-crunching task - but how many people freaking out about performance actually do those?), you won't even notice any difference even if it isn't optimized. If you're doing anything of interest in the loop body, it will dwarf the difference (again, if any). Especially if you're doing any I/O.

*Even if there is memory allocation, it boils down to pushing and popping a few bytes on the native stack, which in turn boils down to adding an integer constant to a hardware register. All C and C++ programs use that stack for their local variables, and non of those ever complained about its performance... if you have to reserve space, you can't get faster than using the stack.

*If you have to ask this kind of question, you're not someone who could do anything about it. Those people know to just (1) measure it, (2) look at the generated code and (3) look for large-scale optimizations before even thinking on this level ;)


text:
Q: Ansible exit code for a role or a playbook, not each individual task Is it possible to capture an exit code for an Ansible role or playbook (not each individual task) and branch depending on the exit code?
We have an application that needs to create a specific flag (success/failure) for each Ansible ROLE, not task. One exit code per role.

A: You can catch the error of the include module. I mean if you create a role and inside the tasks there is a main.yml which looks like this:
---
- include: first_server.yml
  register: first_server

- include: second_server.yml
  register: second_server
  when: first_server | success

In the next role which will be the web:
---
- include: first_web.yml
  register: first_web
  when: second_server | success

- include: second_web.yml
  register: second_web
  when: second_server | success


text:
Q: "Column not found" error when using "left" "mid" or "Substr" in MS Query and thanks in advance for any help.
I'm using Microsoft Query to interrogate Sage 50 tables.
I'm trying to create a user defined field containing only the first digit of a customer account reference.
I have been able to achieve this result when interrogating SAP tables, by using the Left or Mid functions.
When I try exactly the same method with Sage, I get the error "column not found"
The SQL is as follows:
SELECT INVOICE.ACCOUNT_REF, LEFT(INVOICE.ACCOUNT_REF,1)
FROM INVOICE INVOICE
WHERE (INVOICE.ACCOUNT_REF Like "CHA002")

I'd expect the result of this to be "C" but I get

Column Not Found

Please help! I also will need to do similar to isolate the year from a date field - currently I get the same error here as well :-(

A: Please note that you need the % character for the like operator:
SELECT ACCOUNT_REF, LEFT(ACCOUNT_REF,1)
FROM INVOICE
WHERE ACCOUNT_REF Like "CHA002%"

A: You may try this. Try to give some column name alias to your result column.
 Also need to change " to '.
SELECT INVOICE.ACCOUNT_REF, LEFT(INVOICE.ACCOUNT_REF,1) as "COLNAME"
FROM INVOICE INVOICE
WHERE (INVOICE.ACCOUNT_REF Like "CHA002")

As You commented about SAGE
In SAGE you need to use mid function mid$(EXP_STRING,EXP_POS,EXP_NB) or may be Instr with same syntax.
For more info on SAGE you may find this LINK.
SELECT INVOICE.ACCOUNT_REF,  mid$(INVOICE.ACCOUNT_REF,1,1)
FROM INVOICE INVOICE
WHERE (INVOICE.ACCOUNT_REF Like "CHA002")

A: I have a concern about your table alias name INVOICE INVOICE.
Can you please change the table alias name different than the actual table name, something like IV.
So the query below may work:
SELECT IV.ACCOUNT_REF, LEFT(IV.ACCOUNT_REF, 1) AS FirstCharacter
FROM INVOICE IV
WHERE IV.ACCOUNT_REF LIKE 'CHA002'


text:
Q: How do I filter out human users only from list of all azure AD users? (no service accounts or rooms) I am using the Graph API (beta) and getting a list of all users from /users. As expected, this returns a list of all users including service accounts and conference rooms. Is there any reliable way I can filter only human employees out from this list?
I've tried using the properties "assignedPlans" and "assignedLicenses" to try and pinpoint human users, but it doesn't work perfectly.

A: It seems that there are no such a property that well distinguishes human and other user type.
If you want to distinguishes room account, you can refer to this Microsoft Graph API: findRooms to get the room accounts and exclude them from your initial user list.
BTW, what do you mean by "service accounts"?


text:
Q: How does second-order logic relate to lambda calculus? How does second-order arithmetic/logic relate to lambda calculus? By lambda calculus, I mean both typed and untyped. And is there any relationship with recursive and recursively enumerable sets?
Edit: some edits.

A: The question is rather vague. However, I recall something that you may be interested in:
System F is a typed lambda calculus that has a very interesting property:

An arithmetic function can be represented in System F if and only if it can be proved total in second order Peano arithmetic.

This also means that in System F we can represent basically all total functions we can ever imagine.
There is also a weaker system called Gödel System T, for which there is a similar theorem:

An arithmetic function can be represented in System T if and only if it can be proved total in first order Peano arithmetic.

System T is the simply typed calculus enriched with booleans, natural numbers and primitive recursion on them.
Also:

*

*All functions representable in System F and System T are total.

*This means that those systems (unlike the untyped lambda calculus) are not Turing complete.

All this is described in detail in Proofs and Types by Jean-Yves Girard, Yves Lafont and Paul Taylor.

A: The obvious result that comes to mind (which talks both of second-order logic and computability) is that second-order consequence -- when defined using the natural 'full' semantics (so second-order quantifiers run over all subsets of the domain) -- is not recursively axiomatizable.
Otherwise it is unclear what kind of relation is being enquired about.


text:
Q: Why would I use ANOVA instead of a Rank-Sum test? A colleague of mine with little statistics experience is trying to perform an experimental evaluation of a computer program. He created a between subjects design and solicited test subjects.
11 people were given his "new and improved" computer program to use. 10 others got the "old and boring" computer program to use, for the same task.
He asked me, and several other people around the lab how to analyze his data.
I told him he should examine the data for normality. If it was normally distributed, he should use a t-test. If it was not, he should use a Wilcoxon rank sum test.
One of my colleagues told him he should use ANOVA, even though he only has 2 groups. Apparently using ANOVA on non-normal data in R produces a new degree of freedom measure which can be put into a t-test.
I've never heard of such a thing. Is this true? Is it statistically valid? Why would anyone use it instead of just doing a rank-sum test?

A: Using ANOVA in R does not produce anything different from using ANOVA in another program, and with two groups the results will be equivalent to an equal variance t-test. The t-test is known to be robust to deviations from normality, though with unequal variances a Welch's t-test is probably preferrable.
In the special case of a score based on the number of correct answers on a multiple choice test, the distribution of the score is probably an overdispersed binomial. In that case the "correct" analysis might be a GLM model with a quasi-binomial distribution. Of course, the results might be quite similar to the unequal variance t-test.
Here is a simple simulation based example with 20 questions, and unequal variances. Welch's t-test gives a result much closer to the overdispersed binomial regression.
set.seed(3413)
#generate first sample
p1 <- 1/(1+exp(-1+rnorm(10,sd=1)))
x1 <- rbinom(10, size=20, p=p1)
#generate second sample
p2 <- 1/(1+exp(-3+rnorm(10, sd=1)))
x2 <- rbinom(10, size=20, p=p2)
#combine two sets
x <- c(x1,x2)
g <- gl(2,10)

#summaries:
tapply(x, g, mean)
   1    2
12.6 19.2
tapply(x, g, sd)
       1        2
3.921451 1.032796

#t-test:
t.test(x ~ g, var.equal=TRUE)

        Two Sample t-test

data:  x by g
t = -5.1468, df = 18, p-value = 6.765e-05
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -9.294136 -3.905864
sample estimates:
mean in group 1 mean in group 2
           12.6            19.2

#without equal variances:
t.test(x ~ g, var.equal=FALSE)

        Welch Two Sample t-test

data:  x by g
t = -5.1468, df = 10.243, p-value = 0.0004016
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -9.448128 -3.751872
sample estimates:
mean in group 1 mean in group 2
           12.6            19.2

#overdispersed binomial regression:
summary(glm(cbind(x, 20-x) ~ g, family="quasibinomial") )

Call:
glm(formula = cbind(x, 20 - x) ~ g, family = "quasibinomial")

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.5340  -0.8386  -0.2199   1.2778   2.7581

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.5322     0.2242   2.374 0.028946 *
g2            2.6458     0.5962   4.438 0.000318 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for quasibinomial family taken to be 2.343713)

    Null deviance: 120.242  on 19  degrees of freedom
Residual deviance:  45.197  on 18  degrees of freedom
AIC: NA

Number of Fisher Scoring iterations: 5

A: First, the data should not be checked for "normality". This is a useless test. The t test is quite robust to departures from this assumption anyway.
Second, the t test is just a special case of ANOVA for two groups.
If you believe the data to likely be close to a normal distribution (based on experience of the variable in question, visualization of a histogram, but NOT using a normality test), just use the t test. If not, use the rank sum test.

A: The Wilcoxon is vastly superior to the ANOVA in most cases, especially with non-normal data (read anything by Cliff Blair or Shlomo Sawiliowsky for references). The ANOVA is somewhat robust to non-normality, but not very. Additionally the Wilcoxon (as with most rank based statistical tests) are more powerful and increase in power with non-normal data. However, some fields tend to have a bias against distribution free statistical tests. This bias is founded in the tradition and NOT the math. Both statistical tests are the same in R, SPSS, SAS, Minitab, etc.


text:
Q: Magento stock sync using a lot of memory- what options do i have to reduce memory usage? I have a file of around 100,000 sku's that need to have their quantity updated in Magento.
For speed reasons, I am doing a few things:
1. I am generating an array of SKU, Product ID and SKU so that I don't have to do a call for each product to find the product ID from the SKU code, or to get the current quantity.
2. The current quantity from above is then compared to the quantity in the file. If it is the same, then no update occurs.
3. We are using a multi warehouse plugin and so I also keep a list of the cataloginventory_stock_item item_id so that I can just call the model and update it.
My issue is, is that the process is using almost 2GB of memory. I can't quite see why. The file that I am reading line by line is only 5MB. I run the following functions and put the results into an array which must be where the memory is getting used.
protected function _getStockItemsAsArray() {
    $stockCollection = Mage::getModel("cataloginventory/stock_item")->getCollection();

    $out = [];
    foreach ($stockCollection as $stock) {
      $product_id = $stock->getData("product_id");
      $warehouse_id = $stock->getData("stock_id");
      $stock_item_id = $stock->getData("item_id");
      $qty = $stock->getData("qty");
      $is_in_stock = $stock->getData("is_in_stock");

    $out[$product_id][$warehouse_id]["stock_item_id"] = $stock_item_id;
    $out[$product_id][$warehouse_id]["qty"] = $qty;
    $out[$product_id][$warehouse_id]["is_in_stock"] = $is_in_stock;
  }

  return $out;
}

protected function _getCurrentStockAsArray() {
  $resource = Mage::getSingleton("core/resource");
  $readConnection = $resource->getConnection("core_read");

  $query = "
    SELECT
      p.sku,
      p.type_id,
      w.stock_id,
      SUM(IFNULL(pe.qty,0)) pending_qty,
      SUM(s.qty) on_hand_qty
    FROM
      " . $resource->getTableName("catalog_product_entity") . " p
    CROSS JOIN
      " . $resource->getTableName("cataloginventory_stock") . " w
    INNER JOIN
      " . $resource->getTableName("cataloginventory_stock_item") . " s on
      s.product_id = p.entity_id
    LEFT OUTER JOIN
    (
      SELECT
        oi.product_id,
        oi.stock_id,
        IFNULL(SUM(qty_ordered),0) qty
      FROM
        " . $resource->getTableName("sales_flat_order_item") . " oi
      INNER JOIN
        " . $resource->getTableName("sales_flat_order") . " o ON
        oi.order_id = o.entity_id
      WHERE
        o.tigers_export_status IN('Incomplete', 'Failed', 'Pending', 'Exporting')
        AND o.status NOT IN('canceled', 'closed')
      GROUP BY
        oi.product_id,
        oi.stock_id
    ) pe ON
      pe.product_id = p.entity_id
      and pe.stock_id = w.stock_id
    WHERE
      p.sku IS NOT NULL
      OR p.sku != ''
    GROUP BY
      p.sku,
      p.type_id,
      w.stock_id
  ";
  $data = $readConnection->fetchAll($query);

  $out = [];
  foreach( $data as $key => $value ) {
    $out[$value["sku"]][$value["stock_id"]]["on_hand_qty"] = (int)$value["on_hand_qty"];
    $out[$value["sku"]][$value["stock_id"]]["pending_qty"] = (int)$value["pending_qty"];
    $out[$value["sku"]][$value["stock_id"]]["type_id"] = (int)$value["type_id"];
  }
  return $out;
}

protected function _getSkuToProductIDAsArray() {
  $resource = Mage::getSingleton("core/resource");
  $readConnection = $resource->getConnection("core_read");

  $query = "
    SELECT
      sku,
      entity_id
    FROM
      " . $resource->getTableName("catalog_product_entity") . "
    WHERE
      sku IS NOT NULL
    ";
  $data = $readConnection->fetchAll($query);

  $out = [];
  foreach( $data as $key => $value ) {
    $out[$value["sku"]] = (int)$value["entity_id"];
  }
  return $out;
}

What other options are available to use less memory but still have similar performance?

A: Using the database adapter method fetchAll() to fetch large result sets will definitely cause a heavy demand on system and resources.
Your code may execute for a very long time and PHP will probably run out of memory if you're fetching a large amount of data.
You can fix this inefficient memory utilization by replacing:
$data = $readConnection->fetchAll($query);
$out = [];
foreach( $data as $key => $value ) {

By:
$data = $readConnection->query($query);
$out = [];
while ($value = $data->fetch()) {

This way, each database row is fetched separately using the fetch() method to reduce resource consumption.
The database server will execute only one query and the database buffer will be used for retrieving records one by one.


text:
Q: How can I change the values of all the clusters obtained in an image to a new range that represents different levels of color intensity? I'm doing some image analysis of samples of pseudomona. I'm using k-means clustering to obtain different levels of presence of the bacteria along the sample, as it changes tonality as it increases its presence.

Now I want to obtain a GLCM matrix to look into contrast, entropy and other parameters, as I think it will give new information about biofilm growth and morphology. I've been using 8 clusters as a default in all my images (subjective choice), I do not want to use and 8-bit square matrix (256x256 square) because it sounds computationally expensive and wrong, an idea that came to me is to replace the values of every cluster with its correspondent level: 1-8, and then obtain a 3-bit square matrix to analyze everything in the image.
My question goes into how do I change the values of every cluster to a new value?, this new value should go from 1-8, from the palest color to the most intense. Also, how do I obtain a percentage representation of the clusters and the color it represents? I'm looking into it, but a little help would be appreciated.


text:
Q: changing the id of div with jquery of javascript I have a html file that has a section for writing mdxquery , file sends queries to a js file and that file use this queries and other information and show a map on my html file, know i need to change this mdxqueries automatically by selecting different checkbox, i define different queries for different selections(my selectins are limmited), and now i want replace them in div section for it i defined different div(as you'll see dives are particular and the content of them is inside the div tag and arent changeable) that have different queries, now the problem is that, the js file read the queries ofdiv with just particular div, therefor i need to change the id of div , here is my cod that dont work, please see the code and tell me what is wrong:

A: I see a code $("#All State").is(":checked"), this could be potentially wrong.
Here you are trying to grab element with Id - "All State", but HTML Id's cannot have spaces in between, If that's not meet code inside If condition will not be executed and Id will not change.

A: I usually use getElementBy, for example I do this
var myDiv =  document.getElementById('div1');
myDoiv.setAttribute('id', 'div2');


text:
Q: Using covering spaces to show that there is no continuous odd map $S^n \to S^1$ I have the following question from a past exam about basic algebraic topology:

Let $p:S^1 \to \mathbb{R}\mathbb{P}^1$ be the obvious covering map. For $n\geq 2$, show that a continuous map $f:\mathbb{R}\mathbb{P}^n \to \mathbb{R}\mathbb{P}^1$ always lifts to a continuous map $\tilde{f}:\mathbb{R}\mathbb{P}^n \to S^1$ with $p \circ \tilde{f} = f$.
Deduce that, for all $n \geq 2$, there is no continuous map $F:S^n \to S^1$ with $F(x) = -F(-x)$ for all $x$.

I have no trouble with the first part, and am able to make some headway into the second, but I need help getting the result. The examiner's report says that one is supposed to use uniqueness of lifts to finish the argument, and I don't see how to apply it.
My Attempt
The first part is straightforward. Note that $\mathbb{R}\mathbb{P}^n$ has fundamental group $\mathbb{Z}/2\mathbb{Z}$. The homomorphism $f_*:\pi_1(\mathbb{R}\mathbb{P}^n) \to \pi_1(\mathbb{R}\mathbb{P^1})\cong \mathbb{Z}$ thus maps the nontrivial element of $\pi_1(\mathbb{R}\mathbb{P}^n)$ to an element $n$ of $\mathbb{Z}$ with $2n = 0$, hence $n = 0$, so $f_*\pi_1(\mathbb{R}\mathbb{P}^n)$ is trivial.
In particular $f_*\pi_1(\mathbb{R}\mathbb{P}^n, y) \subseteq p_*\pi_1(S^1, \tilde b)$, where we have chosen basepoints $y, \tilde b, b$ for our spaces such that $f(y) = b, p(\tilde b) = b$. Now, since $\mathbb{R}\mathbb{P}^n$ is path-connected and locally path-connected, by a standard theorem referred to in my course as existence of lifts, we have that $f$ admits a lift $\tilde f:(\mathbb{R}\mathbb{P}^n, y)\to (S^1,\tilde{b})$.
Let $q:S^n\to\mathbb{R}\mathbb{P}^n$ be the obvious two-sheeted covering. Suppose that a continuous odd $F:S^n \to S^1$ exists. The condition that $F$ is odd means that for $x, y \in S^n$, we have
$$q(x) = q(y) \implies y = \pm x \implies F(y) = \pm F(x) \implies  p(F(x)) = p(F(y))$$
so there is a well-defined map $f:\mathbb{R}\mathbb{P}^n \to \mathbb{R}\mathbb{P}^1$ with $f(q(x)) = p(F(x))$ for $x \in S^n$. So the following diagram commutes:

Now, by our result from the first part of the question, $f$ actually has a lift $\tilde f:\mathbb{R}\mathbb{P}^n \to S^1$. From here I'm not sure how to proceed. The hint in the examiner's report says I should use uniqueness of lifts, but here we only have one lift, so I don't see a way to do this. I guess we want to construct some distinct lift that agrees with $\tilde f$ at some point, but I haven't been able to find such a construction.

A: You have made a choice (which is always a hazard for uniqueness) when you chose $+F(x)$ from $\pm F(x)$ to construct your $f$.  Let's call that map $f^+$ to record that choice.  There is also an $f^-$ constructed from $-F(x)$.  This gives two lower maps in your commutative diagram (parallel to the two upper maps) and the two are not the same.  Consequently, there are two distinct commuting paths in the diagram, but they do not "mix" -- whatever map you pick on the upper side you must pick the matching map on the lower side --  from $\mathbb{R}P^n$ to $S^1$, giving distinct lifts $\widetilde{f^+}$ and $\widetilde{f^-}$, contradicting uniqueness of lifts.
A better diagram would be $\require{AMScd}$
\begin{CD}
S^1 @<{-F}<< S^n @>{+F}>> S^1\\
@VVV @VVV @VVV \\
\Bbb{R}P^1 @<{f^-}<< \Bbb{R}P^n @>{f^+}>> \Bbb{R}P^1
\end{CD}
This diagram commutes.  However if we add the identity map between the pair of $S^1$s or between the pair of $\Bbb{R}P^1$s or between both pairs, the resulting diagram does not commute, explicitly demonstrating a failure of uniqueness of lifts.


text:
Q: Image of $\frac{2x}{\ln(x)}$ I'm trying to calculate the image of $f(x)=\frac{2x}{\ln(x)}$. I tried to find the horizontal asymptotes. But I couldn't. the $\lim_{x \to \infty} f(x)$  is $\infty$. I also tried to find the oblique one but I couldn't.
I have no clue.

A: For $x \in [0,1)$ the function $\frac{2x}{\ln{x}}$ will range from $0 \text{  to } -\infty$, this is because there is an asymptote at $x=1$ and our function is negative and decreasing in that range (with a max value of $0$ at $x=0$).
For $x \in (1,\infty)$ the function $\frac{2x}{\ln{x}}$ is always positive, has a positive second derivative, a vertical asymptote at $x=1$ and goes to infinity as $x$ grows large. That means there is only extrema point which must be a minimum in this range. We can find that to be at $x= e$ where the minimum value of the function is $\frac{2e}{\ln{e}}=2e$. So we know in the domain $x \in (1,\infty)$ our function ranges over $[2e, \infty)$.
Since those two domains cover the entire valid domain of our function we can say its range is given by
$$(-\infty,0] \cup [2e,\infty)=\mathbb{R} \setminus (0,2e) .$$


text:
Q: java.lang.RuntimeException: Uncompilable source code error I am a beginner in java programming and i have a question for you.
I am using netbeans 8.0.2 and i have this error :

------ Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol symbol:   class Spacer
  location: class demineur.views.ParameterDialog at
  demineur.views.ParameterDialog.initComponents(ParameterDialog.java:59)
  at demineur.views.ParameterDialog.(ParameterDialog.java:12) at
  demineur.controllers.Controlleur.(Controlleur.java:32) at
  demineur.Demineur.main(Demineur.java:19) Java Result: 1

What should i do ?
package demineur.views;

import java.awt.*;
import com.intellij.uiDesigner.core.*;

import javax.swing.*;

public class ParameterDialog extends JPanel {
    private JFrame frame;

    public ParameterDialog() {
        initComponents();

        ButtonGroup group = new ButtonGroup();
        group.add(easy);
        group.add(medium);
        group.add(hard);
    }

    public void display(JPanel panel) {
        frame = new JFrame("Options");
        frame.setContentPane(panel);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public int getLevel(){
        int level = 1;
        if(medium.isSelected()){
            level = 2;
        }
        else if(hard.isSelected()){
            level = 3;
        }
        return level;
    }

    public JButton getStartGame() {
        return startGame;
    }

    public void hide() {
        frame.setVisible(false);
    }

    private void createUIComponents() {
        easy = new JRadioButton("D�butant (10x10 cases avec 10 mines)", true);
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        // Generated using JFormDesigner Evaluation license - unknown
        createUIComponents();

        hard = new JRadioButton();
        medium = new JRadioButton();
        Spacer hSpacer1 = new Spacer();
        JLabel label1 = new JLabel();
        JPanel panel1 = new JPanel();
        startGame = new JButton();
        Spacer hSpacer2 = new Spacer();

        //======== this ========

        // JFormDesigner evaluation mark
        setBorder(new javax.swing.border.CompoundBorder(
            new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
                "JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
                javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
                java.awt.Color.red), getBorder())); addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});

        setLayout(new GridLayoutManager(6, 1, new Insets(10, 10, 10, 10), -1, -1));

        //---- hard ----
        hard.setText("Expert (20x24 cases avec 100 mines)");
        add(hard, new GridConstraints(3, 0, 1, 1,
            GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
            GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
            GridConstraints.SIZEPOLICY_FIXED,
            null, null, null));

        //---- medium ----
        medium.setText("Interm\u00e9diaire (16x16 cases avec 40 mines)");
        add(medium, new GridConstraints(2, 0, 1, 1,
            GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
            GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
            GridConstraints.SIZEPOLICY_FIXED,
            null, null, null));

        //---- easy ----
        easy.setText("D\u00e9butant (10x10 cases avec 10 mines)");
        add(easy, new GridConstraints(1, 0, 1, 1,
            GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
            GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
            GridConstraints.SIZEPOLICY_FIXED,
            null, null, null));
        add(hSpacer1, new GridConstraints(5, 0, 1, 1,
            GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
            GridConstraints.SIZEPOLICY_CAN_GROW | GridConstraints.SIZEPOLICY_WANT_GROW,
            GridConstraints.SIZEPOLICY_CAN_SHRINK,
            null, null, null));

        //---- label1 ----
        label1.setEnabled(true);
        label1.setText("Veuillez choisir votre niveau de difficult\u00e9 : ");
        add(label1, new GridConstraints(0, 0, 1, 1,
            GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
            GridConstraints.SIZEPOLICY_FIXED,
            GridConstraints.SIZEPOLICY_FIXED,
            null, new Dimension(500, 61), null));

        //======== panel1 ========
        {
            panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));

            //---- startGame ----
            startGame.setText("Lancer le jeu !");
            panel1.add(startGame, new GridConstraints(0, 1, 1, 1,
                GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
                GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
                GridConstraints.SIZEPOLICY_FIXED,
                null, null, null));
            panel1.add(hSpacer2, new GridConstraints(0, 0, 1, 1,
                GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
                GridConstraints.SIZEPOLICY_CAN_GROW | GridConstraints.SIZEPOLICY_WANT_GROW,
                GridConstraints.SIZEPOLICY_CAN_SHRINK,
                null, null, null));
        }
        add(panel1, new GridConstraints(4, 0, 1, 1,
            GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
            GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
            GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
            null, null, null));
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    // Generated using JFormDesigner Evaluation license - unknown
    private JRadioButton hard;
    private JRadioButton medium;
    private JRadioButton easy;
    private JButton startGame;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}

A: The log clearly says, cannot find symbol Spacer. I suppose you did not import the requisite.


text:
Q: Microsoft Graph API - Request Photo by size I'm looking at the Microsoft Graph API Beta for Users/Photo operations documentation and I am comparing it to the Outlook REST API. In the Outlook REST Beta there is the option of retrieving a photo by size.
GET https://outlook.office.com/api/beta/Users('{user_id}')/photos('{size}')/$value
I do not see a way in Graph API to request a photo by size. Is there anyway to do this? If not, is this a planned feature?

A: When using the Microsoft Graph SDK you can do it this way:
var graphClient = GetGraphServiceClient();
var photoStream = await graphClient.Users[userId].Photos["120x120"].Content.Request().GetAsync();

// or

var photoStream = await graphClient.Me.Photos["120x120"].Content.Request().GetAsync()

A: This is a doc error and we will fix it.  The equivalent request (see below) is supported today in Microsoft Graph.
GET https://graph.microsoft.com/beta/users('{user_id}')/photos('{size}')/$value


text:
Q: hsv_to_rgb isn't the inverse of rgb_to_hsv on matplotlib I tried to convert an image to hsv and back to rgb, but somehow I lost color information.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

And I also replicated the problem on shell too, just writing this line after importing also gives the same result.
plt.imshow(
  matplotlib.colors.hsv_to_rgb(
    matplotlib.colors.rgb_to_hsv(mpimg.imread('go2.jpg'))
  )
)

Can you tell me what am I doing wrong?

A: edit: this is only a partial solution,
see discussion at https://github.com/matplotlib/matplotlib/pull/2569
This is an integer division issue.  numpy is serious about it's types and seems to not respect from __future__ import division.   The simple work around is to convert your rgb values to floats before calling rgb_to_hsv or patch the function as such:
def rgb_to_hsv(arr):
    """
    convert rgb values in a numpy array to hsv values
    input and output arrays should have shape (M,N,3)
    """
    arr = arr.astype('float')  # <- add this line
    out = np.zeros(arr.shape, dtype=np.float)
    arr_max = arr.max(-1)
    ipos = arr_max > 0
    delta = arr.ptp(-1)
    s = np.zeros_like(delta)
    s[ipos] = delta[ipos] / arr_max[ipos]
    ipos = delta > 0
    # red is max
    idx = (arr[:, :, 0] == arr_max) & ipos
    out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
    # green is max
    idx = (arr[:, :, 1] == arr_max) & ipos
    out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
    # blue is max
    idx = (arr[:, :, 2] == arr_max) & ipos
    out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
    out[:, :, 0] = (out[:, :, 0] / 6.0) % 1.0
    out[:, :, 1] = s
    out[:, :, 2] = arr_max
    return out

A: This problem is reproducible for me (matplotlib 1.3.0).  It looks like a bug to me.  The issue seems to be that in the rgb_to_hsv step, the saturation is being dropped to zero.  At least for most colours:
import numpy as np
darkgreen = np.array([[[0, 100, 0]]], dtype='uint8')
matplotlib.colors.rgb_to_hsv(darkgreen)                  # [0.33, 1., 100.], okay so far
darkgreen2 = np.array([[[10, 100, 10]]], dtype='uint8')  # very similar colour
matplotlib.colors.rgb_to_hsv(darkgreen2)                 # [0.33, 0., 100.], S=0 means this is a shade of gray

I think the correct place to report bugs is on the github issue tracker.


text:
Q: Android Room with deferred foreign key I have several tables that are periodically updated from the server (Benefit, Branch, Coupon) and two more tables that are only local (FavoriteBenefit, UsedCoupon). ER diagram looks like this:

Whenever a Benefit is deleted on the server, I also want to delete an appropriate entity from FavoriteBenefit. For that, I can use onDelete = ForeignKey.CASCADE and whenever parent Benefit no longer exists in the database, FavoriteBenefit gets deleted as well. Sounds good.
A problem arises whenever I use
@Insert(onConflict = OnConflictStrategy.REPLACE) to update benefits in the database. REPLACE actually performs a DELETE and INSERT but DELETE internally triggers onDelete of FavoriteBenefit and as a result, all data in that table gets deleted as well.
(A similar problem occurs with Coupon and UsedCoupon tables.)

I am looking for a way to temporarily disable Foreign Key constraints until the end of the transaction. That is, do not validate Foreign Keys during the transaction but only at the end of the transaction.
I still want Room to automatically delete entities that do not have a valid parent.

It seems that marking foreign key as defferred by setting deferred = true on the @ForeignKey definition should do exactly what I am trying to achieve.

boolean deferred ()
A foreign key constraint can be deferred until the transaction is complete. This is useful if you are doing bulk inserts into the database in a single transaction. By default, foreign key constraints are immediate but you can change it by setting this field to true.

But even when I set the deferred flag it seems to have no effect because FavoriteBenefit is still being deleted every time.
Am I understanding the deferred flag incorrectly?

A: I don't know if it's still relevant to you but I had a similar problem. I've tried to put deferred flag in both places: relation class itself and as a pragma. And in the both cases items were deleted due OnConflictStrategy.REPLACE strategy (which executes DELETE operation as you have mentioned). The workaround I've found is to use an "UPSERT-like" query. UPSERT statement support was added in SQLite last year, so Room does not support it yet, but you can write something like this:
@Dao
abstract class BaseDao<T> {

    /**
     * Insert an item in the database.
     *
     * @param item the item to be inserted.
     * @return The SQLite row id
     */
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    abstract fun insert(item: T): Long

    /**
     * Insert an array of items in the database.
     *
     * @param items the items to be inserted.
     * @return The SQLite row ids
     */
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    abstract fun insert(items: List<T>): List<Long>

    /**
     * Update an item from the database.
     *
     * @param item the item to be updated
     */
    @Update
    abstract fun update(item: T)

    /**
     * Update an array of items from the database.
     *
     * @param item the item to be updated
     */
    @Update
    abstract fun update(item: List<T>)

    @Transaction
    fun upsert(item: T) {
        val id = insert(item)
        if (id == -1L) {
            update(item)
        }
    }

    @Transaction
    fun upsert(items: List<T>) {
        val insertResult = insert(items)
        val updateList = mutableListOf<T>()

        for (i in insertResult.indices) {
            if (insertResult[i] == -1L) {
                updateList.add(items[i])
            }
        }

        if (updateList.isNotEmpty()) {
            update(updateList)
        }
    }
}

The logic behind the code is simple - if the table already contains records (this is checked after insert by filtering rowids) - we should update them.
Credits

A: The reason is that ON DELETE CASCADE is a trigger-like action and it's executed immediately. See the issue and the comment.
There's also a more detailed explanation from the PostgreSQL team:

Yeah, this is per SQL spec as far as we can tell.  Constraint checks can
be deferred till end of transaction, but "referential actions" are not
deferrable.  They always happen during the triggering statement.  For
instance SQL99 describes the result of a cascade deletion as being that
the referencing row is "marked for deletion" immediately, and then

*All rows that are marked for deletion are effectively deleted
at the end of the SQL-statement, prior to the checking of any
integrity constraints.

And take a look at the similar SQLite question which contains a few workarounds.

A: I faced this problem before and I solved it by create new syntax called delsert.
Here is an example:
    @Query("DELETE FROM patient")
    public abstract void delete();

    @Query("DELETE FROM patient WHERE p_id IN (SELECT p_id FROM patient WHERE p_id NOT IN (:ids))")
    public abstract void deleteUnused(List<Long> ids);

    @Transaction
    public void delsert(List<Patient> patientList) {
        if (CommonUtils.isListEmpty(patientList)) {
            this.delete();
            return;
        }

        List<Long> idsPatient = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            patientList.forEach(order -> idsPatient.add(order.getId()));
        else
            for (Patient id : patientList) idsPatient.add(id.getId());

        deleteUnused(idsPatient);

        insert(patientList);
    }


text:
Q: rational solutions of $r^n-s^n=1$? How can we treat with the Diophantine equation: For what integer values of $a,b,x,y$ and integer $n>1$
$$
\left(\frac ab\right)^n-\left(\frac xy\right)^n=1?
$$
Thanks.

A: As Wojowu said, when $y,b\ne0$
$\left(\frac{a}{b}\right)^{n}-\left(\frac{x}{y}\right)^{n}=1 \iff a^ny^n=x^nb^n+b^ny^n \iff a^ny^n=b^n(x^n+y^n)$
I'm going to search only solutions where $\operatorname{gcd}(a,b)=\operatorname{gcd}(x,y)=1$.
For $n>2$ according to Fermat's last theorem, it must be $a^ny^n = 0$ or $b^ny^n =0$ or $x^nb^n=0$, but $y,b$ must be $\ne0$, so the only solutions are trivial

*

*if $n>2$ is odd $S=\{a=b\ne0,x=0,y\ne0\}\cup\{a=0,b\ne0,x=-y\ne0\}$

*if $n>2$ is even $S=\{a=\pm b\ne0,x=0,y\ne0\}$
With $n=2$ there are also many non-trivial solutions using pythagorean triples:
$\begin{cases}a=r^2+s^2\\b=2rs\\x=r^2-s^2\\y=b\end{cases}$
where $r,s \in \mathbb{Z}-\{0\}$


text:
Q: HABTM Relationships and the Join Table I'm trying to connect the values of two join tables that I have and show the results based on a conditional relationship...and i'm having some problems
I have a Users Model(:name, :password, :email), and Events model(:name, :etc) and Interests model (:name)
I created about 5 records in each model.
Then I created two join tables -> UsersInterests and EventsInterests; each not containing a primary key and only comprised of the user_id/interest_id and event_id/interest_id respectively.
Then I added to the model files the HABTM Relationship
users => has_and_belongs_to_many :interests
events => has_and_belongs_to_many :interests
interests => has_and_belongs_to_many :users
         has_and_belongs_to_many :events

Now I wanted to create a controller that finds only the events where the users interests correspond with the events interests
From working on this for a while I've figured that I need something in the area of
@Events = Event.User.find([condition])
[condition] = where users.interest == event.interest

or something like that... I'm kind of lost..How do you state the find condition?...I know how to do the inner join in sql but I'm looking for the elegant Rails way to do this...  any tips guys?

A: The elegant ruby way to do this is with named scopes. However because you've decided to use has_and_belongs_to_many relationships instead of has_many :through relationships, you're going to need to define the join with raw SQL, which isn't very elegant. And because of the way Rails handles SQL generation, you will have to make a scope for use with a single user, and a second named scope for use with many users.
Class Event < ActiveRecord::Base
  ...

  #find events that share an interest with a single user
  named_scope :shares_interest_with_user, lambda {|user|
    { :joins => "LEFT JOIN events_interests ei ON ei.event_id = events.id " +
         "LEFT JOIN users_intersets ui ON ui.interest_id = ei.interest_id",
      :conditions => ["ui.user_id = ?", user], :group_by => "events.id"
    }

  #find events that share an interest with a list of users
  named_scope :shares_interest_with_users, lambda {|users|
    { :joins => "LEFT JOIN events_interests ei ON ei.event_id = events.id " +
         "LEFT JOIN users_intersets ui ON ui.interest_id = ei.interest_id",
      :conditions => ["ui.user_id IN ?", users], :group_by => "events.id"
    }
  }

  #find events that share an interest with any user
  named_scope :shares_interest_with_any_user, lambda {
    { :joins => "LEFT JOIN events_interests ei ON ei.event_id = events.id " +
         "JOIN users_intersets ui ON ui.interest_id = ei.interest_id",
      :conditions => "ui.user_id IS NOT NULL", :group_by => "events.id"
    }
  }

end

Now you can do this to get all the events a user might be interested in:
@events = Event.shares_interest_with_user(@user)

Or this to get all the events a list of users might be interested in:
@events = Event.shares_interest_with_users(@users)

But as I warned, that's not really elegant.
You can greatly simplify the joins if you redefine your relationships to be has_many through relationships with proper join models instead of HABTM relationships. Your case would require the nested has many through plugin for this to work. N.B. You'll have to add corresponding has_many/belongs_to statements in all of the other models. Even the join models.
Class Event < ActiveRecord::Base
  has_many :event_interests
  has_many :interests, :through => :event_interests
  has_many :user_interests, :through => :interests
  has_many :users, :through => :user_interests
  ...

  #find events that share an interest with a list of users
  named_scope :shares_interest_with_users, lambda {|user|
    { :joins => :user_interests, :group_by => "events.id",
      :conditions => {:user_interests => {:user_id => user}}
    }
  }

  #find events that share an interest with any user
  named_scope :shares_interest_with_any_user, lambda {
    { :joins => :user_interests, :group_by => "events.id",
      :conditions => "user_interests.user_id IS NOT NULL"
    }

end

Now, the following will work.
@user = User.first; @users = User.find(1,2,3)

# @events = all events a single user would be interested in
@events = Event.shares_interest_with_users(@user)

# @events = all events any of the listed users would be interested in.
@events = Event.shares_interest_with_users(@user)

You could even define a named scope to select events that haven't happened yet and chain the two:
named_scope :future_events, lambda {
   { :conditions => ["start_time > ?", Time.now]}
}

Events.future_events #=> Events that haven't started yet.

# Events that a user would be interested in but only choose those
# that haven't started yet.
Events.future_events.shares_interest_with_user(@user)


text:
Q: Python as Android build requirement Heres the official link for Android source code build/development.
http://source.android.com/source/building.html
As you can see one of the prerequisites is setting up Python.
From what I have heard/read, only Java is primarily used for Android app development..so why the need for Python ?.
Can you point out what I am obviously missing ?
* This is a newbie question *

A: Even though the target device is running Java based virtual machine, the SDK build scripts may leverage Python.
Thus, Python is required to build Android software or SDK, but Python itself is not run on the device.
Likewise, you need git even though you surely won't run version control system on your phone.


text:
Q: Customizing the setError icon for EditText I want to set a setError method to my EditText, with a custom icon instead of the default Android icon. So I tried this:
((EditText)findViewById(R.id.edtTitle)).setError(getResources().getText(R.string.errEmptyTitle),
         getResources().getDrawable(R.drawable.ico_warning_small);

It shows me the custom message, but not the custom icon. I tried this as well:
Drawable warning = (Drawable)getResources().getDrawable(R.drawable.ico_warning_small);
((EditText)findViewById(R.id.edtTitle))
      .setError(getResources().getText(R.string.errEmptyTitle), warning);

Pretty much the same, but I still decided to give it a go. However this also didn't help - I still can't see the icon.
I tried to use some other Android system icon, just to see if I see them and no, I don't see them as well.
So what am I doing wrong? Is there any way to set that custom icon?

A: If you don't want to show any icon at all, use
editText.setError("error", null);

A: You need to set the bounds on the drawable before using it in setError.
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
editText.setError("error", drawable);

A: This issue is discussed and resolved here:
EditText setError() with icon but without Popup message
I hope that by extending the answer it would not get auto-converted to a comment.

A:     Drawable customErrorDrawable = getResources().getDrawable(R.drawable.error_icon);
        customErrorDrawable.setBounds(0, 0, customErrorDrawable.getIntrinsicWidth(), customErrorDrawable.getIntrinsicHeight());

 editText.setError("please enter data",customErrorDrawable);


text:
Q: Blending two FBOs on iPhone gives strange result? I am programming a small drawing app on the iphone and ran into a problem. When i merge two fbos the color becomes white instead merging. Look at the picture:
http://dl.dropbox.com/u/2025544/help.png
Here the left is rendered as a normal mac program and the right is rendered on the iPhone platform with almost the same code except for using the eos version of the fbo.
Drawing multiple FBOs on top of each other creates the alpha blending i want:
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  myTex.draw(0, 0);

     for(int client = 0; client < 5;client++)
     {
        ofSetColor(
                 datas[client]->myColor.r,
                 datas[client]->myColor.g,
                 datas[client]->myColor.b,
                 datas[client]->myColor.a
                 );

        datas[client]->myTex.draw(0,0);

     }

Merging the two fbos gives med the wrong alpha:
   myTex.begin();
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        ofSetColor(
                 datas[tmpMessage->clientId]->myColor.r,
                 datas[tmpMessage->clientId]->myColor.g,
                 datas[tmpMessage->clientId]->myColor.b,
                 datas[tmpMessage->clientId]->myColor.a
                 );
        datas[tmpMessage->clientId]->myTex.draw(0, 0);

        myTex.end();
        datas[tmpMessage->clientId]->myTex.clear(0, 0, 0, 0);

        datas[tmpMessage->clientId]->touchDown = true;

Please help i am going crazy :-)

A: Did you check what glBlendEquation() is set to?

A: I solved the problem by not using: glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); I have no idea why this solved it... and it seems that other calls screws things up as well...


text:
Q: what is the difference between parameter and variable in ARM template? what is the difference between parameter and variable in ARM template.

A: A parameter value is passed in from the outside, for example by a pipeline using a parameter file. The value of a variable is defined or calculated internally.
Parameters can be used to have the template behave different according to the environment (test, prod for example). A practical example is having a values-prod.json and a values-test.json file with the environment specific values for the parameters.


text:
Q: Creating a list with ng-repeat HTML

        {{pages.page}}

ANGULAR
    app.controller('topbarController', ['$http', function($http) {
    var topbar = this;
    topbar.pages = [];

    $http.get('/Hexdra/app/app_data/pages.json').success(function(data){
        topbar.pages = data;
    });
    }]);

JSON
[
{ "page": "about_me"},
{"page": "index"}
]

I am trying to display a list of pages by using ng-repeat and loading the page data from a JSON through an http.get. My problem is that nothing is displayed on the html page when it is loaded.
I checked this but couldn't seem to get that fix to work.
I am also having a hard time keeping track of all the different names.
1.) I know that my controller is called topbarController. In the HTML the controller scope is then renamed to topbarCtrl.
2.) I then have angular index through my pages object and inside its own div it displays every page.
Fixes are appreciated but also further reading to what has gone wrong would also be appreciated.
Thank you!

A: I had to look over your code a few times, but the issue is in the following line:

You assigned topbar to this in your controller:
var topbar = this;
topbar.pages = [];

Change your ng-repeat to this, and it will work

A: try this
app.controller('topbarController', ['$http', function($http) {
$scope.topbar {
     topbar.pages : []
     };

$http.get('/Hexdra/app/app_data/pages.json').success(function(data){
    $scope.topbar.pages.push(data);
});
}]);

and your html must be like this:

    {{page}}

A: Are you sure that the url that you are giving is proper?
for example it should be like http://localhost:80/Hexdra/app/app_data/pages.json
Try using the absolute url and see if it works


text:
Q: How to import JSON with specifying which fields in the JSON of time type? I'm using such command to import data to RethinkDB
rethinkdb import --force -f ${folder}/json/data.json --table test.data -c localhost:28015

It imports data perfectly. But I have some of fields in my json as time:
{
    "id": "1",
    "date": "2015-09-19",
    "time": {
        "begin": "09:00",
        "end": "10:30"
    }
}

When I'm trying to query these fields like data or time.begin, time.end treating them as time - RethinkDB doesn't understand it and throw exception
r.db('test').table('data').filter(function(t) {
    return t("date").date()
})

RqlRuntimeError: Not a TIME pseudotype: `"2015-09-19"` in:
r.db("test").table("data").filter(function(var_43) { return var_43("date").date(); })
                                                                         ^^^^^^^^^^^^^^

Is any way to specify for RethinkDB which field in the JSON are with time type?

A: JSON doesn't provide a standard way of specifying a time field, but there are a couple ways you can do this with RethinkDB: either modify the data before or after inserting it.  RethinkDB time objects are more than just the strings you have shown here, and contain millisecond time resolution along with timezone data.
Time objects can be constructed using r.now(), r.time(), r.epoch_time(), and r.ISO8601().  Because of the format of your time strings, I would use r.ISO8601().  It is important to note that your data doesn't appear to contain timezone information, so you should be sure that your data won't return incorrect results if they are all put in the same timezone.
Another thing to keep in mind when using times in RethinkDB is that the data will be converted into an appropriate time object in your client.  Since it appears that you are using Javascript, you will get back a Date object.  For Python, you would get a datetime.datetime object, etc.  If you would rather get the raw time pseudotype format (see below), you can specify timeFormat: "raw" as a global optarg to your query (see the documentation for run() for details).
Post-process the data inside RethinkDB
This is probably the easiest option, and what I would recommend.  After importing your data, you can run a query to modify each row to convert the strings into time objects.  Based on the format of your data, this should work:
r.db('test').table('data').replace(function(row) {
    return row.merge({
        'begin_time': r.ISO8601(row('date').add('T').add(row('time')('begin')), { defaultTimezone: '+00:00' }),
        'end_time': r.ISO8601(row('date').add('T').add(row('time')('end')), { defaultTimezone: '+00:00' })
        }).without('date', 'time');
    }).run(conn, callback)

This replaces the date and time fields from all the rows in your test.data table with begin_time and end_time time objects that can be used as you expect.  The defaultTimezone field is required because the time string doesn't contain timezone information, but you should change these values to whatever is appropriate.
Modify the JSON data
This is a bit lower-level and can be tricky, but if you don't mind getting your hands dirty, this could be more suited to your needs.
RethinkDB time objects are communicated in JSON using a particular format to represent a 'pseudotype'.  These are types not standardized in JSON that still exist in RethinkDB.  The format for a time pseudotype looks like this:
{
    "$reql_type$": "TIME",
    "epoch_time": 1413843783.195,
    "timezone": "+00:00"
}

Where epoch_time is the number of seconds since the UNIX epoch (Jan 1, 1970).  If the data you are importing follows this format, you can insert this directly and it will be interpreted by the database as a valid time object.  It would be up to you to modify the data you are importing, but your example row would look something like this:
{
    "id": "1",
    "begin_time": {
        "$reql_type$": "TIME",
        "epoch_time": 1442653200,
        "timezone": "+00:00"
    },
    "end_time': {
        "$reql_type$": "TIME",
        "epoch_time": 1442658600,
        "timezone": "+00:00"
    }
}

My same caveat for timezones applies here as well.


text:
Q: Webview not working as desired in case of HTML5 cache I have created an application using Titanium Appcelerator in which I am using a webview to show some webpages. All the webpages to be displayed in the webview are HTML5 cache enabled, as I want the webpages to be available even when the application is running offline.
The problem which I am facing is that, the webview is not able to show the cached webpages when there is no network connection. But I have tested all the webpages in the browser, and all of them are working fine.
I am facing this problem for Android platform.
This is the code for the webview:
 //FirstView Component Constructor
function FirstView() {
    //create object instance, a parasitic subclass of Observable
    var self = Ti.UI.createView();

 var webview = Ti.UI.createWebView({
    url: 'http://www.w3schools.com/html/tryhtml5_html_manifest.htm'
});

self.add(webview);

    return self;
}

module.exports = FirstView;

The very url is working fine in the browser. How should I solve this?

A: you can use local html and it use jquery .ajax for load another webpage like that
    //inside local page


text:
Q: How to properly ask an input from user in LispWorks? I have this code:
(defvar x)
(setq x (read))
(format t "this is your input: ~a" x)

It kinda work in Common Lisp but LispWorks it is showing this error:
End of file while reading stream #<Synonym stream to
*BACKGROUND-INPUT*>.

I mean I tried this: How to read user input in Lisp of making a function. But still shows the same error.
I hope anyone can help me.

A: You probably wrote these three lines into Editor and then compiled it.
So, you can write this function into Editor:
(defun get-input ()
  (format t "This is your input: ~a" (read)))

Compile Editor and call this function from Listener (REPL).
CL-USER 6 > (get-input)
5
This is your input: 5
NIL

You can also use *query-io* stream like this:
(format t "This is your input: ~a" (read *query-io*))

If you call this line in Listener, it behaves like read. If you call it in Editor, it shows small prompt "Enter something:".
As you can see, no global variable was needed. If you need to do something with that given value, use let, which creates local bindings:
(defun input-sum ()
  (let ((x (read *query-io*))
        (y (read *query-io*)))
    (format t "This is x: ~a~%" x)
    (format t "This is y: ~a~%" y)
    (+ x y)))

Consider also using read-line, which takes input and returns it as string:
CL-USER 19 > (read-line)
some text
"some text"
NIL

CL-USER 20 > (read-line)
5
"5"
NIL


text:
Q: How to set the monitor on button? I add the button dynamic in android. How to set the monitor on button?
I want to realize a function like I add a button into the main interface, how to add a monitor on this button.
Then I accept a voice message. How to play the voice message?

A: myBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Start accepting voice message
            }
        });


text:
Q: Get Size (x, y, width, height) of UIButtons So I'm trying to implement this:
https://github.com/aleksandrshoshiashvili/AwesomeSpotlightView
Therefore I would like to set the spotlight view to the actual x,y position of my buttons, which obviously varies from device to device (e.g. iPhone SE is different from iPhone 11 Pro Max).
This is what I tried:
let spotlight2 = AwesomeSpotlight(
    withRect: CGRect(
        x: confirmButton.frame.origin.x,
        y: confirmButton.frame.origin.y,
        width: confirmButton.frame.width,
        height: confirmButton.frame.height
    ),
    shape: .roundRectangle,
    text: "put my text here"
)

But that only uses the x, y, width, height which I used at my UIViewController...
(by the way: The Button changes its position and size perfectly from device to device).
Do you have any idea?
Thank you!

A: You should call view.layoutIfNeed() and then get your frame, x, y. That way it will return to you the right value


text:
Q: Querypath and Malformed HTML I'm using QueryPath to manipulate a pages DOM. The page I'm manipulating has some tags that QueryPath doesn't know how to interpret.
I've tried passing the following as options but I still get errors:
ignore_parser_warnings
use_parser (html)
I get the following errors with these enabled:
Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Tag nobr invalid in Entity
Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: htmlParseEntityRef: expecting ';' in Entity
Any help would be greatly appreciated.

A: Use htmlqp() instead of qp(). The htmlqp() function does a substantial amount of fixing for yucky HTML.

A: Try the libxml functions
libxml_use_internal_errors(TRUE);
$dom->load('whatever'); // or whatever you use for loading the DOM
libxml_clear_errors();

Instead of just clearing the erros, you can opt to handle them, though the above should be sufficient for most cases.

A: Just use an @ in front of your QueryPath functions to suppress the warnings. While invalid HTML may generate warnings, it can generally handle it just fine.


text:
Q: What does Eclipse project with icon "m" and exclamation mark means? I have a Maven Project in Eclipse (Version: Oxygen.3a Release - 4.7.3a). The Project folder is showing an icon with "M" and an exclamation mark. Anyone knows what does this icon mean?

I have searched through the list of icons here, but it wasn't in the list: Eclipse JDT Icons

A: That "M" indicates a Maven project. The red exclamation mark usually indicates a problem/error, often in the build path.


text:
Q: MySQL: where clustered (logical indexes) save Non-Clustered file stored in data files, Clustered index stores data in logical index order.
Where does logical order resides?

A: Most MySQL indexes are structured as BTrees.  (See Wikipedia)
(I am excluding FULLTEXT and SPATIAL indexes from this discussion.)
InnoDB's PRIMARY KEY is a BTree and "clustered" with the data.  That is, the data is stored in PK order in the BTree.
InnoDB "secondary keys" and all MyISAM indexes are stored in separate BTree structures.
In the leaf node of a MyISAM index is an offset into the data file of where the entire row is stored.  In the leaf node of an InnoDB secondary index is a copy of the PRIMARY KEY column(s).
All indexes are stored "ascending" in numerical (if some numeric column) or collation (if some string type) order.
(I don't know what you mean by "logical", but maybe I answered it.)


text:
Q: Will updating a micrometer gauge ever block the calling thread? Will updating a micrometer gauge ever block the calling thread (eg perform I/O)?
I believe the answer is "no, I/O happens in a separate metrics collection thread" but would like to know of exceptions to this, edge cases, ..
Thanks
Tarik

A: It depends what do you mean by calling thread.
If you mean the user thread that registers the gauge, the answer is no, at that point the method that you feed to the gauge is not even called.
If you mean the thread that will "ship" the metrics, that will be blocked. This is usually a separate thread (since most of the registries are push based) but in case of Prometheus (which is pull-based) the gauge will block the Prometheus endpoint and the thread that serves it.
For this reason, in Micrometer, instead of registering the blocking method to the gauge, you can have an intermediate "state" object that you update periodically from a separate thread (blocking) and read it from the gauge (non-blocking), e.g.:
AtomicInteger currentValue = registry.gauge("test.gauge", new AtomicInteger(0));

And you can modify the currentValue from another thread, see the docs
You can do this with any arbitrary objects, e.g.:
State state = registry.gauge("test.gauge", Collections.emptyList(), new State(), State::getValue);

Where getValue does not block just give you the latest value while on another thread you can update the value encapsulated in the State object.
Here are a few lines showing that the method you register into the gauge is blocking:
public class GaugeSample {
    public static void main(String[] args) throws InterruptedException {
        PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
        System.out.println("registering the gauge...");
        Gauge.builder("test.gauge", GaugeSample::getValue)
                .register(registry);

        System.out.println("scraping...");
        System.out.println(registry.scrape());
    }

    private static double getValue() {
        try {
            Thread.sleep(5_000);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }

        return 42;
    }
}


text:
Q: Gradle version change I am using Gradle version 4.2.2 and  kotlin_version "1.5.20" in my kotlin android project. If i upgrade gradle in my project to 7 version, is there any problem will arise?. Since in my android studio gradle update is recommended. please anyone help me to fix this issue. I am using android studio dolphin version 2021.3.1 patch 1.
buildscript {
    ext {
        kotlin_version = "1.5.20"
        lifecycleVersion = '2.3.1'
        coroutines = '1.3.9'
        roomVersion = '2.3.0'
        nav_version = '2.3.5'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
     }
   }

    allprojects {
    repositories {
        google()
        jcenter()
        // mavenCentral()
        maven { url 'https://jitpack.io' }
    }
}


text:
Q: Plot Two Circles and color their difference I am trying to plot two circles with radius 1 and another with radius 9. Both are centered at $(0,-1)$. I then want to color in the distance between the circle of radius 9 and the circle of radius 1.
Plot[Graphics[{Blue, Circle[{0, -1}, 9]}] Graphics[{Blue, Dashed,
Circle[{0, -1}, 1]}], {x, -10, 10}, {y, -10, 10}]

I have the above, but it is wrong. I would like a graph of both with axes.
I am really trying to plot the region in the complex plane from $1< \mid(z+i)\mid \le3$, which I determined to be the two circle from above.

A: Using Region objects is overkill if your problem only entails drawing out these circles, but if you want to do further calculations with them, the approach might still interest you. Besides, it quite directly translates your question about the difference of two geometric regions into the MMA language.
DiscretizeRegion[
 RegionDifference[Disk[{0, -1}, 9], Disk[{0, -1}, 1]],
 MaxCellMeasure -> 0.01, PlotTheme -> "Polygons", Axes -> True
]

The RegionDifference region is now a fully computable geometric region, i.e. for instance you could use it as an integration domain, to solve differential equations, etc. See for instance: Derived Regions.

A: With borders:
Graphics[{LightBlue, Disk[{0, -1}, 9], Blue, Circle[{0, -1}, 9],
  Dashed, Thick, Circle[{0, -1}, 1], White, Disk[{0, -1}, 1]},
 Axes -> True]

A: Just for Fun.
The equation for a Circle with center at the origin would be
circle = r^2 == x^2 + y^2

And we can use this knowledge to plot a circle with Radius r
r = 1;
RegionPlot[r^2 > x^2 + y^2, {x, -2, 2}, {y, -2, 2}]

The equation for a Circle from the origin shifted would be
circleShifted = r^2 == (x - a)^2 + (y - b)^2

and with the Parameters given
r1 = 1; r2 = 9;
{a, b} = {0, -1};

we can plot the desired Function
RegionPlot[{r1^2 < (-a + x)^2 + (-b + y)^2 < r2^2},
{x, -12, 12}, {y, -12, 12}, Axes -> True, BoundaryStyle -> Red,
PlotStyle -> {Blue}]