text:
Q: Sum of digits recurrence
The first number in a sequence is $7$. The next one we obtain as follows: we compute the square of the previous number $7^2 = 49$, then compute the sum of the digits of this square and increase it by $1$, i.e. the second number is $4+9+1 = 14$. We repeat this procedure to get $14^2 = 196$, and the third number of the sequence, which is $1+9+6+1 = 17$, and so on. What would be the $1999$th number in this sequence?

The sequence can be defined as $a_1 = 7$ and $a_{n+1} = s(a_n^2)+1$ where $s(n)$ denotes the sum of the digits of a positive integer $n$ and we want to find $a_{1999}$. I didn't see how to use the sequence to find this term.

A: The sequence is: 7,14,17,20,5,8,11,5,... and now you see it repeats with a period of 3. In particular, we have  $a_{3k+1}=11$ for $k>1$, and so $a_{1999}=a_{3*666+1}=11$

A: If you observe first few terms we get a pattern after some terms. The terms are $7,14,17,20,5,8,11,5,8,11.. $ from here you can tell what is $a_{1999} $ as $5,8,11$ are repeating.


text:
Q: close window (node js) I want it to end Roblox but I cant get it to work
The code I found
exec('tasklist', (err, out, code) => {
    const id = processIdFromTaskList("RobloxPlayerBeta.exe", out);
    process.kill(id, "SIGKILL");
});

Node = v18.13.0
The error I get:
 [Error_Handling] :: Uncaught Exception/Catch (MONITOR)
ReferenceError: processIdFromTaskList is not defined
    at D:\Js\Natro-macro-control-Testing\Commands\Control\close.js:15:16
    at ChildProcess.exithandler (node:child_process:411:7)
    at ChildProcess.emit (node:events:513:28)
    at maybeClose (node:internal/child_process:1091:16)
    at ChildProcess._handle.onexit (node:internal/child_process:302:5) uncaughtException
 [Error_Handling] :: Uncaught Exception/Catch
ReferenceError: processIdFromTaskList is not defined
    at D:\Js\Natro-macro-control-Testing\Commands\Control\close.js:15:16
    at ChildProcess.exithandler (node:child_process:411:7)
    at ChildProcess.emit (node:events:513:28)
    at maybeClose (node:internal/child_process:1091:16)
    at ChildProcess._handle.onexit (node:internal/child_process:302:5) uncaughtException

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python modularity best practices I've been struggling conceptually with the design of my large program. The general layout is something like this:
def mainFunc(parm_1, parm_2, ..., parm_n):
  # do step 1
  # do step 2
  # ...
  # do step m

My question is this: Should I make each step its own function? I'd never want to call any step as a function outside of mainFunc. So, alternatively, would it be better to make each step a snippet? What's the practical difference between calling a function and executing a snippet which does the same thing? (Assuming of course that any unneeded variables are deleted at the end of the snippet.)
I truly don't know which approach is better in the long run. Any suggestions would be greatly appreciated.

A: If each step makes sense on its own, then it might be better to make functions. In that way you can document on each function what it does and it will also be easier to isolate bugs. In summary, I believe using functions makes the code easier maintain.


text:
Q: Classic asp Request Form error 80004005 I having problem when trying to post data to my ASP file with integrated pipeline.
ASP CODE:
<%
Response.Write request.form("StatusDate")

%>

HTML CODE:
<!DOCTYPE html>
<html>
<body>

<form action="myASPFile.asp" method="post">
StatusDate: <input type="text" id="StatusDate" name="StatusDate"><br>

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

</body>
</html>

the page will show :error '80004005'
When I change the integrated mode to Classic Code, the request form is working.
What is the setting that I have missed out in integration mode in order to do the request form for post data


text:
Q: Waiting for a thread to finish from a 3rd party library (OpenMap/Java)? My application currently has an interesting problem. This problem is with OpenMap but could probably be applied to any 3rd party library.
In this particular example, our code needs to create our OpenMap tool and load its layers (in the background) and take a screenshot of a particular point of interest.
However, the problem is that the OpenMap library creates its own thread(s) to load these layers, thus returning to our code to take a screenshot immediately and most times the screenshot is empty or incomplete.
The pseudo-code of our application is like this:
check database for layers
load layers using OpenMap
take screenshot of map at point of interest

I've assumed that some sort of thread management was in order, but how can this be done when the library is using its own thread(s) that we have no access to? Also, OpenMap has no returns or flags to indicate that these thread are finished (that I've seen).
Any suggestions?
Thank you

A: I don't know OpenMap, but the normal way is to register some callback with the 3rd party library. In Java that means implementing an Interface and registering as a listener at the object on which you call the API method.
You (almost?) never have to (or should) know something about the internal thread handling of a library!

A: Layers can be written for OpenMap so they can respond to projection queries and render into a java.awt.Graphics object.  Extend the OMGraphicHandler layer, override the prepare() method so  it returns an OMGraphicList for the projection set on the Layer.  If you call Layer.renderDataForProjection(), the OMGraphicList returned in prepare will be rendered.
The com.bbn.openmap.image.ImageServer is a good object to use for managing the creation of images for your Layers.

A: Had the same problem with the 3rd party jpeg extractor pulling the image before the MapBean was finished producing the image.  Followed the hint about the invoke later and added the following code between my layer handling code and my export to graphic code:

//...OpenMap editing code stops here ...

final Runnable doWaitUntilTheMapBeanIsFinishedRendering = new Runnable() {
   public void run()
   {
       System.out.println("Ding, fries are done!");
   }
};

try
{
    SwingUtilities.invokeAndWait( doWaitUntilTheMapBeanIsFinishedRendering );
}
catch( Exception e )
{
    e.printStackTrace();
}

byte[] image = JPEGImageFormatter.getImageFromMapBean( mapbean );


text:
Q: Generate tree from file with indents using anytree I'm using anytree to generate a tree from a file, Tree.txt. Each indent is 3 spaces ( ). Here's what my file looks like:
ROOT
   Node1
      Node2
         Node3
            Node4
   Node5
   Node6

And here's what I have so far for the generating code:
from anytree import Node, RenderTree, find_by_attr

def parse_tree():
    with open('Tree.txt', 'r') as file:
        file_contents = file.readlines()
        root = Node("ROOT")

        current_indent = -1 # store index for comparing later
        for (index, line) in enumerate(file_contents):

            leading_spaces = len(line) - len(line.lstrip(' '))
            indent = int(leading_spaces / 3) # indent = 3 spaces

            if indent > current_indent: # node must be 1 level down

                # get the previous Node (1 level up)
                previous_line = file_contents[index - 1].strip()
                current_line = line.strip()
                parent = find_by_attr(root, previous_line)
                Node(current_line, parent=parent) # start searching from top node (root) for `previous_line`
                current_indent = indent
            else: # node is on same level or higher
                print(f"What to do for {line.strip()}?")
                # what should I do here?

        print(RenderTree(root)) # print the output

parse_tree()

However, this prints out:
What to do for Node5?
What to do for Node6?
Node('/ROOT')
└── Node('/ROOT/Node1')
    └── Node('/ROOT/Node1/Node2')
        └── Node('/ROOT/Node1/Node2/Node3')
            └── Node('/ROOT/Node1/Node2/Node3/Node4')

The generated tree is fine, but only up until Node4 - Node5 and Node6 are missing. This is expected, because I didn't handle the case when the current indent is smaller than the previous indent (see # what should I do here?).
What should I do when the current indent is smaller than the previous indent? I know I need to go up n level higher, but how do I find out which level that is?

A: You'll need a kind of stack to keep track of the depth of the nodes, then you can use the number of initial spaces to determine which parent node to append each leaf to. E.g., three spaces means one level down, so you need to append to the root node at index 0 in the stack. (You could also say that by using a stack we are taking the absolute depth of the leaves, while you tried to solve it relatively if I'm making any sense). I suspect if you use find_by_attr, that might not work in case there are leaves with the same name.
treestring = '''
ROOT
   Node1
      Node2
         Node3
            Node4
   Node5
   Node6'''.strip()

leaves = treestring.splitlines()

# initialize stack with the root node
stack = {0: Node(leaves.pop(0))}

for leaf in leaves:

    # determine the node's depth
    leading_spaces = len(leaf)-len(leaf.lstrip(' '))
    level = int(leading_spaces/3)

    # add the node to the stack, set as parent the node that's one level up
    stack[level] = Node(leaf.strip(), parent=stack[level-1])

tree = stack[0]

for pre, _, node in RenderTree(tree):
    print(f"{pre}{node.name}")

Result:
ROOT
├── Node1
│   └── Node2
│       └── Node3
│           └── Node4
├── Node5
└── Node6


text:
Q: Find a majorizing function Please, could somebody help me find a function $f(x)$ such that
$| \frac{1}{n+n^2 \sin(xn^{-2})}| \le f(x)$ for each $n \in (0, \infty)$. $f(x)$ has to be $\ge 0$ for every $x \in (0, \infty)$ and integrable in $(0,\infty)$.
I've been trying, but nothing came to my mind...

A: It may be useful to know that if $a^2\lt b^2$ then $$\int{dx\over a+b\sin x}={-1\over\sqrt{b^2-a^2}}\log{b+a\sin x+\sqrt{b^2-a^2}\cos x\over a+b\sin x}$$


text:
Q: XCode and Instruments: How to get the app memory peak I'd like to show the memory peak (not 'leak', but the highest quantity of memory used in small amount of time) of an iPhone app i am running in the simulator. Where shall i look precisely?
PS I am using libxml2 and i suppose that the allocations done by the library aren't considered

A: Use the "Allocations" performance tool by selecting Run | Run with Performance Tool | Allocations in Xcode. This will show you everything that your app allocates including items in libxml2. You may not to see exact line numbers of memory allocations in the library, but you will be able to see where the majority of your allocations are happening.


text:
Q: PyQt - parent for widgets - necessary? I tried creating GUI with a few widgets, all of them without secifying a parent.
It worked fine.
Is this Ok, or there is reason to specify the parent?
Thanks!

A: In general, it's better to specify a parent wherever possible, because it can help avoid problems with object cleanup. This is most commonly seen when exiting the program, when the inherent randomness of the python garbage-collector can mean objects sometimes get deleted in the wrong order, causing the program to crash.
However, this find of problem does not usually affect the standard GUI widgets, because Qt will automatically reparent them once they have been added to a layout. The more problematic objects are things like item-models, item-delegates, graphics-scenes, etc, which are closely linked to a view.
Ideally, a pyqt program should have one root window, with all the other objects connected to it in a parent-child hierarchy. When the root is deleted/closed, Qt will recursively delete all its child objects as well. This should leave only the pyqt wrapper objects behind, which can be safely left to the python garbage-collector to clean up.
A more constructive benefit of specifying parents, is that it simply makes objects more accessible to one another. For instance, a common idiom is to iterate over a group of buttons via their parent:
    for button in parent.findChildren(QAbstractButton):
        print(button.text())


text:
Q: How to loop thru view model for particular value using foreach and where (NUBE)  I am trying to loop thru a view model and show rows when a field has a particular value.  (IE In a Master/Detail model I have pulled all my orders in one list and all the detail in another. When the user picks the particular order from the first list I just want to iterate thru the detail list and show those line items for edit/delete purposes.
This code works from testing if I hardcode the value (2953) but I wish to pass a value and am not sure if Viewbag or razor is the way to go.  I would like to maintain a consistent framework throughout.
@foreach (var row in Model.SplitTankAssignmentItems.Where(x => x.MeterValueID == 2953) ) // row.splitTicketID) )
{

    :
    :
    :

}

A: The ViewBag is exactly for this purpose.
On your control-action method you can set up the ViewBag and in your view you can read it.
Controller
public IActionResult Index()
{
    :
    ViewBag.ValueToUse = 2953
    Return View(model);
}

View
@foreach (var row in Model.SplitTankAssignmentItems.Where(x => x.MeterValueID == (int)ViewBag.ValueToUse) ) // row.splitTicketID) )
{

    :
    :
    :

}

Notes: Remeber to cast your ViewBag property to the type you need, and keep in mind that ViewBag is only for one call, usually to take information from controller to view. It won't stay from view to controller neither from an action method to action method (RedirectTo)


text:
Q: Convert pandas.DataFrame to numpy tensor using factor levels for shape I have data from a full factorial experiment.  For example, for each of N samples, I have J types of measurement and K measurement loci.  I receive this data in long format, for example,
import numpy as np
import pandas as pd
import itertools
from numpy.random import normal as rnorm

# [[N], [J], [K]]
levels = [[1,2,3,4], ['start', 'stop'], ['gene1', 'gene2', 'gene3']]

# fully crossed
exp_design = list(itertools.product(*levels))

df = pd.DataFrame(exp_design, columns=["sample", "mode", "gene"])

# some fake data
df['x'] = rnorm(size=len(exp_design))

which results in 24 observations (x) with a column for each of the three factors.
> df.head()
    sample  mode    gene    x
0   1       start   gene1   -1.229370
1   1       start   gene2   1.129773
2   1       start   gene3   -1.155202
3   1       stop    gene1   -0.757551
4   1       stop    gene2   -0.166129

I want to convert these observations to the corresponding (N,J,K)-shaped tensor (numpy array).  I was thinking pivoting to wide format with a MultiIndex, then extracting values would generate the correct tensor, but it simply comes off as a column vector:
> df.pivot_table(values='x', index=['sample', 'mode', 'gene']).values
array([[-1.22936989],
       [ 1.12977346],
       [-1.15520216],
       ...,
       [-0.1031641 ],
       [ 1.1296491 ],
       [ 1.31113584]])

Is there a quick way to get tensor formatted data from a long format pandas.DataFrame?

A: Try with
df.agg('nunique')

Out[69]:
sample     4
mode       2
gene       3
x         24
dtype: int64
s=df.agg('nunique')
df.x.values.reshape(s['sample'],s['mode'],s['gene'])
Out[71]:
array([[[-2.78133759e-01, -1.42234420e+00,  5.42439121e-01],
        [ 2.15359867e+00,  6.55837886e-01, -1.01293568e+00]],
       [[ 7.92306679e-01, -1.62539763e-01, -6.13120335e-01],
        [-2.91567999e-01, -4.01257702e-01,  7.96422763e-01]],
       [[ 1.05088264e-01, -7.23400925e-02,  2.78515041e-01],
        [ 2.63088568e-01,  1.47477886e+00, -2.10735619e+00]],
       [[-1.71756374e+00,  6.12224005e-04, -3.11562798e-02],
        [ 5.26028807e-01, -1.18502045e+00,  1.88633760e+00]]])


text:
Q: Store a 4D array in a Vector? I'm collecting data into a 4D array (it's how most of the code is already implemented) and I'm recording the data over time (i.e. there will be multiple 4D arrays).
The total size of the 4D array is 8x2x8x150 of floats i.e. float data[8][2][8][150]
I want to be able to store each subsequent incoming 4D array into a vector for saving/manipulation later.
I understand, though, that arrays in C++ can't be stored in vectors as is. How can I easily store this data for an undetermined amount of time (i.e. not a fixed vector size)? Keep in mind that this is a fairly large data set (~38Kb per 4D array)

A: You can create a helper class that stores the data in a std::vector but provides the interface of a 4D array.
struct My4DArray
{
   My4DArray(int d1, int d2, int d3, int d4) :
     d1(d1), d2(d2), d3(d3), d4(d4), data(d1*d2*d3*d4) {}

   float& at(int i1, int i2, int i3, int i4)
   {
       return data[getIndex(i1, i2, i3, i4)];
   }

   int getIndex(int i1, int i2, int i3, int i4)
   {
      assert(i1 >= 0 && i1 < d1);
      assert(i2 >= 0 && i2 < d2);
      assert(i3 >= 0 && i3 < d3);
      assert(i4 >= 0 && i4 < d4);

      // ??? Need to verify the formula.
      return (((i1*d2 + i2)*d3 + i3)*d4 + i4);
   }

   int d1;
   int d2;
   int d3;
   int d4;
   std::vector<float> data;

};

A: You could define an alias for defining an std::array of some time with multiple dimensions almost as easy as with C-style arrays:
template<typename Type, std::size_t N, std::size_t... Sizes>
struct multi_array {
    using type = std::array<typename multi_array<Type, Sizes...>::type, N>;
};

template<typename Type, std::size_t N>
struct multi_array<Type, N> {
    using type = std::array<Type, N>;
};

template<typename Type, std::size_t... Sizes>
using multi_array_t = typename multi_array<Type, Sizes...>::type;

and then, since std::array is storable in an std::vector, just use the resulting array:
using my_array = multi_array_t<int, 2, 3>;
my_array arr1 {{
    {{1, 2, 3}},
    {{4, 5, 6}}
}};
my_array arr2 {{
    {{7, 8, 9}},
    {{10, 11, 12}}
}};

std::vector<my_array> vector {arr1, arr2};
assert(vector[0][0][1] == 2);
assert(vector[1][1][2] == 12);

Live demo

A: Interesting question. I think you might be interested in Pramod Gupta's C++ Multi-dimensional Arrays talk at this year's cppcon.
Basically, using his orca_array library (header-only, MIT license), you should be able to do something like this:
#inclue <vector>
#include "orca_array.hpp"

std::vector<orca_array::array4d<double>> my_vector_of_4d_arrays;

A: You can store it a one-dimensional array of 19200 elements, accessed as
array[i*2400 + j*1200 + k*150 + l] // array[i,j,k,l]


text:
Q: Z-Index positioning for jvectormap tooltip I'm using ´jvectormap´ plugin and positioning the .jvectormap-tip class accordingly to this answer
The problem is, my tooltip have z-index: 999; and, although neither my contact form or footer section has it set, my tooltip is going beneath the contact form and above the footer section as shown on the picture below.
I also have tried to add z-index:1 to the form but did not worked.
What should I do to position the tooltip above anything on the page ?

A: I achieved what I want just adding a higher z-index value for the tooltip ancestor( because it haves relative position) then the form ancestor.


text:
Q: How to update velocity in a Kalman filter? I am learning about the Kalman filter, and having difficulty understand how to construct a Kalman filter when velocities are introduced. Let's say we are tracking the (x-position, y-position) of an object, and we have a sensor which estimates this position. One way to construct the Kalman filter is to exclude any velocity, such that the prior prediction of the next position is just the old position.
But a better way would be to include the object's velocity. The state vector would then include the x-velocity and y-velocity, i.e. state = (x-position, y-position, x-velocity, y-velocity). The value of x at the next timestep would then be x + dt * x-velocity, and similarly for y.
My question is: how do we update x-velocity and y-velocity? Whilst we have a sensor which estimates positions, we don't have a sensor which estimates velocities. Therefore, we cannot update the velocities using the observation model. We could then assume that the velocity doesn't change, but this is very limiting in my application, as I know that the velocity does change significantly.
One idea I had was to emulate an observation model, by saying that the measured velocity is the difference between the current position and the previous position. Then, I could use an observation model in the same way as with the position measurement. However, this feels like a bit of a hack, since this is not a sensor in the true sense; I am just emulating a sensor using old data. And it seems like this could be incorporated in a more direct way, than by "pretending" I have some sensor which gave me this data.
Can somebody please help me understand this?? Thanks!

A: The idea in a Kalman filter is that you typically don't measure all the states, so it is a bit unclear what reference you are using where this setup wouldn't be answered already in the definition of the filter and the basic equations.
Write your dynamics as $x_{k+1} = Fx_{k} + Gw_k$ (where $x_k$ denotes your 4 states and $w_k$ is assumed process noise). The measurement model is $y_k = Cx_k + \eta_k$ where $C$ thus only would have two rows in your case. At this point, you just apply standard theory to derive the Kalman gain (i.e. solve the Riccati equation)
Edit: Perhaps I missed the core part of the question: How you define the dynamic model of the state is up to you. Typical approach is to say that the acceleration is random, i.e. $x_{k+1} = x_{k} + w_k$ for the velocity states.


text: Q: Cucumber - exit test feature, when scenario fails (Javascript) I have react app, and I'm testing it with Cucumber. I have several scenarios in one feature file, each one is dependent of the previous scenario, so if one fails, then others will fail too. The question is when one scenario fails, how to stop launching other tests, exit feature file and clear data after it?


text:
Q: ng-include Won't Work Without  Tags I am starting to get to grips with a lot of the angularjs tutorials out on the net and I seem to have stubbled upon something that my googlefu cant seem to crack.
Below is my html. In my app.js I simply instantiate the angular module and declare 'ui-router' as a dependancy, nothing flash.

Now for some reason, the files that are included using ng-include need to have  tags wrapped around their content or nothing is displayed.
I haven't seen this mentioned anywhere so is there something awry here as I'm totally lost. The current work around is fine but It feels funky.
NOTE: I am using live-server package from npm live-server to have my local file refresh in the browser on save. I don't think this is the issue as even if I simply just open the index.html file it still doesn't work (but that's because of chrome's safety rules).
Cheers!

A: Yep, had the same problem with ng-include and Live-Server not loading the partial. ng-include displays the partial in my localhost but not live-server.
This issue has been fixed in the latest version of live-server. So I updated my live-server to version 0.7.1 and ng-include now works just fine.
GitHub - tapio commented 15 days ago
"I've published version 0.7.1 to npm which seems to fix this issue. Feel free to test and report any further problems. :)"
GitHub live-server issue


text:
Q: How to get all the categories including the child as an object in Wordpress? I would like to get the categories in hierarchical structure. All i know is wp_dropdown_categories(), but this method returns the categories with the html elements. is there any method in Wordpress to get the categories & child as a php object or do i need to write own function to fetch categories recursively ? i need to modify the select tags & options too.
Here is what i have done so far .
$themesArgs = array(
   'hide_empty' => 0,
   'hierarchical'=> 1,
   'exclude'=> '',
   'echo'=> 0,
   'name'=>'themes',
   'id'=>'themes',
   'child_of'=>3,
);

$allCats = $cat_dropdown = preg_replace(
    '^' . preg_quote( '<select ' ) . '^',
    '<select multiple placeholder="Themes" ',
    wp_dropdown_categories($themesArgs)
);

print_r($allCats);

im new to Wordpress development.thanks in advance

A: Use this code this is working fine
$category = get_the_category(get_the_ID());
$catid=$category[0]->category_parent;
if($catid==0){
  $catid=$category[0]->cat_ID;
}
$categories = get_categories('child_of='.intval($catid));
foreach ($categories as $category) {
    if ($category->parent ==$catid):
        echo ''.$category->cat_name.'';
        $subcategories=  get_categories('child_of='.intval($category->cat_ID));
        foreach ($subcategories as $subcategory) {
            echo '';
            echo ''.$subcategory->cat_name.'';
        }
    endif;
}

A: Use wp_list_categories to get all categories. If you need to output them in a special format, use a custom Walker.
class MyCustomWalker extends Walker_Category {
// override functions as needed
}

wp_list_categories(array("option" => "value", "walker" => new MyCustomWalker));

A:  <?php

  $taxonomy     = 'product_cat';
  $orderby      = 'name';
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no
  $title        = '';
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;
        echo '
slug, 'product_cat') .'">'. $cat->name .'';

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo  $sub_category->name ;
            }
        }
    }
}
?>

This will list all the top level categories and subcategories under them hierarchically. do not use the inner query if you just want to display the top level categories. Style it as you like.


text:
Q: sshd log full of "Did not receive identification string from " Mar  2 02:34:02 freetalker3 sshd[28436]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:08 freetalker3 sshd[28439]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:13 freetalker3 sshd[28442]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:19 freetalker3 sshd[28445]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:24 freetalker3 sshd[28448]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:30 freetalker3 sshd[28451]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:35 freetalker3 sshd[28454]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:41 freetalker3 sshd[28457]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:46 freetalker3 sshd[28460]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:52 freetalker3 sshd[28463]: Did not receive identification string from 211.110.33.50
Mar  2 02:34:57 freetalker3 sshd[28466]: Did not receive identification string from 211.110.33.50
Mar  2 02:35:03 freetalker3 sshd[28469]: Did not receive identification string from 211.110.33.50
Mar  2 02:35:08 freetalker3 sshd[28472]: Did not receive identification string from 211.110.33.50
Mar  2 02:35:14 freetalker3 sshd[28475]: Did not receive identification string from 211.110.33.50
Mar  2 02:35:20 freetalker3 sshd[28478]: Did not receive identification string from 211.110.33.50
Mar  2 02:35:25 freetalker3 sshd[28481]: Did not receive identification string from 211.110.33.50
Mar  2 02:35:31 freetalker3 sshd[28484]: Did not receive identification string from 211.110.33.50
Mar  2 02:35:36 freetalker3 sshd[28488]: Did not receive identification string from 211.110.33.50

My /var/log/auth.log is full of these messages, spammed every 6 seconds.
my server is on vps and the ip seems like it is an internal ip. what could be the cause of this issue?

A: Such messages are thrown by SSH when someone tried to access it but did not finish the steps. For example if NMS is checking whether port ssh 22 is up or not, it will simply try to connect on port 22 and if the connection is successful, it will hang up, in such cases SSH reports the same.
So it is because of an SSH port scan.

A: Actually, this was from my hosting provider - they spam my VPS every 6 seconds, to show my server status on their web console. My server is displayed as active if my sshd answers them.
I just installed OpenVPN and allowed SSH only via that - so, according to my providers my server boasts 100% downtime.

A: Some miscreant (surprise!) is hammering at ssh to try to find a username/password combination that gets them into the system. Probably from some botnet doing the same to who knows how many other unsuspecting victims.
Install something like fail2ban or DenyHosts (some of both should be available for any Linux distribution), or set up your local firewall to limit SSH connection attempts. Changing the SSH port makes the dumb brute force tries fail, but it also makes legitimate uses fail.

A: This is most likely a keepalive (verifying the server is responding) from a comm. device.

A: Try changing the ssh port from 22 to another one in sshd_config:
sudo nano /etc/ssh/sshd_config

If it doesn't stop messages, the issue can also be caused by this: Freebpx causes sshd errors in /var/log/secure log file or see discussion here "Did not receive identification string" in auth.log on Ubuntu forums.

A: It might also be an attempt to carry out a well known buffer overflow exploit.
It's documented in the filter /etc/fail2ban/filter.d/sshd-ddos.conf, which you can enable to protect yourself by these hack attempts:
Fail2Ban ssh filter for at attempted exploit
The regex here also relates to a exploit:
http://www.securityfocus.com/bid/17958/exploit
The example code here shows the pushing of the exploit straight after
reading the server version. This is where the client version string normally
pushed. As such the server will read this unparsible information as
"Did not receive identification string".

The target string for this exploit is (guess what?) "Did not receive identification string from ..."
You can distinguish legitimate connections coming from your provider network for monitoring purpose, by any other unauthorised sources, simply by checking the network range of the remote IP address.
It is possible to instruct fail2ban filter (through 'ignoreregex' directive) in order to ignore legitimate attempt accordingly.

A: In my case, this was caused by the Health Check for my Elastic Load Balancer (ELB). I, indeed, want the load balancer to ensure that sssd is running on my host, so this message was expected in my use case. For my specific use-case, using AWS FireLens, I was able to filter these messages out using the exclude-patterns property of the configuration object.
This issue was noted above in a comment, but I missed it the first few times I read this post, so I wanted to post it as a separate, top-level answer.

A: In my case those log entries were produced every 5 minutes because of a regular service scan by samhain - even though I was using some custom port (other than 22) for the SSH server. Disabling the detection of new services should prevent you from these annoying log entries (but may also weaken the protection by your IDS).

A: If your ever wondering who's port scanning or trying to authenticate on your machine just check:
# whois 211.110.33.50

# KOREAN(UTF8)

조회하신 IPv4주소는 한국인터넷진흥원으로부터 아래의 관리대행자에게 할당되었으며, 할당 정보는 다음과 같습니다.

[ 네트워크 할당 정보 ]
IPv4주소           : 211.110.0.0 - 211.110.239.255 (/17+/18+/19+/20)

etc.


text:
Q: what is the use refs/for/refs/* in gerrit? Trying to understand refs/for/refs/* feature in gerrit. This question is not about refs/for/master.

*

*when can we use this refs/for/refs/* feature.

*Could some one explain best use case for this.

A: According to the documentation the refs/for/* syntax is just a short name for refs/for/refs/*:

Gerrit supports using either the full name or the short name for a branch. For instance, this command:
git commit
git push origin HEAD:refs/for/master
is the same as:
git commit
git push origin HEAD:refs/for/refs/heads/master

Whether you use one or the other is up to you. Since other examples in the documentation use the "refs/for/*" form, you might want to stick to that.

A: refs/for/refs/*  in Gerrit permission allows users to push their commits for Gerrit review.
example:
git push origin HEAD:refs/for/some_branch


text:
Q: Redirect after login using params Currently, when you login as a user, regardless of where from, you are taken to your homepage. I would like to check for params in the url and redirect based on that param.
Here's the code:
def after_sign_in_path_for(resource)
    if params['redirect'] == 'SomeParameter'
      return special_url
    else
      return home_url
    end
end

If I use the regular login form with no params, I get taken to home_url. When I try to go to /user/login?redirect=SomeParameter, I still get taken to home_url. By the way, both routes are valid (if I just test special_url, it works just fine).
What am I missing?

A: Does the home page redirect you to the login form if you aren't signed in?
Devise will store the page that you were on when you attempted to log in, and redirect to it when you log in.
This will take precedence over the after_sign_in_path_for, so if you are going Home page => Auto-redirect to Login => log in, then the return value of the after_sign_in_path_for doesn't matter.
If that is the case, you can play with stored_location_for (Devise and stored_location_for: how do you store the return location?) to alter where you go.


text:
Q: Упорядочить слова по алфавиту Программа должна принимать на вход предложение и выводить его слова в алфавитном порядке. У меня была реализация, когда слова передавались как просто аргументы массива, но после того как я попытался реализовать ввод предложения с клавиатуры, у меня стало вылазить Segmentation fault (core dumped), после ввода самого предложения. В чем моя ошибка? Кто откликнулся, заранее спасибо
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void sort_words(char *words[], int count)
{
    char *x;

    for (int i = 0; i < count; i++)
    {
        for (int j = i + 1; j < count; j++)
        {
            if (strcmp(words[i], words[j]) > 0)
            {
                x = words[j];
                words[j] = words[i];
                words[i] = x;
            }
        }
    }
}

int main()
{
    char *words[4];
    printf("Введите 5 слов \n");
    scanf("%s%s%s%s%s", &words);

    sort_words(words, 5);

    for (int i = 0; i < 5; i++)
    {
        printf("%s", words[i]);
    }
    printf ("\n");
}

P.S. формат %s не подходит, но и ошибку не вызывает. Нужный мне не нашел, буду благодарен за подсказку

A: Выделять можно память для строк в общей памяти с помощью malloc, я пока предлагаю ограничиться просто массивом строк. Копировать строки с помощью = не получиться, вы просто копируете адреса строк. Нужно использовать функции для копирования строк strcpy. Я поменял аргумент , чтобы он принимал указатель на массив, вместо вектора, исправил на правильное копирование строк.
// gcc -Wall -Wextra -Wpedantic -std=c11 scanstr.c -o scanstr

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void sort_words(int count,char words[count][120])
{
    char x[120];

    for (int i = 0; i < count; i++)
    {
        for (int j = i + 1; j < count; j++)
        {
            if (strcmp(words[i], words[j]) > 0)
            {
              strncpy(x,words[j],120);
              strncpy(words[j],words[i],120);
              strncpy(words[i],x,120);
            }
        }
    }
}

int main()
{
    char words[5][120];
    printf("Введите 5 слов \n");
    for(int i = 0;i<5;++i)
      scanf("%120s", words[i]);

    sort_words(5,words);
    printf("--sorted--\n");
    for (int i = 0; i < 5; i++)
    {
        printf("%s\n", words[i]);
    }
    printf ("\n");
}


text:
Q: Correct way to pass std::vector from class to external function I am attempting to pass a std::vector of a custom class datatype to an function external to the main class. However, I am not sure of the best way to do this. Currently it produces segmentation faults.
Let me explain, I have tried to create a minimum reproducible example below:
I have a class in a header file Poses.h
class Pose
{
  public:
  double x;

  Pose(double x_)
  {
    x = x_;
  }
};

In the main header, lets call it foo.h
#include <vector>
#include "foofcn.h"

class foo{
  public:
  void begin()
  {
  std::vector<Pose> myPoses;
  myPoses[0] = Pose(1);
  myPoses[1] = Pose(2);
  foofcn(myPoses);
  }
};

Where foofcn.h is
#include <vector>
#include "Pose.h"
#include <iostream>

void foofcn(std::vector<Pose> myFooPoses)
{
  int xx;
  xx = myFooPoses[0].x;
  std::cout << xx << std::endl;
}

This currently produces an error: Segmentation fault (core dumped)
Any help is appreciated


text:
Q: How to unit test Content provider and DB calls in robolectric which has native dependencies I want to use robolectric(3+) for unit testing in my project. The issue is that in our project we are not using the sqlite dependencies from android.database.sqlite but the compiled source code from sqlite project(org.sqlite.database). This is because we are using hardware based encryption in our DB for security. The dependencies on org.sqlite.database calls native code.
Robolectric does not support any external native code(will give java.lang.UnsatisfiedLinkError). The ContentProvider and SQLite helper class in my project references the code in org.sqlite.database packages for creating tables, building queries, table joins.
Now, I can create another content provider for test cases, but it can cause code duplication and it won't be testing the actual content provider. Within the content provider, I can separate DB operations into different classes but again it will be code duplication. It seems like I have to run them as instrumented test cases. If anybody has some suggestions, it will be great.

A: We are running those tests as instrumented tests. Currently robolectric does not support any outside native code and gives this error when trying to access any native method.
So there was no other option other than to run all the DB related unit tests on a device.


text:
Q: Delphi Dataset not in edit or insert mode I have tried to search this but found nothing that helped me. I am trying to work on a school project where I need to add a record to an Access database but I am getting the error "dataset not in edit or insert mode.
sName := ledName.Text;
sUName := ledUserName.Text;
sPass := ledPassword.Text;
sEmail := ledEmail.Text;
sCell := ledPhone.Text;

dmUsers.tblUsers.ReadOnly := False;

dmUsers.tblUsers.Open;
dmUsers.tblUsers.Insert;

dmUsers.tblUsers.Last;
dmUsers.tblUsers['UserName'] := sUName;
dmUsers.tblUsers['Password'] := sPass;
dmUsers.tblUsers['Email'] := sEmail;
dmUsers.tblUsers['Cell Number'] := sCell;
dmUsers.tblUsers['Actual Name'] := sName;
dmUsers.tblUsers['Balance'] := 0;
dmUsers.tblUsers['Points'] := 0;

dmUsers.tblUsers['Present'] := False;

dmUsers.tblUsers.Post;

I don't know what I'm doing wrong. Any help would be appreciated.

A: If you call methods on the dataset that can change the active record (like First, Last, Next or Locate) the dataset will call CheckBrowseMode, which will Post changes if modifed or Cancel the fresh record if not modifed. The result is the dataset being in dsBrowse, causing it to not accept editing.
So change your code to something like the following. I'll use Append, as your Last call suggests you wanted to have the new record at the end of the dataset.
sName := ledName.Text;
sUName := ledUserName.Text;
sPass := ledPassword.Text;
sEmail := ledEmail.Text;
sCell := ledPhone.Text;

dmUsers.tblUsers.ReadOnly := False;

dmUsers.tblUsers.Open;

dmUsers.tblUsers.Append;

dmUsers.tblUsers['UserName'] := sUName;
dmUsers.tblUsers['Password'] := sPass;
dmUsers.tblUsers['Email'] := sEmail;
dmUsers.tblUsers['Cell Number'] := sCell;
dmUsers.tblUsers['Actual Name'] := sName;
dmUsers.tblUsers['Balance'] := 0;
dmUsers.tblUsers['Points'] := 0;

dmUsers.tblUsers['Present'] := False;

dmUsers.tblUsers.Post;


text:
Q: How to declare cluster in java? I need to create clusters that contain elements. The clusters should be created at run-time and elements to be added to it. How do I do it in Java?
I thought of declaring a class as a cluster, but then I cant declare objects dynamically and iterate over them.

A: You really haven't explained what a cluster is, but you can add "elements" to a List. Or indeed anything else in the Collections library. Instantiate when you feel like it:
List<YourObject> cluster = new ArrayList<YourObject>();

and add additional elements when you want, the list will grow automatically:
cluster.add(yourObject);

You can also iterate over a list.

A: I'm not sure I quite understand the question, but you might want to look at the Collections framework.
http://download.oracle.com/javase/tutorial/collections/index.html


text:
Q: Implement Google+ Sign-In with React Native I'm wanting to integrate G+ Sign In (as per https://developers.google.com/+/mobile/ios/sign-in) in a React Native app. I have Facebook Sign In working via http://brentvatne.ca/facebook-login-with-react-native/ which is working perfectly, but I'm not sure what to do at this point of the G+ docs:

In your view controller's .h file, import GooglePlus/GooglePlus.h, and declare that this controller class implements the GPPSignInDelegate protocol

If anyone could provide some pointers/code samples?
Thanks!

A: EDIT 2017
Within the Expo framework, which is now the default for react-native apps, there is built in Google Authentication available:
Expo documentation: https://docs.expo.io/versions/latest/sdk/google.html
Get Android and iOS client ids: https://console.developers.google.com/apis/credentials
import React from 'react'
import Expo from 'expo'
import Button from 'react-native-button'

class Login extends React.Component {
  signInWithGoogleAsync = async () => {
    try {
      const result = await Expo.Google.logInAsync({
        androidClientId: process.env.GOOGLE_ANDROID_CLIENT_ID,
        iosClientId: process.env.GOOGLE_IOS_CLIENT_ID,
        scopes: ['profile'],
      })

      if (result.type === 'success') {
        return result
      }
      return { cancelled: true }
    } catch (e) {
      return { error: e }
    }
  }

  onLoginPress = async () => {
    const result = await this.signInWithGoogleAsync()
    // if there is no result.error or result.cancelled, the user is logged in
    // do something with the result
  }

  render() {
    return (<Button onPress={this.onLoginPress}>Login</Button>)
  }
}

OLD ANSWER
There is now a library for signing in with Google+ for react-native: https://github.com/devfd/react-native-google-signin

A: So this is only semi-related to React Native, since your main issue seems to be writing the Obj-C side of the G+ sign in. To that end, grab the iOS Quick Start app for Google Plus:
https://developers.google.com/+/quickstart/ios
Follow the instructions to open the sample project and you'll find the SignInViewController.m file which contains this line:
@interface SignInViewController () <GPPSignInDelegate>

That appears to be what you're after.
Once you have that working, you'll need to implement the connection to React Native. The Facebook post you linked to shows how to do that, but the official documentation is here:
http://facebook.github.io/react-native/docs/nativemodulesios.html#content
I also wrote a post to show the simplest Native Module I could think of, which I think describes the general concept pretty well:
http://colinramsay.co.uk/2015/03/27/react-native-simple-native-module.html

A: After so much struggle I have gone through all the issues we face with Google+ signin integration in React Native app.
Kindly find a step by step changes need to be done
1. Create Project in Google Cloud Platform : Try free trail
I am using google cloud platform, if you are not using that, you just enable apis under google console

*Enable Google+ API for your project and generate API Key in your google cloud console

*Set YourSHA-1 key and package name (as given in AndroidManifest.xml ) of your android project ( Note: if you are using expo for this, then you should eject expo first to achieve this, Read How To Eject Expo )
To generate your own SHA-1 use the command -> keytool -list -v -keystore mystore.keystore
NOTE : If Your build is debug build then theSHA-1 generated with above command won't work, kindly check your adb logs carefully, theSHA-1 being used by your android debug build will be logged in the device log. To check device log run the below command from your /Users//Library/Android/sdk/platform-tools —> adb logcat

*Import the same project in firebase : If you are not using firebase then skip this step and next step

*Setup android project in your firebase project, then setup authentication methods being used in your app.

*Then setup sameSHA-1 Key for your firebase project: Navigate to Project setting from side bar and click on general , select android app and set SHA-1 key
NOTE: Once SHA-1 is setup, download google-services.json file in the same page. and keep the file under your android project director app folder /ReactNativeProjectFolder/android/app

*add 'react-native-google-signin' and 'firebase' modules

npm install react-native-google-signin –save
npm install firebase –save

*Add dependency in your /app/bundle.gradle

Note : in below code those excludes are most important, or else you will encounter strange linking errors.
implementation project(':react-native-google-signin')

if your app is using some other dependencies like react-native-maps or react-native-social-share then do below changes as well
implementation(project(":react-native-google-signin")){
    exclude group: "com.google.android.gms" // very important
}
compile(project(':react-native-maps')) {
      exclude group: 'com.google.android.gms', module: 'play-services-base'
      exclude group: 'com.google.android.gms', module: 'play-services-maps'
    }
implementation 'com.google.android.gms:play-services-base:11.+'
implementation 'com.google.android.gms:play-services-maps:11.+'

*your android/bundle.gradle file should look as follows
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.0.0' // <--- add this
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}
ext {
    compileSdkVersion   = 23
    targetSdkVersion    = 23
    buildToolsVersion   = "23.0.1"
    googlePlayServicesVersion = "10.2.4"
    androidMapsUtilsVersion = "0.5+"
}

*un below commands
npm install
react-native link

*Once you run react native link – check android/settings.gradle file , cross check that there should not be duplicate lines of content.

So far we have done project level configurations, now let us see code changes

*React Native Google sign-in/sign-up using firebase code
import {
    GoogleSignin
} from 'react-native-google-signin';
import firebase from 'firebase';
function googleAuthConfig(successCallback, failureCallback) {
    GoogleSignin.configure({
            iosClientId: CLIENT_IDS.GOOGLE_IOS_CLIENT_ID,
            webClientId: '',
            hostedDomain: '',
            forceConsentPrompt: true,
            accountName: ''
        })
        .then(() => {
            console.log('Google Config Success');
            successCallback();
        })
        .catch((err) => {
            console.log('Google Config Error');
            failureCallback(err);
        });
}
function googleSignin() {
    googleAuthConfig(() => {
        GoogleSignin.signIn()
            .then((user) => {
                const {
                    accessToken
                } = user;
                var credentials = firebase.auth.GoogleAuthProvider.credential(null, accessToken);
                firebase.auth().signInWithCredential(credentials)
                    .then((firebaseResult) => {
                        loginToSG(dispatch, firebaseResult, props, 'Google', registerCallback);
                    })
                    .catch(error => console.log('error while checking with firebase', error));
            })
            .catch((err) => {
                console.log(err);
            });
    }, (googleConfigErr) => {
        console.log(googleConfigErr);
    });
}

*Finally the most important step is -> once do npm cache clean, delete your existing app from device, delete build folders then run the app
react-native run-android
Credits : Step by step guide with screenshots and code snippets


text:
Q: Escape new line in jil file How could I escape new line in autosys jil file?
delete_job: <job name>
insert_job: <job name> job_type: c
command: <sh file>
machine: <host>
owner: <owner>
permission: gx,mx
condition: s(A, 06.00)
    & s(B, 06.00)
std_out_file: <job name>.out
std_err_file: <job name>.err
alarm_if_fail: 0

Previous gives me error:
CAUAJM_E_50254 Unexpected line for <job name>: &


text:
Q: how do i use alexa's data.alexa.com url i want to read the country of any website from Alexa's Data from XML
so i tried
http://data.alexa.com/data?cli=10&url=http://www.flipkart.com
but this just returns the following for all domains
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ALEXA VER="0.9" URL="alexa.com/" HOME="0" AID="=">
<RLS TITLE="Related Links" PREFIX="http://" more="0">
<RL HREF="www.alexa.com/blocker?tag=pfcp2YmYvjxYjfxUj=0000000000000&ref=data.alexa.com/" TITLE="Please click here to continue using Alexa"/>
</RLS>
</ALEXA>

is there another way to axes alexa data

A: You need to sign up with Amazon Web Information Service at https://aws.amazon.com/awis/


text:
Q: JavaScript Failed to fetch in Windows Forms BlazorWebView Using Visual Studio Community 2022 and .NET6, created a Blazor WebAssembly project which included some JavaScript that used fetch to call an API. This works fine.
I then moved most of the code into a Razor class library (RCL) in order to be able to use it from my Blazor WebAssembly or from a Windows Forms BlazorWebView. The Blazor WebAssembly using the RCL works fine. But the Windows Forms BlazorWebView using the RCL fails as soon as the JavaScript uses fetch to call the API.
To simplify matters, I have removed the RCL from the equation and started over with a simple Windows Forms app using BlazorWebView. I used this Microsoft tutorial and reproduced the problem. If I can find a solution to this, then hopefully I can use it for the RCL approach as well.
Here is what I added to the tutorial above to reproduce the problem:
I added some JavaScript (Counter.js) to the wwwroot folder of the project:
window.CounterJSFunctions = {
    callFetch: async () => {
        const response = await fetch('http://12.34.56.78:5001/api/values');
        return await response.text();
    }
};

I referenced the JavaScript from the index.html in the wwwroot folder of the project:

I modified the Razor component (Counter.razor) to call the API directly (which works) and then by means of the JavaScript (which fails):
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime
@inject HttpClient Http

Counter

Current count: @currentCount

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private string currentCount = "";

    private async void IncrementCount()
    {
        // this works:
        //currentCount += await Http.GetStringAsync("http://12.34.56.78:5001/api/values");
        // this fails:
        currentCount += await JSRuntime.InvokeAsync<string>("CounterJSFunctions.callFetch");
    }
}

The exception I get says:
Microsoft.JSInterop.JSException: 'Failed to fetch
TypeError: Failed to fetch
    at Object.callFetch (https://0.0.0.0/Counter.js:4:32)
    at https://0.0.0.0/_framework/blazor.webview.js:1:3332
    at new Promise (<anonymous>)
    at beginInvokeJSFromDotNet (https://0.0.0.0/_framework/blazor.webview.js:1:3306)
    at https://0.0.0.0/_framework/blazor.webview.js:1:40711
    at EventTarget.<anonymous> (<anonymous>:7:62)
    at EmbeddedBrowserWebView.<anonymous> (<anonymous>:1:37376)'

The source is System.Private.CoreLib and there is no inner exception.
I made sure CORS is enabled on the API, and tried a different public API as well. I was expecting the JavaScript to behave the same as in the browser (using WebAssembly). Any ideas are greatly appreciated.
Edit
Fiddler reveals that no request is sent. If I call a public API on HTTPS, it works. If I call a public API on HTTP, it fails. I need to call the API on HTTP, so how can I do this?


text: Q: Magento 2.4 upgrade Class 'Zend_Controller_Request_Http' not found I recently updated from Magento 2.2 to Magento 2.4 and I have some custom modules which are throwing errors like these when I run setup:di:compile in my terminal. I have observed that in vendor folder the zendframework is now changed to zendframework1. However I cannot understand how to find the file and resolve this error. My custom modules extend Zend_Controller_Request_Http. Any help is appreciated. Thank you.


text:
Q: Python dictionary comprehension not counting correctly Going through some code from a competition that finished about a week ago, NCSS Challenge, and I am trying to replace lists and dictionaries with a comprehension but I can't manage to get the dict comprehension to work.
I had the code
for i in a:
  b[i] = b[i] + 1

and I tried replacing the code with
b = dict((i, b[i] + 1) for i in a)
but that doesn't work, I don't know how to get the dictionary to count properly
entire code:
a = [i[:-1] for i in open("votes.txt")]
b = {}

for i in open("votes.txt"):
  b[i[:-1]] = 0

#b = dict((i, b[i] + 1) for i in a)
for i in a:
  b[i] = b[i] + 1

for i in b:
  print(str(i) + ': ' + str(b[i]))

I know my code isn't very good, I just started recently, please don't judge to hard.
votes.txt:
Pedro Sanchez
Trisha Jenner
Trisha Jenner
Summer Wheatley
Pedro Sanchez
Pedro Sanchez
Trisha Jenner
Pedro Sanchez
Summer Wheatley

My code works fine using the for i in a loop but using a dictionary comprehension it displays the text below.
I expect the output to display
Pedro Sanchez: 4
Trisha Jenner: 3
Summer Wheatley: 2

when using the dict comprehension
but it instead displays
Pedro Sanchez: 1
Trisha Jenner: 1
Summer Wheatley: 1

A: Your code doesn't work because the expression on the righthand side of the equals sign gets evaluated before the lefthand name is assigned to, so each time it looks up b[i] it's seeing 0, as defined in the previous step.
As for how to fix it, ultimately you want to use collections.Counter instead, which is basically a wrapper on a dict:
from collections import Counter

with open("votes.txt") as f:
    a = f.read().splitlines()

b = Counter(a)
for k, count in b.items():
    print('{}: {}'.format(k, count))

Output:
Pedro Sanchez: 4
Trisha Jenner: 3
Summer Wheatley: 2


text:
Q: Verbs for the word achievements e.g other achievements he ... are (fill ... in) Does this make sense?

Other achievements he attained...

Or is it "obtained"?
Thank you everyone! This is my first time using this website and you have been very helpful.

A: If you must use the noun "achievement" (rather than the verb "achieve") and find yourself in need of a verb to go with it, there are possibilities but all of them sound a little bit awkward.
Perform, win, score or gain are the sorts of things I have in mind.
e.g. He performed the remarkable achievement of three birdies in a row.
But it would be less wordy to say He achieved three birdies in a row.
As someone has noted achieve and achievement are already strong words.
Of course achievement works well with the verb to be, as in To have climbed Everest is a stunning achievement.


text:
Q: Dynamically resize a UIImage width within a UITableView Cell in Xcode I am using the code below to put together my UITableView. The Cell height allows the first three rows to show in the table without scrolling. Everything is fine with those first three rows. But as soon as I scroll down past the original first three rows, the image in the myImage inherits the width of cells in the first three rows and does not resize according to the value extracted from the array based on indexPath.row.
The cell is obviously being reused from the else statement from the originally painted cells but I need to figure out a way to allow the myImage width to vary for each row.
Any help is Greatly Appreciated!
lq
- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

const NSInteger LABEL_TAG = 1001;
const NSInteger IMAGE_TAG = 1002;

UILabel *myLabel;
UIImageView *myImage;

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    // Create the cell

    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
                        reuseIdentifier:CellIdentifier]
                        autorelease];

    // Constant values

    const CGFloat LABEL_HEIGHT = 20;
    const CGFloat LABEL_WIDTH = 140;
    const CGFloat LABEL_INDENT = 1;
    const CGFloat LABEL_TOP = 0.065 * myTableView.rowHeight;

    // Create the label;

    myLabel = [[[UILabel alloc] initWithFrame:
            CGRectMake(
                LABEL_INDENT,
                LABEL_TOP  + LABEL_HEIGHT,
                LABEL_WIDTH,
                LABEL_HEIGHT)]
            autorelease];

    [cell.contentView addSubview:myLabel];

    // Configure the label

    myLabel.tag = LABEL_TAG;
    myLabel.backgroundColor = [UIColor clearColor];
    myLabel.textColor = [UIColor blueColor];
    myLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 3];
    myLabel.textAlignment = UITextAlignmentRight;

    // Create the image (NOTE: THIS IS THE PROBLEMATIC PART)

    // Extract the width for the image based on an array value for each row:

    int xValue = [[myArray objectAtIndex:(indexPath.row)]intValue];
    float xLength = (float)xValue / 100;

    myImage = [[[UIImageView  alloc] initWithFrame:
                CGRectMake(
                    LABEL_INDENT + 53,              // This places the image to the right of the label
                    LABEL_TOP  + LABEL_HEIGHT,
                    xLength * LABEL_WIDTH,

// This is where the width of each row is adjusted
                        LABEL_HEIGHT]
                    autorelease];
    [cell.contentView addSubview:myImage];

    myImage.contentMode = UIViewContentModeLeft;
    myImage.image = [UIImage imageNamed:@"ProgressBar.png"];
    myImage.clipsToBounds = YES;

} else {

    // Re-use cells

    myLabel = (UILabel *)[cell viewWithTag:LABEL_TAG];
    myImage = (UIImageView *)[cell viewWithTag:IMAGE_TAG];
}

return cell;

}

A: The above reuses the cells, as you draw attention to in your comments, but; after finding a cached cell you do the setup again, not matter if the cell is old or new.
The UITableViewCell is a "two-parter", the first time a cell is referenced it is instantiated and build, all the subsequent times it is referenced it should only be updated. (a cell is referenced each time it is scrolled onto the screen or the tableview is reloaded etc. this happens often so to save CPU time it is also best not to do the same setup again and again).
So, try approaching it like this instead:
- (void) configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    UILabel *settingText = [ISInterfaceElement getLabel:Headline]; //Opps... ISInterfaceElement is my custom class. All it does is return a UILabel with settings that comply for a Headline label, according to an enum in the header.
    [settingText setFrame:CGRectMake(0.0f, 15.0f, 320.0f, 20.0f)];
    [settingText setTextAlignment:UITextAlignmentCenter];
    [settingText setTag:SETTINGS_LABEL];
[cell addSubview:settingText];
    UIView *background = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 50.0f)];
    [cell addSubView:background]; //added
    [background release]; //added

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        [self configureCell:cell atIndexPath:indexPath];
    }

    [(UILabel*)[cell viewWithTag:SETTINGS_LABEL] setText:@"Settings…"];

    return cell;
}

So the cellForRowAtIndexPath call the configureCell method if it needs a new cell setup, else it simply
updates the cell with the correct value from the model (usually [someArray objectAtIndex:indexPath.row] but in my case just a string.
So send along any parameter(height) you need the configureCell method to know to be able to build your cell, and do all the building in that method and all the updating in cellForRowAtIndex.
Hope it makes sense:)


text:
Q: How fusion reactor could be operated on space craft? Considering that space craft uses engines only during acceleration and deceleration, how fusion reactor will be operated?
For example:

*

*it will be started / stopped for each maneuver

*will be working on full power all time

*scale down its output?


text:
Q: Criar form e gridView dinamicamente com VB6 Eu preciso criar um formulario dinamicamente pelo codigo e adicionar um gridView e um botao a esse formulario, alguem pode me ajudar?

A: Veja essa referência, How To Dynamically Add Controls to a Form with Visual Basic 6.0 https://support.microsoft.com/en-us/kb/190670 .


text:
Q: Why value of Double can't be converted to Any? With Xcode 9 GM (Swift 4), I see
error: cannot convert value of type 'Double' to specified type 'Any?'
for code:
var a: Any? = +30.0

Why?

A: The + is causing confusion.
var a: Any? = 30.0

works.
Or you can create a Double and assign that:
var a: Any? = Double(+30.0)


text:
Q: back button navigation very slow I am using following code to push viewcontroller from another viewcontroller .
ProductDetailViewController * productDetails = [self.storyboard instantiateViewControllerWithIdentifier:@"ProductDetailViewController"];
[self.navigationController pushViewController:productDetails animated:YES];

Now this is the code gets called on tap of back button
[self.navigationController popViewControllerAnimated:YES];

Problem is when I tap on back button, navigation becomes very slow. Any suggestion to solve this.


text:
Q: Injecting Multiple EJBs I have a workflow class where I'm injecting several EJB's at the top of my class using the @EJB tag:
@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class WorkflowBean {

   @EJB
   private BeanOne beanOne;
   @EJB
   private BeanTwo beanTwo;
   @EJB
   private BeanThree beanThree;
   @EJB
   private BeanFour beanFour;
   @EJB
   private BeanFive beanFive;
   @EJB
   private BeanSix beanSix;

Is there a better, more organized way of injecting these at the top of my code, maybe on one line somehow?  The code works perfectly fine, but I think I am going to add a few more beans by the time the code is complete and I feel that it is starting to cause my code to look cluttered.

A: There's nothing inherently wrong with doing it that way, but it can get a bit cluttered.
If you could identify and group together behaviors based on business behavior, it might reduce the number of @EJB annotations.  For instance, if beanOne, beanTwo, and beanThree all relate to user management, you could create a userManagement bean, inject them there, and then only inject the one userManagement bean in your workflow bean.  It also might help with self-documentation a bit as well.
IMHO, your workflow bean should pretty much just be calling other beans that encapsulate the business logic, instead of trying to define it all here.


text:
Q: Blackberry Simulator Network issue on Windows7/64bit/32bit(on vmfusion), what to do? i have Windows 7 64bit on my PC and i have Windows 7 32bit on my vmfusion on mac.
The problem is as follows, if i run early version of blackberry simulators (not touchscreen, but with scroll ball), i do not get network access. I try to run MDS as i have read on forums, but it looks like MDS quits, and i still have no network acess.
The new simulators, let me just run them, and i dont even need to lunch mds, i get access to network with no problem. But the project i am working on, requires me to test mobile site again older blackberry devices.
So here is what i have done so far:

*

*Made sure i have following for java: "C:\Program Files (x86)\Java\jre6" "C:\Program Files (x86)\Java\jdk1.5.0_22" "C:\Program Files (x86)\Java\jre1.5.0_22", do i need anything else?

*set up environment path variable to bin folders: C:\Program Files (x86)\Java\jdk1.5.0_22\bin;C:\Program Files (x86)\Java\jre1.5.0_22\bin;

*installed everything at separate location as administrator (D:\Programs\Research In Motion), so not to have any write/read issues.

*installed MDS and then BlackBerry Smartphone Simulators 4.5.0 - 4.5.0.81 (8100)
now i try to run MDS first, and i see two cmd/three windows popping up one after another, and closing right away. I start up simulator and everything starst great, but when i go to browser and try to navigate to web resource i get an error "Unable to connect to the selected Mobile Data Service, please try again later".
Little edit:
I have moved my effort to XP, which solved MDS start up issue, but simulator still cant establish network connection. See screen shot.

A: To start MDS you will have to start a console with "Run as administrator" then go to the path where you installed mds and start the .bat file from your elevated console.

Here the console command to start MDS.

EDIT
When MDS is running you can connect to it with your browser to see what is not working
goto : http://localhost:8080/


text:
Q: Internet Explorer inline list for navigation menu I'm having a problem with getting Internet Explorer to display my menu bar correctly. The menu items should be in an inline list across the page but they remain in a list going down the page with bullet points.
Please see this fiddle for inspection.
I have been viewing in IE7 but as far as I'm aware the problem remains in IE9. Thanks for your help.

A: To make it work with IE8/IE9 you will need IE html5 Shiv (just create elements with Javascript).
But be sure to make them  display:block; in your CSS!!  You can also have Google shiv to host it for you:Google IE html5 ShivMore about using  IE Shiv: HERE But you can also make it yourself like this :
Your Fiddle HERE
<style type="text/css">
nav{
display:block;
}
</style>

<script type="text/javascript">
document.createElement("nav");
</script>

A: You are using the <nav>  HTML5 element. IE 8 and lower do not style unknown / unsupported elements.


text:
Q: Exit Intent in Mobile using javascrpt or jQuery I tried modifying the plugin to show a modal popup when a website visitor leaves the page using haschange, but it still doesn't work. How to get it to work? I need help fixing it
 $(document).ready(function(e) {

    var exit_intent_popup_hash = 'b'
    window.location.hash = exit_intent_popup_hash
    window.history.back()

    setTimeout(function() {
        window.history.forward()
        $('.fel-modal-parent-wrapper').each(function() {

            var $this = $(this);
            var tmp_id = $this.attr('id');
            var popup_id = tmp_id.replace('-overlay', '');
            var trigger_on = $this.data('trigger-on');
            var exit_intent = $this.data('exit-intent');

            if ('automatic' == trigger_on) {
                if ('yes' == exit_intent && FelModalPopup_canShow(popup_id)) {

                    $(window).hashchange(function() {
                        if (window.location.hash !== `#${exit_intent_popup_hash}`) {
                            FelModalPopup_show(popup_id);
                            window.history.forward()
                        }
                    }, false);
                }
            }
        });
    }, 500);
});


text:
Q: How do I get the text from a tkinter Entry widget? I have been trying everything and im pretty much exhausted. The problem is that there comes up an error "Can't convert 'Entry' object to str implicitly" And i doesnt find any way to make it work.
Here is the code:
from tkinter import *

def wcommand():
     import webbrowser
     new=2;
     url='https://'+w
     webbrowser.open(url,new=new);

root = Tk()

Label (root, text="Nettadresse:").grid(row=0)
w = Entry(root)
w.grid(row=0, column=1,)

b1 = Button(root, text='Kjør!', command=wcommand).grid()

root.mainloop()

A: Use .get method to get the text from the Entry widget:
url='https://{}'.format(w.get())

A: There are several things wrong with your code. First, you don't need those semicolons. Second, you don't want url='https://'+w there, you want url='https://'+w.get() there. The .get() will retrieve the string contents of that Entry widget. Third, instead of:
Label (root, text="Nettadresse:").grid(row=0)

you should do:
mylabel = Label(root, text="Nettadresse:")
mylabel.grid(row=0)

This will ensure that you can refer to this Label object later, in case you want to reconfigure it or move it or something. Fourth, you should import webbrowser as the second line of your code, right below from tkinter import *, rather than every time that function is called.


text:
Q: Cayley Transform, Exponential Mapping and more... Assume a self-adjoint operator, represented as hermitian matrix $H=H^\dagger$. To my knowledge there are at least 2 mappings of $H$ onto unitary matrices:

*

*Cayley's Transformation with $U_1=\frac{H+i1}{H-i1}$ ($1$ is a unit matrix of appropriate dimension)

*Exponential Mapping with $U_2=e^{iH}$.

Are there other mappings with a different structure and if not can one prove that?

A: Assume that a mapping $H\mapsto U$ is of such a form that $U$ can be expressed as a power series in $H$ (I don't think this is a huge loss of generality to assume this, perhaps none.) Then
$$
U=c_{0}I+c_{1}H+c_{2}H^{2} + c_{3}H^{3} + \cdots
$$
Since $U$ unitary implies $e^{i\theta}U$ is unitary, then WLOG we may take $c_{0}$ to be real. Moreover, if $U$ is unitary, then $U^{-1}= U^{*}$, so (assuming $U^{-1}$ can be represented as a power series in $H$)
$$
U^{-1}=c_{0}I+c_{1}^{*}H+c_{2}^{*}H^{2} + c_{3}^{*}H^{3}+ \cdots
$$
The condition $UU^{-1} = I$ gives
$$
I=UU^{-1}=c_{0}^{2}I+c_{0}(c_{1}+c_{1}^{*})H+\cdots
$$
whereupon we immediately determine that $c_{0}=1$ and that $c_{1}+c_{1}^{*}=0$. Hence $c_{1}$ is purely imaginary, and we write $c_{1}=ib_{1}$. With this in hand, we expand the products of these power series again:
$$
I=UU^{-1}=I+(c_{2}+c_{2}^{*}+b_{1}^{2})H^{2}+\cdots
$$
so that $2\mathfrak{R}(c_{2})=-b_{1}^{2}$ but the imaginary part of $c_{2}$ is a free parameter. So we've already found 2 free parameters, each of which generate infinite families of unitary maps $H\mapsto U$. So there are a ton of these maps.

A: Suppose that $H\mapsto U$ and $Hv=\lambda v$. Then for 1) $Uv = \frac{\lambda+i}{\lambda-i}v$ and for 2) $Uv = \exp(i\lambda)v$. Let $Uv=\kappa v$.
For 1) as $\lambda \rightarrow \infty$, $\kappa \rightarrow 1$. However, $\kappa$ never attains the value of $1$ and so the Cayley Transform does not map Hermitian matrices onto the unitary matrices (it is, however, one-to-one).
For 2) $\exp(i(\lambda + 2n\pi))=exp(i\lambda))$. So the matrix exponential is not one-to-one (it is, however, onto).
In the comments it is mentioned that a bijection is desired. We limit ourselves to a class of functions that preserve eigenvectors while mapping real eigenvalues to complex ones of modulus 1. This would include the power series in $H$, as assumed in Nick's answer. Thus, we can simply look for bijective maps from $\mathbb{R}\rightarrow S^1$.
Since $\mathbb{R}$ and $S^1$ are not homeomorphic, there are no bi-continuous bijections between the two.
There are, however, discontinuous bijections between the two sets (see this question for bijection from $(0,1) \rightarrow (0,1]$, which gives us a bijection $\mathbb{R}\rightarrow S^1$. However, in this example, there are countably infinite discontinuities, so it is not a particularly nice bijection).
Without rigor, I would say that none of the power series mappings would be invertible on the basis that the series would need to converge everywhere (or the mapping is ill-defined) and therefore will be continuous everywhere. Since our mapping is defined by the power series, it is analytic, hence we can find a power series for the inverse function by the Lagrange inversion theorem (there is possibly an issue if the derivative at a point is 0, but since the function is invertible it hopefully isn't a problem). Therefore, the inverse is continuous. Therefore, if a power series is a bijection it is bicontinous. This is a contradiction (as $\mathbb{R}$ and $S^1$ are not homeomorphic). Therefore, no power series in $H$ gives a bijection from the Hermitian to unitary matrices.


text:
Q: What url should i give on tag to save to CameraRoll react-native? While saving image to camera roll what uri should be given to the the 'tag' to save to camera roll.
I tried to give the path of camera roll as asset-library://asset/
but throws an error saying Could not find asset with UUID (null)

A: It's actually expecting the uri of an image asset. So the method seems to only be able to update existing assets. Try deploying your app with a placeholder image and then have the app update it. Remember to pass in the placeholder image's uri.


text:
Q: 'How delayed is the flight?' - Is it the right expression? The word delay simply means that the thing is not on time but pushed further in time. However, it does not show any amount (of hours?). In this...

How delayed is the flight? [From 250 Ways to Say it in Business English by Andrew D. Miles]

...rightly expressed? Frankly, I'm not fully convinced. Or it should be...

How many hours the flight is delayed by? That's because when we ask someone about the flight delay at the airport, we certainly require the 'number of hours' not how it got delayed.

If I ask how delayed is the flight, does it mean How the flight is delayed? and I am likely to get an answer - "The pilot did not report on time and this is how the flight is delayed."
I agree that Why is the flight delayed? should be the question but the way I put my answer, how also works, doesn't it?

A: Yes.
(At least for what you intend to ask)
Here's why:

*

*"how" can refer to degree

From Wiktionary

*

*To what degree

*"How old are you?"
I'm sure you won't answer: I am old because time works that way.
The answer "I am very old." is perfectly fine, albeit very literal. In the same way, "How delayed is the flight?" begs for a very literal answer: "I am very delayed." It's just that specifying how many hours the flight is delayed or saying your age expounds on "how" better than just saying "very".
However, if you ask questions like "How good are you?" it is hard to quantify the degree unlike time or age.

A:
How delayed is the flight?

Is asking specifically for the length of the delay.  "25 minutes."

Why is the flight delayed?

Is asking for the reason the flight is delayed.  "There is weather in Topeka."

How is the flight delayed?

This is a valid question, but really only if you worked for the airline and wanted to know how to actually record the delay.

How long is the delay? or How long is the flight delayed?

Feels like the most correct way to express this.


text:
Q: How to only show all articles that contains a particular value? Currently using Laravel 8, I have to show on a page all articles but only the ones that contain a specific row value in my Database. For instance, in this one, I have a column in the desired table that is called "is_reserved" as TinyInt acting as a True or false (1-0).
I have searched absolutely everywhere and I cannot understand nor find the right syntax for filtering and show only articles that aren't reserved (is_reserved = 0).
In my blade view file, I have a @foreach loop that fetches my item from my controller, like the following below. Which works by the way, just not the way I intend it to be. I'm out of ideas.
TL:DR: I just want to be able to show all items from my database but only the ones with a specific row value.

    @foreach ($donations as $donation)

        image }}" alt="image" class="col" style="border-radius: 100%;">

{{ Str::limit($donation->description, 80) }}

Location: Quebec

Meteo: Cold

                    <button class="col-5 btn yellowBtn">reserve</button>
                    id)}}">View

    @endforeach

A: Move the logic to the controller / service before looping through them, then send the necessary rows to your blade (probably with a $is_reserved boolean in the array/object)
Keep in mind that if you're diving into logic in the blade / template file itself, it's best to move it back a step and just provide the template the simplest data you can.
Taking your question as an example, before sending the rows to the template, and just show the ones that match your need.
e.g.
$rows = DB::table('your_table')->where('is_reserved', '1')->get();
return $rows; //or extend your template here

Otherwise, you can ad an @if condition right to your template, and render only if ceratin condition is met


text:
Q: Before Update not working in a Trigger framework I tried implementing Tony Scott's tidy trigger pattern and failed to understand why there is a separate method for each trigger event apart from bulkBefore() & bulkAfter() methods. Why non-bulk handler methods take single sObject records? Why not do all the processing in bulkBefore() & bulkAfter() methods by calling separate apex classes ? That could be another topic/question.
I switched to lightweight Trigger framework for the interest of time - Details
I'm trying to override the attachment name with parent record name. I have a similar code in before Insert which works. But the before update handler method is not working as expected.
Before Insert code which works fine -
public void BeforeInsert(List<SObject> newRecs)
{
    set<id> itemids = new set<id>();
    for(attachment att: (List<attachment>)newRecs){
        if(att.parentid.getSobjectType() == Expense_Item__c.sObjectType){
            itemids.add(att.ParentId);
        }
    }

    Map<Id,expense_item__c> itemMap = new Map<Id, expense_item__c>([select name from expense_item__c where id in :itemids]);

    for(attachment att:(List<attachment>)newRecs)
    {
        if((att.parentid.getSobjectType() == Expense_Item__c.sObjectType) && itemMap.containsKey(att.ParentId))
        att.Name= itemmap.get(att.ParentId).name;
    }

}

Before Update event code which's not working.
public void BeforeUpdate(Map<Id, SObject> newRecMap, Map<Id, SObject> oldRecMap) {

    list<attachment> newRecs = newRecMap.values();
    set<id> itemids = new set<id>();
    for(attachment att: (List<attachment>)newRecs){
        if(att.Parentid.getSobjectType() == Expense_Item__c.sObjectType){
            itemids.add(att.ParentId);
        }
    }

    Map<Id,expense_item__c> itemMap = new Map<Id, expense_item__c>([select name from expense_item__c where id in :itemids]);

    for(attachment att: newRecs)
    {
        if((att.parentid.getSobjectType() == Expense_Item__c.sObjectType) && itemMap.containsKey(att.ParentId))
        att.Name= itemmap.get(att.ParentId).name;
    }

A: I'm going to attempt to answer at least part of your question regarding the Tony Scott's TriggerFactory. Here's some of his code taken from an org I'm working in right now that just includes the bulk handler methods for the base class:
/**
 * private static method to control the execution of the handler
 *
 * Arguments:   ITrigger handler - A Trigger Handler to execute
 */
private static void execute(ITrigger handler)
{
    // Before Trigger
    if (Trigger.isBefore)
    {
        // Call the bulk before to handle any caching of data and enable bulkification
        handler.bulkBefore();

        // Iterate through the records to be deleted passing them to the handler.
        if (Trigger.isDelete)
        {
            for (SObject so : Trigger.old)
            {
                handler.beforeDelete(so);
            }
        }
        // Iterate through the records to be inserted passing them to the handler.
        else if (Trigger.isInsert)
        {
            for (SObject so : Trigger.new)
            {
                handler.beforeInsert(so);
            }
        }
        // Iterate through the records to be updated passing them to the handler.
        else if (Trigger.isUpdate)
        {
            for (SObject so : Trigger.old)
            {
                handler.beforeUpdate(so, Trigger.newMap.get(so.Id));
            }
        }
    }
    else
    {
        // Call the bulk after to handle any caching of data and enable bulkification
        handler.bulkAfter();

        // Iterate through the records deleted passing them to the handler.
        if (Trigger.isDelete)
        {
            for (SObject so : Trigger.old)
            {
                handler.afterDelete(so);
            }
        }
        // Iterate through the records inserted passing them to the handler.
        else if (Trigger.isInsert)
        {
            for (SObject so : Trigger.new)
            {
                handler.afterInsert(so);
            }
        }
        // Iterate through the records updated passing them to the handler.
        else if (Trigger.isUpdate)
        {
            for (SObject so : Trigger.old)
            {
                handler.afterUpdate(so, Trigger.newMap.get(so.Id));
            }
        }
    }

    // Perform any post processing
    handler.andFinally();
}

What I hope you'll notice is that there are only two places in the bulk before and bulk after where the code isn't essentially doing a record by record iteration. That place is at the beginning of each bulk method before any of the if statements begin. Once you move further into the bulk handlers, you begin iterating in for loops. That's how his pattern is intended to work. It's not intended to process any records other than in a record by record basis.
If you want to have methods like yours, since both of them contain queries, what you'd want to do put a section in the andFinally section that either adds that code using if(trigger.isBefore && trigger.isInsert) to which in the first case you pass all of the trigger.new so records to it for processing (pass both the trigger.new and trigger.old  records in the 2nd the second example).
From there you can either pass them to another trigger handler class for processing or you can run the query from inside the andFinally method since it's doesn't run inside of a loop.
I'll add that this pattern requires you to think differently than what you've been used to with the way you're taught to write triggers using the standard documentation. It takes some time to adapt to it.
Edit 1 in response to comments
DML is intended only to occur either in the andFinally or in a Helper Class (preferred) that's called from the andFinally method.* SOQL can occur at the beginning of the Trigger Handler Class, in a Helper Class, or in the andFinally method. As I recall, Tony's model shows it occurring in a separate Helper class that runs in a before context to run a query to get Accounts on Opportunity. I believe it's called from the start method or "constructor" section of the Trigger Object Handler.
You may find it helpful to try and think of these initial Trigger Object Handlers that are being spawned by his TriggerFactory as something along the lines of a "Dispatcher" class. Use these Dispatcher Classes to send ALL of your records to another Helper Class that later sorts and processes your records for you according to the logic you want to use. In essence, these Dispatchers only bulk your records for you. If you try to use them to sort records for you, and you have either a lot of different helpers or complex logic, they can very quickly get really messy and incredibly difficult to work with.
It's best to send the real work you want to do to methods that are in other supporting helper classes for each trigger object handler you have in your TriggerFactory classes. In other words, don't expect to only have one class that does all of your work for you. You want to have a separation of concerns here.
Edit2 in response to comments
Comment: I have to update related records based on the status__c of the current chunk of records, approach (1) can I go directly to AfterInsert method and collect the ids and then process it using a helper class in AndFinally method or (2) collect up in bulkAfter and then process it using a helper class in AndFinally ?
You could do this in several different ways, including using a Helper Class & method linked to the BulkAfter section that selects AfterInsert insert records for addition to a list that gets processed in andFinally. Quite honestly, I think that would be a poor use of the helper method and muddies up the trigger. Instead, bulk all of your AfterInsert records, then send them directly to an AfterInsert Helper Class for sorting and further processing for update in the handler class.
I'd do something like this in the andFinally() method:
    if(trigger.isAfter && trigger.isInsert){
        SharingHandler EICS = new SharingHandler(newLst,oldLst,newMap,oldMap,trigger.isBefore,trigger.isAfter,trigger.isInsert,trigger.isUpdate);
     }

My SharingHandler class's constructor (or one of them) will expect the two lists, two maps and 4 booleans. One can easily get away with only sending the two lists since you can readily rebuild the maps as follows:
map<id,sObjectName>oldMap = new map<Id,sObjectName>();
//  then doing:
oldMap.putAll(oldLst)

So, it isn't critical to pass the maps to the handler as they can easily be reconstructed without the need to iterate in a loop.


text:
Q: How can I send inputs to a raspberry from a website? I would like to make a website using the MEAN stack to control a raspberry pi 2. How do send commands to a Raspberry PI via a web interface?

A:
How do send commands to a Raspberry PI via a web interface?

*

*Put the Raspberry Pi on your network.

*Put an http server on your Raspberry Pi.

*Create the desired web pages in whatever http server environment you choose.

*Connect your web browser to the server on the Raspberry Pi to display desired web pages.

*Send commands to the Raspberry Pi from the web pages, either with form POSTs, Javascript Ajax calls or Javascript webSocket messages.

I have a Raspberry Pi that I use as a home automation controller.  I've built a web server on it using node.js and Express.  I have settings pages that communicate with the web server using form POSTs.  I have buttons on the web page that communicate with the server using Ajax calls.  I have real-time updates that the server sends back to the web page via a socket.io connection to update status display in the web page (in my case, real-time temperature readings).  Which to use for any given action depends upon the details of the specific operation.


text:
Q: Approximation of a 2 variable function. If the weight of an object that does not float in water is $x$ pounds in the air and its weight in water is $y$ pounds , then the specific gravity of the object is :
$S= \dfrac{x}{x-y}$
For a certain object x and y are measured to be 1.2lbs and 0.5lbs. It is known that the measuring instrument will not register less than the true weights , but it could register more than the true weights by as much as 0.01lbs.
We need to find the maximum possible error is $S$.
Maximum possible error in $S$ is represented as $\dfrac{\Delta S}{S}$ , and ,
$\Delta S = S_x \Delta x+ S_y \Delta y$
The question says ,

"It is known that the measuring instrument will not register less than
  the true weights , but it could register more than the true weights by
  as much as 0.01lbs."

So what I gathered from this was , $\Delta x \leq 0.01$ , similarly $\Delta y \leq 0.01$ , but couldn't get the correct answer ..
Am I speculating wrong ?
Kindly help !


text:
Q: Appengine Django custom validations How can I write a custom django validation for Google AppEngine.
The case is I have a model which has a field whose value should be greater than an already existing value in the datastore for the same attribute.
Thanks in advance.

A: The sample code is here: http://docs.djangoproject.com/en/1.1/ref/forms/validation/#cleaning-a-specific-field-attribute
You should run the code which checks the form.is_valid() and saving the entity in a transaction for consistency.  Look at the 'isolation and consistency' section here: http://code.google.com/appengine/docs/python/datastore/transactions.html


text:
Q: How could this C fragment be written more safely? I have the following C code fragment and have to identify the error and suggest a way of writing it more safely:
char somestring[] = "Send money!\n";
char *copy;

copy = (char *) malloc(strlen(somestring));

strcpy(copy, somestring);
printf(copy);

So the error is that strlen ignores the trailing '\0' of a string and therefore it is not going to be allocated enough memory for the copy but I'm not sure what they're getting at about writing it more safely?
I could just use malloc(strlen(somestring)+1)) I assume but I'm thinking there must be a better way than that?

EDIT: OK, I've accepted an answer, I suspect that the strdup solution would not be expected from us as it's not part of ANSI C.  It seems to be quite a subjective question so I'm not sure if what I've accepted is actually the best.  Thanks anyway for all the answers.

A: I can't comment on the responses above, but in addition to checking the
return code and using strncpy, you should never do:
printf(string)

But use:
printf("%s", string);

ref: http://en.wikipedia.org/wiki/Format_string_attack

A: char somestring[] = "Send money!\n";
char *copy = strdup(something);

if (copy == NULL) {
    // error
}

or just put this logic in a separate function xstrdup:
char * xstrdup(const char *src)
{
    char *copy = strdup(src);

    if (copy == NULL) {
       abort();
    }

    return copy;
}

A: char   somestring[] = "Send money!\n";
char   *copy;
size_t copysize;

copysize = strlen(somestring)+1;
copy = (char *) malloc(copysize);
if (copy == NULL)
    bail("Oh noes!\n");

strncpy(copy, somestring, copysize);
printf("%s", copy);

Noted differences above:

*

*Result of malloc() must be checked!

*Compute and store the memory size!

*Use strncpy() because strcpy() is naughty. In this contrived example it won't hurt, but don't get into the habit of using it.

EDIT:
To those thinking I should be using strdup()... that only works if you take the very narrowest view of the question. That's not only silly, it's overlooking an even better answer:
char somestring[] = "Send money!\n";
char *copy = somestring;
printf(copy);

If you're going to be obtuse, at least be good at it.

A: *

*strlen + 1, for the \0 terminator

*malloc may fail; always check malloc return value

A: Ick... use strdup() like everyone else said and write it yourself if you have to. Since you have time to think about this now... check out the 25 Most Dangerous Programming Errors at Mitre, then consider why the phrase printf(copy) should never appear in code. That is right up there with malloc(strlen(str)) in terms of utter badness not to mention the headache of tracking down why it causes lots of grief when copy is something like "%s%n"...

A: I would comment to previous solutions but I do not have enough rep.
Using strncpy here is as wrong as using strcpy(As there is absolutely no risk of overflow). There is a function called memcpy in < string.h > and it is meant exactly for this. It is not only significantly faster, but also the correct function to use to copy strings of known length in standard C.
From the accepted answer:
char   somestring[] = "Send money!\n";
char   *copy;
size_t copysize;

copysize = strlen(somestring)+1;
copy = (char *) malloc(copysize);
if (copy == NULL)
    bail("Oh noes!\n");

memcpy(copy, somestring, copysize); /* You don't use str* functions for this! */
printf("%s", copy);

A: Ways to make the code safer (and more correct).

*

*Don't make an unnecessary copy.  From the example, there's no apparent requirement that you actually need to copy somestring.  You can output it directly.

*If you have to make a copy of a string, write a function to do it (or use strdup if you have it).  Then you only have to get it right in one place.

*Whenever possible, initialize the pointer to the copy immediately when you declare it.

*Remember to allocate space for the null terminator.

*Remember to check the return value from malloc.

*Remember to free the malloc'ed memory.

*Don't call printf with an untrusted format string.  Use printf("%s", copy) or puts(copy).

*Use an object-oriented language with a string class or any language with built-in string support to avoid most of these problems.

A: to add more to Adrian McCarthy's ways to make safer code,
Use a static code analyzer, they are very good at finding this kind of errors

A: The best way to write it more safely, if one were to be truly interested in such a thing, would be to write it in Ada.
somestring : constant string := "Send money!";
declare
   copy : constant string := somestring;
begin
   put_line (somestring);
end;

Same result, so what are the differences?

*

*The whole thing is done on the stack
(no pointers). Deallocation is
automatic and safe.

*Everything is automaticly range-checked so
there's no chance of buffer-overflow
exploits

*Both strings are constants,
so there's no chance of screwing up
and modifying them.

*It will probably be way faster than the C, not only because of the lack of dynamic allocation, but because there isn't that extra scan through the string required by strlen().

Note that in Ada "string" is not some special dynamic construct. It's the built-in array of characters. However, Ada arrays can be sized at declaration by the array you assign into them.

A: The safer way would be to use strncpy instead of strcpy. That function takes a third argument: the length of the string to copy. This solution doesn't stretch beyond ANSI C, so this will work under all environments (whereas other methods may only work under POSIX-compliant systems).
char somestring[] = "Send money!\n";
char *copy;

copy = (char *) malloc(strlen(somestring));

strncpy(copy, somestring, strlen(somestring));
printf(copy);