text:
Q: keyset pagination with full text search on postgresql I have a table 'users' with +100,000 records. I want to start making use of keyset pagination to speed up the process of fetching records.
The following query works. This query fetches the second page of the recordset (starting at user_id: 1001, and fetching until user_id: 2000).
SELECT
    user_id,
    username
FROM
    users
WHERE
    user_id > 1000
ORDER BY
    user_id ASC
LIMIT
    1000

The problem is: I don't want to order the records on user_id. I have a column named "tokens" which is a to_tsvector column. I want to perform full text search on the recordset and order the users on rank. The new query:
SELECT
    user_id,
    username,
    to_tsrank(tokens, plainto_tsquery('search query')) AS rank
FROM
    users
WHERE
    tokens @@ plainto_tsquery('search query')

How can I apply a keyset pagination on this second query, so the results are ordered on rank instead of user_id?
Important:
I tried this one, but this does not work!
SELECT
    user_id,
    username,
    to_tsrank(tokens, plainto_tsquery('search query')) AS rank
FROM
    users
WHERE
    tokens @@ plainto_tsquery('search query')
AND
    to_tsrank(tokens, plainto_tsquery('search query')) < $1 // $1 = last fetched rank
ORDER BY
    rank DESC
LIMIT
    1000

Let's say, when the results are ranked on 'rank', the 1,000th result has a rank of 0.5. $1 (last fetched rank) would be 0.5, so I would select all results with rank < 0.5. The problem is: some results may have the same rank. So if the 1,001th record would also be rank = 0.5, it wouldn't be fetched because I say in my query rank < 0.5. I also cannot say rank <= 0.5because that would fetch the previous results with rank = 0.5 again.
Does anyone know the solution to this problem?

A: You have to provide a fully deterministic ORDER BY.  Assuming user_id is unique:
ORDER BY rank desc, user_id

Then your WHERE would include:
AND (rank < :last_rank or (rank = :last_rank and user_id > :last_user_id))

But this will not be efficient, so you might as well just do OFFSET.
Better yet, don't do it at all.  No human is realistically going to read through 1000 results, and think "You know, I'd like to do this a few more times".  The only one who will do that is the web scraper, and the only reason the web scraper will do it is because it is the only method you offer.  Just let them set a LIMIT which is as high as they want, and offer no pagination.


text:
Q: Controls all stuck in top left corner when I debug my VS for Mac iOS app I've been working through the introductory Hello, iOS project in VS for Mac, and I believe I've done everything according to the instructions.  The layout of my storyboard looks fine, however when I debug my application, all the controls are stuck in the top left of the screen in the iOS simulator.  Am I missing something obvious here?

A: Well, it looks like I must have done something wrong the first time.  I deleted and recreated the app, and it worked fine the second time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flask App with Gunicorn in production giving Error: socket hang up I have a Flask app running as a Docker container using Gunicorn on a Paperspace server -
Dockerfile
FROM ubuntu:18.04
FROM python:3
RUN apt-get update -y && apt-get install -y python-pip python-dev
COPY . /backend
WORKDIR /backend
RUN pip3 install -r requirements.txt
EXPOSE 8000
CMD gunicorn --timeout 10000 --workers 4 --log-level debug --bind 0.0.0.0:8000 wsgi:app

app.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, request

UPLOAD_FOLDER = '/uploads'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/upload_file', methods=['GET', 'POST'])
def upload_file():
    return "it works fine"

wsgi.py
from api import app

if __name__ == '__main__':
    app.run()

I run it using
sudo docker run -it -p 8000:8000 myFlaskApp:1.28

On firing the API (/upload_file) from Postman, I'm getting

Error: socket hang up

But, this API works fine on localhost (http://0.0.0.0:8000)

A: Try running the gunicorn server on it's own first in the terminal(without docker)
gunicorn -w xx -t xx -b 0.0.0.0:8080 wsgi:app

If gunicorn runs fine then its something wrong with the dockerfile. I think you should make ENTRYPOINT as gunicorn and then in CMD specify the params.
ENTRYPOINT ["gunicorn"]
CMD ["-w", "4", "-t", "10000", "-b", "0.0.0.0:8080", "wsgi:app"]


text:
Q: Geodesic measurements for short distances throughout US? My ArcGIS experience has been limited to working on large-scale maps with planar projections. I'm moving to a project in which I want to calculate the distance between pro sports facilities throughout the U.S. and their city's respective downtown/central business district (both defined as geocoded points).
My primary interest is in relative distances, and my question is whether using a geographic coordinate system for US map points and using "Near" to calculate geodesic distances between stadia and downtowns is a sound approach to avoiding issues that would arise from calculating distance based on a projection of the US?

A: I am afraid that the answer is no: what you mean to do is correct but it will not work like this in ArcGIS with Near.
From the help, you can read that :

The distances calculated by this tool are in the unit of the
  coordinate system of the input features. If your input is in a
  geographic coordinate system and you want output distances to be
  measured in a linear unit (as opposed to decimal degrees), you must
  first project your input to a projected coordinate system using the
  Project tool. For best results, use an equidistant projection or a
  projection intended for your study area (UTM, for example)

in other words, if you use a geographic coordinate system, near will work as if it was a cartesian coordinate system.
You should instead use the Haversine approximation (see here ) or, better, the Vicenty's formula to find your solution (see @Michalis Avraam's answer)

A: No, if using the ArcGIS "Near" tool because, even if the coordinate system is geographic/geodetic, it does not calculate geodesic distances; it merely treats those geographic coordinates as though they were projected and thus gives results that cannot be compared across the US.

Yes, if you correctly calculate geodesic distances using geographic coordinates between points in or near downtown -- and you compare those with similar calculations made in completely different cities across the US -- you will have sound results. Doing it correctly means using spherical trigonometry (or some other geodetic technique).
Conversely, if you merely use plane coordinates -- taken from a single, national map projection -- and plane geometry for the same types of comparisons, you will not get sound results.
There are many questions that deal with such problems/methods on this site.

A: There are some methods to calculate geodesic distances such as the haversine formula and Vincenty's formulae. These formulae are commonly used. The inverse Vincenty distance formula is the more accurate method to calculate the geodesic distance and is used in Google Maps, but it is slow.


text:
Q: Does there exist something like an $H_3$ and $H_4$ (icosahedral) Lie algebra or algebraic group? The (finite-dimensional) complex simple Lie algebras have been classified by Killing and Cartan a long time ago in the $\mathsf{A}_n,\mathsf{B}_n,\mathsf{C}_n,\mathsf{D}_n$ families and $\mathsf{G}_2,\mathsf{F}_4,\mathsf{E}_6,\mathsf{E}_7,\mathsf{E}_8$ exceptional cases.  So the non-crystallographic $\mathsf{H}_3$ and $\mathsf{H}_4$ Coxeter groups (i.e., icosahedral symmetry) do not appear as Weyl groups of such algebras.
On the other hand, there is also no such thing as a field with one element, yet it is interesting to construct something which might play that role.  Perhaps more relevantly here, there is no such thing as a tiling of the plane with regular pentagons, but there is something of the sort.  And the concept of finite-dimensional simple Lie algebra can be generalized in various ways, e.g., Kac-Moody algebras.
So I've often wanted to ask: is there something which is remotely like the $\mathsf{H}_3$ and $\mathsf{H}_4$ Lie algebras or algebraic groups?  They should probably be $33$- and $124$-dimensional respectively, and certainly the golden ratio $\frac{1+\sqrt{5}}{2}$ should play an important role in their definition (posing as an integer).

A: As far as I know, nobody has proposed candidates for such Lie algebras or algebraic groups.  From the viewpoint of Chevalley's old work on structure and classification (over an arbitrary algebraically closed field), it's hard to see what kind of algebraic group would fit.
On the other hand, it's useful to be aware of the natural embeddings of the non-crystallographic finite (real) reflection groups into crystallographic ones (Weyl groups).   See for example the notes on page 48 of my 1990 textbook on reflection groups, expanded somewhat in my list of revisions here.  The earliest source I know is a 1979 paper (MR) by Sekiguchi and Yano showing how to embed $H_3$ into the Weyl group $D_6$ via a natural "folding" process of Coxeter graphs.   In 3.9(b) of a 1983 paper freely available here, Lusztig similarly showed how to embed $H_4$ into $E_8$, justified by an application of his Hecke algebra formalism.   A posthumous 1988 paper by Oleg Shcherbak here gives the most comprehensive and elementary account of such embeddings, including even the non-crystallographic dihedral types.   (He was a student of V. Arnold in Moscow.)
Note that the folding process here is a somewhat more devious version of the popular foldings in Lie theory which correlate well with fixed point subgroups: for example, $E_6$ folds to $F_4$.     In all these foldings, the Coxeter numbers of the finite reflection groups involved coincide.   But I don't know any plausible way to extract from the embeddings of non-crystallographic types any associated finite dimensional Lie algebras (or algebraic groups).    Maybe look at Kac-Moody theory or such?

A: I will address an "easier question", namely analogues of algebraic groups corresponding to finite dihedral groups $I_2(n)$ of non-crystallographic type. At least in this case, we have candidate groups, but their theory was never developed much.
First of all, Tits had realized in 1950s that semisimple algebraic groups (more precisely, sets of $F$-points of such groups for fields $F$) can be  realized as automorphism groups of certain simplicial complexes, called (thick) spherical buildings modeled on Coxeter complexes of finite Coxeter groups $W$. In 1977 Tits proved existence of such buildings for all finite dihedral groups $I_2(n)$. It is known (it might be already in Tits' 1977 work, I forgot) that buildings for $I_2(n)$ constructed by Tits (provided that some care is taken during the construction) have large groups of automorphisms $G$, namely, they are flag-transitive. At the very least, this follows from the work of Tent. In particular, these groups $G$ have  structure of BN pairs, etc. However, algebraic nature (in the sense of connection to algebraic geometry and Lie algebras) of groups $G$ remains a mystery. Some circumstantial evidence that such connection exists appears in my paper with Arkady Berenstein (where you can also find references to the relevant work of Tits and of Tent):
A. Berenstein, M. Kapovich, Stability inequalities and universal Schubert calculus of rank 2, Transformation Groups, Vol. 16 (2011) p. 955-1007.
Now, the bad news is that Tits also proved that there are no thick spherical buildings for the Coxeter groups $H_3$ and $H_4$. It is quite possible that one needs to relax spherical building axioms but at this stage it is very much unclear how in order to make a meaningful connection to the group theory.

A: One potential answer to your question is given by the theory of $p$-compact groups. See
Grodal, The classification of p-compact groups and homotopical group theory. Proc. Intl. Congress of Mathematicians 2010 (Hyderabad, 2010), Volume II, 973–1001.
and the references therein. The notion of a p-compact group is homotopical, and there is a classification in terms of root data over $\mathbb{Z}_p$ (once it has been defined what this means).
In Table 1 of the above paper one can can see a classification of the irreducible $\mathbb{Q}_p$ reflection groups. In particular the dihedral groups (line 2), as well as $H_3$ ("$G_{23}$" in the table) and $H_4$ ("$G_{30}$") all occur, with the later two definable over $\mathbb{Q}_p$ if and only if $p = 1$ or $4$ modulo 5.


text:
Q: CSS rules not applied to elements appended from jquery I've search through the similar questions but none answered my problem. (all those problems seemed related to typos)
I'm just making this for fun.  I'm creating a table using jquery based on json data. Problem is, the appended table rows don't inherit any of the CSS rules.  I feel like I've read about the cause for this before, specifically to tables, but the info eludes me.
HTML:

f

b

a

CSS:
    tr:nth-child(even){background:blue}
    tr:nth-child(odd){background:green}

JS:
        // Build some test data
        var data = [];
        var cols = ['Col-A','Col-B','Col-C','Col-D'];
        for (i=0;i<10;i++){
            data.push(['A_'+i,'B_'+i,'C_'+i,'D_'+i]);
        }
        // data that would be sent to
        var json = JSON.stringify({columns:cols, data:data});

        // build the table
        $('#mytable').tables(json);

    });

    // the magic function
    jQuery.fn.tables = function(json) {
        var obj = JSON.parse(json);
        var head = this.find('thead');
        var bod  = this.find('tbody');

        // Build columns
        head.append('
');
        for (i=0;i<obj.columns.length;i++){
            head.append(''+obj.columns[i]+'	');

        }
        head.append('
');

        // Add row data
        for (i=0;i<obj.data.length;i++){
            bod.append('
');
            for(j=0;j<obj.data[i].length;j++){
                bod.append(''+obj.data[i][j]+'	');
            }
            bod.append('
');
        }

        return this;
    }

A: With this code you don't append one full row at a time, but only fragments. What you'll expect to be rendered?
head.append('
');
...
head.append('
');

For this to work, your magic function should be something like this:
    // the magic function
    jQuery.fn.tables = function(json) {
        var obj = JSON.parse(json);
        var head = this.find('thead');
        var bod  = this.find('tbody');

        // Build columns
        var row = '
';
        for (i=0;i<obj.columns.length;i++){
            row += ''+obj.columns[i]+'	';
        }
        row += '
';

        head.append(row); // append the full row

        // Add row data
        row = '';
        for (i=0;i<obj.data.length;i++){
            row += '
';
            for(j=0;j<obj.data[i].length;j++){
                row += ''+obj.data[i][j]+'	';
            }
            row += '
';
        }

        bod.append(row); // append the full row

        return this;
    }

Function which appends one full row at a time.

A: @Razvan hit the nail on the head, but I think there is a much more idiomatic way of doing this. After all, we are using jQuery, so we might as well be efficient.

jQuery.fn.tables = function(json) {
  var obj = JSON.parse(json);
  var head = this.find('thead');
  var bod  = this.find('tbody');

  // Build columns
  head.append($('
').append(obj.columns.map(e => $('').text(e))));

  // Add row data
  obj.data.forEach(r => bod.append($('
').append(r.map(e => $('').text(e)))));

  return this;
}

// Build some test data
var data = [];
var cols = ['Col-A','Col-B','Col-C','Col-D'];
for (i=0;i<10;i++){
    data.push(['A_'+i,'B_'+i,'C_'+i,'D_'+i]);
}
// data that would be sent to
var json = JSON.stringify({columns:cols, data:data});

// build the table
$('#mytable').tables(json);
tr:nth-child(even){background:blue}
tr:nth-child(odd){background:green}

f

b

a

Basically, I use a couple chained-together arrow functions along with .forEach and .map to append the  and  elements to the respective rows and append the rows to the table in a single statement.


text:
Q: Why is a function parameter considered an undefined variable? I've been looking around for a while, but I can't seem to find something that describes and answers the problem I've been having.  Namely, I have a function being defined in a ball class that checks to see if it and another ball are intersecting (due to the balls being kept on the same z-plane and the radius being the same for all of them, I've simplified the problem to that of intersecting circles).  This function is as follows (where both obj and other are of the class ball, and where the ball class contains a position vector of length 3):
function intersected = ball_intersection(obj, other)
    intersected = (obj.position(1)-other.position(1))^2+(obj.position(2)-other.position(2))^2 <= (2*ball.radius)^2;
end

I get the following error:
Undefined variable other.

Error in ball/ball_intersection (line 29)
            intersected = (obj.position(1)-other.position(1))^2+(obj.position(2)-other.position(2))^2 <= (2*ball.radius)^2;

Error in ball/move (line 56)
                if ball_intersection(other)

Error in finalproject (line 41)
    cueball.move(0.0001, 0, 0, 9.32, 4.65, otherball);

For some reason, Matlab thinks that a function parameter is undefined, and I don't know how to make it know that it is in fact defined right there.
Any and all help is appreciated - thanks for reading!

A: ball_intersection has to be called with two input arguments.
Most likely, you want to change line 56 of ball to if ball_intersection(obj,other), or if obj.ball_intersection(other).


text:
Q: How to add info window in angular google maps with out marker? I am trying below angular plugin for google maps.
https://ngmap.github.io/
can any one please help me how to add info window, with out a marker ?
Thanks in advance

A: According to Info Windows:

Typically you will attach an info window to a marker, but you can also
  attach an info window to a specific latitude/longitude

The following example demonstrates how to attach an info window to a specific latitude/longitude:

angular.module('ngMap').run(function($rootScope, NgMap) {
  NgMap.getMap().then(function(map) {
    $rootScope.map = map;
    var iw = map.infoWindows.bar;
    iw.setPosition(new google.maps.LatLng(-25.363882,131.044922));
    map.showInfoWindow('bar');
  });
});
.ng-map-info-window {
    background-color: navy;
    color: #fff;
  }
  .ng-map-info-window div:first-child > div:nth-child(1) {
    border-top-color: navy !important;
  }
  .ng-map-info-window div:first-child > div:nth-child(3) div {
    background-color: transparent !important;
  }
  .ng-map-info-window div:first-child > div:nth-child(4) {
    background-color: transparent !important;
  }

    Info Windows

 This example displays a marker at the center of Australia. When the user clicks the marker, an info window opens.
    <ng-map default-style="true" center="-25.363882,131.044922" zoom="4">

      <info-window id="bar" >

Uluru

Uluru, also referred to as Ayers Rock, is a large sandstone rock formation in the southern part
              of the Northern Territory, central Australia. It lies 335 km (208 mi) south west of the nearest large town,
              Alice Springs; 450 km (280 mi) by road. Kata Tjuta and Uluru are the two major features of the Uluru - Kata
              Tjuta National Park. Uluru is sacred to the Pitjantjatjara and Yankunytjatjara, the Aboriginal people of the
              area. It has many springs, waterholes, rock caves and ancient paintings. Uluru is listed as a World Heritage
              Site.

Attribution: Uluru,
            http://en.wikipedia.org/w/index.php?title=Uluru (last visited June 22, 2009).

      </info-window>
    </ng-map>

jsFiddle


text:
Q: Reasonable data-structure type for a Directed graph in Ocaml I want to use an adjacency list to represent a graph structure, I don't need my edges to be weighted.
I want to practice simple exercises like finding a cycle, BFS, DFS , adding remove edges... nothing fancy. (I could do it with Hashtables as well, but I need more List practice)
type 'a dgraph = DG of ('a * 'a list) list

My questions are :

*

*Is this a reasonable representation for a DG ?

*shouldn't these be a recursive type ? (somehow feels more natural)

I don't want to shoot myself in the foot and make a poorly designed type from the beginning, that will lead to a more complex implementation.
Example :
let g =
    DG (
        [
            ('a', ['c'; 'd']);
            ('c', ['d']);
            ('b', ['a'; 'e']);
        ]
    )

Note :
I didn't find on http://ocaml.org/learn/tutorials/99problems.html#Graphs the adjacency list representation.

A: This is a perfectly good representation of a graph. You need to make sure the labels are unique. Also you have no distinction between the labels and other possible contents of the nodes.
With this structure, going from a label to the node with the label requires a search of the outer list. If your graphs get large, this is probably going to start taking too long. So you will need to construct an ancillary map from label to node. I have done this myself many times.
Another solution is to have node indices that are independent of the node contents. This also reduces the difficulty in dealing with duplicate labels. I'm working on graph problems right now and the structure is basically like this:
 type 'a mygraph = ('a * int list) array

The 'a type represents the contents of a node, and array indices are used to link them together.
I've also worked with a structure that uses a hash table rather than an array. This works well when you have some unique identifier in your node type that you can use as an index. (Or you can use arbitrarily constructed indices.) The advantage of the hash table structure is that it's easier to modify the graph.
It might seem like your data structure should be recursive, but (in my opinion) this mixes up the graph and the representation of the graph. If you want your data structure to actually be a graph rather than just represent one, it does have to be recursive. Something like this:
type 'a rgraph = RG of 'a * 'a rgraph list

A data structure like this is almost impossible to work with in an eager language like OCaml. It's extremely difficult to construct the required values when they have cycles.
It can be done using let rec:
# let rec rg1 = RG (17, [rg1]);;
val rg1 : int rgraph = RG (17, [<cycle>])

However I've personally never seen "real world" code that works with a structure like this. Note that this use of let rec is marked as a language extension in the OCaml manual (Section 7.2, Recursive definitions of values).
You can make such a data structure more tractable by using references, something like this maybe:
type 'a rrgraph = RRG of 'a * 'a rrgraph list ref

Then you can create your nodes and link them together afterward. I have used structures like this in the past, but I felt I lost some of the nice guarantees of working with immutable data.
# let node1 = RRG (7, ref []);;
val node1 : int rrgraph = RRG (7, {contents = []})
# let node2 = RRG (8, ref []);;
val node2 : int rrgraph = RRG (8, {contents = []})
# let RRG (_, links) = node1 in links := [node2];;
- : unit = ()
# let RRG (_, links) = node2 in links := [node1];;
- : unit = ()
# node1;;
- : int rrgraph = RRG (7, {contents = [RRG (8, {contents = [<cycle>]})]})

An advantage of a representation like this is that you can freely create new nodes without needing to maintain a central table that contains all of them. And the garbage collector takes care of removing nodes that are no longer reachable.


text:
Q: Robotframework can't identify the value of a list element when the index as a loop variable This is my code in robotframework, i want to remove the $,K,M,B from the list, and i try like this
${testList}    create list    a$    bK    cM
FOR    ${index}    IN RANGE    0    5
    ${testList}[${index}]    remove string    ${testList}[${index}]    $    K    M    B
END

but i get the error log : No keyword with name '${testList}[${index}]' found.
i confirm the string library is imported successfully
Am I doing something wrong? why robot cannot read the value?
Python version is 3.7.5 and ride version is 1.7.4.2
Updated i found a solution like this
    ${TestList}    create list    a$    bK    cM
    FOR    ${index}    IN RANGE    0    3
        ${value}    remove string    ${TestList}[${index}]    $    K    M    B
        set list value    ${TestList}    ${index}    ${value}
    END
    log    ${TestList}

But i still don't understand why the first solution went wrong..

A: The first one failed because it expects either a keyword or an empty variable to be filled with the results from a following keyword in the first position, like so:
 This is a keyword

 ${value}    remove string    etc.

However what you gave it in your first example was
${testList}[${index}]    remove string    ${testList}[${index}]

which is neither.


text:
Q: In WPF if we create multiple rectangles using item-container , then rectangles are getting overlapped on each other
In WPF if we create multiple rectangles using item-container , then rectangles are getting overlapped on each other with inconsistent gaps?
Here you can see from 0-100 rectangle should be separated consistently but that didn't happened and then from 120-200 you can observe overlapping and shades.
**Note: All the values coming from converters are perfectly fine. So converters are not the issue.
I tried different ways like using SnapDeviceToPixels and RenderTransform too but it didn't worked
`
<ItemsControl ItemsSource="{Binding HighLightRegions}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <Canvas Height="{Binding ActualHeight, ElementName=myRectangle}"
                                    Width="{Binding ActualWidth, ElementName=myRectangle}"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.Style>
                        <Style>
                            <Setter Property="Canvas.Right" Value="0"/>
                            <Setter Property="Canvas.Bottom" Value="0"/>
                        </Style>
                    </ItemsControl.Style>
                    <ItemsControl.ItemContainerStyle >
                        <Style>
                        </Style>
                    </ItemsControl.ItemContainerStyle>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate DataType="plotLineViewModel:HighLightRectType">
                            <Canvas Height="{Binding ActualHeight, ElementName=PlotArea}">
                                <Rectangle Fill= "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.FrameOverlayColor}"
                                           HorizontalAlignment="Left"
                                           VerticalAlignment="Top"
                                           Opacity=".6" Stroke="{StaticResource MyChartPlotBackgroundBrush}"
                                           Height ="{Binding Path=ActualHeight, ElementName=myRectangle}">
                                    <Canvas.Left>
                                        <MultiBinding Converter="{StaticResource  ChartViewXCordinateConverter}" >
                                            <Binding Path="ActualWidth" ElementName="myRectangle" />
                                            <Binding Path="Location.X" />
                                            <Binding Path="DataContext.XAxisMax" ElementName="XPosition"/>
                                            <Binding Path="DataContext.XAxisMin" ElementName="XPosition"/>
                                        </MultiBinding>
                                    </Canvas.Left>
                                    <Rectangle.Width>
                                        <MultiBinding Converter="{StaticResource  ChartViewXCordinateConverter}" >
                                            <Binding Path="ActualWidth" ElementName="myRectangle" />
                                            <Binding Path="Width" />
                                            <Binding Path="DataContext.XAxisMax" ElementName="XPosition" />
                                            <Binding Path="DataContext.XAxisMin"  ElementName="XPosition"/>
                                        </MultiBinding>
                                    </Rectangle.Width>
                                </Rectangle>
                            </Canvas>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

`


text:
Q: Calculate $\int_0^{\infty } \left(x-\log \left(e^x-x\right)\right) \, dx$ Calculate the following integral:
$$\int_0^{\infty} \left(x-\log \left(e^x-x\right)\right) \ \mathrm{d}x.$$
For recreational purposes, I calculate several interesting integrals, and I came across this case that blocks me.
One can immediately notice that $\log \left(e^x-x\right)\sim_{+\infty} x$ (since $\lim_{x\to +\infty}\frac{x}{\log(e^x-x)}=1$). But I am unable to calculate the indefinite integral of this function or to establish the value of this improper integral in any other way.
Nevertheless, it is of course possible to calculate the result numerically ($\approx 1.15769475$) to an arbitrary precision, but I am more interested in the exact value and the method to get it.

A: Here is a little more general solution:
Notice that your integral is equivalent to
$$-\int_0^{+\infty} \log(1-xe^{-x})\,dx$$
Now, let
$$I(a)=-\int_0^{+\infty} \log(1-xe^{-ax})\,dx \qquad \text{ for } a\in\mathbb{R}^+ $$
Then,
\begin{align}
I'(a)&=-\int_0^{+\infty} \frac{x^2 e^{-ax}}{1-xe^{-ax}}\,dx \\
&=-\int_0^{+\infty} x^2 e^{-ax} \sum_{n=0}^{+\infty} e^{-anx} x^n \\
&=-\sum_{n=0}^{+\infty}\int_0^{+\infty} e^{-ax(n+1)} x^{2+n} \,dx \\
&=-\sum_{n=1}^{+\infty} \int_0^{+\infty} e^{-anx} x^{n+1}\,dx \\
&=-\sum_{n=1}^{+\infty} \frac{(n+1)!}{(an)^{n+2}}
\end{align}
Then
\begin{align}
I(a)&=C+\sum_{n=1}^{+\infty} \frac{1}{a^{n+1}(n+1)} \frac{(n+1)!}{n^{n+2}} \\
&=C+\sum_{n=1}^{+\infty} \frac{n!}{a^{n+1} n^{n+2}}
\end{align}
For some constant $C$.

A: Off-topic but amazing (at least to me !)
Starting from Leucippus's answer
$$
I=\int_{0}^{\infty} \left(x - \ln(e^{x} - x)\right) \,dx =\sum_{n=1}^{\infty} \frac{n!}{n^{n+2}}
$$ how many terms would we need to add in order to have $p$ significant figures ?
Writing
$$J_k=\sum_{n=1}^{k} \frac{n!}{n^{n+2}}\implies \frac{(k+1)!}{(k+1)^{k+3}}< 10^{-p}$$ Taking logarithms, using Stirling approximation and continuing with Taylor series we have
$$\log \left(\frac{(k+1)!}{(k+1)^{k+3}} \right)=-k-\frac{3 }{2}\log (k)+\frac{1}{2} \log (2 \pi )-1+O\left(\frac{1}{k}\right)$$ Since the constant term is very small $\frac{1}{2} \log (2 \pi )-1\approx -0.081 $ we can just solve for k  the equation$$k+\frac{3 }{2}\log (k)=\log(10^p)\implies k=\frac 32 W\left(\frac 23 10^{(2p/3)}\right)$$ where appears Lambert function.
Since the argument is large, we can compute its value using
$$W(x)=L_1-L_2+\frac{L_2}{L_1}+\frac{L_2(L_2-2)}{2L_1^2}+\frac{L_2(6-9L_2+2L_2^2)}{6L_1^3}+\cdots$$ where $L_1=\log(x)$ and $L_2=\log(L_1)$.
For a few values of $p$, the table below gives the corresponding $k$.
$$\left(
\begin{array}{cc}
p & k \\
 6 & 10.315 \\
 7 & 12.348 \\
 8 & 14.418 \\
 9 & 16.517 \\
 10 & 18.638 \\
 11 & 20.778 \\
 12 & 22.932 \\
 13 & 25.099 \\
 14 & 27.277 \\
 15 & 29.464 \\
 16 & 31.659 \\
 17 & 33.861 \\
 18 & 36.068 \\
 19 & 38.282 \\
 20 & 40.500
\end{array}
\right)$$
Trying for $p=10$ $$J_{18}\approx 1.15769475242$$ $$J_{19}\approx 1.15769475259$$ $$J_{20}\approx 1.15769475265$$ while the infinite summation would give $$J_{\infty}\approx 1.15769475268$$

A: \begin{align}
\int_{0}^{\infty} (x - \ln(e^{x} - x)) \ \mathrm{d}x &= \int_{0}^{\infty} (x - \ln(e^{x}) - \ln(1-x e^{-x}) ) \ \mathrm{d}x \\
&= - \int_{0}^{\infty} \ln(1 - x e^{-x}) \ \mathrm{d}x \\
&= \sum_{n=1}^{\infty} \frac{1}{n} \,  \int_{0}^{\infty} x^{n} \, e^{-n x} \ \mathrm{d}x \\
&= \sum_{n=1}^{\infty} \frac{n!}{n^{n+2}} \approx 1.15769.
\end{align}


text:
Q: Capturing user who changes database I work on a few projects with a front end recently moved to vb.net, the back-end's remain in access .accdb format.
With an Access front end I was able to set up some data macros that captured the username of a person making changes and record them in an audit table, it looks like it will be a little harder with a .net front-end.
Is there any way to pass this information from the front end to the database ? Or is there a method of making the back-end look at the function that is stored there (It doesn't seem to work at the moment)
This is the code I have in the back
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Function GetUserName() As String
' Returns the network login name
Dim lngLen As Long, lngX As Long
Dim strUserName As String
    strUserName = String$(254, 0)
    lngLen = 255
    lngX = apiGetUserName(strUserName, lngLen)
    If lngX <> 0 Then
        GetUserName = Left$(strUserName, lngLen - 1)
    Else
        GetUserName = ""
    End If
End Function

I have a public function doing the same in the front-end, also called getusername()

A: My friend, here we're talking about principal differences between working within enclosed environment of MS Access, not just as database but also the application. Since everything inside Access is native to itself, you have access to all the internals. Now you moving away from that model and your design should change accordingly. Here you are in, lets call it client-server environment, and client knows little besides connection string and server knows nothing about client.
This is not an issue how to retrieve user name or some other information from code. Your goal is to design a system which will support auditing. You have audit table already - this is good.
Depending on your security model, you either use user name of the machine user, or user name of the application user. But you have it - in VB it is easy.
Without knowing your Audit structure, I can tell that the way it is usually done, when data is changing, you create Sql transaction using Ado.Net, and under this transaction you insert you audit data and then you do your CRUD on real data. Then you commit. This way, you either succeed or fail both - no data modified without audit.
Now, another step  is to add to your table (if you don't have already) 4 fields:

CreatedBy, CretedDate, ModifiedBy, ModifiedDate.

Each record will be ready to display who was playing with your system and when.
And this is how your Access Db gets the user:

*

*via sql that contains user column and data "insert into ... values('" & user & "', ...."

*via separate audit call that contains user name

*via stored procedure where 1 parameter can be dedicated to pass user info


text:
Q: Display thumbnailPhoto from Active Directory C# Using C# MVC 5 to pull data from active directory from a search. One of which I need it to pull the thumbnail photo.
So my LDAP connection grabs initial data and does the conversion of the thumbnail to byte[] successfully, at least it looks like it from debugging. Then when I try to convert the byte array to an image I get an "parameter is not valid" error.
Here's my Controller:
  [HttpPost]
public ActionResult Index(string userName, string searchFilter)
{
    /**********Establish Connection********/
    DirectoryEntry dir = createDirectoryEntry();
    DirectorySearcher search = new DirectorySearcher(dir);
    /****Refer to class constructor****/

    /********Create the List to store results in***************/
    List<ADUser> Users = new List<ADUser>();
    string DisplayName = "", SAMAccountName = "", Mail = "", Description = "", Department = "", TelephoneNumber = "", Fax = "";
    byte[] ThumbnailPhoto;
    string searchFilters = searchFilter.ToString();
    /*******Filter parameters************/
    if (searchFilters == "1")
    {
        search.Filter = "(&(objectCategory=Person)(objectClass=User)(&(anr=" + userName + "* )(displayName=*)(sn=*)))";
        //(&(department=" + userName + "* )(displayName=*)(sn=*))(&(telephoneNumber=" + userName + " )(displayName=*)(sn=*))
    }
    else if (searchFilters == "2")
    {
        search.Filter = "(&(objectCategory=Person)(objectClass=User)(&(department=" + userName + "* )(displayName=*)(sn=*)))";
    }
    else if (searchFilters == "3")
    {
        search.Filter = "(&(objectCategory=Person)(objectClass=User)(&(telephoneNumber=" + userName + "* )(displayName=*)(sn=*)))";
    }
    SearchResultCollection searchresult = search.FindAll();
    search.PropertiesToLoad.Add("Displayname");
    search.PropertiesToLoad.Add("SAMAccountName");
    search.PropertiesToLoad.Add("Mail");
    search.PropertiesToLoad.Add("Description");
    search.PropertiesToLoad.Add("TelephoneNumber");
    search.PropertiesToLoad.Add("Fax");
    search.PropertiesToLoad.Add("Department");
    search.PropertiesToLoad.Add("thumbnailPhoto");
    /*****************Filtering and populating the List****************/

    if (searchresult != null)
    {
        foreach (SearchResult iResult in searchresult)
        {
            ADUser userAttributes = new ADUser("", "", "", "", "", "", "", null);

            foreach (string PropertyName in iResult.Properties.PropertyNames)
            {
                foreach (Object key in iResult.GetDirectoryEntry().Properties[PropertyName])
                {
                    try
                    {

                        switch (PropertyName.ToUpper())
                        {
                            case "DISPLAYNAME":
                                DisplayName = key.ToString();
                                userAttributes.Name = DisplayName;
                                break;

                            case "SAMACCOUNTNAME":
                                SAMAccountName = key.ToString();
                                userAttributes.DomainUserName = SAMAccountName;
                                break;

                            case "MAIL":
                                Mail = key.ToString();
                                userAttributes.EmailAddress = Mail;
                                break;

                            case "DESCRIPTION":
                                Description = key.ToString();
                                userAttributes.JobDescription = Description;
                                break;

                            case "TELEPHONENUMBER":
                                TelephoneNumber = key.ToString();
                                userAttributes.TelephoneNumber = TelephoneNumber;
                                break;

                            case "FAX":
                                Fax = key.ToString();
                                userAttributes.FaxNumber = Fax;
                                break;

                            case "DEPARTMENT":
                                Department = key.ToString();
                                userAttributes.Department = Department;
                                break;

                            case "THUMBNAILPHOTO":
                                BinaryFormatter bf = new BinaryFormatter();
                                MemoryStream ms = new MemoryStream();
                                bf.Serialize(ms, key);

                                ThumbnailPhoto = ms.ToArray();
                                userAttributes.ThumbnailPhoto = ThumbnailPhoto;
                                break;
                        }
                    }
                    catch
                    {

                    }
                }
            }

            Users.Add(userAttributes);
        }

        return View(Users);
    }

    return View();
}

My constructor:
public class ADUser
    {
        private string name;
        private string domainUserName;
        private string emailAddress;
        private string jobDescription;
        private string telephoneNumber;
        private string faxNumber;
        private string department;
        private byte[] thumbnailPhoto;

        public ADUser(string name, string domainUserName, string emailAddress, string jobDescription, string telephoneNumber, string faxNumber, string department, byte[] thumbnailPhoto)
        {
            this.name = name;
            this.domainUserName = domainUserName;
            this.emailAddress = emailAddress;
            this.jobDescription = jobDescription;
            this.telephoneNumber = telephoneNumber;
            this.faxNumber = faxNumber;
            this.department = department;
            this.thumbnailPhoto = thumbnailPhoto;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string DomainUserName
        {
            get { return domainUserName; }
            set { domainUserName = value; }
        }

        public string EmailAddress
        {
            get { return emailAddress; }
            set { emailAddress = value; }
        }

        public string JobDescription
        {
            get { return jobDescription; }
            set { jobDescription = value; }
        }

        public string TelephoneNumber
        {
            get { return telephoneNumber; }
            set { telephoneNumber = value; }
        }

        public string FaxNumber
        {
            get { return faxNumber; }
            set { faxNumber = value; }
        }

        public string Department
        {
            get { return department; }
            set { department = value; }
        }

        public byte[] ThumbnailPhoto
        {
            get { return thumbnailPhoto; }
            set { thumbnailPhoto = value; }
        }

And now my View;
@model List<webby.Helpers.ADUser>
@using System.Drawing;
@{
    ViewBag.Title = "Directory";
}

Directory

            Here you will be able to search through the directory to find people that you are looking for.
            You can search by the person's name, their department or by their location.

            For a printable version please click here.

        @using (Html.BeginForm("Index", "Directory", FormMethod.Post))
        {

                Search Employee: @Html.TextBox("userName")

                <input type="radio" name="searchFilter" id="rdUser" value="1" checked />
                By User
                @*<input type="radio" name="searchFilter" id="rdDept" value="2" />
                    By Department
                    <input type="radio" name="searchFilter" id="rdExt" value="3" />
                    By Extension
*@
                <input type="submit" value="Search" class="btn btn-default" />

        }

        @using (Html.BeginForm("Index", "Directory", FormMethod.Get))
        {

                <input type="submit" value="Clear" class="btn btn-default" />

        }

            @if (Model != null)
            {
                foreach (var item in Model)
                {

                            @Html.DisplayFor(modelItem => item.Name)

                            @Html.DisplayFor(modelItem => item.TelephoneNumber)

                            @Html.DisplayFor(modelItem => item.EmailAddress)

                            @Html.DisplayFor(modelItem => item.Department)

                            @if (item.ThumbnailPhoto != null)
                            {

                                using (MemoryStream s = new MemoryStream(item.ThumbnailPhoto))
                                {
                                    s.Seek(0, SeekOrigin.Begin);
                                    Bitmap.FromStream(s);
                                }

                            }

                        @*
                                @Html.ActionLink("Details", "Details")
                            	*@

                }
            }

Any ideas would be much appreciated. Cheers
Edit: Its in a hexadecimal format of 0x00, would this have anything to do with it?


text:
Q: UIImage Text Overlay - CGPoint Incorrect; Wrong Image Size? I'm trying to overlay text on the bottom-left corner of a UIImage.  I get the image from the device's camera roll, perform the overlay, then assign it to a UIImageView on a ViewController.  The vertical CGPoint is never correct, however, as the height of the image seems to be different than what I'm getting from view.bounds.height.  The following is what I've been working with; what change should I make to be able to get the correct CGPoint to assign the overlay label to? Thanks!
Result (should be bottom-left):

class PhotosVC: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var photoView: UIImageView!

func presentPicker() {
    let picker = UIImagePickerController()
    picker.delegate = self
    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {
        action in
        picker.sourceType = .camera
        self.present(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {
        action in
        picker.sourceType = .photoLibrary
        self.present(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

 override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    presentPicker()
}

override func viewDidLoad() {
    super.viewDidLoad()
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    picker.dismiss(animated: true, completion: nil)
    guard let image = info[.originalImage] as? UIImage else {
        print("Issue getting photo from imagePickerController")
        return }

    let CGPointBottomLeft = photoView.bounds.height
    print(photoView.bounds.height) // Is 336

    let imageWithText = textToImage(drawText: "Overlayed text", inImage: image, atPoint: CGPoint(x: 0, y: CGPointBottomLeft))
    self.photoView.image = imageWithText
}

 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
     dismiss(animated: true, completion: nil)
 }

func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
    let textColor = UIColor.white
    let textFont = UIFont(name: "Helvetica Bold", size: 212)! // Only visible if huge

    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    let textFontAttributes = [
        NSAttributedString.Key.font: textFont,
        NSAttributedString.Key.foregroundColor: textColor,
        ] as [NSAttributedString.Key : Any]
    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

    let rect = CGRect(origin: point, size: image.size)
    text.draw(in: rect, withAttributes: textFontAttributes)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}


text:
Q: Need to create a calendar with drag and drop events. Which control to use? I'm using VB.Net 2012 Express
I need to create a calendar which will have drag and drop elements. I'll be linking it to a database but first I need to work out which control to use to create the calendar display.
I want to be able to create events by dragging a rectangle with the mouse.  Also to move the event by dragging and dropping the event.
I'm trying to use a tablelayoutpanel (tlp).  I can create the tlp programmatically, but can't see how to tell which row or column the mouse is in when I click, as it only gives me the X and Y but not the tablelayoutpanel row or column.
How can I find out which row/column I was in on mouse down, and which row/column on mouse up? Or am I barking up the wrong tree entirely?

A: Thanks OneFineDay, you set me on the right path.  I veered off a bit, but came up with this and it works:
 Private Sub Layout_Calendar_MouseDown(sender As Object, e As MouseEventArgs) Handles Layout_Calendar.MouseDown
    Dim x As Integer
    x = e.X

    Dim y As Integer
    y = e.Y

    Dim Allcolumns() As Integer
    Dim ColumnLocation As Integer
    Dim Column As Integer

    Dim Allrows() As Integer
    Dim RowLocation As Integer
    Dim Row As Integer

    'find column
    Allcolumns = Layout_Calendar.GetColumnWidths()
    ColumnLocation = 0
    Column = 0
    For Each Colwidth In Allcolumns
        ColumnLocation += Colwidth
        If x < ColumnLocation Then
            Exit For
        Else
            Column += 1
        End If
    Next

    Allrows = Layout_Calendar.GetRowHeights()
    RowLocation = 0
    Row = 0
    For Each Rowwidth In Allrows
        RowLocation += Rowwidth
        If y < RowLocation Then
            Exit For
        Else
            Row += 1
        End If
    Next

    Console.WriteLine("Column:" & Column & " Row:" & Row)

End Sub


text:
Q: Codeigniter - is it risky to modify the cart $product_name_rules to accept any character? I'm using the Cart Class in CI, and my product names contain lots of "dangerous" characters, such as apostrophe, brackets, semicolon, ampersands, and many non latin characters.
The Cart Class limits the allowed characters like so:
var $product_name_rules = '\.\:\-_ a-z0-9'; // alpha-numeric, dashes, underscores, colons or periods

I know I can extend the Cart Class and override this limitation with something like this in a MY_Cart Class:
$this->product_name_rules = '\d\D';

But this makes me wonder - perhaps the CI people had a reason for limiting the product names. Maybe by removing the limitation I'm opening a backdoor to hackers.
Obviously, when I add items from the cart to my database, I use Active Records and query binding, which should (to my best understanding) provide a sufficient defense against sql injections and the like.
So what was the idea behind limiting the characters in the first place?

A: NO! Well, let me say: "None that I could see":
Although codeigniter seemed to throw some errors when I modified regex of the cart core directly. So I just tweaked by leaving what's there and just adding /d/D at the end like this:
var $product_name_rules = '\.\:\-_ a-z0-9\d\D'; // alpha-numeric, dashes, underscores, colons or periods

To not mess with original classes for reasons you might not know, try to extend the class
You could find guides here:

http://ponderwell.net/2010/07/codeigniter-extending-the-cart-class-for-robust-product-names/

Create a file in application/libraries and call it "MY_cart.php". In that file, paste the following code:
< ?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Cart extends CI_Cart {
    function __construct() {
        parent::__construct();
        $this->product_name_rules = '\d\D';
    }
}

A: Its worth getting to know the CI cart library. Because then when you make your own cart, it will make you feel really good about yourself. :-) Seriously though, everyone who tries the CI cart runs into this issue and there are many posts about it. So yes you can modify it so you can use different characters in the names - but i would seriously urge you to make your own cart as soon as possible.
what does a shopping cart really need from the product page? It needs the ID of the product, and the Qty. thats it - everything else should come directly from your product table.
do not set up your app so that there is a price on a product page, and then you take that price and send it to the cart. someone could easily modify the form and send a lower price to the cart.
so verify the product id - then get the product price DIRECTLY from the product table. and thats easy because you just did it to show the product. you can also get the product name that way and - hey suddenly you dont have to worry at all about dangerous characters, and you know that the price will be accurate.

and Steward has the excellent answer for working with ci cart lib, and the blog post he links to steps through the issues. you can also copy parts of the cart lib and put them in MY_cart, its a good way to see how it works and you can do simple mods.


text:
Q: Object doesn't support property or method 'dataTable' Hi I am trying to implement a data table in Visualforce page. I have included the jquery.js, DataTable.Min.Js, Datatable.js in the page in this order. I have initialize the data table like below
$(document).ready( function () {
          var oTable1 = $('#LeadTable').dataTable( {
                "sPaginationType": "full_numbers",
                "aoColumnDefs": [ { "bVisible": false, "aTargets": [ ] }],
                "bLengthChange": false,
                "bAutoWidth": false,
                "iDisplayLength" : 20,
                "aaSorting": [[ 4, "desc" ]],
                "oColumnFilterWidgets": { "aiExclude": [ 0, 3, 4 ] }
           });
});

I am getting the error "Object doesn't support property or method 'dataTable'". I check what is the issue?
Thanks.
VF page
<apex:page controller="HomeBasedClass"  id="thePage" >
    <apex:stylesheet value="{!$Resource.RoleHierarchyPopupStyle}"/>

       Please Wait...

    <apex:form id="formId" style="display:none;">

        <apex:includeScript value="{!$Resource.DtJQueryJs}"/>
        <apex:includeScript value="{!$Resource.DtDataTableMinJs}"/>
        <apex:includeScript value="{!$Resource.DtDataTableJs}"/>
        <apex:stylesheet value="{!URLFOR($Resource.DataTables, 'media/css/DataTablesAdvancedExample.css')}"/>

<apex:image value="{!$Resource.LoadingImage}"></apex:image>

Please Wait. Loading...

        <apex:actionStatus id="splashStatus"  onstart="startSplash();" onstop="endSplash();" />

        <apex:actionFunction name="ajaxSetClientLoaded" action="{!setClientLoaded}" immediate="true" rerender="formId"/>
        <apex:sectionHeader subtitle="Home Base - Sales Rep Dashboard"/>
        Leads   |<apex:outputLabel >   </apex:outputLabel><apex:outputLabel >Job Profiles</apex:outputLabel><apex:outputLabel >   |</apex:outputLabel>   Opportunities   |   Activities   |   Orders & Deliveries

        {!$UserRole.Name}

            <apex:outputPanel styleClass="DescAddresspopupBackground" layout="block" />
            <apex:outputPanel id="fulfillingBranchPanel" style="-moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 10px;" styleClass="custDescAddressPopup" layout="block" >

[X]

                    <apex:iframe src="/apex/testpage" width="100%" height="350px" scrolling="true"/>
            </apex:outputPanel>

        <apex:pageBlock id="leadSection" >

Leads

                        <apex:outputPanel id="componentPnl">
                            <c:LeadGraphComponent userId="{!SelectedUserId}" id="LeadComponent"/>
                        </apex:outputPanel>

                                     Company
                                     Name
                                     Phone
                                     Servicing Branch ID
                                     Created Date
                                     Last Activity Date
                                     Next Activity Date

                                 <apex:repeat value="{!LstLeadGrid}" var="c">

                                        {!c.Company}
                                        {!c.Name}
                                        {!c.Phone}
                                        {!c.Servicing_Branch_Id__c}

                                             <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                                <apex:param value="{!c.Created_Date_Time__c}"/>
                                            </apex:outputText>

                                             <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                                <apex:param value="{!c.Last_Activity_Datetime__c }" />
                                            </apex:outputText>

                                             <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                                <apex:param value="{!c.Next_Activity_Date__c}" />
                                            </apex:outputText>

                                 </apex:repeat>

        </apex:pageBlock>

        <apex:pageBlock id="jobProfileSection" >

Job Profiles

                        <apex:outputPanel id="componentPnl">
                            <c:JobProfileComponent userId="{!SelectedUserId}" id="JpComponent"/>
                        </apex:outputPanel>

                                     Job profile Name
                                     Job Profile ID
                                     BranchID
                                     Valuation
                                     GC Name
                                     JS City
                                     JS State
                                     Job Name
                                     JS Zip

                                 <apex:repeat value="{!LstJobProfileGrid}" var="c">

                                        {!c.Name}
                                        {!c.Job_Profile_ID__c}
                                        {!c.Branch_ID__c}
                                        {!c.Valuation__c}
                                        {!c.GC_Awarded_Dodge__c}
                                        {!c.Job_Site_City__c}
                                        {!c.Job_Site_State__c}
                                        {!c.Name}
                                        {!c.Job_Site_Zip__c}

                                 </apex:repeat>

        </apex:pageBlock>

        <apex:pageBlock id="OpportunitySection">
            <c:OpportunityComponent userId="{!SelectedUserId}" id="OppComponent"/>
        </apex:pageBlock>

        <apex:pageBlock id="TaskSection">

My Activities
         Create New Opportunity

                        <apex:selectList value="{!SelectedTaskName}" size="1" style="width:250px;">
                            <apex:selectOptions value="{!lstTaskOptions}"/>
                            <apex:actionSupport event="onchange" action="{!ChangeSelectedTaskName}" rerender="TaskSection" status="splashStatus"/>
                        </apex:selectList>

                         Subject
                         Due Date
                         MMI Call Type
                         Account Name
                         Name
                         Related To
                         Phone

                        <apex:repeat value="{!LstTaskGrid}" var="c">

                              {!c.Subject}
                              <td style= "{!IF(AND(NOT(ISBLANK(c.ActivityDate)),c.ActivityDate- Today() < 0), 'color:red;', 'color:black;')}">
                                  <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                      <apex:param value="{!c.ActivityDate}" />
                                  </apex:outputText>

                              {!c.Call_Type__c}
                              {!c.Account.Name}
                              {!c.Who.Name}
                              {!c.What.Name}
                              {!c.Who.Phone}

                         </apex:repeat>

        </apex:pageBlock>

        <apex:pageBlock id="OrderSection">

Orders & Deliveries

                        <apex:selectList value="{!SelectedlstOrdDelivOptionsName}" size="1" style="width:250px;">
                            <apex:selectOptions value="{!lstOrdDelivOptions}"/>
                            <apex:actionSupport event="onchange" action="{!ChangeOrderDelivery}" rerender="OrderSection" status="splashStatus"/>
                        </apex:selectList>

                        <apex:selectList value="{!SelectedOrdDelivTimeName}" size="1" style="width:250px;">
                            <apex:selectOptions value="{!lstOrdDelivTimeOptions}"/>
                            <apex:actionSupport event="onchange" action="{!ChangeOrderDelivery}" rerender="OrderSection" status="splashStatus"/>
                        </apex:selectList>

                         Account #
                         Account Name
                         Order Type
                         Transaction Code
                         Servicing Branch ID
                         Item Code
                         Total Amt
                         Delivery Date
                         Activation Date
                         Fuel Surcharge Delivery
                         Fuel Surcharage PickUp
                         PPE
                         LLW
                         Delivery Contact Name
                         Delivery Contact #
                         Order #

                      <apex:repeat value="{!LstOrdersAndDelieveriesGrid}" var="c">

                              {!c.Account_Number__c}
                              {!c.Name}
                              {!c.Transaction_Code__c}
                              {!c.Transaction_Code__c }
                              {!c.Transaction_Code__c}
                              {!c.Item_Code__c}
                              {!SUBSTITUTE(TEXT(ROUND(c.Total__c, 0)), ".", "," )}

                                   <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                      <apex:param value="{!c.Delivery_Date__c}"/>
                                  </apex:outputText>

                                   <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                      <apex:param value="{!c.Activation_Date__c}"/>
                                  </apex:outputText>

                                <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                      <apex:param value="{!c.Fuel_Surcharge_Delivery__c}"/>
                                </apex:outputText>

                                <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                                      <apex:param value="{!c.Fuel_Surcharage_PickUp__c}"/>
                                </apex:outputText>

                              {!c.PPE__c}
                              {!c.LLW__c}
                              {!c.Delivery_Contact_Name__c}
                              {!c.Delivery_Contact_Number__c}
                              {!c.Order_Number__c}

                      </apex:repeat>

       </apex:pageBlock>

    </apex:form>

</apex:page>

A: seems that you should to use the following fix:
 var j$ = jQuery.noConflict();

The problem is that force.com also includes a lot of javascript libraries that also may use this $ symbol as a shortcut and this can cause all sorts of problems.
Now where ever you would normally use $, use j$.


text:
Q: How can I find all the matrices that commute with this matrix? I would like to find all the matrices that commute with the following matrix
$$A = \begin{pmatrix}2&0&0\\ \:0&2&0\\ \:0&0&3\end{pmatrix}$$
I set $AX = XA$, but still can't find the solutions from the equations.

A: >>> from sympy import *
>>> A = diag(2,2,3)
>>> X = MatrixSymbol('X',3,3)
>>> Matrix(A*X - X*A)
Matrix([
[      0,       0, -X[0, 2]],
[      0,       0, -X[1, 2]],
[X[2, 0], X[2, 1],        0]])

If $\rm A X = X A$, then $x_{13} = x_{23} = x_{31} = x_{32} = 0$. The other five entries are unconstrained.
We can also vectorize $\rm A X = X A$, which yields the following homogeneous linear system
$$\left( (\mathrm I_3 \otimes \mathrm A) - (\mathrm A \otimes \mathrm I_3) \right) \mbox{vec} (\mathrm X) = 0_9$$
or,
$$\begin{bmatrix}0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\end{bmatrix} \mbox{vec} (\mathrm X) = \begin{bmatrix} 0\\0\\0\\0\\0\\0\\0\\0\\0\end{bmatrix}$$
Again, we conclude that $x_{13} = x_{23} = x_{31} = x_{32} = 0$.

A: Block matrices provide an immediate insight. Let
$$A = \left[\begin{array}{l}2&0&0\\0&2&0\\0&0&3\end{array}\right] = \left[\begin{array}{l|l}a&0\\\hline0&3\end{array}\right]$$
The submatrix $a = 2I_2$. Now define the block matrix
$$X = \left[\begin{array}{l|l}b&0\\\hline0&c\end{array}\right]$$ with conformal block sizes. That is, $c=constant$ and
$$b = \left[\begin{array}{l}b_{11}&b_{12}\\b_{21}&b_{22}\end{array}\right] $$
has arbitrary complex elements.
The equation to solve is
$$[A,X] = AX - XA = \left[\begin{array}{l|l}a&0\\\hline0&3\end{array}\right] \left[\begin{array}{l|l}b&0\\\hline0&c\end{array}\right] - \left[\begin{array}{l|l}b&0\\\hline0&c\end{array}\right] \left[\begin{array}{l|l}a&0\\\hline0&3\end{array}\right] =  \left[\begin{array}{l|l}0&0\\\hline0&0\end{array}\right]$$
We have two equations:
$$ b a =  a b$$
$$ 3c = 3c$$
The second equation is trivial: $c$ is arbitrary. The first equation is just
$$ 2bI_{2} = 2 I_{2} b$$
Since the identity matrix commutes with every matrix, the $b$ matrix is arbitrary.
To conclude, the solution matrix has five arbitrary complex numbers arranged so:
$$X = \left[\begin{array}{ll|l}b_{11}&b_{12}&0\\b_{21}&b_{22}&0\\\hline0&0&c \end{array}\right] $$
One sees the benefit of this form in analyzing matrices of the form
$$A = \left[\begin{array}{l}c_{i} I_{i}&0&0 & 0\\0&c_{j}I_{j}&0 & 0\\0&0&c_{k}I_{k} & 0 \\ 0 & 0 & 0 & \ddots\end{array}\right]$$

A: $AX$ doubles the first two rows of $X$, and triples the third row.
$XA$ doubles the first two columns of $X$, and triples the third column.  These two must agree.
This gives us a matrix $$X=\left(\begin{matrix}*& * & 0\\*&*&0\\0&0&*\end{matrix}\right)$$
Where $*$ can be anything.

A: If
$B:= \left( \begin{matrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 1 \end{matrix} \right)$,
then your matrix becomes $A = 2I + B$. Thus a matrix $C$ will commute with $A$ if and only if $C$ commutes with $B$. But note
$BC = \left( \begin{matrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 1 \end{matrix} \right)\left( \begin{matrix} a & b & c \\ d & e & f \\ g & h & i \end{matrix} \right) = \left( \begin{matrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ g & h & i \end{matrix} \right)$
and
$CB = \left( \begin{matrix} a & b & c \\ d & e & f \\ g & h & i \end{matrix} \right) \left( \begin{matrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 1 \end{matrix} \right) = \left( \begin{matrix} 0 & 0 & c \\ 0 & 0 & f \\ 0 & 0 & i \end{matrix} \right)$.
It follows that $BC = CB$ if and only if $c=f = g = h = 0$


text:
Q: Dependency Injection error after upgrading to Weblogic 12c I recently upgraded from Weblogic 11g to 12c.  Getting this error in standard output when MyOtherBean tries to inject MyStartupBean using the @EJB annotation:
 [exec] <Mar 6, 2017, 9:39:45,547 AM EST> <Warning> <EJB> <BEA-010065> <MessageDrivenBean threw an Exception in onMessage(). The exception is:
 [exec]  javax.enterprise.inject.InjectionException: Exception trying to inject java EE injection point into class: com.foo.My.cache.ejb.MyOtherBean..
 [exec] javax.enterprise.inject.InjectionException: Exception trying to inject java EE injection point into class: com.foo.My.cache.ejb.MyOtherBean.
 [exec]     at com.oracle.injection.integration.ModuleContainerIntegrationService.performJavaEEInjection(ModuleContainerIntegrationService.java:405)
 [exec]     at com.oracle.injection.provider.weld.WeldInjectionServicesAdapter.aroundInject(WeldInjectionServicesAdapter.java:49)
 [exec]     at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
 [exec]     at org.jboss.weld.injection.producer.ResourceInjector.inject(ResourceInjector.java:72)
 [exec]     at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:121)
 [exec]     Truncated. see log file for complete stacktrace
 [exec] Caused By: com.bea.core.repackaged.springframework.beans.factory.BeanCreationException: Dependency injection failure: can't inject the value 'com.foo.My.common.ejb.MyStartupBean_pqx8ri_Impl@39dc616' into the field 'private com.foo.My.common.interfaces.MyStartup com.foo.My.cache.ejb.MyOtherBean.startup'; nested exception is java.lang.IllegalArgumentException: Can not set com.foo.My.common.interfaces.MyStartup field com.foo.My.cache.ejb.MyOtherBean.startup to com.sun.proxy.$Proxy352
 [exec]     at com.oracle.pitchfork.inject.FieldInjection.apply(FieldInjection.java:45)
 [exec]     at com.oracle.pitchfork.inject.Jsr250Metadata.performInjection(Jsr250Metadata.java:228)
 [exec]     at com.oracle.pitchfork.inject.Jsr250Metadata.applyInjections(Jsr250Metadata.java:215)
 [exec]     at com.oracle.pitchfork.inject.Jsr250Metadata.inject(Jsr250Metadata.java:197)
 [exec]     at com.oracle.injection.integration.ModuleContainerIntegrationService.performJavaEEInjection(ModuleContainerIntegrationService.java:398)
 [exec]     Truncated. see log file for complete stacktrace
 [exec] Caused By: java.lang.IllegalArgumentException: Can not set com.foo.My.common.interfaces.MyStartup field com.foo.My.cache.ejb.MyOtherBean.startup to com.sun.proxy.$Proxy352
 [exec]     at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
 [exec]     at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
 [exec]     at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
 [exec]     at java.lang.reflect.Field.set(Field.java:764)
 [exec]     at com.oracle.pitchfork.inject.FieldInjection.apply(FieldInjection.java:43)
 [exec]     Truncated. see log file for complete stacktrace

This is the MyStartup interface:
@Remote
public interface MyStartup extends my.base.BaseObj
{
   public java.util.Collection getX( ) ;
   public java.util.Collection getY( ) ;
}

And the MyStartupBean ejb:
@Stateless
@CallByReference
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
@TransactionManagement(TransactionManagementType.CONTAINER)
public class MyStartupBean extends BaseSessionBean implements MyStartup
{
   public java.util.Collection getX( ){
        //do stuff
   }

   public java.util.Collection getY( ){
        //do stuff
   }
}

And finally the MyOtherBean class which calls the MyStartup interface/MyStartupBean ejb:
@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic") }, mappedName="jms/CacheRefreshTopic")
@MessageDestinationConfiguration(connectionFactoryJNDIName="jms/CacheRefreshCF")
@TransactionAttribute(value=TransactionAttributeType.SUPPORTS)
@TransactionManagement(value=TransactionManagementType.CONTAINER)
public class MyOtherBean implements MessageListener
{
    ...
    @EJB private MyStartup startup;
    ...
}

A: Why is MyStartup marked as @Remote but you are trying to inject an implementer of him as a local bean using the @EJB annotation?
After I changed the marker annotation to @Local, the code has begun to be successfully deployed on my Oracle WebLogic 12.2.1.2.0 domain.


text:
Q: Java getter return type based on object type What I am trying to achieve is something like the following:
public class Foo {
    Object o;

    public Foo(Object o) { //takes object
        this.o = o;
    }

    public <T> T getO() { //the return type of this should be the object type
        return (T) o;
    }
}

For example:
Object o = "123"; // imagine this comes from external system and can be anything
Foo foo = new Foo(o);
String foo = foo.getO(); //returns String

I saw a few examples doing something similar using Google Guava TypeToken but couldn't get exactly the behavior I want.

A: You can do what you want if you make Foo have the correct type
public class Foo<T> {
   T data;

   public Foo(T d)
   {
      this.data = d;
   }

   public T getData()
   {
     return data;
   }
}

Then your examples will work as:
Foo<String> foo = new Foo<>("123"); //passing String
String foo = foo.getData(); //return String

Foo<Float> foo = new Foo<>(123f); //passing float
float foo = foo.getData(); //return float

EDIT: the original question was updated slightly. However, the basic problem remains that a Java method must declare its return type. One can get close if one can use covariant returns in some fashion by extending a hierarchy. There are examples Overriding a method with different return types and Can overridden methods differ in return type.
One could also consider a Factory pattern to assist with the approach. So it would be
Foo foo = FooFactory.geetFoo(originalData);  // the specific foo would vary
String s = foo.getData();


text:
Q: How to run a Excel document through a Python program I am trying to run a few hundred Trip Advisor reviews through a Sentiment Analysis program (via textblob), so that it will read each review and provide a sentiment for it. The program already works in that you can type a sentence in and it will return the sentiment (i.e. positive, negative, neutral). I would like to run a excel document through the program without having to manually type in each review. Ideally, the program returns a sentiment on each review.....How do I do this?
This is the code I already have...
from textblob import TextBlob
import string

z = 10

poscounter = 0

negcounter = 0

neucounter = 0

totalsentences = 0

while z > 0:

y = input("Type your sentence ").lower()
    y = y.translate(str.maketrans('', '', string.punctuation))
    y1 = TextBlob(y)
    sentCheck = y1.sentiment.polarity

    if y == "stop":

            print(f"Positive Sentiment: {(poscounter/totalsentences) * 100} %")
            print(f"Negative Sentiment: {(negcounter/totalsentences) * 100} %")
            print(f"Neutral Sentiment: {(neucounter/totalsentences) * 100} %")
            exit()

    xplitIt = y.split(" ")

    for something in xplitIt:
        if something == "crowded" or something == "busy" or something == "crowds" or something == "hate" or something == "hated":
            print("negative")
            sentCheck = -0.1
            break

    if sentCheck==0:
        print("neutral")
        neucounter+=1

    elif sentCheck>0 and sentCheck <=1:
        print("positive")
        poscounter+=1

    elif sentCheck == -0.1 or sentCheck < 0:
        negcounter+=1
        if sentCheck != -0.1:
            print("negative")

    totalsentences = totalsentences + 1

A: There are libraries to read text from word documents. You can have a look at textract that was suggested in this answer.
The text you read will probably have multiple reviews that you have to split into a list of reviews (e.g. with python's split() function). You can then give each of these reviews as y into your algorithm.
How you have to process your input depends on the structure of your document. You should include an example in your question if you need further help.


text:
Q: How can I print objects to the console? I am trying to select all data that is stored in a list where the username == the parameter.
I'm having trouble printing it in the right format. Currently, the output is productsClass.Products where I'd like it to be the data. Any help or hints are greatly appreciated.
Thanks
public class Products {
    public string productName;
    public string productType;
    public int productCost;
    public string userName;
}

public class ProductController {
    public List<Products> productsList;

    public ProductController() {
        productsList = new List<Products>();
    }

    public void CreateNewProduct(string username, string productName, string productType, int productCost) {
        Products product = new Products();
        product.userName = username;
        product.productName = productName;
        product.productType = productType;
        product.productCost = productCost;
        productsList.Add(product);
    }

    public void ListAllProducts(string username) {
        IEnumerable<Products> listProducts = from s in productsList
                                             where s.userName == username
                                             select s;
        foreach (var product in listProducts) {
            Console.WriteLine(product);
        }
    }
}

A: According to Object.ToString Method

Object.ToString method return the fully qualified name of the object's type.

If you need to print product, you have to override .ToString() as below:
public class Products
{
    ...

    public override string ToString()
    {
        return String.Format("Name: {0}, Type: {1}, Cost: {2}, UserName: {3}", productName, productType, productCost, userName);
    }
}

A: Your Question is a bit unclear about what exactly you want to print and in what format but given that you said you want all the data this could be a solution:
public void ListAllProducts(string username) {
        IEnumerable<Products> listProducts = from s in productsList
                                             where s.userName == username
                                             select s;
        foreach (var product in listProducts) {
            Console.WriteLine(product.userName +"\t"+ product.productName +"\t"+ product.productType +"\t"+ product.productCost);
        }
    }

This would print out all of your variables of the object. Because if you give the object as only Parameter to WriteLine() it will only print out its type.

A: You cannot just print the class instance. Try to print the properties instead.
Console.WriteLine(product.productName);

A: You can achieve the expect result by using System.Text.Json then do Console.WriteLine(JsonSerializer.Serialize(product))

A: If you want to show the data in a specific way the best would be to override the ToString() method in your Products class and then call it inside Console.WriteLine


text:
Q: How can I resolve error lnk2019 C++ by changing project settings I am engaged in a legacy project that is written very incomprehensibly. The fact is that the project was written a long time ago and developed for x86. Nevertheless, it starts and works. But since I didn't set up visual studio, it gives the error LNK2019 (unresolved external symbol). Please help me solve this problem! The project really works, just something needs to be done in the project settings, but I don't understand what.
So, I have this three errors:

Error LNK2019 unresolved external symbol "int __stdcall cv::_interlockedExchangeAdd(int *,int)" (?_interlockedExchangeAdd@cv@@YGHPAHH@Z) in function "public: void __thiscall cv::Mat::release(void)" (?release@Mat@cv@@QAEXXZ).  Swimm   E:\data\study\practice\Swimm\speedDlg.obj   1

Error  LNK2019 unresolved external symbol "void __stdcall cv::fastFree(void *)" (?fastFree@cv@@YGXPAX@Z) in function "public: __thiscall cv::Mat::~Mat(void)" (??1Mat@cv@@QAE@XZ). Swimm   E:\data\study\practice\Swimm\speedDlg.obj   1

Error  LNK1120 unresolved externals: 2 Swimm   E:\data\study\practice\Swimm\Debug\Swimm.exe    1

I understand, that LNK1120 error is due to the presence of LNK2019 errors


text:
Q: nvm installation error - yo: command not found I was going to install hubot. When I installed nvm, it failed, and I can't use nvm -v to view its version. I don't know the reason why it failed.
Here is the error log:
npm ERR! Linux 4.4.0-21-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "yo" "generator-hubot"
npm ERR! node v4.2.6
npm ERR! npm  v3.5.2
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! spawn-sync@1.0.15 postinstall: `node postinstall`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the spawn-sync@1.0.15 postinstall script 'nodepostinstall'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the spawn-sync package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node postinstall
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs spawn-sync
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls spawn-sync
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR!     /home/shi/npm-debug.log

shi@shi-VirtualBox:~$ sudo npm install -g coffee-script
/usr/local/bin/coffee -> /usr/local/lib/node_modules/coffee-script/bin/coffee
/usr/local/bin/cake -> /usr/local/lib/node_modules/coffee-script/bin/cake
/usr/local/lib
└── coffee-script@1.10.0

shi@shi-VirtualBox:~$ cd myhubot

shi@shi-VirtualBox:~/myhubot$ yo hubot
yo: command not found

shi@shi-VirtualBox:~/myhubot$ cd ..

shi@shi-VirtualBox:~$ yo hubot
yo: command not found

A: git clone git://github.com/creationix/nvm.git ~/.nvm
nvm install 4.2.6
npm install -g yo generator-hubot
mkdir myhubot && cd myhubot
yo hubot

Partial source: hubot of github


text:
Q: View PDFs and Office Documents from within own App? I'm planning an iOS application which will allow browsing documents on my server using a WebService. The user will have the option to download documents (PDF and MS Office) to have them available offline.
Now I know that iPhone/iPad is capable of viewing all kinds of document formats, including PDF, DOC(X), XLS(X) if they are received through email for instance. I assume they are all handled by the same "preview module".
The question is: if I have the documents in my app's storage, how can I use the same functionality?
Solution in ObjC or MONOTOUCH is fine, or just pointing my into the right direction in general.
René

A: You can use the UIDocumentInteractionController which will present the user with a menu offering them "Quick Look" (which will open the file in the app) or the option to open the file in another app depending on what the user has installed.
Same sample code I've used looks like this (where e.Result is the result of a call to my web service).
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(path, e.Result.Filename);
if (!File.Exists(filePath))
{
    File.WriteAllBytes(filePath, e.Result.DocumentData);
}

UIDocumentInteractionController docControl = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filePath));
docControl.Delegate = new UIDocumentInteractionControllerDelegateClass(this);

InvokeOnMainThread(delegate {
    docControl.PresentOptionsMenu(new RectangleF(0,-260,320,320), tbnv.View, true);
});

The delegate class contains overrides for the view where the preview view will appear (so you want to pass the current view to this and ensure that this is the view the preview will be presented in).

A: In my app, I allow users to view PDF's in-app by using a UIWebView control, and just loading the url of the PDF in it.  That should work for internal PDFs also.  I've never tried it with other types of docs, but I imagine the same approach would work.


text:
Q: C# & WP8.1 Insert result of query select into array I have C# project for Windows Phone 8.1 with SQLite database.
Database contain a table, from which need select all data, and write it into array. Also have 2 classes: Links (like name of table) - contain description of table; Repository - class for methods.
I dont know how create method for inserting.
Begin like: using (var statement = SQLiteConnection.Prepare("SELECT _id, link FROM links WHERE _id=?")), but what next?

A: It's so simple.
Use class for description table (Linkes) to create new array(type). In other class create List method with query what you need.
public  List <Linkses> Gettha()
        {
            List<Linkses> lin = new List<Linkses>();
            using (var statement = con.Prepare("SELECT _id, link FROM links"))
            {
                 while (statement.Step() == SQLiteResult.ROW)
                 {
                     Linkses link = new Linkses();
                     link.Id = (long)statement[0];
                     link.Linochka = (string)statement[1];
                     lin.Add(link);
                    }
            }
            return lin;
        }

Then you must call that method with ToArray.
Linkses[] holla = App.repo.Gettha().ToArray();


text:
Q: Can I restrict cfmail to only send mail from a given domain using cf admin We have had issues with our server being used to send spam via cfmail to our remote SMTP server.  I cannot see where it is occurring, but the emails are sent from a domain that is not one on our server.
Is there a way using ColdFusion administrator to specify that only emails showing as from someone@mydomain.com are sent to the SMTP host via the spool?
Thanks in advance,
Paul

A: It sounds to me like the <cfmail> side of things here is a red herring and you have got an open relay on your mail server. You seriously need to disable that immediately! If your SMTP server has to relay email for your CFML app then make sure it's not configured to relay everything, instead just for the IP address of the CF server, or for the credentials the CF server uses to connect to it.
If you don't know how to configure the relaying settings for your SMTP server, raise another question on serverfault.com asking how. Provide the exact details of your SMTP server, as well as the requirement to still allow relaying for the CF server.


text:
Q: jQuery .animate(), problems with toggle I'm relatively new to js and I'm trying to implement a simple .animate() feature in my portfolio. As you can see here, with the code I wrote the div called ribbon slides down perfectly, but it seems to ignore the "else" part of the script.
I know I'm probably doing a dumb mistake, but I can't seem to be able to work out anything better at the moment!
Sorry for my bad english, sucks to be Italian.

A: Just came up with a solution for another one like this a minute ago.
http://jsfiddle.net/HF5A5/
Basically you multiply the value by 1 or -1 and then toggle that value.
$(document).ready(function() {
    var direction = -1;
    $('#toggle').click(function() {
            direction -= direction * 2;
            $('#ribbon').animate({
                marginTop: "+=" + direction * 300 + "px"
            }, 1700);
            return false;
    });
});

or better yet: http://jsfiddle.net/HF5A5/1/
$(document).ready(function() {
    var direction = 1;
    $('#toggle').click(function() {
            $('#ribbon').animate({
                marginTop: "+=" + direction * 300 + "px"
            }, 1700, function(){
                $(this).stop();
                direction -= direction * 2;
            });
            return false;
    });
});

A: Just taking what you had, simply put the if inside the click event.
http://jsfiddle.net/Rkqge/12/
$(document).ready(function() {
  $('#toggle').click(function() {
    if ($('#ribbon').css("margin-top") == "-300px") {
        $('#ribbon').animate({
            marginTop: "0px"
        }, 1700);
    } else {
        $('#ribbon').animate({
            marginTop: "-300px"
        }, 1700);
    }
 });
});


text:
Q: Why won't my program work? I have a java program that I had working perfectly, but somehow, overtime it failed. I'm really not sure how and I'm not sure why, so I'm hoping a new pair of eyes will help solve the problem. Please help, thanks! The program is a simple "poker" code that outputs 5 random cards from the deck.
The program was working when I first ran it but for some strange reason it doesn't run anymore.
I keep getting the errors...
"cannot resolve symbol rank.length",
"cannot resolve symbol suit.length",
"Package java.Random does not exist"

The Program:
import java.Random.*;
import java.io.*;
import java.util.*;

public class Poker {

    public static void main(String[] args) {

        //initialize variables
        int suits = suit.length;
        int ranks = rank.length;
        int n = suits * ranks;
        //counter
        int m = 5;

         // create a deck of 52 cards
         String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
         String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
                           "Jack", "Queen", "King", "Ace"
                         };

         // initialize deck
         String[] deck = new String[n];
         for (int i = 0; i < ranks; i++) {
             for (int j = 0; j < suits; j++) {
                 deck[suits*i + j] = rank[i] + " of " + suit[j];

         }
         }

        // create random 5 cards
        for (int i = 0; i < m; i++)  {
            int r = i + (int) (Math.random() * (n-i));
            String t = deck[r];
            deck[r] = deck[i];
            deck[i] = t;
        }

        // print results
        for (int i = 0; i < m; i++){
            System.out.println(deck[i]);

        }
    }
}

A:
cannot resolve symbol rank.length

That's because you try to access rank.length before declaring rank.
Try:
//first declare arrays
// create a deck of 52 cards
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
                   "Jack", "Queen", "King", "Ace"
                 };

//then find out their length
int suits = suit.length;
int ranks = rank.length;
int n = suits * ranks;
//counter
int m = 5;

Package java.Random does not exist

It's true, it's import java.util.Random, not import java.Random.*, the java.Random package doesn't exist.

A: First, the package java.Random really does not exist.  But I don't see where you're using Random anyway, so just remove that import statement.  Even if you were using Random, you are already importing it with java.util.*.
For the other two errors, you declared the variables you're referring to (suit and rank) after you used them.  Declare them before you use them.

A:   int suits = suit.length;
  int ranks = rank.length;
  int n = suits * ranks;

the above lines should be placed below

String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
                           "Jack", "Queen", "King", "Ace"
                };

also remove import java.Random.*


text:
Q: What are the limits of Postgresql's large object facility? I've not found an equivalent of the about PostgreSQL page that covers the limitations of the large object facility in particular, but reading between the lines I think the following is true:

*

*No more than 32TB of large objects can be stored (reason: they are all stored in a single table named pg_largeobject, and the per-table size limit is 32TB (assuming default page size)).

*No more than 2^32 large objects can be stored (reason: the primary key of pg_largeobject is an oid which is a 32-bit quantity).

*pg_largeobject cannot be partitioned (reason: because it's a system catalog?)

Is this all correct?

A: These 3 points are correct. We might add

*A large object cannot exceed 4TB for PostgreSQL 9.3 or newer, or 2GB for older versions. This is based on the release notes:

E.11.3.5. Data Types
Increase the maximum size of large objects from 2GB to 4TB (Nozomi Anzai, Yugo Nagata)

Also, the binary contents are sliced into tiny chunks of 2000 bytes in pg_largeobject. There is one row per chunk, so when importing large contents (large by today's standards), the number of rows in this table tend to grow quickly.
Although that does not imply a hard limit, users should be aware of that for performance reasons.


text:
Q: Regex Expression for Hashtags /(?:\s|^)(?:#(?!(?:\d+|\w+?_|_\w+?)(?:\s|$)))(\w+)(?=\s|$)/i

This is the current expression i use. It works fine except the dash - is not allowed. I need this: #what-ever to be captured.
How can i add the dash to this expression ?

A: Just add the pattern which was present inside the first capturing group that is \w plus - into a character class. So that it would capture a word character or a - symbol. + after the character class makes the previous token to repeat one or more times.
(?:\s|^)(?:#(?!(?:\d+|\w+?_|_\w+?)(?:\s|$)))([-\w]+)(?=\s|$)
                                             |here|

DEMO


text:
Q: Java string.split( ) on comma or end-of-line I'm terrible with regex stuff. I have data that looks like this:
abc,42,4/04/1992,,,something,   ,2/05/2007,dkwit,,334,,,

The meaning of the data itself is somewhat irrelevant, the point is that it's comma-delimited, you could refer to the data between commas as "columns", and some columns may be whitespace or empty (later on, whitespace columns and empty columns are ignored). I need to split the string into an array based on the comma delimiter. I tried
new StringTokenizer(string, ",")

but that will skip over tokens where the data between columns is empty, so I tried using string.split(","). The problem with that is it would skip the last three columns in the data above. You could say after the "334", it behaves like StringTokenizer, skipping the columns with no whitespace or no data in them.
Can I make string.split( ) behave in such a way that it will continue to split until it comes across an end of line, or is there a better way to do this?

A: You can use the overloaded String#split(String,int) method, and set the limit to a negative number:
String text = "abc,42,4/04/1992,,,something, ,2/05/2007,dkwit,,334,,,";
String[] tokens = text.split(",", -1);

The limit parameter is explained in the linked Javadoc:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

A: Easiest way to parse CSV (comma-separated values) data is with CVS parser. One of simplest ones is OpenCVS. Here is example of how you can do it:
String data = "abc,42,4/04/1992,,,something,   ,2/05/2007,dkwit,,334,,,";

CSVReader reader = new CSVReader(new StringReader(data));
for (String[] tokens = reader.readNext(); tokens != null; tokens = reader.readNext()) {
    for (String token : tokens){
        System.out.print("<" + token + ">\t");
    }
    System.out.println();
}

Output (I added < and > to show where value starts and ends):
<abc>   <42>    <4/04/1992> <>  <>  <something> <   >   <2/05/2007> <dkwit> <>  <334>   <>  <>  <>


text:
Q: QT-Box-Editor.exe v1.10 and v1.09 are infected with virus, any clue where else I can download a virus free exe? I tried to download the above exe file from this site,
https://github.com/zdenop/qt-box-editor/downloads
however, both ver 1.10 and 1.09 are infected with virus when checking against virustotal.com
For ver 1.10, VirusTotal returned :

*

*MaxSecure Trojan.Malware.300983.susgen

*McAfee    Artemis!5C87D43589E7

*McAfee-GW-Edition
BehavesLike.Win32.Trojan.fc

*SecureAge APEX Malicious
I googled, however, failed to get a virus free version of the exe at other sites.
Can anyone help ?
I don't know how to build an exe from the source file, if need be, where can I get instruction set to build the exe ? like linking all the needed dependencies with the correct version, what software required to be installed to compile the source code.
Any help is much appreciated.
Thanks


text:
Q: zeroclipboard pasting actual swf / js file Has anyone ran into ZeroClipboard pasting the actual file extension and not the desired content?
My code is

   <button id='#copy_button' data-clipboard-target='to_copy'>Copy To Clipboard</button>

This should be copied text


text:
Q: Issue in reading google text document I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
            GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
            oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
            oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
            oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
            oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
            DocsService client = new DocsService("sakshum-YourAppName-v1");
            client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
            URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
            DocumentQuery dquery = new DocumentQuery(feedUrl);
            dquery.setTitleQuery("blood_donor_verification_template_dev");
            dquery.setTitleExact(true);
            dquery.setMaxResults(10);
            DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
            System.out.println("feed size:" + resultFeed.getEntries().size());
            String emailBody = "";
            for (DocumentListEntry entry : resultFeed.getEntries()) {

                System.out.println(entry.getPlainTextContent());
                emailBody = entry.getPlainTextContent();
            }

Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception

A: finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
                String docId = entry.getDocId();
                String docType = entry.getType();
                URL exportUrl =
                              new URL("https://docs.google.com/feeds/download/" + docType
                                  + "s/Export?docID=" + docId + "&exportFormat=html");
                MediaContent mc = new MediaContent();
                mc.setUri(exportUrl.toString());

                MediaSource ms = client.getMedia(mc);
                InputStream inStream = null;
                try {
                    inStream = ms.getInputStream();
                    int c;
                    while ((c = inStream.read()) != -1) {
                        emailBody.append((char)c);
                    }
                  } finally {
                    if (inStream != null) {
                      inStream.close();
                    }
                  }
            }


text:
Q: Why doesn't CodeIgniter have an option to use $_SESSION? I'm using CodeIgniter for the first time, and I'd like to store sessions server-side in Memcache.
However, it seems like the only built-in option is to use a MySQL database table (ci_sessions). Is this true?
Why doesn't CodeIgniter offer the option to plug in to the session auto-global ($_SESSION) and then let you pick your storage engine?
It seems this would be much easier than baking in their own solution.
If I was using Drupal or some other framework I could simply configure session storage in my PHP config file, but now it seems I need to add in a library or write something just to be able to use Memcache.