text:
Q: Waiting for Variable Change Here my code snippet written in Qt.
bool myFunc()
{
  .......
  while(!tcpCommunicator->isLoginReplyExist)
  {
    qApp->processEvents(QEventLoop::AllEvents);
  }
  .......
  return tcpCommunicator->res;
}

After "isLoginReplyExist" is changed by another part of program I want to exit from loop, is there any better way to accomplish this?
Thanks.

A: if myFunc() is a method of some class (for example Class1) you can inherit this class from a QObject and define a slot:
Class1 : public QObject
{
Q_OBJECT
...
public slots:
void mySlot(bool tcpResult);
...
}

The object, which change the tcpCommunicator state (Class2) should have the signal:
Class2 : public QObject
{
Q_OBJECT
...
signals:
void tcpChangedTo(bool);
...
}

At last you should connect the signal and the slot. And so, when tcpCommunicator is changed, mySlot(bool res) is executed. If Class1 and Class2 objects are working in different threads you should use Qt::QueuedConnection type, when connecting the signal to the slot.


text:
Q: Abs. positioned element inside Button is not positioned correctly I'm trying to put an icon inside a button element and I'm getting strange positioning but in Firefox 4. Check out this demo http://jsfiddle.net/j6q2e/3/
It works as expected in Chrome and IE but in Firefox the icon is completely off the reservation. Is that a known bug? Is there a way to fix that?
(I don't want to use <a> because it's a submit button for a form and I want to keep it that way. I also would like to avoid using background-image style because the icon is in a CSS sprite image and to use as background-image I'd have to save it as a separate PNG.)

A: Just a quick update to get this thing "answered"...
So yeah, this is a bug in Firefox, and still is as of version 5. Chrome, IE9 and Opera all correctly position the icon inside the button.
There is another SO thread dealing with it and here's the Mozilla bug.

A: You should be able to keep it as a sprite and use it as a background image, just adjust the space around that image to allow for the size of your button. You might want to also consider diagonal sprites to help solve your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q:  object within SVG floats outside it's foreign object container I have an svg object im my HTML page which contains several foreign objects. All of which work as I expect them to and scale responsibly along with the svg, aside from the video element.
The video element does not respect it's container objects width/height. Neither am I able to use the default video control options, the play menu is displayed but not interactable. This problem only occurs in Chrome, Firefox displays the element as expected and the video is playable.
printscreen comparing chrome (fail) with firefox (success)
What I've already tried to solve this problem (with no success):

*

*Replace  object with iFrame (same problem)

*Use Jquery video plugin to handle CSS (like jQuery.fitvids)

*Wrap video in container div (tried position responsive/absolute/fixed/..)

*Wrap video in second foreignObject element

*Practically any possible combination for x, y, width and height on both video object as it's container. (If I use non responsive values for width and height I can position it but I need the responsiveness as it's parent can change size, also the menu to play and pause the video still won't work)

#svgContainer {
  width:500px;
  height:250px;
  background-color:#34ff00;
}

#videoTitle {
  font-size:80px;
  font-weight:bold;
}

#videoObject {
  width:100%;
  height:auto;
  object-fit:contain;
}

  <?xml version="1.0" encoding="utf-8"?>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 959.8 540">
    <g id="DIA_REGULARMEDIAVIDEO">
      <foreignObject x="50" y="25" width="655" height="69">

My video

      </foreignObject>
      <foreignObject x="0" y="120" width="959.8" height="420">
          <video id="videoObject" x="0" y="0" width="300" controls="" preload="">
          <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4"/>
          </video>
      </foreignObject>
    </g>
  </svg>


text:
Q: Updating user-level I am trying to update User-level by a simple form but it showing me undefined index and not updating the level wil anybody help me to do this?

Update User Level

<form action="" method="POST">
UserID:

<input type="text" name="upduser" maxlength="30">

Designation code:

<?php
//require 'config.php';
$options = '';
$filter=mysql_query("select`user_dsgntn_code` from `hr_user`");
while($row = mysql_fetch_array($filter)) {
    $options .="<option>" . $row['user_dsgntn_code'] . "</option>";
}
            $dropdown="<form id='designation' name='designation' method='POST' action=''>
                <select name='updlevel' onchange='showUser(this.value)'>
                  " . $options . "
                </select>
            </form>";
        echo $dropdown;
        //do_alert("$options");
        ?>

<input type="submit" value="Update Level">
</form>
<?
//require 'config.php';

if ( isset( $_POST['upduser'] ) && ! empty ( $_POST['upduser'] )&&
isset ($_POST['updlevel']));
{
$updtuser=$_POST['upduser'];
$updtlevel=$_POST['updlevel'];
$sql_upd="update `hr_user` set user_dsgntn_code='$updtlevel' WHERE user_id='$updtuser'";
$result = mysql_query($sql_upd) or die(mysql_error());
}

A: Remove the extra form around the <select>.

Update User Level

<form action="" method="POST">
UserID:

<input type="text" name="upduser" maxlength="30">

Designation code:

<?php
//require 'config.php';
$options = '';
$filter=mysql_query("select`user_dsgntn_code` from `hr_user`");
while($row = mysql_fetch_array($filter)) {
    $options .="<option>" . $row['user_dsgntn_code'] . "</option>";
}
            $dropdown="<select id='designation' name='updlevel' onchange='showUser(this.value)'>
                  " . $options . "
                </select>";
        echo $dropdown;
        //do_alert("$options");
        ?>

<input type="submit" value="Update Level">
</form>


text:
Q: Weighted sum of multiple columns in R using tidyverse I'm trying to produce a weighted sum per factor level. I have four columns of data:
col1 = surface area
col 2 = dominant
col 3 = codominant
col 4 = sub

1    2    3     4
125  A    NA    NA
130  A    NA    B
150  C    B     NA
160  B    NA    NA
90   B    A     NA
180  C    A     B

*

*If only column 2 is filled, the value gets the full amount of column 1.

*If cols 2 and 3 are filled, the value in col 1 gets split in half.

*If cols 2, 3 and 4 are filled, the value in col 1 gets split in three.

*If col 2 and 4 are filled, the value in col 1 gets divided as 75/25.

So, for the above example output, my new dataframe would be:
1    2
A    326.9
B    331.4
C    134.4

I fiddled around with ifelse and came op with something like (for two columns for this example):
     df1 <- df %>%
            mutate(weighted_dominant = ifelse(!is.na(dominant) & is.na(codominant), Surface_Area,
            Surface_Area/2),
                   weighted_codominant = ifelse(!is.na(codominant), Surface_Area/2, NA )

Now i isolate the columns of intereset:
df2 <- df1 %>% select(dominant, weighted_dominant) %>%
               group by (dominant) %>%
               summarise (sum = sum(weighted_dominant)

also perform this for the codominant column, bind the rows of the two new dataframes and do the summarise function again.
This gets the job done, but also takes like 50 lines of code and is, in my opinion, not very clean.
My question:
Are there better (tidyverse) ways to do this kind of weighted summarisation?

A: Is this what you're looking for:
# your data
df <- read.table(text = "
125  A    NA    NA
130  A    NA    B
150  C    B     NA
160  B    NA    NA
90   B    A     NA
180  C    A     B", header = FALSE)
names(df) <- c("surface_area", "dominant", "codominant", "sub")

# make a matrix out of the last 3 columns
m <- as.matrix(df[2:4])

# get a logical matrix of non-NA
x <- !is.na(m)

# calculate as follow:
# T  NA  NA  ->  1    0    0
# T   T  NA  ->  1/2  1/2  0
# T  NA   T  ->  1/2  0    1/2
# T   T   T  ->  1/3  1/3  1/3
x <- x * (1/rowSums(x))

# correct exception
# T  NA   T  ->  0.75  0  0.25
exception  <- c(dominant=0.5 , codominant=0, sub=0.5 )
correction <- c(dominant=0.75, codominant=0, sub=0.25)
x[apply(x, 1, identical, exception), ] <- correction

# multiply by surface_area
x <- x * df$surface_area

# sum by each letter
stack(tapply(x, m, sum))
#>   values ind
#> 1  327.5   A
#> 2  372.5   B
#> 3  135.0   C

The final numbers are not the same, did I understand wrong your explanation? It is not really clear to me.

A: With tidyverse you could consider the following approach.
Include row numbers as a separate column, so you can make evaluations within each row. The pivot_longer will put your data into long format.
After grouping by row number, you can determine values for A, B, and C depending on which columns are missing. This assumes there is always a "dominant" column (otherwise, you could adjust the logic here).
Then, remove your NA, and total up the weighted values for A, B, and C.
df %>%
  mutate(rn = row_number()) %>%
  pivot_longer(cols = c(dominant, codominant, sub)) %>%
  group_by(rn) %>%
  mutate(weight = case_when(
    is.na(value[name == "codominant"]) & is.na(value[name == "sub"]) ~ as.numeric(Surface_Area),
    is.na(value[name == "codominant"]) & name == "dominant" ~ Surface_Area * .75,
    is.na(value[name == "codominant"]) & name == "sub" ~ Surface_Area * .25,
    is.na(value[name == "sub"]) ~ Surface_Area / 2,
    TRUE ~ Surface_Area / 3
  )) %>%
  drop_na() %>%
  group_by(value) %>%
  summarise(total = sum(weight))

Output
  value total
  <chr> <dbl>
1 A      328.
2 B      372.
3 C      135


text:
Q: Is possible to change the type of an attribute from an arff with pyweka? I have an arff like that :
@relation 'Base de datos modelos 1 y 2'

@attribute BMI numeric
@attribute ROM-PADF-KE_D numeric
@attribute Asym-ROM-PHIR(≥8)_discr {No_Bilateral_Asymmetry,Bilateral_Asymmetry}
@attribute Asym_SLCMJLanding-pVGRF(10percent)_discr {No_Bilateral_Asymmetry,Bilateral_Asymmetry}
@attribute Asym_TJ_Valgus_FPPA(10percent)_discr {No_Bilateral_Asymmetry,Bilateral_Asymmetry}
@attribute DVJ_Valgus_KneeMedialDisplacement_D_discr numeric
@attribute Soft-Tissue_injury_≥4days {No,Yes}

@data
18.716444,33,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,0,No
22.182267,41,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,2,No
25.352783,35,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,1,No
21.332873,33,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,0,No
23.085619,25,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,3,Yes
21.428649,42,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,No_Bilateral_Asymmetry,1,No

and i want to change the numeric type of "@attribute DVJ_Valgus_KneeMedialDisplacement_D_discr" to {0,1,2,3}
Is it possible?

A: You can use the NumericToNominal filter for that purpose.
The attribute that you want to convert is the 6th one, so you need to do something like this:
import weka.core.jvm as jvm
from weka.core.converters import load_any_file, save_any_file
from weka.filters import Filter

jvm.start()
data = load_any_file("/some/where/data_in.arff", class_index="last")

f = Filter(classname="weka.filters.unsupervised.attribute.NumericToNominal", options=["-R", "6"])
f.inputformat(data)
filtered = f.filter(data)

save_any_file(filtered, "/some/where/data_out.arff")

jvm.stop()


text:
Q: I have an iPad mini 2, with ios 7.2, can i manually upgrade to 8.1.2 and still jailbreak it? I just bought my wife an iPad mini 2, ( it was still factory sealed) it has 7.2 on it and I'd  like to know if I can still update it to 8.1.2 and jailbreak it. I know downgrading from 8.1.3 can no longer be done but what about upgrading from older firmware to 8.1.2? It's this still possible even if apple is no longer signing it?
Thanks,
Ocha

A: No, you cannot. Apple is no longer signing the 8.1.2 update, as can be seen in the chart at The iPhone Wiki.

Edit: The screenshot got partially cut-off, but the upshot is that all devices that support 8.1.2 were listed under the same item, and all stopped signing on 10 February 2015.


text:
Q: Bluetooth issues with Microsoft 6000 keyboard Ubuntu 10.10 64 bit
I can't get the keyboard to connect at ALL. I've tried both the default Bluetooth install via the graphical interface and installed bluez-gnome as well.
sudo hidd --connect

sudo hidd --search hcitool scan

Doesn't work either. When doing search the keyboard is found, but won't connect.
The keyboard connects fine in Windows and OSX using the same Bluetooth USB dongle.
Update 1: I am going to try: http://www.siamnet.org/Wiki/Ubuntu-AppleBluetoothKeyboard
Will update here if any updates. If anyone has a suggestion I welcome it.


text:
Q: How to track an event that is defined using multiple variables? An app that lists events relative to user location, e.g. If user opens the app in Paris, France, it will say that there is Bolshoi Ballet event that is playing today 12:00. When user clicks on the showtime, he is taken to an external website that handles booking.
I am interested in two events:
User clicked on the event:

*

*Event name (in this example [ite], "screening-view").

*event variable associated with the screening (ite., "Bolshoi Ballet").

*date variable associated with the screening.

*time variable associated with the screening (ite., 12:00).

*location (country) variable associated with the screening (ite., Paris).

*vendor variable associated with the screening (ite., whatever external website handles booking).

User viewed event:

*

*Event name (in this example [ite], "screening-book").

*event variable associated with the screening (ite., "Bolshoi Ballet").

*date variable associated with the screening.

*time variable associated with the screening (ite., 12:00).

*location (country) variable associated with the screening (ite., Paris).

*vendor variable associated with the screening (ite., whatever external website handles booking).

I have looked into different options how to approach this requirement and the closest that I can see is using analytics.js events. However, it allows to register only one value (number) associated with the event:
ga('send', 'event', 'category', 'action', 'label', value);

From what I can tell, this cannot be used to visualise events (e.g. how many events have been viewed today) and analyse data (e.g. how many events have been "booked" where event is "Bolshoi Ballet" and country is "France").
Note, all variables (including country) are associated with event in this example, not derived values (e.g. not user country based on their IP).

A: Actually the event allows you to associate four values, since category, action and label can and should be utilized, too.
For anything else you have to set up custom dimensions. First you have to create them in the properties setting in you GA admin panel (under "custom definitions", and you probably want to go for hit scope). Then you can pass values in your event tracking calls. You have to pass them into the configuration object of the event tracking call (as opposed to set them via the set method) to make sure they are only associated with that specific event and not with all hits on that website. You do not address custom dimensons by the name you gave them in the backend (that's for the reports only) but by the string "dimension" followed by the numeric index.
ga('send', {
  'hitType': 'event',
  'eventCategory': 'screening-view',
  'eventAction': 'Bolshoi Ballet',
  'eventLabel': '2015/12/12',
  'dimension1': '10pm', // time
  'dimension2': 'Opéra national de Paris', // location
  'dimension3': 'you know, that little ticket stall close to Monmatre' // vendor
});

You only have 20 custom dimension per property in the free version of GA. And they won't show up in the standard reports (you can set them as secondary dimension, though), but you can use them in segments, in view filters and most importantly in custom reports.

A: Best way to handle this is by using event based analytics tool such as: Mixpanel.com , Kilometer.io or Kissmetrics.
Tacking an event(with an array of key:value metadata) is exactly what those tools were designed to do.


text:
Q: How to timeout in DOORS DXL? The want the execution to stop for example 5 seconds and then resume execution. the code below seems to be fine but it's not working. It executes directl, it doesn't wait. Can please someone help?
sleep_(50)
string out=""
print win32SystemWait_("cmd.exe /C echo hallo", out, -1)
print "Output :" out

A: Okay I found an answer my code is correct.
The thing is void sleep_(int milliseconds)


text:
Q: call controller method from directive when I am using controller of directive also. I have a directive and now I want to send same data to other controller's methods and this controller is totally independent of this directive. this other controller is actually resides out the current directory.
How can I do this in angularjs?

A: Create an angular service and inject in both the controllers. Update a variable in that service from controller 1 and retrieve in controller 2. Something like this -
myApp.factory('myFactory', function () {
    // declare and store the value in a local variable here
    var prop = '';

    return {
        getProperty: function () {
            return prop;
        },
        setProperty: function(value) {
            prop = value;
        }
    };
});

function Ctrl1($scope, myFactory) {
    myFactory.setProperty('myValue');
}

function Ctrl2($scope, myFactory) {
    val = myFactory.getProperty();
}

An angular service is a Singleton, so it maintains the state throughout the code.

A: In angularjs there is an idea about directive scope.It lets you to use data for directive with 3 ways.
1) string @
2) biDirectional =
3) functional &
I think you have heard about these.This link maybe can help you.
https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object


text:
Q: How to activate the buttons in a Tableview of BSP application (SAP) In a Bsp application i need to activate and make these buttons of a tableview work,currently the buttons are present and part of the layout, but they dont work,anyone has any idea how i could make them work?The buttons that i need to activate are maximize,minimize,standard etc.
Thanks in advance,
Shamiron

A: Check the code for button, there itself you can resize the button
<Input Type = 'Submit'  ... >

I think in that you didnt mention event handler tab section.
<input type=submit name="onInputProcessing(back)" value="home">


text:
Q: Play .mxf files in browser (chrome, Firefox, Edge, ect.) I am trying to create a website that should display videos stored on a server accessable trough a database.
The videos are storaged as .mxf files and are quite large and high quality.
I am not able to convert the files to MP4 which would solve the issue since i could use HTML5 video to display them.
I need to be able to pause/play, jump to different parts of the videos, change volume and all that as well.
I have tried to find a player that allows me to do this for some time now but have not found one. Does any body know if there is a player that requires no installation client side and can play the .mxf files in browser? Or if there is any way i can create the functionallity myself?


text:
Q: Cancelled SQL Server delete statement in the middle of running on server A delete statement was accidentally ran, but cancelled within a few seconds by a programmer in sql server management studio.  Is it possible to know what records were deleted and to recover them?  This is for sql server 2008.

A: Contact your dba, to recover the data. You can see the last executed queries, but you will need elevated access to run this statement:
SELECT  O.Name, o.type_desc, ps.last_execution_time
FROM sys.dm_exec_query_stats AS PS
CROSS APPLY sys.dm_exec_sql_text(PS.sql_handle) t
INNER JOIN sys.sql_modules as M
ON M.object_id = t.objectid
INNER JOIN sys.objects as O
ON M.object_id = o.object_id
order by ps.last_execution_time desc;

You can also try to look for it in the cache using this: sys.dm_exec_cached_plans


text:
Q: C# Value from another List linked to value I am trying to get the productname from the List where it matches the Productid from the List using LINQ but I have no luck.
The ProductID is in both lists and It should be linked somehow.
I tried:
Product product = products.FirstOrDefault(x => x.ProductName == orderDetail.ProductID);

        List<orderDetail> orderDetails = Database.getOrderDetails();
        List<Product> products = Database.getProducts();

        textBox1.Text = Convert.ToString(orderDetail.OrderID);
        textBox2.Text = Convert.ToString(Productname);
        textBox3.Text = Convert.ToString(orderDetail.UnitPrice);
        textBox4.Text = Convert.ToString(orderDetail.Quantity);
        textBox5.Text = Convert.ToString(orderDetail.Discount);

A: I think you want something like this, but it's not very clear how your Product and Order objects are structured.  (You'll also probably want some null checks.)
OrderDetails orderDetails = Database.GetOrderDetails().First();
List<Product> products = Database.GetProducts();

var name = products.First(p => p.ProductID == orderDetails.ProductID).ProductName;

A: Why matching x.ProductName with orderDetail.ProductID here: Product product = products.FirstOrDefault(x =>  == orderDetail.ProductID);?
If you're trying to get the product of the list with products, that matches the ProductID of your orderDetail, you'll just have to do it like that:
Product product = products.FirstOrDefault(x => x.ProductID == orderDetail.ProductID);

If, of course, both Product and the class of your orderDetail object have the same .ProductID property.
Or I've missunderstood something?

A: Modify the earlier query, I quess you need the results as follows.
         This query would return all the product names whose productid exists in both the list.
         There are two ways we can achieve this results set.
List<orderDetail> orderDetails = Database.getOrderDetails();
List<Product> products = Database.getProducts();

// This is a SQL like query
var productNames =  from ord in orderDetails
join pr in products
on ord.ProductID equals pr.ProductID
select pr.ProductName;

Alternativey, You can also use `Join()`

//This is extention method query
var productNames = orderDetails.Join(products,
ord => ord.ProductID,
                       pr => pr.ProductID,
(orderdetail, productdetail) =>  productdetail.ProductName);


text:
Q: rails - printing text using iteration I am trying tp print a non updateable value in my  page.
So far it displays
<%= f.fields_for :ingredients do |builder| %>
 <fieldset>
    <%= builder.text_area :name %>
 </fieldset>
<% end %>

which works and I need it to display a non updatable - plain text. So I tried to do
Option 1
<%= f.fields_for :ingredients do |builder| %>
 <fieldset>
    <%= builder.label :name, "Ingredients" %>
 </fieldset>
<% end %>

But no success. this does work:
option 2
<% @recipe.ingredients.each do |ingredient| %>
   <%= ingredient.name %>
<% end %>

What is the main difference between option 1 and 2  ? I prefer using option 1 with the
 tag. what am I doing wrong?

A: Label is used to create a label for a field, and not meant to show its value. Option 2 is exactly how you would display the contents of the name field. Option 1 style of formatting is to show the literal 'Ingredients' instead of 'name'. Ususally, that would be followed by <%= builder.text_area :name %>.
Another possible inconsistency: @recipe.ingredients is an array, so there is no field called ingredients.name. As a test, try ingredients[0].name.
So in option 1, try:
<% ingredient = @recipe.ingredients[0] %>
<%= f.fields_for :ingredient do |builder| %>
 <fieldset>
    <%= builder.label :name, "Ingredients" %>
 </fieldset>
<% end %>

If that printed the label 'Ingredients', then you could print the list of ingredients with:
Ingredients:
<% @recipe.ingredients.each do |ingredient| %>
   <%= ingredient.name %>
<% end %>


text:
Q: Getting line of best fit in scatterplot using Mtcars example Hello how do you get the line of best fit on the Weight vs Milage scatterplot? even though they are kinda dispersed. Below are my codes:
plot(x = mtcars$wt,y = mtcars$mpg,
     xlab = "Weight",
     ylab = "Milage",
     xlim = c(2.5,5),
     ylim = c(15,30),
     main = "Weight vs Milage")

A: Since you're working with base R's plot, you can do:
plot(x = mtcars$wt,y = mtcars$mpg,
 xlab = "Weight",
 ylab = "Milage",
 xlim = c(2.5,5),
 ylim = c(15,30),
 main = "Weight vs Milage")
abline(lm(mpg ~ wt, data = mtcars), col = "red")

Explanation: lm(mpg ~ wt, data = mtcars) regresses mpg on wt in a simple linear model; abline can take lm return objects as input to draw the regression line.

A: library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  stat_smooth(method = "lm", col = "red", se = F)


text:
Q: Laravel copy record and duplicate with new values But not with unique field I want to duplicate my records with a new value.
I am using these codes and they are working well with unique field (id).
$task = tableName::find($request->id);
    $newTask = $task->replicate();
    $newTask->newField= 2;
    $newTask->save();

My table looks like :

id
no
first
second
newField

1
45
1000
650
1

2
52
4500
45
1

3
45
1250
75
1

4
58
7500
86
1

5
45
250
72
1

i want to duplicate all my rows with a new value. Just newField must be 2.

A: You need to fetch all records against a specific no. Try something like this
$tasks = tableName::where('no',$request->id)->where('newField',1)->get();
foreach($tasks as $task)
{
    $newTask = $task->replicate();
    $newTask->newField= 2;
    $newTask->save();
}

Please check official documentation as well.


text:
Q: Spring Data Rest Unit Tests Selectively Pass I am investigating the use of Spring Data Rest (2.0.1.RELEASE and Spring 4.0.2.RELEASE), and have written a simple service. I have also written a simple test class (see below) using DbUnit.
Unfortunately when I run the tests only the findAll method passes. If I comment out the findAll method then the findInvestigationalProductById passes and directLink fails. If I then comment out findInvestigationalProductById then directLink passes.
None of these methods changes data state, so I would like to know if there is some configuration I have overlooked that can cause this behaviour.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/com/perceptive/ctms/core/tests-context.xml"})
@WebAppConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
                          DbUnitTestExecutionListener.class })
@DatabaseSetup("investigational-products-data.xml")
public class InvestigationalProductTests {
  private MockMvc mockMvc;

  @Autowired
  private WebApplicationContext wac;

  @Before
  public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void findAll() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/investProduct"))
      .andExpect(status().isOk())
      .andExpect(content().contentType("application/hal+json"));
    resultActions.andExpect(jsonPath("$_embedded.investigationalProduct", hasSize(3)));
    resultActions.andExpect(jsonPath("$_embedded.investigationalProduct[0].investigationalProductCode", is("ACTIVE1")));
    resultActions.andExpect(jsonPath("$_embedded.investigationalProduct[1].investigationalProductCode", is("ACTIVE2")));
    resultActions.andExpect(jsonPath("$_embedded.investigationalProduct[2].investigationalProductCode", is("ACTIVE3")));
  }

  @Test
  public void directLink() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/investProduct/3"))
      .andExpect(status().isOk())
      .andExpect(content().contentType("application/hal+json"));
    System.out.println(resultActions);
    resultActions.andExpect(jsonPath("$investigationalProductCode", is("ACTIVE3")));
  }

  @Test
  public void findInvestigationalProductById() throws Exception {
    ResultActions resultActions = mockMvc.perform(get("/investProduct/search/findInvestigationalProductById?id=3"))
      .andExpect(status().isOk())
      .andExpect(content().contentType("application/hal+json"));
    resultActions.andExpect(jsonPath("$_embedded.investigationalProduct", hasSize(1)));
    resultActions.andExpect(jsonPath("$_embedded.investigationalProduct[0].developmentName", is("developmentName3")));
  }
}

A: This is a misunderstanding about how @DatabaseSetup works. The problem tests are all dealing with referencing data by a generated id. The API states:

Test annotation which indicates how to put a database into a know
  state before tests are run. This annotation can be placed on a class
  or on methods. When placed on a class the setup is applied before each
  test methods is executed.

which to my mind is a little ambiguous, but additional documentation states:

By default setup will perform a CLEAN_INSERT operation, this means
  that all data from tables referenced in the DataSet XML will be
  removed before inserting new rows.

i.e. tests should not assume that the database (including any sequence numbers) is put into a clean state, just that the data is clean.
Adding the following code
  private static int currentOffset = 0;
  private static final int TEST_OFFSET = 3;

  /**
   * After each test is run DatabaseSetup annotation deletes records
   * and inserts fresh ones - this means we need to keep track of the
   * current offset
   */
   @After
   public void offset() {
     currentOffset += TEST_OFFSET;
   }

(with occasional modifications to currentOffset when testing inserts) can keep track of the current ids.
This does not seems ideal, but I do not know a way of resetting the database to a truly clean state.


text:
Q: Driver has null value when using Page object patter design Driver has a null value when i get the value from a BasePage attribute:

    public abstract class BasePage
    {
        public static IWebDriver Driver { get; }
        public BasePage(IWebDriver driver)
        {

        }
    }

Driver  instance is created in a different class

    [Binding]
    public class WebDriverSupport
    {
        private readonly IObjectContainer objectContainer;
        private ChromeDriver webdriver;

        public WebDriverSupport(IObjectContainer objectContainer)
        {
            this.objectContainer = objectContainer;
        }

        [BeforeScenario]
        public void InitializeWebDriver()
        {
            this.webdriver = new ChromeDriver();
            objectContainer.RegisterInstanceAs<IWebDriver>(webdriver);
        }
    }

I think that i'm getting the value before instance start. what do you say?
As all callses use Base class this my be a problem.

A: I resolved this by:
1 add set to property
 public static IWebDriver Driver { get; set; }

2 -  pass the driver id  to BasePage.Driver
     public void Initialize()
        {
            this.webdriver = new ChromeDriver();
            BasePage.Driver = webdriver;
            objectContainer.RegisterInstanceAs<IWebDriver>(this.webdriver);
        }


text:
Q: MySql | How to compute this I have this table
Grade        Lec         Lab
1.5           3           0
1.5           3           0
1.5           2           1

The formula will be like this
1.5 * 3
1.5 * 3
1.5 * (2+1) = 13.5 / 9 = 1.5

13.5 is the total then 9 is the total sum of the lec + lab
What query should I use?
How can i add this to query WHERE Lec + Lab = 15. If lec + lab is 15 above will show but if lower than 15 it will not show then i want to limit the show in 20

A: SELECT SUM(Grade * (Lec + Lab)) / SUM(Lec + Lab) FROM t;

| SUM(Grade * (Lec + Lab)) / SUM(Lec + Lab) |
| ----------------------------------------: |
|                                       1.5 |

db<>fiddle here

A: using the previous answer
you can use a subquery to achieve the additional filter
select grade from (select sum(grade * (lec + lab)) / sum(lec + lab) from t) as final where grade >= 15

or
just use having
SELECT (SUM(Grade * (Lec + Lab)) / SUM(Lec + Lab)) as grade FROM t having grade >= 15;
in addition, you can use
grade * (
case
 when Lec > 0 then Lec + Lab
 when Lec < 0 then Lec - Lab
 else Lec
end )
you can read about having clause here


text:
Q: How to trigger Django signals only once on multiple receivers I am looking for a way to do the following (keep in mind, if this is not possible with signals, I'm happy if you know any alternatives)
But let's say we have a signal defined as follows:
from django.dispatch import receiver

@receiver(post_save, sender=Model1)
@receiver(post_save, sender=Model2)
@receiver(post_save, sender=Model3)
def my_signal_handle(sender , **kwargs)
    # some code here

Now, all 3 models (Model1, Model2, Model3) are related. So when creating a new resource, one can provide all informations, which results in all 3 tables being saved with a new row. I would love to only trigger my_signal_handle once in that case. So basically per transaction.
Also, when updating for example, one could only update, let's say Model3, and in that case I still want this signal to run.
So goal is -> No matter how many models are affected, I want to run this signal once.
Hope it makes sense, happy to clarify better if needed. I was looking at adding a signal per transaction or something, but couldn't find exactly what I need.


text:
Q: Exceeding memory issues on server using PHP PHP has memory limits set at a global level in the PHP.ini file. I also know that they can be configured at the local level.
Our memory limit for a query is set to 132MB, but we keeping getting errors like this:
Fatal error: Allowed memory size of 161480704 bytes exhausted (tried to allocate 32 bytes) in #{removed_file_path}/script.php on line #{line}

Currently, we are monitoring our systems through an errror log file, that caches errors while users are browsing a page, as well as using cron; however, these don't get logged anywhere.
The error can be fixed by changing any calls to mysql_query to mysql_unbuffered_query, however I need to know where this needs to be changed for all files on the server. If the script is actually not having memory issues, then I don't want to change the code since I want the server to read the results to RAM wherever possible.
We don't want to increase our memory limit in PHP since our host advises us against that.
What can be done to fix the memory issues? We are running on CentOS 6.7.


text:
Q: Wrong result in a simple ipython script I defined a simple function that operates on 1st and 3rd rows of a 3x3 matrix:
In [1]: from numpy import *
     from sympy import Symbol

In [2]: def ifsin(mat):
     mat[2,:]+=1
     mat[0,:]=mat[0,:]/pow(mat[2,:],mat[2,:]>0)
     return mat

In [3]:Ay=Symbol('Ay')
     By=Symbol('By')
     q=array([[Ay,-10 ,By],[0,0.4,1],[-1 ,-1, -1]])
     q

Out[3]:

 array([[Ay, -10, By],
        [0, 0.4, 1],
        [-1, -1, -1]], dtype=object)

In [4]:V=ifsin(q)
        q

Out[4]: array([[Ay, -10.0, By],
        [0, 0.4, 1],
        [0, 0, 0]], dtype=object)

Why was updated 3rd row of matrix q?
Also if I eval following:
In [5]:M=ifsin(V)
       q

Out[5]: array([[Ay, -10.0, By],
            [0, 0.4, 1],
            [1, 1, 1]], dtype=object)

Again 3rd row of q is updated!!
I tried this script on "Computable" (ipad app) and ipython notebook on ubuntu 14.04 (python 2.7.6) with the same results
Thanks in advance for your help.
updated…
I changed my function to:
def ifsin(m):
  return vstack([m[0,:]/pow(m[2,:]+1,(m[2,:]+1)>0),m[1,:],m[2,:]+1])

And now all works fine. Thanks!!

A: You are literally asking for that update on this line:
mat[2,:]+=1

In numpy syntax, this means "update row 2 of the array named mat by incrementing each value by 1".


text: Q: E and B field from Time Varying Current How would I go about calculating the B field and E field from a time varying current charging a capacitor. Theoretically I feel like a solution should exist, but there seems to be a dependence between the two fields that is recursive, the change in the E field makes a change in the B field, but that makes a change in the E field... How do you solve this?q


text:
Q: Coefficients and Derivatives of Polynomials, and Solving $f' = f$ Hi so I have been spending a long time trying to figure these two problems out,
1) Make up a few polynomials, express them as polynomials in $x-2$ and show that the coefficients are related to the derivatives at $2$.
2) Show that the only functions $f$ with $f' = f$ are $f(x) = e^x$
I think that for the first one I'm supposed to use some polynomials as an example to prove something, but I don't know how. And for the second one I believe I need to show constant multiples of $e^x$

A: 1
\begin{alignat}{4}
f(x) &= b_0 + &b_1(x-2) + &b_2(x-2)^2 &+ \cdots + &\,b_n(x-2)^n &\qquad f(2) &= b_0\\
f'(x) &= &b_1 + &2b_2(x-2) &+ \cdots + &\,nb_n(x-2)^{n-1} &\qquad f'(2) &= b_1 \\
f''(x) &= &  &2b_2 &+ \cdots + &\,n(n-1)b_n(x-2)^{n-2} &\qquad f''(2) &= 2b_2 \\
\end{alignat}
The idea is, every time you differentiate, you get rid of the constant term, and every other term's degree is decremented by 1. When you plug in $2$, all the non-constant terms evaluate to $0$, so you are left with a constant term that is the result of the repeated differentiation of a single term. In general:
$$ f^{(m)}(2) = m! \cdot b_m $$
This is the essence behind Taylor polynomials. I recommend looking into it.
2
If we have a function $f(x)$ such that:
$$ f'(x) = f(x) $$
We see that:
\begin{align*}
\frac{d}{dx}\left[f(x)e^{-x} \right] &= \frac{d}{dx}\left[f(x)\right] \cdot e^{-x} + f(x) \cdot \frac{d}{dx}e^{-x} \\
&= f'(x)e^{-x} -f(x)e^{-x} \\
&= e^{-x}\left[f'(x)-f(x) \right] \\
&= e^{-x} \cdot 0 \\
&= 0
\end{align*}
Therefore, $f(x)e^{-x}$ is constant, meaning $f(x) = c e^{x}$ for some constant $c$.

A: The $2$nd part will be functions of the form $ce^x$ for any real constant $c$.
It's equivalent to solving the differential equation $dy/dx=y$.


text:
Q: Enforcing Java Security Policy based on signedBy I'm trying to enforce a security policy, giving Java classes signed by a certain signer certain permissions. My security policy file looks as following:
// ========== SYSTEM CODE PERMISSIONS =========================================
grant codeBase "file:${java.home}/conf/*" {
        permission java.security.AllPermission;
};

// These permissions apply to all shared system extensions
grant codeBase "file:${java.home}/jre/lib/ext/*" {
        permission java.security.AllPermission;
};

// These permissions apply to all shared system extensions
grant codeBase "file:${java.home}/lib/ext/*" {
        permission java.security.AllPermission;
};

// ========== CLASS PERMISSIONS =========================================
keystore "file:/C:/Program Files/Java/openjdk-12/lib/security/cacerts";
keystorePasswordURL "file:/C:/Shared/Team/java-jar-signed/keystore.password";
grant signedBy "mycompany" {
    permission java.security.AllPermission;
    permission java.io.FilePermission "C:\\*", "read,write,execute";
    permission java.io.FilePermission "C:\\", "read,write,execute";
};

The Keystore cacerts contains a certificate with the alias mycompany. The JAR file im testing the security policy with has been signed with the private key of that certificate. When I execute the JAR file with
java -Djava.security.manager -Djava.security.policy=rules.policy -Djava.security.debug=access -cp ReadC-signed.jar ReadC

I get
access: access denied ("java.io.FilePermission" "C:\" "read")

When I use codeBase "path/to/jar" instead of signedBy "mycompany" it works perfectly fine. Does anybody know what could be going wrong here?


text:
Q: LNK error 2001 while building wpa_supplicant I am trying to build wpa_supplicant application on Windows using VS2005. When I build it, I am getting a Link error:
------ Rebuild All started: Project: wpa_cli, Configuration: Release Win32 ------

Deleting intermediate and output files for project 'wpa_cli', configuration 'Release|Win32'

Compiling...
wpa_ctrl.c
wpa_cli.c
os_win32.c
common.c

Linking...

wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_init
wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_unregister_read_sock
wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_register_timeout
wpa_cli.obj : error LNK2001: unresolved external symbol _edit_redraw
wpa_cli.obj : error LNK2001: unresolved external symbol _edit_init
wpa_cli.obj : error LNK2001: unresolved external symbol  _eloop_register_read_sock
wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_destroy
wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_terminate
wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_register_signal_terminate
wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_run
wpa_cli.obj : error LNK2001: unresolved external symbol _eloop_cancel_timeout
wpa_cli.obj : error LNK2001: unresolved external symbol _edit_deinit
wpa_cli.obj : error LNK2001: unresolved external symbol _edit_clear_line

D:\Interworking\wpa_supplicant-1.0.tar\wpa_supplicant-1.0\wpa_supplicant-1.0
\wpa_supplicant\vs2005\Release\wpa_cli.exe : fatal error LNK1120: 13 unresolved externals

I have given additional Include directories where eloop_init, eloop_unregister_read_sock etc.. defined.

A: Another common question:
In addition to the additional include directories(so your code can compile), you should also add the linked libraries(so your code can link): It should be in

Project properties/Configuration properties/Linker/Input/Additional
  Dependencies

In VS2010, it would be like:

Other versions of Visual Studio should be similar.


text:
Q: Flag or review a bounty award / Chronological vs Undefined-basis of granting bounties? This example (which in the name of transparency, happens to involve a question to which I provided an answer) - closely matched, if not directly inspired, influenced, or otherwise made obvious - the bounty-granted solution...  However, it was posted almost a week prior to the "winning" answer...
Is there any mechanism to ensure that early-posters to such bountiful questions are not clobbered in latter days by "me-too's", "oh yeah and this too's", along with several other elaborations of varying usefulness to the original solution?
Granted, in this case, I have benefited from 4x the up votes for my answer, but it raises the question of limited accountability by the bounty-setter as to who receives the final reward.  Is there any peer-type review process or flagging system for the choice of bounty-awardee?
If not, it would seem that the current system has the unfortunate effect of de-incentivizing early posts to such questions, for the fear that any effort put forth will simply be usurped by opportunists later in the course of the week.
Running Android apps on web browser

A:
it would seem that the current system has the unfortunate effect of de-incentivizing early posts to such questions

This is absolutely correct.  My experience is that placing a bounty on a question most frequently gives you answers in the last few days - not the first several.
One way to overcome the problem, as a bounty-awarder
However, even if the bounty period is short, later answers will take advantage of earlier answers.  Take, for example, my latest attempt to get quick answers to difficult problems:
Fast method to copy memory with translation - ARGB to BGR
I'm offering four 500 point bounties (2,000 rep total) to the best answers.
As you can see, the latest answer takes points from several existing answers and compares them so it's easier to determine the performance difference - something that particular user might not have been interested in doing, or perhaps even able to do, without viewing the answers already in place.
Now, I'm going to be particular in awarding my bounties so that all the major contributors are awarded as promised.
However, that's not the case with regular bounty problems.  Frankly I'm not sure there's a good solution - in the same way that the fastest answer gets a bump (fgitw) for normal questions, the slowest answer (scite) often wins the bounties.
Conscientious bounty awarders spend time carefully evaluating all the answers, and many do take into account the earlier answers, however, as your example demonstrates, the later answer which builds on your answer is arguably better.
Options for bounty-hunters
My experience, though, is that your time is better spent on regular questions during the 7 day waiting period for a bounty than on the bounty itself.  If you spend an hour you [i]might[/i] get the bounty.  If you spread that hour across 5-6 questions, you are much more likely to get the same 50-100 points that you might get on the bounty.
I only attempt bounties that I know so well, that I don't need references to provide a comprehensive answer.
Further, contrary to the problem you describe in the OP, I try to answer early - first, there's less competition, and second if you get a uber-comprehensive answer in early, very few people will attempt to try to best it, since it already includes most of the angles they might approach, and theirs would obviously be duplicate work.
Conclusion
So, yes, it is a problem.  No, there is no solution that can be technically implemented.  Yes, there are some strategies that work - either answer late and enhance other contributions, or answer early with so much firepower no one else will touch it.


text:
Q: Spring security - oauth2 resource server tests I am having some problems when testing an oauth2 resource server using @WebMvcTest and the POST HTTP method.
I always receive a 403 status code when I don't send the csrf token, even though the token is not required when I am using a bearer token.
Here is the POST method that I want to test.
@PostMapping("/message")
public String createMessage(@RequestBody String message) {
    return String.format("Message was created. Content: %s", message);
}

Here is my security config:
http.authorizeRequests(authorizeRequests -> authorizeRequests
   .antMatchers("/message/**")
   .hasAuthority("SCOPE_message:read")
   .anyRequest().authenticated()
).oauth2ResourceServer(oauth2ResourceServer ->
    oauth2ResourceServer
    .jwt(withDefaults())
);

I am following the tests provided in the samples of spring-security.
The following test was supposed to pass but it fails because the csrf token is not sent in the request.
mockMvc.perform(post("/message").content("Hello message")
    .with(jwt(jwt -> jwt.claim("scope", "message:read")))
    .andExpect(status().isOk())
    .andExpect(content().string(is("Message was created. Content: Hello message")));

When I add the csrf token to the request, the test passes:
mockMvc.perform(post("/message").content("Hello message")
    .with(jwt(jwt -> jwt.claim("scope", "message:read")))
    .with(csrf()))
    .andExpect(status().isOk())
    .andExpect(content().string(is("Message was created. Content: Hello message")));

When I run the application, there is no need to send a csrf token in the POST request.
I have forked the Spring Security GitHub repository and the project with this failing test is available at this link.
Is there a way for me to configure my tests so I don't need to send the csrf token in the POST request?

A: In order for the CSRF filter to detect that you are using a JWT token, you will need to include the JWT token in your request as an Authorization header, or as a request parameter.
The tests that you have mentioned have a mock JwtDecoder, which means you can use any string as your token and mock the decoded value.
Your test would then become:
Jwt jwt = Jwt.withTokenValue("token")
        .header("alg", "none")
        .claim("scope", "message:read")
        .build();
when(jwtDecoder.decode(anyString())).thenReturn(jwt);
mockMvc.perform(post("/message")
        .content("Hello message")
        .header("Authorization", "Bearer " + jwt.getTokenValue()))
        .andExpect(status().isOk())
        .andExpect(content().string(is("Message was created. Content: Hello message")));

If you are not mocking the JwtDecoder then you would need to retrieve a valid bearer token and pass that in the Authorization header.

A: First with Bearer access-token, you might be able to disable sessions (STATELESS session-management), and, as so, CSRF protection (CSRF attack vector is session).
Second there is a .csrf() MockMvc request post-processor which would simulate the CSRF token if you want to keep cessions (and CSRF protection).
Last, what jwt() request post-processor does is configuring directly the security context with a JwtAuthenticationToken instance, not creating a valid JWT token set as Bearer access-token. With MockMvc, Authorization header is not decoded nor converted to an Authentication instance. => What you should set before MockMvc request execution for your test to pass are authorities, not scope claim:
.with(jwt(jwt -> jwt.authorities(List.of(new SimpleGrantedAuthority("SCOPE_message:read")))))

Note that you could also simply decorate your test function with:
@WithMockJwtAuth("SCOPE_message:read")

From this lib I maintain


text:
Q: Error when creating custom module for ejabberd I'm having problems while trying to create custom modules for ejabberd.
Using:
ejabberd 19.05.81 (from source)
ubuntu server 18.04
I created the hello_world module following the tutorial from
https://docs.ejabberd.im/developer/extending-ejabberd/modules/
I tried putting the source file mod_hello_world.erl inside the src folder and then compiled using make install. Everything goes smoothly, but if I add the module on ejabberd.yml then start the node, I get a crash:
19:59:43.683 [critical] Failed to start ejabberd application: Invalid value of option modules: 'mod_hello_world' is not a ejabberd module
I tried using the folder $HOME/.ejabberd-modules/sources and the command ejabberdctl module_install mod_hello_world, and when checking if it was installed using modules_installed, it is there.
Still, I get the same error, described above.
Does anyone knows what I'm doing wrong?

A:
I tried putting the source file mod_hello_world.erl inside the src
  folder and then compiled using make install. Everything goes smoothly,
  but if I add the module on ejabberd.yml then start the node, I get a
  crash:

Problem confirmed. Since a recent commit, gen_mod requires the ejabberd modules to export four functions. The documentation page you found with the mod_hello_world source code isn't yet updated, so ejabberd complains that it doesn't recognize the erlang module as an ejabberd module. Thanks for mentioning it!
I've updated the documentation source code, but I guess will not be updated online since the next release. This updated source code works correctly, please try it:
-module(mod_hello_world).

-behaviour(gen_mod).

%% Required by ?INFO_MSG macros
-include("logger.hrl").

%% gen_mod API callbacks
-export([start/2, stop/1, mod_options/1, depends/2]).

start(_Host, _Opts) ->
    ?INFO_MSG("Hello, ejabberd world!", []),
    ok.

stop(_Host) ->
    ?INFO_MSG("Bye bye, ejabberd world!", []),
    ok.

depends(_Host, _Opts) ->
    [].

mod_options(_Host) ->
    [].


text:
Q: How can i reverse numbers with loop I trued to use my code that was written in c++ to output reversed number with while loop and i got output of "Infinity"
Can somebody explain why it happened and is there any other method to make it with loop instead of split().reverse().join()
Here is my code:
var n = 352, reverse = 0, remainder;

while (n>0) {
    remainder = n%10;
    reverse = reverse * 10 + remainder;
    n = n / 10;
}

console.log(reverse);

A: The only missing term is rounding of the number to nearest integer.
Here is updated code.
var n = 352, reverse = 0, remainder;

while (n>0) {
    remainder = n%10;
    reverse = reverse * 10 + remainder;
    n = Math.floor(n / 10);
}

console.log(reverse);

A: Use:
 n = parseInt(n / 10);

instead of
 n = n / 10;


text:
Q: Need a hint: prove that $[0, 1]$ and $(0, 1)$ are not homeomorphic I need a hint: prove that $[0, 1]$ and $(0, 1)$ are not homeomorphic without referring to compactness. This is an exercise in a topology textbook, and it comes far earlier than compactness is discussed.
So far my only idea is to show that a homeomorphism would be monotonic, so it would define a poset isomorphism. But the can be no such isomorphism, because there are a minimal and a maximal elements in $[0, 1]$, but neither in $(0, 1)$. However, this doesn't seem like an elemenary proof the book must be asking for.

A: Let $f:[0,1]\to (0,1)$ be a homeomorphism. Let us suppose, for a contradiction, that $f$ is not monotonic. In particular, either there exists:
(1) $a<b<c$ with $f(a)<f(b)$ and $f(b)>f(c)$
                    or

(2) $a<b<c$ with $f(a)>f(b)$ and $f(b)<f(c)$.
Let us consider case (1) without loss of generality.
Exercise 1: Prove that the image of $(a,c)$ under $f$ is not open in $(0,1)$. In particular, we have a contradiction and $f$ must be monotonic.
Let us assume without loss of generality that $f$ is monotonically increasing.
Exercise 2: Prove that $f$ is not surjective. In particular, we have a final contradiction.
Therefore, $f$ is not a homeomorphism.
The following exercises are relevant:
Exercise 3: Prove that there is a continuous surjection $f:(0,1)\to [0,1]$. Do you think that there is a continuous surjection $f:[0,1]\to (0,1)$?
Exercise 4: Does there exist a surjective open map (i.e., open sets are mapped to open sets) $f:[0,1]\to (0,1)$. Do you think that there is a surjective open map $f:(0,1)\to [0,1]$?
Exercise 5: Find an example of a continuous bijection between topological spaces that is not a homeomorphism.

A: Here's a hint.  If $X$ and $Y$ are homeomorphic (via $f$) then $X \setminus \{x\}$ and $Y \setminus \{f(x)\}$ (subspace topologies) are homeomorphic via the restriction of $f$, for any $x \in X$.

A: $\text{id}_{(0,1)}$ has no maximum (easy)
Every continuous function $f$ on $[0,1]$ has a maximum, otherwise pick $x_n$ such that $f(x_n)>\text{sup}f([0,1])-\frac{1}{n}$ for all $n$. Then Bolzano-Weierstraß does it.

A: There is no continuous and bijective function $f:(0,1) \rightarrow [0,1]$. In fact, if $f:(0,1) \rightarrow [0,1]$ is continuous and surjective, then $f$ is not injective, as proved in my answer in Continuous bijection from $(0,1)$ to $[0,1]$.  This is a consequence of the intermediate value theorem, which is a theorem about connectedness. Are you allowed to use that?


text:
Q: Some HTTPS connections via NAT fail, but work on firewall itself I am having trouble establishing some HTTPS connections from internal machines, even though these same connections work if initiated on the firewall itself.
The firewall machine is running Ubuntu 10.04.1 and shorewall 4.4.6.  The internet connection is Bell PPPoE DSL (in Canada).  I have tried various MTU settings, it doesn't seem to make any difference.  Other protocols (HTTP, FTP, etc) generally work.
The problem seems to be limited to certain sites; this one never works from an internal machine, but always works from the firewall itself:
From internal machine:
$ wget https://images.fedex.com/images/ascend/shared/headers/nxgen/corp_logo.gif
--2011-01-13 20:51:31-- https://images.fedex.com/images/ascend/shared/headers/nxgen/corp_logo.gif
Resolving images.fedex.com... 184.24.96.69
Connecting to images.fedex.com|184.24.96.69|:443... connected.
^C

From firewall:
$ wget https://images.fedex.com/images/ascend/shared/headers/nxgen/corp_logo.gif
--2011-01-13 20:58:28-- https://images.fedex.com/images/ascend/shared/headers/nxgen/corp_logo.gif
Resolving images.fedex.com... 184.24.96.69
Connecting to images.fedex.com|184.24.96.69|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 840 [image/gif]
Saving to: `corp_logo.gif'
2011-01-13 20:58:28 (149 MB/s) - `corp_logo.gif' saved [840/840]

This URL always works from both internal and firewall:  https://encrypted.google.com/images/logos/ssl_logo_lg.gif
Any troubleshooting tips would be greatly appreciated!

A: While MTU changes on the firewall (PPPoE settings) never had any effect, reducing MTU on client machines solves the problem.  1500 -> 1454 and it works beautifully.


text:
Q: Inheritance in Laravel Language Files I need a hierarchical structure for my language files in laravel. Imagine that I have following language file for /resources/lang/en/entity.php
<?php

return [

    'show' => 'Show Item',
    'view' => 'View Item',
    'edit' => 'Edit Item',
    'create' => 'Create a new Item',

];

Now I need a new file for post entity at /resources/lang/en/post.php but I don't want to copy all texts from entity.php file into the new file. I just need to change create message for the new entity. Something like following.
<?php

return [

    // Inherit the rest of texts from entity.php
    'create' => 'Create a new Blog Post',

];

Is there anyway to achieve this?
Thank you all in advanced.

A: If you insist on to have something like inheritance behavior in your language files, as first solution that it comes in my mind is using to array_merge method:
// entity.php
return [
    'show' => 'Show Item',
    'view' => 'View Item',
    'edit' => 'Edit Item',
    'create' => 'Create a new Item',
];

// post.php
$terms = (include 'entity.php')

return array_merge($terms, [
    'create' => 'Create a new Blog Post',
];)

Have fun :)

A: You could create a new helper for that:
function translate($trans, $fallback) {
    return __($trans) === $trans ? __($fallback . '.' . explode('.', $trans)[1]) : __($trans);
}

And then use it like this:
translate('post.create', 'entity');

A: Instead of having lots of separate language files another approach would be to create a single file which groups labels for an element. For example, all of your button labels for the whole app could be stored in a file at /resources/lang/en/buttons.php You just need to be a bit more careful choosing labels. The contents of buttons.php could be
<?php

return [

    'show_item' => 'Show Item',
    'view_item' => 'View Item',
    'edit_item' => 'Edit Item',
    'create_new_item' => 'Create a new Item',
    'create_new_blog_post' => 'Create a new Blog Post',
    //add all labels here
];

Then if you need a button label anywhere on your site you can get it from the buttons.php file. For example, your show item button would be
<button type="button">{{ __('buttons.show_item') }}</button>


text:
Q: Ruby on Rails. Using Google Client API to parse emails I am new to Ruby and have a question about how to do a specific task on Rails.
I have a list of inventory and each item has a specific Stock ID that is emailed to my personal Gmail account. I want my web application to listen for emails from a specific email account. When my gmail receives an email from that specific account I want my application to parse it for a couple of fields and insert the stock ID into my database.
For example:
Let's say my database has an item with style code: A5U31 and size:10.
The email will say something like item with style code: A5U31 and size:10 has Stock ID:329193020.
I want my Rails application to search the database for an entry with that specific style code and size, and when it finds an entry to simply insert the stock ID into the row.
I am trying to using the Google-API-Client gem to this, but I am struggling, because I am still a beginner. So far I have done this quick-start guide to authenticate my gmail account with my rails app.
https://developers.google.com/gmail/api/quickstart/ruby?authuser=2
If someone could help me figure out how to write this sort of code and where to put it in my app(models, controllers, views) that would be very appreciated. Thanks!

A: I know it's been several months since you posted this, so you probably already have it worked out, but in case you still need a solution (or if someone else wants to do something similar), I'll share my thoughts:
At a high level, it sounds like your plan is

*

*Identify when a new email has come in (either by polling or by using a push notification).

*Grab the new email's content.

*Parse the email's content in order to extract relevant data.

*Use the data to query and update a database.

Based on the documentation for the Gmail API, it does look like you should be able to set up push notifications, so you won't have to poll the endpoint to get the information you need.
However, my big takeaway from this list is that none of the items on it really require Rails, since you're not exposing an external web API for requests. I suppose that you could leverage ActiveRecord to create an item model and use that to manage the database; however, since it seems like you'd only need to make some basic SQL queries (and the same ones each time), I'm not sure that bringing in ActiveRecord adds much value.
If I were trying to solve this problem myself, I would probably create a simple Ruby program that (a) uses the gem you mentioned to handle push notifications from the Gmail API, and (b) uses another gem to connect to whatever kind of database you're using (e.g. pg for Postgres) and make the necessary queries.
(All of this assumes, of course, that you aren't specifically using Rails for some other reason, e.g. adding this feature to an existing Rails application).


text:
Q: Google Sheets API V4 - Autofill Error - No grid with id: 0 I am trying to make an AutoFillRequest using a SourceAndDestination object to describe the area to autofill. I've tested autofill requests using a GridRange object and everything works fine, but can't seem to get the SourceAndDestination working. Here is an example where I'm trying to autofill down the first row for 2 more rows.
HTTP POST
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}:batchUpdate

Request Body
{
  "requests": [
    {
      "autoFill": {
        "sourceAndDestination": {
          "dimension": "ROWS",
          "fillLength": 2,
          "source": {
            "sheetId": 1150108545,
            "endRowIndex": 1,
            "startRowIndex": 0
          }
        },
        "useAlternateSeries": false
      }
    }
  ]
}

The response has an error code 400:

message = "Invalid requests[0].autoFill: No grid with id: 0" status =
  "INVALID_ARGUMENT"

A: Sorry about that, this was a bug on the server. It's now fixed, so the above should work.


text:
Q: SqlServer 2000 compatibility The developer environment db server is SqlServer 2005 (developer edition)
Is there any way to make sure my SQL Queries will run in SqlServer 2000?
This database is set to Compatibility level "SQL Server 2000 (80)" but some queries that run without problems in the development system can not run in the Test Server (SqlServer).
(The problems seems to be in subqueries)

A: Compatibility levels are designed to work the opposite way - to allow an older version of T-SQL code to work without modifications on a newer version of SQL Server.  The changes typically involve T-SQL syntax and reserved words, and it's possible to use SQL Server 2005 features such as INCLUDED columns in indexes on a database in Compatibility Level 80.  However, you can't use 2005 T-SQL features such as CROSS APPLY.
Your best option is to develop/test all your code against a SQL Server 2000 instance.  Note that you can use 2005's Management Studio to connect to the SQL Server 2000 instance, so you don't have to go backwards with regards to tools.

A: Problem solved:
In correlated subqueries you have to (in SQL2000) explicitly define the external field.
SQL2005:
SELECT * FROM Loans WHERE EXISTS (SELECT * FROM Collaterals WHERE COLLATERAL_LOAN=LOAN_NUMBER)

SQL2000:
SELECT * FROM Loans WHERE EXISTS (SELECT * FROM Collaterals WHERE COLLATERAL_LOAN=Loans.LOAN_NUMBER)

A: You should always explicitly define all fields, otherwise you will not get an error when you make a mistake and write
SELECT * FROM Loans WHERE EXISTS (SELECT * FROM Collaterals WHERE LOAN_NUMBER=Loans.LOAN_NUMBER)

If Collaterals-table doesn't have column LOAN_NUMBER, the Loans-table is used instead.


text:
Q: creating a pandas dataframe from a database query that uses bind variables I'm working with an Oracle database. I can do this much:
    import pandas as pd
    import pandas.io.sql as psql
    import cx_Oracle as odb
    conn = odb.connect(_user +'/'+ _pass +'@'+ _dbenv)

    sqlStr = "SELECT * FROM customers"
    df = psql.frame_query(sqlStr, conn)

But I don't know how to handle bind variables, like so:
    sqlStr = """SELECT * FROM customers
                WHERE id BETWEEN :v1 AND :v2
             """

I've tried these variations:
   params  = (1234, 5678)
   params2 = {"v1":1234, "v2":5678}

   df = psql.frame_query((sqlStr,params), conn)
   df = psql.frame_query((sqlStr,params2), conn)
   df = psql.frame_query(sqlStr,params, conn)
   df = psql.frame_query(sqlStr,params2, conn)

The following works:
   curs = conn.cursor()
   curs.execute(sqlStr, params)
   df = pd.DataFrame(curs.fetchall())
   df.columns = [rec[0] for rec in curs.description]

but this solution is just...inellegant. If I can, I'd like to do this without creating the cursor object. Is there a way to do the whole thing using just pandas?

A: Try using pandas.io.sql.read_sql_query. I used pandas version 0.20.1, I used it, it worked out:
import pandas as pd
import pandas.io.sql as psql
import cx_Oracle as odb
conn = odb.connect(_user +'/'+ _pass +'@'+ _dbenv)

sqlStr = """SELECT * FROM customers
            WHERE id BETWEEN :v1 AND :v2
"""
pars = {"v1":1234, "v2":5678}
df = psql.frame_query(sqlStr, conn, params=pars)

A: As far as I can tell, pandas expects that the SQL string be completely formed prior to passing it along. With that in mind, I would (and always do) use string interpolation:
params = (1234, 5678)
sqlStr = """
SELECT * FROM customers
WHERE id BETWEEN %d AND %d
""" % params
print(sqlStr)

which gives
SELECT * FROM customers
WHERE id BETWEEN 1234 AND 5678

So that should feed into psql.frame_query just fine. (it does in my experience with postgres, mysql, and sql server).


text:
Q: What's the correct PEP8 practice for this long Python line? How should I break down this line so it abides by PEP8?
    assert (sum(map(lambda x: len(x),
                    (activities,apps,classes,users,verbs))) ==
            Object.query
                  .filter(Object.status != ObjectStatusChoices.DELETED)
                  .count())

A: If you rewrite things into separate lines, this never comes up.
It also lets you give meaningful names to the intermediate values (which I had to guess at, but presumably you know them), or even refactor bits of logic out into functions (which you can also give meaningful names to).
For example, not changing any of your logic, or even rewriting any of it (except to use len in place of lambda x: len(x)):
lengths = map(len, (activities,apps,classes,users,verbs))
db_query = Object.query.filter(Object.status != ObjectStatusChoices.DELETED)
assert sum(lengths) == db_query.count()

A: First of all, keep in mind that there is no single "correct PEP8 answer" to this.  I prefer:
in_mem = sum(len(x) for x in (activities,apps,classes,users,verbs))
in_db = Object.query.filter(
                        Object.status != ObjectStatusChoices.DELETED
                        ).count()
assert in_mem == in_db

Definitely if you find yourself with a statement that needs to be split onto five lines, you probably want more statements.


text:
Q: Preserve /etc/network/interfaces configuration when changing PCIe cards I have several NICs in my Ubuntu 16.04 box (3 of them at the moment). As best I can tell their names are related to their PCIe names. My problem is that when I add or remove a card of any type (graphics, HBA, etc) the interface names seem to change and then the booting hangs for several minutes trying to bring the network up. If I have to reboot several times then this really adds up.
This is my /etc/network/interfaces:
auto lo
iface lo inet loopback

auto enp8s0
iface enp8s0 inet manual

auto enp5s0
iface enp5s0 inet manual

auto enp6s0f0
iface enp6s0f0 inet manual

auto enp6s0f1
iface enp6s0f1 inet manual

auto br0
iface br0 inet dhcp
    hwaddress 50:e5:49:ed:72:3d
    bridge_ports enp8s0 enp6s0f0 enp6s0f1 enp5s0
    bridge_stp off

A: Udev has a mechanism to fixate the name of network devices

First, take note of your interfaces mac-addresses. You can see them with ip a or ifconfig -a
Second, the file /etc/udev/rules.d/70-persistent-net.rules  has to be created manually in 16.04.
Use your favorite editor
sudo nano /etc/udev/rules.d/70-persistent-net.rules

The line for fixing the interface name of the NIC with MAC address "02:01:02:03:04:05" to "eth0" is:
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="02:01:02:03:04:05", ATTR{dev_id}=="0x0", ATTR{type}=="1", NAME="eth0"

So for your first interface called enp8s0it would be
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="<the-mac-address>", ATTR{dev_id}=="0x0", ATTR{type}=="1", NAME="enp8s0"

You have to make an entry for each network card. This takes effect on reboot.

*

*Disclaimer: For Ubuntu versions before 16.04 you have to add KERNEL=="eth*" *


text:
Q: save sprated with comma in row in sql server and exclude some column value I have SQL table like this
Table:1
CERT SPEC  ClientID
all   1    8
all   2    8
all   3    8
1    all   9
2    all   9

Table: 2
certs
ID  Name
1   A
2   B
3   C

Table: 3
SPECS
ID  Name
1   X
2   Y
3   Z

Result table
CERT SPEC   ClientID
all   X,Y,Z 8
A,B   all   9

I have use stuff and xml path for but did not get the expected result.
Please help me with this.


text:
Q: How to get maven to use the installed java to create the jar file? I am trying to create a jar file from my spring project. I use the command mvn package. These are the contents of my pom.xml-
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cgny</groupId>
    <artifactId>apm</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>apm</name>
    <description>APM</description>
    <properties>
        <java.version>16</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- latest influxdb dependency -->
        <dependency>
            <groupId>org.influxdb</groupId>
            <artifactId>influxdb-java</artifactId>
            <version>2.21</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180130</version>
        </dependency>

        <!-- XMl Parser -->
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom2</artifactId>
            <version>2.0.3</version>
        </dependency>

        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.5.2</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

The source and target has been set to java 1.8, but when I run the jar file using java -jar, I get the UnsupportedClassVersion error.
I know this happens because the version of java which compiled the project is different from the one I am using to run the jar file, but my java version is 1.8.0_51, which I have also tried as the target and source in the pom file, with the same result.
JAVA_HOME and the PATH variable have been set with the correct directories.
How do I configure maven so that it just uses the installed java?
Edit: The error message-
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/cgny/apm/ApmApplication has been compiled by a more recent version of the Java Runtime (class file version 60.0), this version of the Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:151)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:108)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:58)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88)

A: The error means that com/cgny/apm/ApmApplication was compiled with Java 16 and therefore cannot be used with Java 8.

A: The compiled jar was fine, I just had java 8 installed, which was somehow overriding the JAVA_HOME and Path variables. The java -version now shows 16 instead of 1.8.


text:
Q: Prove $\alpha \in R[[x]]$ is a unit iff $a_0 \in R$ is a unit
Prove $\alpha \in R[[x]]$ is a unit iff $a_0 \in R$ is a unit.

$"\Rightarrow"$ suppose $\alpha \in R[[x]]$ is a unit, where $\alpha = \sum_{n=0}^{\infty} a_nx^n$
then there exists an inverse $\beta = \sum_{n=0}^{\infty} b_nx^n$
stuck at this spot,
$(\sum_{n=0}^{\infty} a_nx^n)(\sum_{n=0}^{\infty} b_nx^n) = \sum_{n=0}^{\infty}(\sum_{k=0}^{n}(a_kb_{n-k}))x^n$
A little mixed up on how this becomes $1 = \sum_{n=0}^{\infty}e_nx^n$ where $e_0 =1, e_{n>0} = 0$ and why that would make $a_0b_0 = 1$ which would make $a_0 \in R$ a unit. I haven't tried the other direction yet.
EDIT
Maybe I get it, because we assumed this sum is a unit then its inverse exists and so the $x^0=1$ and all $a_ib_i=1$ thus $a_0b_0=1$ which gives $a_0$ is a unit in $R$

A: $\alpha \beta =1$ means $(a_0 + a_1 x+\cdots)(b_0 + b_1 x+ \cdots)=1+0x+\cdots$ so $a_0b_0+ (a_1b_0+a_0 b_1)x+\cdots=1+0x+\cdots$ therefore $a_0b_0=1$

A: We know (if $\beta = \alpha^{-1}$) that
$$ 1 = \sum_n e_n x^n = \sum_n \sum_{k=0}^n a_k b_{n-k} x^n $$
That is
$$ \forall n \ge 0 : e_n = \sum_{k=0}^n a_k b_{n-k} $$
especially (let $n = 0$):
$$ 1 = e_0 = a_0 b_0 $$
(hence $a_0$ is a unit).
For the other direction, suppose $a_0$ is a unit with inverse $b_0 := a_0^{-1}$. We want to define $\beta = \sum_n b_n x^n$ such that
$$ 0 = \sum_{k=0}^n a_k b_{n-k}, \quad n \ge 1 $$
This is achieved by inductively defining
$$ b_n := -a_0^{-1} \sum_{k=1}^n a_k b_{n-k} $$
Then $\beta := \sum_n b_n x^n$ is an inverse to $\alpha$.


text:
Q: Apache kafka HighLevel Consumer - Understanding I have been looking around Apache kafka for implementing a HighLevel consumer (I do not want to play with the message, I just simply need to put the data into MongoDB) v0.8.1.1
I have looked at below links which shows very great details about how to implement the consumer.
Apache Kafka consumer wiki
Another kafka consumer
But I am still clueless as to how the Consumer restarts after all the threads are shutdown. E.g. Lets say I have 4 threads of consumer running and they consumed all the messages from kafka broker so once there are no messages all the consumers will do nothing and after specific timeout it will be shutdown so I am not sure that how the consumer is again restarted when there are new messages in kafka broker.
Can someone share some code or atleast some pointers on this. Also is there a way where we can have our business logic in some callback method which will get called when there are messages instead of having while loop.

A: I think you may be misunderstanding the use of timeouts during shutdown. Theoretically, you're consuming an infinite stream of events regardless of the time between those events, so your consuner should never be shut down unless you're updating the code or a machine crashes. In the event of actually needing to shut down the consumer, what the 10000 millisecond timeout does is gives the Kafka consumer enough time to write its last read offset to ZooKeeper so that when the consumer is restarted it will resume from the last offset it processed. This consumer shut down normally occurs when your program is shut down (perhaps an InterruptedException is caught), not just the consumer. Thus, the consuner is restarted when your program is restarted.
EDIT
I should add that the reason Kafka's ConsumerIterator follows this model of never ending consumption. The iterator's next method will always block until it can read the next message. Therefore, the only way the timeout in the example is ever reached is if the consumer threads are shut down by some exception.
EDIT 2
I haven't seen any Kafka consumer API that supports callbacksI think your only option right now is writing your own callback implementation, e.g.:
public interface Callback {
  void call(MessageAndMetadata message);
}

Executor executor = Executors.newCachedThreadPool();
final Callback<byte[], byte[]> callback = new MyCallback();
while (it.hasNext()) {
  final MessageAndMetadata message = it.next();
  executor.submit(new Runnable() {
    public void run() {
      callback.call(message);
    }
  });
}

You might be interested that they're currently rewriting the consumer API for Kafka 0.9, but I don't think I've seen callbacks in the rewrite (though I could be wrong).


text:
Q: UINavigationController flow for login ios Solved:
once the user has logged in / signed up, use the following code to transition to the main storyboard...
 UIWindow* window = [[UIApplication sharedApplication] keyWindow];

 window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateInitialViewController];

I have the following UINavigationController flow to handle logging in...the top segue after the tabbarcontroller goes to a uinavigationcontroller that is the root for a viewcontroller.

When the user is already logged in the "this segue works" is executed so that the user doesn't have to log in at the login screen. That works perfectly. The issue I run into is when the user has to login...the segue from the login/signup screen to the login screen works perfectly, but when I go from the login screen to the tabbar the following happens:

This really shouldn't happen because I have the following code in my viewcontroller.m (gotten to here is called)
- (void)viewDidLoad {
    ...
    self.navigationItem.title = @"Messages";
    self.navigationItem.hidesBackButton = YES;

    NSLog(@"gotten to here");
    ...
}

Does anybody know why this is happening?

A: I like to keep my login flow separate from the normal app flow. This means that I don't link a segue from the login screen to the app, but I handle that in my AppDelegate:
if ([MyUserHandler sharedHelper].isAuthenticated) {
    [self presentMainInterface];
} else {
    [self presentWelcomeInterface];
}

Where the first method does this:
- (void)presentMainInterface
{
    self.window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
}

and the other presents the login screen:
- (void)presentWelcomeInterface
{
    UIViewController* rootController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"loginScreen"];

    UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:rootController];
    self.window.rootViewController = navigation;
}

This way the login screen is loaded only when the user is not authenticated.

A: Make a custom class (sub class) of UITabBarControler and assign that custom class for your tabbarcontroller in storyboard. Then In viewDidLoad of custom tabbarcontroller add your code
self.navigationItem.hidesBackButton = YES;

It will work fine.


text:
Q: AWS Elastic Beanstalk Worker queue behaviour Using Elastic Beanstalk I create a worker 1.1 tier (64bit Amazon Linux 2014.03 v1.0.3 running Ruby 1.9.3) from the Management Console. When it comes to configuring the worker details I opt for "Autogenerate Queue". When I do so two SQS queues are generated (worker and dead letter), but the "Worker queue URL" for my worker instance is set to the dead letter queue url. I would have thought it should be the worker queue? If I attempt to change it to the worker queue in the worker config, both queues are deleted (worker and dead letter). Can anyone tell me if this is normal behaviour?

A: When you elect the Auto Generated Queue it creates two queue. One is the main and other is for Dead Letter Queue. By default your worker instance listen to the main queue. The dead letter queue is configured in the main queue configuration. If there are many message considered dead not able to process then the main queue puts in to dead letter. Worker queue does not d


text:
Q: Do matrices work within structs in C? I'm trying to make a struct that contains (in this example) the name of the item to buy in an array and in a matrix it's price and the weight of it I should buy. This is just an easy example of what i'm trying to do.
I use strcpy to declare the value just because I learned it this way, I don't if it's the best of the methods.
#include<stdio.h>
#include<string.h>
typedef struct Grocery_list{

    char item_name[2];
    double item_info[2][2];

}Grocery;

int main(){

Grocery market;
strcpy( market.item_name[0], "Apple");
strcpy( market.item_name[1], "Sugar");
strcpy( market.item_info[0][0],200); //apple weight
strcpy( market.item_info[1][0], 3); //apple price
strcpy( market.item_info[0][1], 300);
strcpy( market.item_info[1][1], 4);

printf("%f \n",martket.item_info[1][1]);

return 0;}

The errors are
teste.C: In function 'int main()':
teste.C:14:27: error: invalid conversion from 'char' to 'char*' [-fpermissive]
 strcpy( market.item_name[0], "Apple");
                           ^
In file included from teste.C:2:0:
/usr/include/string.h:129:14: error:   initializing argument 1 of 'char* strcpy(char*, const char*)' [-fpermissive]
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^
teste.C:15:27: error: invalid conversion from 'char' to 'char*' [-fpermissive]
 strcpy( market.item_name[1], "Sugar");
                           ^
In file included from teste.C:2:0:
/usr/include/string.h:129:14: error:   initializing argument 1 of 'char* strcpy(char*, const char*)' [-fpermissive]
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^
teste.C:16:35: error: cannot convert 'double' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)'
 strcpy( market.item_info[0][0],200);
                                   ^
teste.C:17:34: error: cannot convert 'double' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)'
 strcpy( market.item_info[1][0], 3);
                                  ^
teste.C:18:36: error: cannot convert 'double' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)'
 strcpy( market.item_info[0][1], 300);
                                    ^
teste.C:19:34: error: cannot convert 'double' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)'
 strcpy( market.item_info[1][1], 4);
                                  ^
teste.C:21:16: error: 'martket' was not declared in this scope
 printf("%f \n",martket.item_info[1][1]);
                ^

Obviously, I searched for answers and solutions on Google, but everything I tried just caused other errors or even the same. For I'm new in programming in general I don't know what those errors mean.
Thank you in advance

A: The member item_name is an array of two characters, it's not an array of strings, it's just a single string (which can only hold a single character, remember that all strings have a special terminator character). You probably should make this an array of arrays of char, which means it's an array of strings:
char item_name[2][64];  // Two strings, each can hold 63 characters

The member item_info is an array of arrays of double. The strcpy function is for copying strings (arrays of char).
Remember that each element in an array is like a variable, which means you can just assign to it:
market.item_info[0][0] = 200; //apple weight
market.item_info[1][0] = 3; //apple price
market.item_info[0][1] = 300;
market.item_info[1][1] = 4;

And the last error is because you misspelled market.
All of this would be very obvious even to a beginner if you just read the error messages.

A: Three issues:
Your struct doesn't have an array of strings.  It has an array of characters.  You need to add an extra dimension to item_name to have such an array:
typedef struct Grocery_list{

    char item_name[2][50];
    double item_info[2][2];

}Grocery;

Also, you're using strcpy to attempt to copy numerical values.  This function is used for copying strings.  Instead of using this function, perform a simple assignment:
market.item_info[0][0] = 200; //apple weight
market.item_info[1][0] = 3; //apple price
market.item_info[0][1] = 300;
market.item_info[1][1] = 4;

Lastly, you have a typo in your printf statement:
printf("%f \n",martket.item_info[1][1]);

It should be:
printf("%f \n",market.item_info[1][1]);

A: 1 - your declaration of the item_name[2] is correct but you used in the wrong way. this is actually logical error. you need enough room for saving your data such as: apple, sugar and ... the last character of string is '\0'. indeed you just declaring one character for saving "apple" or "sugar".
2 - strcpy is for manipulating of string or array of characters, so you are not authorized to use this function with numerical variables.
3 you have misspelling in last line (before returning to OS).


text:
Q: delay execution of statement until preveouus binding is still in progress (jquery, ajax) in my page i am calling a controller using $.get with some parameters ,
that controller returns me a view page (.aspx),
now, i bind that page to a different  div  every time as this function can be iterated (or called multiple times) these div s are already created and then result is mapped to each div
function getview(Name, Parameters, Target) {
     $.get('Home/Submit',
                    { Name: name,
                      Parameters: Parameters
                    },

       function(result) {

           $("#" + Target).html(result);
           //alert("something");

       });
}

this method is called as:
<div id="{{'_Temp' + Id}}">{{getAction('_AddToFavorite', 'ContentId,'
                                    + Id + ',Version,' + Version + ','li_ContentFavorites_Temp'
                                    + Id)}} </div>

Now what happens here is the html gets bind to respective div but only when that 'alert()' is there
otherwise the view page gets bind randomly (ie sometime it does sometimes it doesn't)
but for last iteration it does.
**I think ** that this is because before the data is actually bind to the respective div the next data(viewpage) comes in.
is there any way to make process stop (or delay) so to bind data properly.

A: if you use .ajax you can use more options - one of these is timeout

A: I had this problem figured out in more then one way, but the easiest solution is always based on jquery ajaxqueue plugin. It just does ajax "one by one" :)
You could stay with Your way, but it would require a lot of debugging - I think Your problem is related to some variables being less local than You think. If You want to load without queueing - please post more details or a link to an example page


text:
Q: Take voltage every 60 seconds C++ Sketch Can someone explain how to modify this program to "ReadAnalogVoltage" once every 60 seconds, forever.
Right now it reads the voltage every millisecond (I think), forever.
Too much information is being generated.
Any suggestions would be appreciated.
Rob.
    > /*
     ReadAnalogVoltage
     Reads an analog input on pin 0, converts it to voltage, and prints
     the result to the serial monitor.
      Attach the center pin of a potentiometer to pin A0, and the outside
     pins to +5V and ground.

     This example code is in the public domain.
   */

   // the setup routine runs once when you press reset:
   void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
   }

   // the loop routine runs over and over again forever:
   void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    float voltage = sensorValue * (5.0 / 1023.0);
    // print out the value you read:
    Serial.println(voltage);
    }

A: There are several ways to lower the sampling rate. Place a counter inside your loop and only print when the counter reaches a certain value. Be sure to reset the value after printing.
int counter = 0;
void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    float voltage = sensorValue * (5.0 / 1023.0);
    // print out the value you read:
    if(counter >= 1000000){
        Serial.println(voltage);
        counter = 0;
    }
}

*The best way to solve this is with an time interrupt. The actual mechanics of setting the interrupt will depend on what hardware you are using.


text:
Q: can not update watchOS and always prompt "Checking for Update..." the iPhone 5s, with version 9.0(13A4254v), always prompts "Checking for Update ..." in Apple Watch app, when I tended to install WatchOS beta software. Anyone can give me a hand?

A: I found theses two threads on the Apple Developer forums. It seems that right now the only solution (for some people anyways) is to reboot the phone as well as the watch, after the configuration file has been loaded onto the watch.
https://forums.developer.apple.com/thread/4251
https://forums.developer.apple.com/message/6740
Also, there could be an issue connecting to the store, preventing you from seeing the update. I connected my iPhone to my computer, and the logs showed it was having connection issues while trying to reach itunesstored. That was on a "guest" network at work, once I switched to a secure network, the connection went through and the watchOS2 update was available.


text:
Q: facebook like button not displayed in firefox when I access my site in firefox, the like button did not appear:
js-projects
It worked in safari and chrome, only disappeared in firefox. the javascript code of loading like button can be found after the

tag, and the social share buttons can be found after clicking on the red button on the top-right part. google+ and twitter buttons work well right now.

A: If this is what you have,try some css:
<fb:like id="facebook-like" href="http://mysite.com/index.php" layout="button_count" width="450" show_faces="false" font=""></fb:like>

Add this to css,it will work.
.fb - like span, .fb - like iframe {
    height: 25px!important;
    width: 150px!important
}


text:
Q: Resultset of Spring 3 MVC and JDBC returns null Hi im new to this Spring , MVC and JdBC support.
I want to be able to connect to a mysql database..but when i run my web it returns null. Below codes i believe should be easy,What am i missing here ? Thanks for all replies
Below is my error when try to query the URL
java.lang.NullPointerException
com.simple.myacc.dao.JdbcContactDao.findAll(JdbcContactDao.java:55)
com.simple.myacc.ContactController.getAll(ContactController.java:44)

My spring.xml
.....

<context:component-scan base-package="com.simple.myacc" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/webcontact" />
    <property name="username" value="root" />
    <property name="password" value="password" />
</bean>

<bean id="jdbcContactDao" class="com.simple.myacc.dao.JdbcContactDao">
    <property name="dataSource" ref="dataSource" />
</bean>

My JdbcContactDao
public class JdbcContactDao {
protected static Logger logger = Logger.getLogger("service");
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

public JdbcContactDao() {

}

public List<Contact> findAll() {

    String sql = "select * from contact";
    List<Contact> contacts = new ArrayList<Contact>();
    List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
    for (Map rs : rows) {
        Contact contact = new Contact();
        contact.setId((Integer) rs.get("id"));
        contact.setFirstname((String) rs.get("firstname"));
        contact.setLastname((String) rs.get("lastname"));
        contact.setEmail((String) rs.get("email"));
        contact.setPhone((String) rs.get("phone"));
        contacts.add(contact);
    }
    return contacts;
}

@Resource(name = "dataSource")
public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;

} }

My controller , some part of it
@RequestMapping(value="/contact/list2",method = RequestMethod.GET)
public String getAll(ModelMap model) {
    dao=new JdbcContactDao();
    List<Contact> contacts = dao.findAll();

     // Attach persons to the Model
     model.addAttribute("contacts", contacts);

     return "contact.list";

}

This is the line that says the NULL
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);

A: A common idiom when using the JdbcTemplate class is to configure a DataSource in your Spring configuration file, and then dependency inject that shared DataSource bean into your DAO classes; the JdbcTemplate is created in the setter for the DataSource.
       private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

You can read more on this here
Your code will look like this
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/webcontact" />
<property name="username" value="root" />
<property name="password" value="password" />

You don't need this
<bean id="jdbcContactDao" class="com.simple.myacc.dao.JdbcContactDao">
<property name="dataSource" ref="dataSource" />

Instead do this
 @Autowired
public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

and annotate your JdbcContactDao class with @Repository
I think that should work

A: I'm guessing line 55 of JdbcContactDao is this one List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);  You declare jdbcTemplate, but never give it a value and it's also not annotated for injection, so it's always going to be null.  So, when you attempt to use it, you will get the NPE.

A: You have your dataSource and your JdbcContactDAO bean configured in the config file.
So in the same way you need to inject the jdbcContactDAO bean into your Controller.
<bean id="myController" class="mypath.MyController">
<property name="dao" ref="jdbcContactDao"/>
</bean>

And in your controller....
public JdbcContactDao dao;

@Resource(name="dao")
public void setDao(JdbcContactDao dao){
    this.dao = dao;
}

@RequestMapping(value="/contact/list2",method = RequestMethod.GET)
public String getAll(ModelMap model) {

    List<Contact> contacts = dao.findAll();

    // Attach persons to the Model
    model.addAttribute("contacts", contacts);

    return "contact.list";

}

A: Had a similar problem was connecting to old tables using java/jdbc
String sql = "select user_name from table"
jdbc.queryForList(sql);

queryReturnList = jdbc.queryForList(sql);

    for (Map mp : queryReturnList){
        String userName = (String)mp.get("user_name");
}

userName was always null.  looking through the map of returned values found that the map was not using user_name but a label set up on the table of "User Name"   Had to have DBA's fix.  Hope this helps