text:
Q: How to use a duplicate search in a SELECT request in SQL I found several duplicate line with this request :
SELECT UID1, UID2, COUNT(*)
FROM TableGroup
GROUP BY UID1, UID2
HAVING COUNT(*) > 1;

Like this :
UID1    UID2
2353    2585    2
2354    2585    2
2355    2585    2
2357    2583    2

UID1 is related with an other table I called NameUID1
2353 Name1
2354 Name2
2355 Name3
2357 Name4

UID2  is related with an other table I called NameUID2
2585 OtherName1
2583 OtherName2

I don't know how to merge  the first request for using it in a new request for have the name associated with the UNID1 et UNID2 Like this :
UID1    UID2
Name1   OtherName1
Name2   OtherName1
Name3   OtherName1
Name4   OtherName2

A: You probably want WITH and joins
WITH cte AS (
    SELECT UID1, UID2, COUNT(*)
    FROM TableGroup
    GROUP BY UID1, UID2
    HAVING COUNT(*) > 1
)
SELECT u1.name, u2.name FROM cte
INNER JOIN NameUID1 u1 ON u1.UID1=u2.UID2
INNER JOIN NameUID2 u2 ON u2.UID2=u2.UID2

A: Use the select clause as rdge Table and join them all
SELECT t1.Mames,t3.Names
FROM NameUID1 t1
INNER JOIN (    SELECT UID1, UID2
    FROM TableGroup
    GROUP BY UID1, UID2
    HAVING COUNT(*) > 1) t2 ON t1.UID1  = t2.UID1
INNER JOIN
NameUID2 t3 ON t2.UID2 = t3.UID2


text:
Q: Conceptual Questions About Processes and Signals I am studying for my final in systems programming and I have a few questions that I cannot answer.

*

*Say a parent process forks off a child process that creates a large object. Can the child pass this object back to the parent fairly easily using just signals?

*A parent process forks off a child process, and the child continues running the same program. Is the best way for the parent to give a data structure to a child that was created before the fork to write to a separate file and give that to the child? (This one I am thinking it is not a good way, because the child will still share some of the parents data, including said data structure)

*Let us say you write a program to measure how quick a
person's fingers are by trapping SIGINT and then asking them to press
Ctrl-C as rapidly as possible. The SIGINT signal handler increments a
global counter every time Ctrl-C is typed. After a predefined time it
stops and prints the global counter divided by the time used.
What is a fundamental problem with this program?
Any help is appreciated.

A: Some quick thoughts on your questions;

*

*No, signals are not good for transferring data. Signals involve a lot of overhead and are not queued very effectively.

*Many methods of IPC are available. The two that are most popular for UNIX are sockets and shared memory (see shm for instance). Sockets are generally better when talking to un-trusted applications. In your example of forking an application pipes would be applicable as well.

*As long as you can handle the interrupt much faster than they are coming in you are OK. Probably in the case with your ctrl-c example you could do the same thing using poll and fcntl (on UNIX) and you would be likely to get better precision.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to use string from a text file as java code lets say i have written "doSomthing()" in a text file. Does anybody know if it is possible to have that text doSomthing() without having to wirite:
if(txt.equals("doSomthing()"){
    doSomthing();
}

A: the answer was indeed in the reflection chapter and it's straight forward. thanx for that StephaneM :
Method method = MyClass.class.getMethod("doSometing", String.Object);
Object returnValue = method.invoke(null, "parameter-value1");


text:
Q: Value of Object in PHP after POST does not match what was sent via Ajax? SO in my JavaScript i create an object which if i console.log(data[71]) I get:
as_of_date
    "2014-01-31"
class_index
    "Class C"
fund_no
    13
with_load
    1
y2004
    0
y2005
    0

y2006
    0
y2007
    0
y2008
    0
y2009
    0
y2010
    "9.46%"
y2011
    "-0.20%"
y2012
    "9.91%"
y2013
    "30.48%"

IN my php i have a foreach that goes through each object posted:
    if($_POST['function'] == 'update_calendar_year') {
        $entries = $_POST['data'];
        foreach ($entries as $entry) {
            $fund_no = $entry['fund_no'];
            $y2004 = preg_replace('/[&%$]+/', '', $entry['y2004']);
            $y2005 = preg_replace('/[&%$]+/', '', $entry['y2005']);
            $y2006 = preg_replace('/[&%$]+/', '', $entry['y2006']);
            $y2007 = preg_replace('/[&%$]+/', '', $entry['y2007']);
            $y2008 = preg_replace('/[&%$]+/', '', $entry['y2008']);
            $y2009 = preg_replace('/[&%$]+/', '', $entry['y2009']);
            $y2010 = preg_replace('/[&%$]+/', '', $entry['y2010']);
            $y2011 = preg_replace('/[&%$]+/', '', $entry['y2011']);
            $y2012 = preg_replace('/[&%$]+/', '', $entry['y2012']);
            $y2013 = preg_replace('/[&%$]+/', '', $entry['y2013']);
            $with_load = preg_replace('/[&%$]+/', '', $entry['with_load']);

When i get to the last entry the following error occurs:
Notice:  Undefined index: y2006 in /home/diamondh/public_html/wp-content/themes/diamond-hill/functions.php on line 69

Notice:  Undefined index: y2007 in /home/diamondh/public_html/wp-content/themes/diamond-hill/functions.php on line 70

If i var dump entries[71] in my PHP i get the following value:
array(5) {
  ["fund_no"]=>
  string(2) "13"
  ["class_index"]=>
  string(7) "Class C"
  ["with_load"]=>
  string(1) "1"
  ["y2004"]=>
  string(1) "0"
  ["y2005"]=>
  string(1) "0"
}

All other passed values are correct it seems to only be the last object that gets half of its value cut off for some reason? The above var_dump should show the same value as my console.log above but does not.
In frustration i tried to pass only data[71] to my php and the value was correct:
    $.ajax({
      type: "POST",
      url: "functions.php",
      data: {
        function: "update_calendar_year",
        data: data[71]
      },
      success: "success",
      dataType: "json"
    });

If i then check what was passed into PHP i get :
array(14) {
  ["fund_no"]=>
  string(2) "13"
  ["class_index"]=>
  string(7) "Class C"
  ["with_load"]=>
  string(1) "1"
  ["y2004"]=>
  string(1) "0"
  ["y2005"]=>
  string(1) "0"
  ["y2006"]=>
  string(1) "0"
  ["y2007"]=>
  string(1) "0"
  ["y2008"]=>
  string(1) "0"
  ["y2009"]=>
  string(1) "0"
  ["y2010"]=>
  string(5) "9.46%"
  ["y2011"]=>
  string(6) "-0.20%"
  ["y2012"]=>
  string(5) "9.91%"
  ["y2013"]=>
  string(6) "30.48%"
  ["as_of_date"]=>
  string(10) "2014-01-31"
}

Which is exactly what i would expect.
Sorry this was so long winded but this is a very odd issue and i have tried everything i could think of and have double checked what was being passed anyway i could.

A: PHP has a limit of 1000 post fields.
You have 71 * 14 fields = 994
And then the next set of 14 fields is being cut off half way through.
Have a look at this SO post for more information.
Either increase your max post fields, or refactor your code and UI to process fewer fields in one go.


text:
Q: Create bean instance at runtime for interface i am kind of stuck on a problem with creating beans, or probably i got the wrong intention.. Maybe you can help me solve it:
I got a application which takes in requests for batch processing. For every batch i need to create an own context depending on the parameters issued by the request.
I will try to simplyfy it with the following example:
I receive a request to process in a batch FunctionA which is a implementation for my Function_I interface and has sub-implementation FunctionA_DE and FunctionA_AT
Something like this:
public interface Function_I {
   String doFunctionStuff()
}

public abstract class FunctionA implements Function_I {

   FunctionConfig funcConfig;

   public FunctionA(FunctionConfig funcConfig) {
      this.funcConfig = funcConfig;
   }

   public String doFunctionStuff() {
      // some code
      String result = callSpecificFunctionStuff();
      // more code
      return result;
   }

   protected abstract String callSpecificFunctionStuff();
}

public class FunctionA_DE extends FunctionA {
   public FunctionA_DE(FunctionConfig funcConf) {
      super(funcConf)
   }

   protected String callSpecifiFunctionStuff() {
      //do some specificStuff
      return result;
   }
}

public class FunctionA_AT extends FunctionA {
   public FunctionA_AT(FunctionConfig funcConf) {
      super(funcConf)
   }

   protected String callSpecifiFunctionStuff() {
      //do some specificStuff
      return result;
   }
}

what would be the Spring-Boot-Way of creating a instance for FunctionA_DE to get it as Function_I for the calling part of the application, and what should it look like when i add FunctionB with FunctionB_DE / FunctionB_AT to my classes..
I thought it could be something like:
PSEUDO CODE
@Configuration
public class FunctionFactory {
   @Bean(SCOPE=SCOPE_PROTOTYPE) // i need a new instance everytime i call it
   public Function_I createFunctionA(FunctionConfiguration funcConfig) {
      // create Function depending on the funcConfig so either FunctionA_DE or FunctionA_AT
   }
}

and i would call it by Autowiring the FunctionFactory into my calling class and use it with
someSpringFactory.createFunction(functionConfiguration);

but i cant figure it out to create a Prototype-Bean for the function with passing a parameter.. And i cant really find a solution to my question by browsing through SO, but maybe i just got the wrong search terms.. Or my approach to solve this issue i totally wrong (maybe stupid), nobody would solve it the spring-boot-way but stick to Factories.
Appreciate your help!

A: You could use Springs's application context. Create a bean for each of the interfaces but annotate it with a specific profile e.g. "Function-A-AT". Now when you have to invoke it, you can simply set the application context of spring accordingly and the right bean should be used by Spring.

A: Hello everyone and thanks for reading my question.
after a discussion with a friend who is well versed in the spring framework i came to the conclusion that my approach or my favoured solution was not what i was searching for and is not how spring should be used. Because the Function_I-Instance depends on the for the specific batch loaded configuration it is not recommended to manage all these instances as @Beans.
In the end i decided to not manage the instances for my Function_I with spring. but instead i build a Controller / Factory which is a @Controller-Class and let this class build the instance i need with the passed parameters for decision making on runtime.
This is how it looks (Pseudo-Code)
@Controller
public class FunctionController {

   SomeSpringManagedClass ssmc;

   public FunctionController(@Autowired SomeSpringManagedClass ssmc) {
      this.ssmc = ssmc;
   }

   public Function_I createFunction(FunctionConfiguration funcConf) {
      boolean funcA, cntryDE;
      // code to decide the function
      if(funcA && cntryDE) {
         return new FunctionA_DE(funcConf);
      } else if(funB && cntryDE) {
         return new FunctionB_DE(funcConf);
      } // maybe more else if...
   }
}


text:
Q: Scope confusion in ng-grid when returning data from modal Here is the Plunker: http://plnkr.co/edit/aqLnno?p=preview
I have a list of persons ($scope.persons) to be displayed in a ng-grid. Each line has a edit button. When the user clicks on the button (ng-click="edit(row)") (see code below), I copy the displayed person (angular.copy(row.entity)) and open a modal dialog. ... so far so good.
When the user clicks "Cancel" on the modal, nothing happens. When the user clicks "Save" on the model, the modified person is returned and should be "reintegrated" in $scope.persons.
This is where the problem starts: I search in $scope.persons to find the correct person and replace it with the person returned from the modal. The log statements show the $scope.persons before and after the modification and everything looks good. However, the ng-grid doesn't seem to care. It still operates on a different (the old) $scope.persons.
If I uncomment the row.entity = person and set the row directly, everything looks fine in the ng-grid. However, as the underlying data model is not changed correctly, a resort will bring up the old (un-modified) person again.
Here is the code of my edit function:
$scope.edit = function(row) {
  $modal.open({
    templateUrl: 'personEdit.html',
    backdrop: true,
    windowClass: 'modal',
    controller: 'PersonModalInstanceCtrl',
    resolve: {
      person: function() {
        return angular.copy(row.entity);
      }
    }
  })
    .result.then(function(person) {
      $log.log('Edited person: ' + JSON.stringify(person));
      angular.forEach($scope.persons, function(p, index) {
        $log.log('p: ' + JSON.stringify(p) + ' index: ' + index);
        if (p.id == row.entity.id) {
          $log.log('scope: ' + JSON.stringify($scope.persons));
          $scope.persons[index] = person;
        }
      });
      $log.log('scope: ' + JSON.stringify($scope.persons));
      // row.entity = person;
    }, function() {});
};

What am I doing wrong with my scopes?
Thanks for any help

A: OK. Again something learnt. The answer of jantimon pointed me in the right direction. But I didn't like how he changed my $scope.persons array (I get this array from a RESTful GET and liked the fact that I can just use the returned JSON as $scope.persons without modification).
Anyway, here is the explanation:
When copying my person from the original $scope.persons list I created a new object in a new memory location:
angular.copy(row.entity)

This is necessary as the user can "Cancel" his edit.
When the user clicks "Save" I have to take this copied person and put it back to $scope.persons instead of the old one. I did this with:
$scope.persons[index] = person;

Although this is correct and gives the desired result (as the log statements show), the persons[index] now points to a different memory location.
BUT: ng-grid internally still points to the old memory location! ng-grid has not memorized the pointer (person[index]) as the data model but instead has memorized the destination of the original pointer (*person[index]) [sorry for my C-stylish talking]. I would consider this a BUG in ng-grid IMHO.
So all I need to do is copy the new person back to the exact same memory location it has come from. Luckily, there is an angular directive for that:
angular.extend($scope.persons[index], person);

If you just replace $scope.persons[index] = person; with angular.extend($scope.persons[index], person); everything works fine.

A: Looks like ng-grid isn't updating correctly when you are changing the array
You might keep the pointer of the row entity like in this example here: http://plnkr.co/edit/0lDoKOg4kXXa51NlSuMg?p=preview
It uses $scope.persons[index].data = person.data; instead of $scope.persons[index] = person;.


text:
Q: Calculating distance between consecutive points in same point layer in QGIS I have a point layer with close to 60.000 points that depict a river course (pixel extracts from satellite image). CRS of the layer is Geographic (Lat, Long).
The pixels are ordered ascendingly from source to outlet with an "ID" and each pixel has latitude and longitude. I want to know the distance in meter between two consecutive points (e.g. between point "ID"=35144 and "ID"=35145, between "ID"=35145 and "ID"=35146, etc.). This sounds very simple but I tried in numerous ways but failed.

I have tried:

*

*to transform the point layer to a line layer to measure the line segments. However, using the Vector Geometry (points to path) or diverse plugins such as NNJoin or MMQGIS I loose the vertexes (individual pixels) and therefore the point to point distance

*to create a distance matrix but this gets messy too, because it is the same layer. Also, other "nearest neighbour"-tools do not work since it is the same layer.

*to use the field calculator and loop through the rows of my dataset --> but how?

A: You can use the following script in QGIS Python Editor. It returns the distance in meter for geographic crs.
Note: ID field should be integer/numeric. If it is string, you get wrong order like: 1, 10, 11, ..., 2, 20, 21, ..., 3, 30, 31, ...
layer_name = 'POINT_LAYER_NAME'
id_field_name = 'ID'

# get layer by name
layer = QgsProject.instance().mapLayersByName(layer_name)[0]

# Add new field. DIST_TO_NXT: distance to the next feature
layer.dataProvider().addAttributes([QgsField("DIST_TO_NXT",  QVariant.Double, len=15, prec=3)])
layer.updateFields()

# get the sorted feature list
request = QgsFeatureRequest().addOrderBy(id_field_name)
feats = list(layer.getFeatures(request))

# find the field's index
field_index = layer.fields().indexFromName("DIST_TO_NXT")

da = QgsDistanceArea()
da.setEllipsoid(layer.crs().ellipsoidAcronym())
# or maybe
# da.setEllipsoid(QgsProject.instance().ellipsoid())

# skipped the last point, not to get IndexError.
for i in range(len(feats[:-1])):
    p1 = feats[i].geometry().asPoint()
    p2 = feats[i+1].geometry().asPoint()

    distance = da.measureLine(p1, p2)

    layer.dataProvider().changeAttributeValues(
                            {feats[i].id(): {field_index: distance}})

PS: The last distance is always NULL.

A: I'm sure there's some less complicated way, but you can use pyqgis like this:
lyr = QgsProject.instance().mapLayersByName('Vertices')[0] #Change Vertices to the name of your layer

orderfield = 'vertex_index' #Change to the name of you order field
distancefield = 'distance' #Field to store the distances in. Add before executing script

features = [[f.id(), f[orderfield], f.geometry()] for f in lyr.getFeatures()] #List all points id, orderfield value and geometry
features.sort(key=lambda x: x[1]) #Sort the list by orderfield
distancefieldindex = lyr.fields().indexFromName(distancefield) #Find index of distancefield

attrmap = {} #A dictionary to store each points id, distance field index and distance in
for e, (f1, f2) in enumerate(zip(features[::1], features[1::1])): #For each point pair, for example point 1 and point2, then point2 and point3
    if e==0: #If first point set distance to 0
        attrmap[f1[0]]={distancefieldindex:0}
    else: #Else calculate the distance between the two points
        attrmap[f1[0]]={distancefieldindex:f1[-1].distance(f2[-1])}

lyr.dataProvider().changeAttributeValues(attrmap) #Update the values
print('Done')

A: I am not sure if this is the best / fastest way, but I think it should work for you:
length(
    make_line(
        $geometry,
        geometry(
            get_feature_by_id('*NAME/ID_of_your_layer*', "*ID_field*"+1)
            )
        )
    )

For "ID" 1 you will get the length from 1 to 2, for 2 you will get 2 to 3 ... for your last point you won't get a length.


text:
Q: socket.io client works in browser but not in node.js The following code only works in the browser. It does not work in node.js
let socket1 = io('http://localhost:3031/nsp')

socket1.on("connect", (error) => {
  console.log("socket1: connect")
});

I am connecting to a netty-socketio (v1.7.7) java server. I am able to connect to the root namespace on both browser and node.js clients and everything works as expected. However, if I try to connect to a namespace, only the browser client can connect as expected.
Furthermore, I can see on the server that the node.js client (v2.4.0) is connecting to the root namespace when it should be connecting to the named namespace "nsp". As such, the clients join the root namespace and seemingly never join the "nsp" namespace.
On further inspection, the only event I can get to fire on the node.js client, when specifying a namespace, after connecting is "ping" all other events (connect,connect_error,error,reconnect...) never trigger.
Update: the above code works when connecting to a node.js server, so the issue appears to be with the netty-socketio server.
Here is how the netty server is initialized:
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(3031);

server = new SocketIOServer(config);
server.addNamespace('/nsp')

A: I finally figured it out. I had to revert the node.js client version to 1.7.4 (https://www.npmjs.com/package/socket.io-client/v/1.7.4) to get it to work. Not sure why I was forced to use such an old client to be able to use namespaces.


text:
Q: silverstripe fluent locale configuration I need help to understand the documentation for Fluent, from here Fluent config documentation
The documentation says:
"You can create locales via the /admin/locales CMS section."
When I create a locale, for example english, and then click on it I get at popup saying "Not Found".
Do I need to install the locale somewhere else before using it?

A: Did you run dev/build?flush=1 when you installed the module? After installation you should have everything read to go, and can start adding locales in the CMS.
Note that when you add your first locale in the CMS, the existing pages you have will not be available in that locale and you'll need to go into the Pages section and publish the pages you want to show up in your default locale.

A: I ran into this aswell.
The problem were missing files in the resouces folder. The 'Not found.' message in the admin panel refers to missing static assets like js and css files from the resouces folder. Open up your dev tools and inspect the 404'd requests. There you can see which files exactly are missing.


text:
Q: Calculation of the derivative of $e^{\cos(x)}$ from first principles The derivative of $e^{\cos(x)}$ is $-\sin(x)e^{\cos(x)}$. However I would like to prove it using first principles, i.e. by using $f'(x)=\lim_{h\to0}\frac{f(x+h)-f(x)}{h}$. I tried Taylor series but it didn't work out. Thanks for any help.

A: When we have a question of calculating the derivative via first principles then it means that the idea is to drill down the definition of derivative via actual examples. It also signifies that the student is beginning to learn differential calculus. It is therefore much better to use techniques which rely on standard limits and don't rely on advanced theorems of differential calculus (like Taylor's series on L'Hospital's rule).
We will make use of the following standard limits $$\lim_{h \to 0}\frac{e^{h} - 1}{h} = 1, \,\,\lim_{h \to 0}\frac{\sin h}{h} = 1$$ We have $f(x) = e^{\cos x}$ and by definition of derivative $$\begin{aligned}f'(x)\, &= \lim_{h \to 0}\frac{f(x + h) - f(x)}{h}\\
&= \lim_{h \to 0}\frac{e^{\cos(x + h)} - e^{\cos x}}{h}\\
&= \lim_{h \to 0}\frac{e^{\cos x}\{e^{\cos(x + h) - \cos x} - 1\}}{h}\\
&= e^{\cos x}\lim_{h \to 0}\frac{e^{\cos(x + h) - \cos x} - 1}{\cos(x + h) - \cos x}\cdot\frac{\cos(x + h) - \cos x}{h}\\
&= e^{\cos x}\lim_{t \to 0}\frac{e^{t} - 1}{t}\cdot\lim_{h \to 0}\frac{\cos(x + h) - \cos x}{h}\\
&= e^{\cos x}\cdot 1\cdot\lim_{h \to 0}\dfrac{-2\sin\left(x + \dfrac{h}{2}\right)\sin\left(\dfrac{h}{2}\right)}{h}\\
&= -e^{\cos x}\cdot\lim_{h \to 0}\sin\left(x + \frac{h}{2}\right)\cdot\lim_{h \to 0}\frac{\sin(h/2)}{h/2}\\
&= -e^{\cos x}\cdot\sin x\cdot 1 = -e^{\cos x}\sin x\end{aligned}$$ In the above derivation we have made the substitution $t = \cos(x + h) - \cos x$ and $t \to 0$ as $h \to 0$.

A: $$f'(x)=\lim_{h\to0}\frac{f(x+h)-f(x)}{h}=e^{\cos x}\lim_{h\to 0}\frac{e^{\cos x(\cos h-1)-\sin x\sin h}-1}{h},$$
we use hospital Rule to compute the limit
We have
\begin{align}
\lim_{h\to 0}\frac{e^{\cos x(\cos h-1)-\sin x\sin h}-1}{h}
&=\lim_{h\to 0}\left[(-\sin h(\cos x)-\cos h\sin x)\ e^{\cos x(\cos h-1)-\sin x\sin h}\right]\\
&=\lim_{h\to 0}(-\sin h(\cos x)-\cos h\sin x)\,\cdot\,\lim_{h\to 0}e^{\cos x(\cos h-1)-\sin x\sin h}\\
&=-\sin x.
\end{align}

A: Indeed, Taylor series about $h \to 0$ works! Your limit calculation for the derivative can be written as:
$$ L = \lim_{h\to 0} \frac{e^{\cos{(x + h)}} - e^{\cos{x}}}{h} = \lim_{h \to 0} \frac{e^{\cos{x}} - e^{\cos{x}} \, h \, \sin{x}  - \frac{1}{2} e^{\cos{x}} (\cos{x} - \sin^2{x}) \, h^2 + \mathcal{O}(h^3) - e^{\cos{x}}}{h}, $$
simplifying and cancelling out every term in $h$ it yields:
$$ L = -e^{\cos{x}} \sin{x} = f'(x).$$
Cheers!
PS: I used Mathematica to perform the Taylor series for speed, but it's only strictly necessary to retain terms of first order in $h$. But, since Taylor expansion requires derivating, this should not be qualified as "first principles".


text:
Q: Probability that Carl has to wait at least 10 minutes for one of the others and for both of the others to show up? This question is for the other subquestions for the same problem here. For those not willing to click the link, I will post the exercise problem here as well.

Alice, Bob, and Carl arrange to meet for lunch on a certain day. They arrive independently at uniformly distributed times between 1 p.m. and 1:30 p.m.
For the rest of the problem, assume Carl arrives first at 1:10 p.m. and condition on this fact.
(b) What is the probability that Carl will have to wait more than 10 minutes for one of the others to show up?
(c) What is the probability that Carl will have to wait more than 10 minutes for both of the others to show up?

Apparently, my approach to the solution has given me the answers in a swapped manner, which I can't understand why. Allow me to elaborate.

My approach
Let's say that the events for Alice and Bob arriving are each $A$ and $B$ i.i.d. on Unif($10,\ 30$).

(b) The probability that Carl will wait more than 10 minutes for at least one of the others to arrive is:
(Probability that Carl waits less than 10 minutes for Alice and more than 10 for Bob) + (Probability that Carl waits less than 10 minutes for Bob and more than 10 for Alice) + (Probability that Carl waits more than 10 minutes for both)
which gives me the result of $(\frac{1}{2} * \frac{1}{2}) + (\frac{1}{2} * \frac{1}{2}) + (\frac{1}{2} * \frac{1}{2}) = \frac{3}{4}$.

(c) Probability that Carl waits more than 10 minutes for both is the probability that $A$ and $B$ both fall in the interval ($20$, $30$) in the total interval ($10$, $30$). Therefore we get the probability $\frac{1}{2} * \frac{1}{2} = \frac{1}{4}$.

However, apparently the correct answer is $\frac{1}{4}$ for (b) and $\frac{3}{4}$ for (c), and I'm not entirely sure why.
The rationale the textbook gives is that for (b) we need to compute the time that both of them arrive after 1:20 p.m., and for (c) we simple take the complement that both of them arrive between 1:10 and 1:20 p.m. $1 - \frac{1}{4}$. I'm not entirely sure how these solutions make sense, though, and was hoping someone would be kind enough to provide me with some insight.

Thank you.

A: It seems to me that questions (b) and (c) are both genuinely ambiguous, and both your solution and the one given in the textbook could be considered correct.

(b) What is the probability that Carl will have to wait more than 10 minutes for one of the others to show up?

I read this as asking for the probability that $\
\min(A, B)>10\ $, where $\ A\ $ is the time Carl has to wait for Alice to arrive and $\ B\ $  the time he has to wait for Alice to arrive.  While this seems to me to be the most natural way of reading the question, I recognise that it can also be read as asking for the probability that at least one of $\ A\ $ and $\ B\ $ is greater than $10$—that is, the probability that $\ \max(A,B)>10\ $—and this may well seem to be the more natural reading to others.

(c) What is the probability that Carl will have to wait more than 10 minutes for both of the others to show up?

I initially read this as asking for the probability that Carl had to wait for more than $10$ minutes for both Alice and Bob to be present—that is, the probability that $\ \max(A,B)>10\ $.  However, it seems to me just as natural to take it as asking for the probability that both Alice and Bob take more than $10$ minutes to arrive—that is, the probability that $\ \min(A,B)>10\ $.

A: So this is my understanding of the problem, the logic was annoying for me to understand as well.
b) So we can also define the event "Carl has to wait more than 10 minutes for one of them to arrive" as none of them arrived between the interval of 1:10-1:20 i.e none of them arrived within 10 minutes.
So we know that The probability of Alice and Bob have not arrived is 0.5 each. So we get the probability of 1/4 that none of them arrived within 10 minutes. From what  I saw in your method you have also considered that one of them arrives within 10 minutes which shouldn't be considered in the problem since it's not at least! Otherwise your method was correct
c)similarly here we know that the probability of each arriving is 0.5 so both of them arriving within the next 10 minutes is 1/4.
If Carl needs to wait more than 10 minutes for them definitely both of them arrive between 1:20-1:30. so if the probability of them arriving before 1:20 is 1/4 then the event that they arrive between 1:20-1:30 corresponds with the event that they did not arrive at between 1:10-1:20 so if the probability that they arrive between 1:10-1:20 is 1/4 then probability that they did not is 3/4.
At least that is what I understood from their explanation I still think it is a bit odd but I this is what I interpretted.


text:
Q: Why Android Studio keeps showing a blue screen or getting stuck at previous changes of the app I'm developing? Android studio is getting stuck constantly and updating or restarting pc is not helping. Sometimes the emulator would show a previous change that was made to the app, while others it would display a blue screen showing that something went wrong without showing more details. I think is not the Wi-Fi connection because I've tried it even within my university campus and the problem keeps appearing.
When these problems are showing but the blue screen is not showing, I'd notice that neither the buttons of the android emulated nor the changes made to the app would be displayed. Sometimes Android SDK and Expo would work properly without my intervention.
Can someone please illustrate me? This is interfering with my app development without it being a direct problem of my app.
Photo of the blue screen
Description of the blue screen
Also, I already searched on StackOverflow and reddit, but I don't find a current answer for this problem.


text:
Q: accessing dict within dict value python tmpDict = {'ONE':{'TWO':{'THREE':10}}}

From this dictionary, how would would print the value 10? This is similar to a previously asked question, but they wanted to know how to add more values.

A: print(tmpDict['ONE']['TWO']["THREE"])

This is a general solution for all keys:
all_values = [tmpDict[i][j][k] for i in tmpDict.keys() for j in tmpDict[i].keys() for k in tmpDict[i][j].keys()]
print(all_values)

A: Generally speaking you can navigate nested dictionaries in Python3 in the following way (d is your dictionary):
def traverse_nested_dict(d, parent_key='root'):
    """ Traverse dictionary and print keys and values
        :param d: a dictionary"""
    for key, value in d.items():
        current_key = parent_key+'.'+key
        if type(value) is dict:
            traverse_nested_dict(value, parent_key=current_key)
        else:
            print(f'{current_key} -> {value}')

for example:
my_dict = {'a': {'b': 3, 'c': {'d': 5}}}
traverse_nested_dict(my_dict)

will produce this output:
root.a.b -> 3
root.a.c.d -> 5

using your input:
tmpDict = {'ONE':{'TWO':{'THREE':10}}}
traverse_nested_dict(tmpDict)

you'll get:
root.ONE.TWO.THREE -> 10


text:
Q: Why do I need to fit a GridSearchCV object to the data before I can get the best parameters and model? My question is similar to the one here, but the answer there does not explain why we must fit to the data before getting the best paramters, it just states that we must. In my understanding, GridSeachCV picks the best model parameters using cross validation, and then returns this best model in the .best_estimator attribute. Then we can fit the that model to our data. But shouldn't we be able to access the parameters it picked and the .best_estimator model before fitting to the data?
As an example, the code below works fine:
logreg = LogisticRegression(solver='liblinear')
params = {'penalty':['l1','l2'], 'C':np.logspace(-3,3,7),}
grid = GridSearchCV(estimator=logreg, params, cv=4)
grid.fit(X_train,y_train)
best_model_params = grid.best_params_
y_pred = grid.predict(X_test)

But the following code does not work:
logreg = LogisticRegression(solver='liblinear')
params = {'penalty':['l1','l2'], 'C':np.logspace(-3,3,7),}
grid = GridSearchCV(estimator=logreg, params, cv=4)
best_model_params = grid.best_params_
grid.fit(X_train,y_train)
y_pred = grid.predict(X_test)

It gives AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'.
On a related note, if grid.best_estimator_ is the best LogisticRegression model (the model with the set of hyperparameters found to be best through cross validation in GridSearchCV) then why do we fit the grid object instead of the grid.best_estimator_ object? E.g. if I could figure out how to access the best_estimator attribute before fitting, would the following code work?:
logreg = LogisticRegression(solver='liblinear')
params = {'penalty':['l1','l2'], 'C':np.logspace(-3,3,7),}
grid = GridSearchCV(estimator=logreg, params, cv=4)
best_model = <somehow get the model GridSearchCV has picked>
best_model.fit(X_train,y_train)
y_pred = best_model.predict(X_test)


text:
Q: android error FATAL EXCEPTION: AsyncTask #1 Help is needed, I just started learning to code and trying to create a product app but I encountered some errors.
Here is my class:
public class AllProductsActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://127.0.0.1/android_connect2/get_all_products.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditProductActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String[]> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        //pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String[] doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON response
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewProductActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllProductsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME},
                        new int[] { R.id.pid, R.id.name });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

And my JSON parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method.equals("GET")){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

This is the error I'm getting:
E/Buffer Error: Error converting result java.lang.NullPointerException
E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
              Process: com.example.androidhive, PID: 3761
              java.lang.RuntimeException: An error occurred while executing doInBackground()
                  at android.os.AsyncTask$3.done(AsyncTask.java:318)
                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                  at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                  at java.lang.Thread.run(Thread.java:761)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
                  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:130)
                  at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
                  at android.os.AsyncTask$2.call(AsyncTask.java:304)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                  at java.lang.Thread.run(Thread.java:761)

Any help is appreciated, I have searched this site for solutions but each question is answered code-specific. Cheers

A: Because this line returns null JSONObject
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

So check first that it's has null value or not before changing it into string
Like..
if (json != null && json.getInt(TAG_SUCCESS) != 0/*or failed value
*/){
// ALSO PARSE RESULT HERE
  // Check your log cat for JSON response
    Log.d("All Products: ", json.toString());
}else{
// SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE
}

Hope this will help you.


text:
Q: Embedding fonts on Android, iOS, and Blackberry - is there a bulletproof solution? I've been working on a mobile web project testing embedded font support, I've tried the Google font API and EOT so far the results are sporadic.
EOT Results so far:-

*

*Blackberry: No support at all (9700, Bold)

*Android: 2.1< No support 3.0> Some support, but renders with errors.

*iOS: 4> Works perfectly.

Google font API has similar results.
So, are there any bullet proof solutions or alternatives for embedding fonts on the mobile web? Research has yielded little useful information so far, since most of the work online seems to pertain to Apps.

A: you could try font-squirrel's font-face generator - although I have not tested it with Blackberry yet, it even works in IE7 (maybe IE6?) and generally outputs a pretty solid solution.


text:
Q: UserControl's DataContext update WPF I have my own usercontrol named FlashControl in the mainwindow. I set the DataContext by following code  in the mainwondow
        (FlashControl.Content as FrameworkElement).DataContext = null;
        (FlashControl.Content as FrameworkElement).DataContext = this.DataContext;
        FlashControl.DataContext = this.DataContext;

My problem is whenever my datacontext change I need to call the above code to reset usercontrol's datacontext. Why Usercontrol's DataContext not updated automatically when main DataContext change? How to do automatic update? Am I missing something?

A: If you want automatic update dont set DataContext directly but Bind it to the value you want.
You should bind in xaml but if you want to do in code behind then you can do:
Binding myBinding = new Binding("DataContext");
myBinding.Source = this;
BindingOperations.SetBinding(FlashControl, FrameworkElement.DataContextProperty, myBinding);


text:
Q: Calling a $scope in a timeout function I have 2 inputs here, one is setting the value using scope and the other is setting the value after the setTimeout, but my problem here is that... it doesn't show the value immediately and I need to click the second input to show the value. Any solution for this?

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.firstInput = "click the second input";
    $scope.secondInput;

    function init(){
     setTimeout(function(){
     $scope.secondInput = "second input";
     }, 1000);
    }
    init();
  }]);

<input type="text" ng-model="firstInput"></input>
<input type="text" ng-model="secondInput"></input>

A: Use $timeout instead of setTimeout

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', '$timeout', function($scope, $timeout) {
    $scope.firstInput = "click the second input";
    $scope.secondInput;

    function init(){
     $timeout(function(){
       $scope.secondInput = "second input";
     }, 1000);
    }
    init();
}]);

  <input type="text" ng-model="firstInput"></input>
  <input type="text" ng-model="secondInput"></input>

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.
For more information, see

*

*AngularJS $timeout Service API Reference

A: First of all you should follow the solution given by @barbsan. using $timeout instead of setTimeout. That being said you'd still want to $scope.$apply().
to do that if you look into angularjs docs for $timeout, the third parameter is for that. so You can just do the following
$timeout(function() {
              $scope.secondInput = "second input";
            }, 1000,true);

A: When you update the second input from setTimeout, the change isn't detected, and you must force change detection manually.
I think adding $scope.$digest(); after $scope.secondInput =... should do the trick.


text:
Q: Does ios_base::sync_with_stdio(false) affect ? It is well known that ios_base::sync_with_stdio(false) will help the performance of cin and cout in <iostream> by preventing sync b/w C and C++ I/O. However, I am curious as to whether it makes any difference at all in <fstream>.
I ran some tests with GNU C++11 and the following code (with and without the ios_base::sync_with_stdio(false) snippet):
#include <fstream>
#include <iostream>
#include <chrono>
using namespace std;

ofstream out("out.txt");

int main() {
    auto start = chrono::high_resolution_clock::now();
    long long val = 2;
    long long x=1<<22;
    ios_base::sync_with_stdio(false);
    while (x--) {
        val += x%666;
        out << val << "\n";
    }
    auto end = chrono::high_resolution_clock::now();
    chrono::duration<double> diff = end-start;
    cout<<diff.count()<<" seconds\n";
  return 0;
}

The results are as follows:
With sync_with_stdio(false): 0.677863 seconds (average 3 trials)
Without sync_with_stdio(false): 0.653789 seconds (average 3 trials)

Is this to be expected? Is there a reason for a nearly identical, if not slower speed, with sync_with_stdio(false)?
Thank you for your help.

A: The idea of sync_with_stdio() is to allow mixing input and output to standard stream objects (stdin, stdout,  and stderr in C and std::cin, std::cout, std::cerr, and std::clog as well as their wide character stream counterparts in C++) without any need to worry about characters being buffered in any of the buffers of the involved objects. Effectively, with std::ios_base::sync_with_stdio(true) the C++ IOStreams can't use their own buffers. In practice that normally means that buffering on std::streambuf level is entirely disabled. Without a buffer IOStreams are rather expensive, though, as they process individual character involving potentially multiple virtual function calls. Essentially, the speed-up you get from std::ios_base::sync_with_stdio(false) is allowing both the C and C++ library to user their own buffers.
An alternative approach could be to share the buffer between the C and C++ library facilities, e.g., by building the C library facilities on top of the more powerful C++ library facilities (before people complain that this would be a terrible idea, making C I/O slower: that is actually not true at all with a proper implementation of the standard C++ library IOStreams). I'm not aware of any non-experimental implementation which does use that. With this setup std::ios_base::sync_with_stdio(value) wouldn't have any effect at all.
Typical implementations of IOStreams use different stream buffers for the standard stream objects from those used for file streams. Part of the reason is probably that the standard stream objects are normally not opened using a name but some other entity identifying them, e.g., a file descriptor on UNIX systems and it would require a "back door" interface to allow using a std::filebuf for the standard stream objects. However, at least early implementations of Dinkumware's standard C++ library which shipped (ships?), e.g., with MSVC++, used std::filebuf for the standard stream objects. This std::filebuf implementation was just a wrapper around FILE*, i.e., literally implementing what the C++ standard says rather than semantically implementing it. That was already a terrible idea to start with but it was made worse by inhibiting std::streambuf level buffering for all file streams with std::ios_base::sync_with_stdio(true) as that setting also affected file streams. I do not know whether this [performance] problem was fixed since. Old issue in the C/C++ User Journal and/or P.J.Plauger's "The [draft] Standard C++ Library" should show a discussion of this implementation.
tl;dr: According to the standard std::ios_base::sync_with_stdio(false) only changes the constraints for the standard stream objects to make their use faster. Whether it has other effects depends on the IOStream implementation and there was at least one (Dinkumware) where it made a difference.


text:
Q: Correct format of protoc go_package? I have an existing project in Go where I'm using Protocol buffers / gRPC. Until recent the go_package option was optional and the resulting Go package name would be the same as the proto package name.
This file lives in the project root. The generated code file (authenticator.pb.go) is living in the same location. Proto file:
syntax = "proto3";

package authenticator;

service Authenticator {...}

Generation command specifies I want to output in the same directory:
protoc --go_out=plugins=grpc:. authenticator.proto

Today I've pulled new version of the protocol buffers compiler and github.com/golang/protobuf/protoc-gen-go. Upon the first run a got a warning:
WARNING: Missing 'go_package' option in "authenticator.proto",
please specify it with the full Go package path as
a future release of protoc-gen-go will require this be specified.
See https://developers.google.com/protocol-buffers/docs/reference/go-generated#package for more information.

The suggested link is more or less useless. But the tutorial is a bit more explicit:

The go_package option defines the import path of the package which
  will contain all the generated code for this file. The Go package name
  will be the last path component of the import path. For example, our
  example will use a package name of "tutorialpb".
option go_package = "github.com/protocolbuffers/protobuf/examples/go/tutorialpb";

After adding this option to the proto file and rerunning the command, the output ends up in this path, relative to the project root. Something like:
$GOPATH/src/github.com/<org>/authenticator/github.com/<org>/authenticator/authenticator.pb.go

I've tried the following alternatives as go_package names:

*

*.

*authenticator
Generation happened in the correct location, but I got the warning back:
WARNING: Deprecated use of 'go_package' option without a full import path...

So what is the correct way without breaking the project layout?

A: The abovementioned error disappeared when I added
option go_package = "github.com/monkrus/grpc-from0;grpc_from0"; as below:

A: If you are using syntax = "proto3";. This issue will bound to happen after the change in grpc code generation processing.To fix this issue
step 1: past this line in your your_file_with.proto
 option go_package = "pb;gen";

step 2 : Suppose you want to generate all files in pb folder replce the pb with your sutable name then run cmd in your terminal window.In my case my all protofile is in proto folder in project directory
 protoc -I=proto --go_out=. proto/*.proto

A: I'm using Go and I want to create *.pb.go in the same folder with *.proto what I do is in *.proto
option go_package = "./{Your folder name}";

Take note, Your folder name will be reflected in the generated *.pb.go package. Then run:
protoc --go_out=.. *proto

A: For pure proto generations you can do the following
protoc --go_out=paths=source_relative:./gen -I. authenticator.proto

or to generate for grpc the following can be used
protoc --go_out=plugins=grpc:./gen --go_opt=paths=source_relative authenticator.proto

If that fails you likely have a newer version of protoc and need to use the following command instead.
protoc --go-grpc_out=./gen --go-grpc_opt=paths=source_relative authenticator.proto

This is just Google making isolated decisions once again about how you should write and manage your code. However if you dig through enough issues of people having similar problems I found the above command can now be used. In addition to adding the full import path as shown in the other answer
option go_package = "github.com/example/path/gen;gen";

Following the above package and protoc command you would have your proto file in the project root with a module name of github.com/example/path. Your code would then be placed inside the gen folder which you will be responsible for creating.
You may need to adjust the output location of source_relative for your use but at least you don't end up with the duplication of paths or having to rely on placing your code in GOPATH again.
This may break going forward because of the additional changes found in this ticket. Unfortunately the binary name is exactly the same so if you run into issues read that ticket and try switching the version that you have installed until the new protoc-gen-go is ready for prod.

A: Hello I will explain step by step how I have generated it by reading the documentation
Create folder grpcgo
mkdir grpcgo && cd grpcgo

Create project
    go mod init projectxxx
    ## Download and install dependencies
    go get google.golang.org/protobuf/cmd/protoc-gen-go
    go get github.com/golang/protobuf

   sudo snap install protobuf or sudo apt  install protobuf-compiler

Create folder proto and inner folder the file .proto
wishlist.proto
syntax = "proto3";

package grpcgo; #Folder

option go_package = "pb;gen"; <-- Add

message Item {
    enum ItemPriority {
        LOW = 0;
        MID = 50;
        HIGH = 100;
    }

    enum ItemStatus {
        INACTIVE = 0;
        ACTIVE = 1;
    }

    string id = 1;
    string wishListId = 2;
    string name = 3;
    string link = 4;
    double price = 5;

    ItemPriority priority = 6;
    ItemStatus status = 7;

}

message WishList {
    enum WishListStatus {
        INACTIVE = 0;
        ACTIVE = 1;
    }

    string id = 1;
    string name = 2;
    WishListStatus status = 3;

}

Compiling proto
protoc -I=$PWD --go_out=$PWD $PWD/proto/*.proto

Documentation:
https://developers.google.com/protocol-buffers/docs/gotutorial
https://blog.friendsofgo.tech/posts/introduccion-a-grpc/
Version:
github.com/golang/protobuf v1.5.2
google.golang.org/protobuf v1.26.0
go version go1.16.5 linux/amd64
#EDIT
$ protoc -I=$PWD --go_out=$PWD $PWD/proto/*.proto
protoc-gen-go: program not found or is not executable
Please specify a program using absolute path or make sure the program is available in your PATH system variable
--go_out: protoc-gen-go: Plugin failed with status code 1.

is solution is instaall protoc-gen-go
sudo snap install protobuf               # version 3.14.0, or
sudo apt  install golang-goprotobuf-dev  # version 1.3.4-2
sudo apt  install protoc-gen-go          # version 1.27.1-1

Edit 2
create dir pb in the root project
protoc -I=$PWD --go_out=$PWD/pb $PWD/protos/*.proto
syntax = "proto3";

package grpcgo;

option go_package = "../pb"; <--

message Item {
    enum ItemPriority {
        LOW = 0;
        MID = 50;
        HIGH = 100;
    }

    enum ItemStatus {
        INACTIVE = 0;
        ACTIVE = 1;
    }

    string id = 1;
    string wishListId = 2;
    string name = 3;
    string link = 4;
    double price = 5;

    ItemPriority priority = 6;
    ItemStatus status = 7;

}

message WishList {
    enum WishListStatus {
        INACTIVE = 0;
        ACTIVE = 1;
    }

    string id = 1;
    string name = 2;
    WishListStatus status = 3;

}

versions:
protoc-gen-go v1.27.1
protoc        v3.12.4

hug from Argentina

A: If your package name is user_service
user_service.proto definition like this:
syntax = "proto3";

package user_service;

service UserService {
}

just add option go_package = "./;user_service"; under package user_service; like this :

syntax = "proto3";

package user_service;

option go_package = "./;user_service";

service UserService {
}

Run the following: protoc *.proto --go_out=plugins=grpc:./ within the user_serivce directory. This should work.

A: You just need to add a Go option which will tell to add file relative to proto file.
protoc --go_out=. --go_opt=paths=source_relative your_file.proto

This will make the your_file.pb.go in same directory as your_file.proto

A: Although the documentation doesn't show, I've made it work by setting the output directory to GOPATH/src.
protoc --go_out=plugins=grpc:$(go env GOPATH)/src authenticator.proto

Hope this can be a time saver for anybody else.

A: Per testing in the go-grpc-http-rest-microservice-tutorial project
https://medium.com/@amsokol.com/tutorial-how-to-develop-go-grpc-microservice-with-http-rest-endpoint-middleware-kubernetes-af1fff81aeb2
and source code
https://github.com/amsokol/go-grpc-http-rest-microservice-tutorial/tree/part2
Trying to generate protobufs but the command kept failing.  Running the command by itself could cause the command to fail silently, or if I tried running the command prefixed with sudo I may get the error:
Please specify a program using absolute path or make sure the program is available in your PATH system variable
--go_out: protoc-gen-go: Plugin failed with status code 1.
I knew the path wasn't a problem, I could echo $PATH and see the GOBIN and GOROOT paths were in path (albeit I am not explicitly exporting either of those vars directly), i.e. at the bottom of .bashrc
# export GOPATH=$HOME/go
# export GOBIN=$HOME/go/bin
# export GOROOT=/usr/local/go/bin
# export PATH=$PATH:$GOBIN:$GOROOT
export PATH=$PATH:$HOME/go/bin:/usr/local/go/bin

$ echo $PATH
/home/tngai/.local/bin:/usr/local/lib/npm/bin:/usr/local/sbin:/usr/local/bin:/usr        /sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/include:/home/tngai/go/bin:/usr/local/go/bin

and if I typed in protoc-gen-go it would not error (but appear to take me to another command line, which I ctrl+c to exit from), so that was not a problem
Long story short, I noted that two params are involved for determining the output path to the generated files and also that If you make the path too long, it may error silently.
Here is it working:
command to generate, where the first two are just file paths to find the proto file and it's dependency proto files, and the go_out which is the prefix path for the output file(s):
//cmd to run to generate protobuf and add it to the output directory
protoc --proto_path=api/proto/v1 --proto_path=third_party --go_out=plugins=grpc:./output todo-service.proto

// or below to add it under the pkg directory
protoc --proto_path=api/proto/v1 --proto_path=third_party --go_out=plugins=grpc:./ todo-service.proto

when combined to the path mentioned in the proto file itself from the required option go_package, which is the next part of the output path.
//todo-service.proto file
syntax = "proto3";
package v1; //name of the folder this is in

import "google/protobuf/timestamp.proto";
import "google/api/annotations.proto";
//import "protoc-gen-swagger/options/annotations.proto";

//new required line I had to add, and which also determines output path of gen file(s)
option go_package = "./pkg/api/v1";

//...commented out the swagger generation per testing just the protobuf generation...

// Task we have to do
message ToDo {
// Unique integer identifier of the todo task
int64 id = 1;
// ...

A: You can simply define your optional import path as follows
option go_package = ".;<Your_Import_path>";

For example, we can assume the package path as "/pub", So the statement as follows.
option go_package = ".;pub";

Then you can simply execute the protoc command to generate the pb.go file
protoc -I=<ABS_PATH_OUTPUT_DIR> --go_out=<ABS_PATH_PROTO_FILE>

A: Add this to your .proto source file
option go_package = "relative_path_to_go_package"; // i.e: ./ if the .proto source file is in the root folder
syntax = "proto3";
package chat;

option go_package = "./";

message Message {
    string body = 1;
}

service ChatService {
    rpc SayHello(Message) returns (Message) {}
}


text:
Q: Vue Duplicate keys detected I have some problems with migrating my vue app from vuesax to bootstrap. I never worked with bootstrap and Vue, so it's kinda hard to adopt the first day.
I a problem like

Duplicate keys detected: '133'.

showing in console, and I have no idea why. I'm using the same scripts as in vuesax but HTML is different.
So I have form repeater that looks like:
<b-row v-for="(product_info, index) in form.product_info">
                        <b-col cols="12" class="mb-2" :style="{animation: 'fadeInDown 0.5s'}">

                            <validation-provider #default="{ errors }" name="Country" rules="required">
                                <b-form-group label="Country" label-for="country" :state="errors.length > 0 ? false:null">
                                    <v-select id="country" v-model="product_info.country" :dir="$store.state.appConfig.isRTL ? 'rtl' : 'ltr'" :options="activeCountries" :selectable="option => ! option.value" label="name" />
                                    <b-form-invalid-feedback :state="errors.length > 0 ? false:null">
                                        {{ errors[0] }}
                                    </b-form-invalid-feedback>
                                </b-form-group>
                            </validation-provider>

                            <validation-provider #default="{ errors }" name="Name" rules="required">
                                <b-form-group label="Name" label-for="name" :state="errors.length > 0 ? false:null">
                                    <b-form-input color="success" label-placeholder="Name" v-model="product_info.name" name="name" type="text" />
                                    <b-form-invalid-feedback :state="errors.length > 0 ? false:null">
                                        {{ errors[0] }}
                                    </b-form-invalid-feedback>
                                </b-form-group>
                            </validation-provider>

                            <validation-provider #default="{ errors }" name="Slug" rules="required">
                                <b-form-group label="Slug" label-for="slug" :state="errors.length > 0 ? false:null">
                                    <b-form-input color="success" label-placeholder="Slug" v-model="product_info.slug" name="slug" type="text" />
                                    <b-form-invalid-feedback :state="errors.length > 0 ? false:null">
                                        {{ errors[0] }}
                                    </b-form-invalid-feedback>
                                </b-form-group>
                            </validation-provider>

                            <validation-provider #default="{ errors }" name="Description" rules="required">
                                <b-form-group label="Description" label-for="description" :state="errors.length > 0 ? false:null">
                                    <b-form-textarea v-model="product_info.description" label="Discription" class="md:mt-10 mt-6 mb-0" rows="3" type="text" name="description" />
                                    <b-form-invalid-feedback :state="errors.length > 0 ? false:null">
                                        {{ errors[0] }}
                                    </b-form-invalid-feedback>
                                </b-form-group>
                            </validation-provider>

                            <b-button v-ripple.400="'rgba(113, 102, 240, 0.15)'" variant="outline-primary" pill @click="deleteProductInfo(index)">x</b-button>
                        </b-col>
                    </b-row>
                    <b-button v-ripple.400="'rgba(113, 102, 240, 0.15)'" variant="outline-primary" pill @click="addProductInfo">Add Product Info</b-button>

And this is scripts
This is how I catch countries from backend:
mounted() {
        Countries.activeCountries().then(response => {
            this.activeCountries = response.data.countries
        });
    },

This is data (product_info is form repeater, packages as well but I haven't migrated it yet):
form: {
                sku: '',
                slug: '',
                category: '',
                type: '',
                product_info: [],
                packages: [],
            },

And those are methods for form repeater:
addProductInfo: function () {
            this.form.product_info.push({
                country: '',
                name: '',
                slug: '',
                description: ''
            });
        },
        deleteProductInfo: function (index) {
            this.form.product_info.splice(index, 1);
        },

The error is coming from:
<v-select id="country" v-model="product_info.country" :dir="$store.state.appConfig.isRTL ? 'rtl' : 'ltr'" :options="activeCountries" :selectable="option => ! option.value" label="name" />

And I have no idea what could cause the problem. Any suggestions?

A: The problem was a duplicate key entry in the database. I had 2 same countries.


text:
Q: Getting error: Class name must be a valid object or a string So I've got an issue with element-api in php, which is a plugin for CRAFT cms, could someone help - what am I doing wrong here? I can't print time.json - always getting :

{"error":{"code":0,"message":"Class name must be a valid object or a
string"}}

here's the code:
<?php

use Craft;
use craft\elements\Entry;
use craft\controllers\TemplatesController;
use League\Fractal\TransformerAbstract;
use craft\web\View;
use craft\elements\User;

return [
    'endpoints' => [
    'tooltip-modal.json' => function() {

        $affiliateId = Craft::$app->request->getParam('entryId');
        $siteLanguage = Craft::$app->request->getParam('siteLanguage');

        $data = [
            'elementType' => Entry::class,
            'paginate' => false,
            'transformer' => function(Entry $affiliate) {
                $view = Craft::$app->getView();
                // $view->setTemplateMode($view::TEMPLATE_MODE_SITE);
                return [
                    'affiliate' => $view->renderTemplate('modals/tooltipAffModal.twig', ['affiliate' => $affiliate])

                ];
            },
            'criteria' => ['id' => $affiliateId, 'site' => $siteLanguage]
        ];

        return $data;
    },
    'time.json' => function() {
        // $userId = Craft::$app->request->request->getParam('userId');

        $data = [
            'elementType' => User::class,
            'paginate' => false,
            'transformer' => function(User $user) {
                return [
                    'date' => $user->winHistory::find()->orderBy(['id' => SORT_DESC])->one()

                ];
            },
            // 'criteria' => ['id' => $affiliateId, 'site' => $siteLanguage]

        ];
        return $data;
    }
    ]
];


text:
Q: How do I read a 16-bit int from a Uint8List in Dart? I have a binary data stored in Uint8List and I'd like to read a 16-bit int from that list. Are there any convenience methods to help with this?
(paraphrasing from a conversation I had with a colleague)

A: You can use the ByteData class:
var buffer = new Uint8List(8).buffer;
var bytes = new ByteData.view(buffer);
bytes.getUint16(offset);

(paraphrased from an answer provided by a colleague)

A: As Seth said, you want a ByteData view of the Uint8List binary data.
It is slightly better to use ByteBuffer.asByteData().
It is a little more concise and works better for testing.
If you have a mock Uint8List and a mock ByteBuffer, new ByteData.view(buffer) will fail, but the mock ByteBuffer's asByteData() method could be made to return a mock ByteData.
var bytes = myUint8List.buffer.asByteData();
bytes.getUint16(offset);

With perfect foresight we would only have asByteData() and not also a redundant public ByteData.view constructor.


text:
Q: Trouble printing Eigen types in gdb using python extension I'd like to print Eigen matrices and vectors in gdb, and so I added the extension to do so found here: https://bitbucket.org/eigen/eigen/src/12a658962d4e/debug/gdb/printers.py
When I try to call print on some Eigen type in ddd, however, I get the following error:
Python Exception <class 'TypeError'> 'map' object is not subscriptable:
Python Exception <class 'TypeError'> 'map' object is not subscriptable:
Python Exception <class 'TypeError'> 'map' object is not subscriptable:

Based on this post I checked that my gcc version is 4.8.2 and my gdb version is 7.7.1, so neither of those are the problem.
Any ideas on how I might be able to fix this?

A: Can you make sure that 2.7.6 is the version that gdb uses by making the following check from it?

*

*Start gdb.

*Type:
import sys
print (sys.version)

*End with CTRL+D


text:
Q: python 'x_min' referenced before assignment error i am new to python and i have been working on trying to plot a scoreplot using matplotlib, however, i kept getting this error, UnboundLocalError: local variable 'x_min' referenced before assignment.Any tips or suggestions would be appreciated.
this is my code
# Plots score plot with data labels
# Pass original data, un-centred scores and returns of PCA to this function. Optional width, height and margin.
# This function returns the axes of the score plot

def scoreplot_label(dt, scores, pca, width=5, height=5, margin=0.5):
    plt.figure(figsize=(width, height))
    # ax = sns.scatterplot(x="PC1", y="PC2", data=scores)
    # I used regplot only because my version of Seaborn is old and does not have scatterplot
    scores['label'] = Y
    ax = sns.lmplot(x='PC1', y='PC2', data=scores, fit_reg=False,
                    scatter_kws={'s':50}, hue='label',
                    scatter=True).set(xlim=(x_min, x_max),
                                      ylim=(y_min, y_max)
                                      ).set_titles("Score plot",
                                                   fontsize=14
                    )

    # (added this section) text for labels
    text_pos = 0.5
    # Print text
    for i, v in enumerate(np.array(scores)):
        ax.text(v[0], v[1]+text_pos, dt.iloc[i,0], color='black',
                ha='center', va='center', fontsize=12)

    # Set limits for figure
    x_min = min(scores['PC1'].min(),0) - margin
    x_max = max(scores['PC1'].max(),0) + margin
    y_min = min(scores['PC2'].min(),0) - margin
    y_max = max(scores['PC2'].max(),0) + margin

    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    ax.set_title("Score plot", fontsize=14)
    plt.plot([x_min, x_max], [0, 0], color='k', linestyle='--', linewidth=1)
    plt.plot([0, 0], [y_min, y_max], color='k', linestyle='--', linewidth=1)
    return ax

    plt.clf
ax3 = scoreplot_label(data, scores2, pca2, width=20, height=20, margin=20)
plt.show()

it says the line has some errors followed by the UnboundLocalError: local variable 'x_min' referenced before assignment
---> 10     ax = sns.lmplot(x='PC1',y='PC2',data=scores,fit_reg=False,scatter_kws={'s':50},hue='label',scatter=True).set(xlim=(x_min, x_max),ylim=(y_min, y_max)).set_titles("Score plot", fontsize=14)

A: set(xlim=(x_min, x_max),ylim=(y_min, y_max)
on this line variables which are used :- x_min, x_max, y_min, y_max you have nowhere defined those, before using it, not inside function neither globally check below snippet you need to define those.
def scoreplot_label(dt, scores, pca, width=5, height=5, margin=0.5):
    plt.figure(figsize=(width, height))
    #ax = sns.scatterplot(x="PC1", y="PC2", data = scores)
    # I used regplot only because my version of Seaborn is old and does not have scatterplot
    scores['label'] = Y

    x_min = 10 #some_value
    x_max = 20
    y_min = 30
    y_max = 40

    ax = sns.lmplot(x='PC1',y='PC2',data=scores,fit_reg=False,scatter_kws={'s':50},hue='label',scatter=True).set(xlim=(x_min, x_max),ylim=(y_min, y_max)).set_titles("Score plot", fontsize=14)

A: You have used a variable before defining it. So you have to define x_min, x_max, y_min and y_max before accessing them.

# Plots score plot with data labels
# Pass original data, un-centred scores and returns of PCA to this function. Optional width, height and margin.
# This function returns the axes of the score plot

def scoreplot_label(dt, scores, pca, width=5, height=5, margin=0.5):
    plt.figure(figsize=(width, height))
    #ax = sns.scatterplot(x="PC1", y="PC2", data = scores)
    # I used regplot only because my version of Seaborn is old and does not have scatterplot
    scores['label'] = Y
# You should define the variables before accessing them
#Set limits for figure
    x_min = min(scores['PC1'].min(),0)-margin
    x_max = max(scores['PC1'].max(),0)+margin
    y_min = min(scores['PC2'].min(),0)-margin
    y_max = max(scores['PC2'].max(),0)+margin
    ax = sns.lmplot(x='PC1',y='PC2',data=scores,fit_reg=False,scatter_kws={'s':50},hue='label',scatter=True).set(xlim=(x_min, x_max),ylim=(y_min, y_max)).set_titles("Score plot", fontsize=14)

    #(added this section) text for labels
    text_pos = 0.5
    # Print text
    for i, v in enumerate(np.array(scores)):
        ax.text(v[0], v[1]+text_pos, dt.iloc[i,0], color='black', ha='center', va='center', fontsize=12)

    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    ax.set_title("Score plot", fontsize=14)
    plt.plot([x_min, x_max], [0, 0], color='k', linestyle='--', linewidth=1)
    plt.plot([0, 0], [y_min, y_max], color='k', linestyle='--', linewidth=1)
    return ax

    plt.clf
ax3 = scoreplot_label(data, scores2, pca2, width=20, height=20, margin=20)
plt.show()


text:
Q: visual studio 2015 hangs on default console application file during debug The default file when I select console application is
#include "stdafx.h"
int main()
{
  return 0;
}

When I click "local windows debugger", the program freezes and nothing happens. Is it possible my debug compiler is not linked to the correct executables?

A: The way it's currently written this will result in a syntax error compilation fault because you forgot a ; after return 0. It's most likely just instantly closing the program though, try to run this code and check if it prints out :

Hello, World!

#include "stdafx.h"

#include <iostream>
int main()
{
  std::cout << "Hello, World!" << std::endl;
  std::cin.get();
  return 0;
}

If this still "freezes" your debugger then I suggest reinstalling your Visual Studio.


text:
Q: Specific usecase for java 8 stream and foreach There is class A:
class A{

private String a;
private String b;
private String status;

/*
. getter & setter
*/

}

And I have a class B:
class B{
private List<List<A>> list;
}

I have to write a logic to iterate over the list of class A in class B to:

*

*Make sure that the status of all the objects of A in the list is having a value of field status as "SUCCESS", if not then don't do step 2 and end the process

*Get the value of field b when field a has a value of "test99" (This would be unique in the list)

Is it possible to do it using streams?

A: Yes, it is possible with Java 8 Streams but I would use more than just forEach():
list.stream()//1
.flatMap(List::stream)//2
.filter(obj->!"SUCCESS".equals(obj.getStatus()))//3
.findAny()//4
.ifPresentOrElse(o->System.out.println(o+" is not successfull"),()->//5
    list.stream()//1
    .flatMap(List::stream)//2
    .filter(obj->"test99".equals(obj.getA()))//6
    .map(obj->obj.getB())//7
    .forEach(this::doSomething);//8
)

It does the following:

*

*get a stream from list

*convert each List in the stream to a Stream and make one stream out of all those streams containing all elements

*get only the elements where status is not SUCCESS

*get an Optional with an element where the status is not SUCCESS

*Execute System.out.println(o+" is not successfull") if such an element exists (you can use ()->{} if you don't want to do anythin in that case) or

*get only the elements where a is test99

*get the b value of those elements

*run a method (in this case doSomething()) with the value of b as a parameter (you could use collect() if you want to e.g get those element in a List


text:
Q: EXC_BAD_ACCESS error tracing the origin I am testing an EXE_BAD_ACCESS error. I have set NSZombieEnabled, MallocStackLogging, MallocStackLoggingNoCompact to YES. now in the debugger I get this message when I run my app in the debug mode from the device I could see this:
iota(3586) malloc: recording malloc stacks to disk using standard recorder
iota(3586) malloc: stack logs being written into /private/var/mobile/Applications/8E21A85B-369E-4487-962B-1550E56602DC/tmp/stack-logs.3586.iota.index
iota(3586) malloc: Please issue: cp /private/var/mobile/Applications/8E21A85B-369E-4487-962B-1550E56602DC/tmp/stack-logs.3586.iota.suRQjy.link /tmp/

and when I am about to hit the error I get,
2011-02-14 14:29:44.350 iota[3586:307] *** -[CFString autorelease]: message sent to deallocated instance 0x81eab70

Finally when I give the command in debugger to see the stack trace
(gdb) shell malloc_history 3586 0x81eab70
I get
malloc_history cannot examine process 3586 because the process does not exist.

Can anyone tell me what I am doing wrong, before the error is about the occur , I set
set env MallocStackLogging 1 in the debugger too

Thanks in Advance

A: It looks like you are releasing an NSString that you don't own. If you get a string from one of the class methods they are delivered as autoreleased objects, so unless you retain it, you shouldn't release it.
For a full explination check out the Memory Management Programming Guidelines.

A: The memory may remain allocated while you are using it, or be released but coincidentally still valid, during testing, but is more likely to be released and show up as bad access errors when running on the device.
The best way to track these things down, and a good idea anyway (even if there are no apparent problems) is to run the app in the Instruments tool, especially with the Leaks option.


text:
Q: Editing/Updating multiple objects at a time on a single page I want to be able to edit / update multiple objects at a time, i.e. a page to render an email field for all users.
The standard approach doesn't work:

*

*form_for requires a single object with an id

*a :put request to the user_path also requires an id parameter
How can I generate a form to update multiple users? I want to use only the built-in Rails form, not a third-party one.

A: Create a form_for to a new endpoint (not the default PUT one), you are not updating 1 resource, that endpoint makes nonsense to be used.
PUT /resource/bulk (for example)
html (i haven't tested this it is just a scheme):
form_tag '/resource/bulk', method: :put do
  @resources.each do |resource|
    text_field_tag("#{resource.id}[email]")
  end
end

action:
#params => { 1 => { "email" => "foo@foo.com" }, 2 => { "email" => "bar@bar.com" } }
def bulk
  resources = params[:form]
  Resource.update(resources.keys, resources.values)
end

this is just a schema of a valid solution, I don't have any Rails app or irb right now to test this solution.


text:
Q: NHibernate could not resolve property of an inherited property Why can't NHibernate access a property inherited from an abstract base class. When I try to use the property in a QueryOver in the Where clause I'm getting

could not resolve property: ID of: TheWorkshop.Web.Models.Customer

var customer = Session.QueryOver<Customer>()
                      .Where(c=>c.ID ==id)
                      .SingleOrDefault<Customer>();

Intelisense helped me build the query and the solution compiles, so there is an ID property on the Customer class. The ID property on Customer is inherited from an abstract Contact class that in turn inherits from a DomainEntity<T> which exposes a protected field.
public abstract class DomainEntity<T>
{
    protected Guid _persistenceId;
    //...
}

public abstract class Contact : DomainEntity<Contact>
{
    public virtual Guid ID
    {
        get { return _persistenceId; }
    }

    public virtual Address Address
    {
        get { return _address; }
        set { _address = value; }
    }

    //...
}

and in the mapping file
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="TheWorkshop.Web"
                   namespace="TheWorkshop.Web.Models"
                   default-access="field.camelcase-underscore"
                   default-lazy="true">
    <class name="Contact" table="Contacts" abstract="true">
        <id name="_persistenceId" column="ID" type="Guid" access="field"
            unsaved-value="00000000-0000-0000-0000-000000000000">
        <generator class="guid.comb" />
        </id>
        <!-- ... -->
        <union-subclass name="Customer" table="Customers">

Following the answer to a similar question I updated to NHibernate 3.3.3-CR1 from NHibernate 3.3.2.4000 but I still have the same issue.

A: The problem was that NHibernate couldn't infer from my mapping how to resolve the ID property. So although the classes compiled fine and the _persistenceId property on the abstract base class could be accessed through a getter on the implementing classes, because of the mismatch in names between _persistenceId and ID NHibernate wasn't able to follow that.
The (easier) solution was to change my names to match up. There is a harder solution which involves implementing the IProperyAccessor, IGetter and ISetter interfaces and in order to provide a path to pass the string ID in order to use the ClassName access strategy.
The simpler of the two solutions was just to rename _persistenceId to _id (and update all the references to it) so
<id name="_persistenceId" column="ID" type="Guid" access="field"
    unsaved-value="00000000-0000-0000-0000-000000000000">

becomes
<id name="Id" column="Id" type="Guid"
    unsaved-value="00000000-0000-0000-0000-000000000000">

Note I was also able to drop the access="field" in the updated id mappings


text:
Q: Given , $X$ is a standard normal R.V , I know $E[X|X>c]$ = $\frac{\phi(c)}{1 - \Phi(c)}$ , how do i derive a similar formula for $var[X|X>c]$ I can derive $E[X|X>c]$ = $\frac{\phi(c)}{1 - \Phi(c)}$ , using the trick $- \int \frac{d \phi(x)}{dx} = \int x \phi(x) dx$. How do I do a similar thing to derive $var[X|X>c]$.

A: I think I figured it out ,
$ var[X|X>c] = E[X^2|X>c] - (E[X|X>c])^2$
$$
E[X^2|X>c] = \frac{\int_{x=c}^{x=\inf}x^2 \phi(x)dx}{1 - \Phi(c)}
$$
Integrating by parts , let $ u = x$ and $ v = x\phi(x)$
$$
= x\int x\phi(x)dx - \int \int x \phi(x)dx
$$
Using the fact that $ \int x\phi(x) dx = -\phi(x)$
$$
E[X^2|X>c] = [x\phi(x)]_{c}^{\inf} + \int_{c}^{\inf} \phi(x) dx
= [-x\phi(x)]_{c}^{\inf} +[\Phi(x)]_{c}^{\inf}
$$
$$
E[X^2|X>c] =\frac{ c \phi(c) + [1 - \Phi(c)]}{1 - \Phi(c)}
$$
Therefore , $$
var[X|X>c] = \frac{ c \phi(c) + [1 - \Phi(c)]}{1 - \Phi(c)} - [\frac{\phi(c)}{1-\Phi(c)}]^2
$$


text:
Q: TVirtualStringTree - variable row height optimization In our application I'm moving from a TStringGrid to TVirtualStringTree component. A lot of data is being displayed (max. 50000 lines and 5 columns). One column contains on or more lines of text. I managed to implement multiline functionality using 'DrawCell' in the stringgrid with optimal performance: instant redraw of all lines (on resize) and scrolling without hitches (I have a list of row heights in memory, which will be updated when redraw is needed).
Transferring this multiline functionality to the VirtualStringTree is not as performant as the stringgrid alternative. I tried numerous implementations but have not yet succeeded. This is easily reproducable in the Demo application of the VirtualStringTree installation package:

*

*In the 'MultilineDemo' form, set the 'rootNodeCount' of the VirtualStringTree to 10.000.

*When running the demo, select 'Automatically adjust node height to node text.'

Initial redraw/repaint will take a while using lots of CPU. Ater each resize, jumping to top/bottom causes the same phenomenon, or even causing a 'stack overflow' exception (but that's another issue ...). The 'OnMeasureItem' method is called way too much, the way I see it (even on 'MouseMove' events).
Has anyone had this problem and managed to find a solution?

A:
This is easily reproducable in the Demo application of the
  VirtualStringTree installation package

At least this performance issue is easily solved by wrapping the call to ReinitNode() in a BeginUpdate() and EndUpdate():
 MLTree.BeginUpdate();
  try
    MLTree.ReinitNode(nil, True);
  finally
    MLTree.EndUpdate();
  end;

I slightly reworked the sample project and the Virtual Treeview today, the sample project works much smoother now. Just try the latest source code from GitHub.


text:
Q: Jira-Hudson-Mercurial integration When a developer commits a bugfix, I want to be able to open up the relevant JIRA issue and see what Hudson build number contains this fix with the Mercurial changeset listed alongside.
Extra points if this information is listed in its own tab (does not pollute the "comments" tab) but shows up alongside comments when the "all" tab is selected.
Any ideas?

A: Have a look at the jira plugin for Hudson. It is a simple plugin, that I think should be pretty sufficient for the most use cases.
On the plugin page another project is referenced. The marvelution Jira Hudson Integration project. It comes with two plugins, one for jira and one for Hudson and if the app lives up the promise, it will be an pretty cool tool. I found two different locations to read about it because they are in the process of moving their site to a wiki; old location and new location.

A: The latest version of the Marvelution plugin is supposed to resolve this problem: http://issues.marvelution.com/browse/MARVJIRAHUDSON-94