text:
Q: How are we able to calculate specific numbers in the Fibonacci Sequence? I was reading up on the Fibonacci Sequence, $1,1,2,3,5,8,13,\ldots $ when I noticed some were able to calculate specific numbers. So far I've only figured out creating an array and counting to the value, which is incredibly simple, but I reckon I can't find any formula for calculating a Fibonacci number based on it's position.
Is there a way to do this? If so, how are we able to apply these formulas to arrays?

A: The closed form calculation for Fibonacci sequences is known as Binet's Formula.

A: You can use Binet's formula, described at http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html
(see also Wikipedia for a proof: http://en.wikipedia.org/wiki/Binet_formula#Closed_form_expression )

A: To expand on falagar's answer, my favourite proof of Binet's formula:
...Which I was going to post a summary of here, but remembered that everything was awful without Tex, so here is a link to some notes on it I found on google.
The basic idea is to treat pairs of fibonnacci numbers, adjacent in the sequence, as vectors. Moving on to the next adjacent pair induces a linear transformation not unlike that of the matrix falagar posted. Calculating eigenvalues and eigenvectors can give a complete prediction of where an initial vector will find itself, predicting the whole sequence.
It's quite a lot of work but I think it's rather illuminating.

A: A lot of people have mentioned Binet's formula.  But I suspect this is not the most practical way to compute the nth Fibonacci number for large n, because it requires either having a very accurate value of $\sqrt{5}$ and carrying around lots of decimal places (if you want to do floating-point arithmetic) or expanding large powers of $1+\sqrt{5}$ using the binomial formula.  The latter comes out to writing the Fibonacci number as a sum of binomial coefficients.
The following formulas hold, though:$$F_{2n-1}=F_n^2+F_{n-1}^2$$$$F_{2n}=(2F_{n-1}+F_n)\cdot F_n$$which you can find derivations of in the Wikipedia article on Fibonacci numbers.  This lets you find $F_k$, for any $k$ even or odd, in terms of two Fibonacci numbers with approximately half the index.  The result is faster than Binet's formula.

A: Also you can use the matrix equation for Fibonacci numbers:
$$
  \begin{pmatrix}1&1\\1&0\end{pmatrix}^n
  =
  \begin{pmatrix}F_{n+1}&F_{n}\\F_{n}&F_{n-1}\end{pmatrix}
$$
To calculate $n$-th power of the matrix you can use
exponentiation by squaring algorithm.
This approach could also be generalized on the case of arbitrary sequence with linear recurrence relation.

A: There's a perfectly general way for this sort of problem.  I used it to look for instances of $p$, such that if $p$ divided a Fibonacci number, so did $p^2$. There are none under twenty million twelftywise $20.00.00.00.00_{120}=4147200000.$
This method can be used with modular arithmetic into the hundreds of millions.
These are a number of different series, the fibonacci, Lucas series, the side and diagonal of the square approximate, and Heron's triangle.  It's written in the REXX programming language.
The actual process is to be found in the 'isoquad' routine, which extends an isoseries (ie a form $T_{n+1}= a.T_n - T_{n-1}$).  The actual equation as written gives $T_p$, given in order $a, p, T_0 ,T_1$.  It relies on that any isoseries, one can take steps of m, and thus take $T_{m+n} = a\text{^^}m \cdot T_n - T_{n-m}$.
The actual process is like this.  The example is to find T(37)  Numbers in brackets are the members of the original T(n).  We halve out the T(n), and increase the step constant to $T(2x) = T(x)^2-2$,  This is the difference between c0, c1, c2, c3.
The values in the second and third columns are as one divides 37 into binary.
 diff          c0   c1   c2   c3   (role, by col 3)     (regular powers)
 (1)  18  1 : (0)  (1)  (2)  (3)   keep odd places       18 1 (1)   (1)
 (2)   9  0 : (1)  (3)  (5)        keep even places       9 0 (2)   (1) = 1+0*2
 (4)   4  1 : (1)  (5)  (9)  (13)  keep odd places        4 1 (4)   (5) = 1+1*4
 (8)   2  0 : (5)  (13) (21)       keep even places       2 0 (8)   (5) = 5+0*8
 (16)  1  0 :  (5)  (21) (37)       keep even places      1 0 (16)  (5) = 5+0*16
       0  1:   (5)  (37)        c2 = 0, so answer in c1.  0 1 (32)  (37) = 5+1*37

The actual method is similar to finding $a^m$ by binary methods, and runs at 2/3 of the speed of said process.
By adjusting the nature of the multiplication to be a modulus, one can test to see if something like $f_{14400}$ is a multiple of 14401 or not.  The heron series, with p set to large powers of 2, is used to find fermat primes, by this very method.
fibon: ; procedure  ;parse arg t0; return isoquad(3,div(t0+2,2),mod(t0,2),1+mod(t0,2))
lucas: ; procedure  ;parse arg t0; return isoquad(3,div(t0+2,2),2-mod(t0,2),3+mod(t0,2))
qside: ; procedure  ;parse arg t0; return isoquad(6,div(t0+2,2),mod(t0,2),2+mod(t0,2)*3)
qdiag: ; procedure  ;parse arg t0; return isoquad(6,div(t0+2,2),  1  ,3+mod(t0,2)*4)
heron: ; procedure  ;parse arg t0; return isoquad(4,t0,2,4)

div:   ; procedure  ;parse arg a, b; c = a % b; if b < a*c then c = c-1 ; return c
mod:   ; procedure  ;parse arg a, b; c = a // b; if c<0 then c=c+b; return c

isoquad:  procedure
parse arg a2, a0, a3, a4
if a0 = 0 then do; a4 = a3; a0 = 1; end
if a0 < 0 then do; a0 = -a0; a4 = a3*a2-a4; end
do forever; if a0 = 1 then leave
a1 = a0//2; a5 = a4*a2 - a3;
if a1 = 0 then a4 = a5
else do; a3 = a4; a4 = a5*a2 - a3; end
a0 = a0 % 2; a2 = a2 * a2 - 2; end
return a4

A: This is an old post, but still... The relation
$$
F_0=1, F_1 =1, F_n = F_{n-1}+F_{n-2}, n \ge 2
$$
defines a linear second order homogeneous difference equation. The solution can be found after computing the roots of the associated characteristic polynomial $p(\lambda)=\lambda^2-\lambda -1$, which are $\lambda = \frac{1 \pm \sqrt{5}}{2}$. The general solution is then given by
$$
F_n= C_1 \left(\frac{1 + \sqrt{5}}{2} \right)^n + C_2 \left(\frac{1 - \sqrt{5}}{2} \right)^n
$$
and the constants $C_1, C_2$ are computed knowing that $F_0 = F_1 = 1$. so, finally,
$$
F_n= \frac{1}{\sqrt{5}} \left(\frac{1 + \sqrt{5}}{2} \right)^n - \frac{1}{\sqrt{5}} \left(\frac{1 - \sqrt{5}}{2} \right)^n
$$
This is obviously equivalent to Binet's formula, but provides a general process to deal with linear recurrences.

A: Wikipedia has a closed-form function called "Binet's formula".
$$F\left(n\right) = {{\varphi^n-(1-\varphi)^n} \over {\sqrt 5}}$$
This is based on the Golden Ratio.


text:
Q: TS generics in functional react components I have a functional component that takes a generic U. How can I access the keys of U and the values of U to use in another generic? CellBase and Matrix come from the 'react-spreadsheet' library. Here's the code:

interface DataEditorAndViewerPageProps<T> {
  getAll: () => Promise<T[]>
  add: (input: Partial<T>[]) => Promise<T[] | ZodMiddlewareError[]>
  updateById: (id: string, input: Partial<T>) => Promise<T | ZodMiddlewareError>
  deleteById: (id: string) => Promise<number | NonZodError>
  selectedColumns: string[]
}

export default function DataEditorAndViewerPage<U extends {
  [key: string | symbol]: unknown
}>(props: DataEditorAndViewerPageProps<U>) {

...

const [spreadsheetHeaders, setSpreadsheetHeaders] = useState<CellBase<keyof typeof U>[]>([]);
  const [addedRows, setAddedRows] = useState<Matrix<CellBase<typeof U[keyof typeof U]>>>([[]]);

...

}

For both lines I get: 'U' only refers to a type, but is being used as a value here.ts(2693)

A: Avoid any and unknown for production.
If you need a callback you can most likely just use () => void or () => Promise<void>
If you don't know the types needed, you should look into a types file or refer to documentation of whatever library you're using.
As per using functional programming for React components, this is a pretty solid template:
export const MyComponent = (props: Props): JSX.Element => <></>

Your components shouldn't need to be so 'smart' that you end up writing many lines of possibly unnecessary code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write less boilerplate in a expression evaluator written with recursion-schemes With the recursion-scheme library
it's easy to write abstract syntax trees and the corresponding expression evaluators:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE LambdaCase #-}

import Data.Functor.Foldable
import Data.Functor.Foldable.TH

data Expr  = Plus Expr  Expr
           | Mult Expr Expr
           | Const Expr
         deriving (Show, Eq)
makeBaseFunctor ''Expr
-- Write a simple evaluator
eval :: Expr -> Int
eval = cata alg
  where
    alg = \case
      PlusF  x y  -> (+) x y
      MultF  x y  -> (*) x y
      ConstF x    -> x

Now look at the case in the alg function in the where clause of eval. I think all the x and y variables
should not be necessary. Therefore I'm looking for some way (a syntax, a language extension etc.)
to remove this boilerplate and just to write:
  PlusF  -> (+)
  MultF  -> (*)
  ConstF -> id

A: https://hackage.haskell.org/package/catamorphism-0.5.1.0/docs/Data-Morphism-Cata.html derives a catamorphism for ExprF.
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE TemplateHaskell #-}

import Data.Functor.Foldable
import Data.Functor.Foldable.TH
import Data.Morphism.Cata

data Expr
  = Plus Expr Expr
  | Mult Expr Expr
  | Const Expr
  deriving (Show, Eq)
makeBaseFunctor ''Expr
$(makeCata defaultOptions ''ExprF)

-- Write a simple evaluator
eval :: Expr -> Int
eval = cata $ exprF (+) (*) id

Note that it can also derive a catamorphism for Expr, yielding eval = expr (+) (*) id and letting you skip Data.Functor.Foldable.TH for this specific usecase.

A: Alternatively you could refactor your language to have binary operations on one hand and unary ones on the other. You'd write:
data BinOp = PlusOp | MultOp deriving (Show, Eq)
data UnOp  = ConstOp deriving (Show, Eq)

data Expr  = Bin BinOp Expr  Expr
           | Un  UnOp  Expr
         deriving (Show, Eq)
makeBaseFunctor ''Expr

The evaluator then becomes:
eval :: Expr -> Int
eval = cata $ \case
  BinF op l r -> bin op l r
  UnF  op v   -> un op v
  where
    bin = \case
      PlusOp -> (+)
      MultOp -> (*)

    un = \case
      ConstOp -> id


text:
Q: Changing attribute of class does not trigger setter and printing it does not trigger getter I'm probably missing something really simple here.
I'm trying to use property() to add getter and setter functions to an attribute of MyClass.
class MyClass:
    def __init__(self, attr):
        self._attr = attr

        def attr_setter(self, value):
            print(f'Setting attr')
            self._attr = value

        def attr_getter(self):
            print('Getting attr')
            return self._attr

        self.attr = property(fget=attr_getter, fset=attr_setter)

c = MyClass('something')
print(c.attr)
c.attr = 'something else'
print(c.attr)

However, the print statements and the assignment do not trigger attr_setter and attr_getter. I get the following output:

property object at <0x0000024A26B489A0>
something else

A: Find the details in comment
class MyClass:
    def __init__(self, attr):
        #self._attr = attr --> you might want to call the setter
        self.attr_setter(attr)

    # correcting the indentation
    def attr_setter(self, value):
        print(f'Setting attr')
        self._attr = value

    def attr_getter(self):
        print('Getting attr')
        return self._attr

    attr = property(fget=attr_getter, fset=attr_setter)

c = MyClass('something')  #Setting attr
print(c.attr) #Getting attr something
c.attr = 'something else' #Setting attr
print(c.attr) #Getting attr something else

# Setting attr
# Getting attr
# something
# Setting attr
# Getting attr
# something else


text:
Q: Solr Search Suggestions I've installed the Solr server on Tomcat, and the basics work just fine - but I can not get suggestions or recommendations to work at all.  (Magento Enterprise 1.14.01 and Solr 3.6.2)
If I take the GET string that is sent to Solr from Magento and run it in a browser, I see the basic results - but no suggestions.
But if I watch the log from Tomcat, the Solr server is processing and knows about suggestions that it should return... but they are not being sent back in the response json.
Example:
What I send to Solr
http://dev.samplesite.com:8080/solr/select?sort=score+desc&stats=true&stats.field=price_0_1&qt=magento_en&fq=%28visibility%3A3+OR+visibility%3A4%29+AND+store_id%3A1&version=1.2&wt=json&json.nl=map&q=bluu&start=0&rows=0

What I receive back from Solr
{"responseHeader":{"status":0,"QTime":185,"params":{"sort":"score desc","start":"0","stats.field":"price_0_1","stats":"true","q":"bluu","json.nl":"map","qt":"magento_en","wt":"json","fq":"(visibility:3 OR visibility:4) AND store_id:1","rows":"0","version":"1.2"}},"response":{"numFound":0,"start":0,"docs":[]},"stats":{"stats_fields":{"price_0_1":null}}}

But in the Solr log, I see these two lines
Jun 02, 2014 8:49:09 PM org.apache.solr.core.SolrCore execute
INFO: [] webapp=/solr path=/select params={sort=score+desc&json.nl=map&wt=json&rows=1&version=1.2&fl=id&start=0&q=blue&qt=magento_en&fq=(visibility:3+OR+visibility:4)+AND+store_id:1} hits=1405 status=0 QTime=1
Jun 02, 2014 8:49:09 PM org.apache.solr.core.SolrCore execute
INFO: [] webapp=/solr path=/select params={sort=score+desc&json.nl=map&wt=json&rows=1&version=1.2&fl=id&start=0&q=bleu&qt=magento_en&fq=(visibility:3+OR+visibility:4)+AND+store_id:1} hits=1 status=0 QTime=8

Solr clearly knows that "blue" has 1405 results and "bleu" has 1 result... which is accurate for our catalog - but something is keeping those suggestions from being sent back to Magento in the JSON string
I'm using the default solrconfig.xml (and other conf files) from sample created by Magento in the apache lib folder.
In the Magento Config for Solr:
Enable Search Suggestions? Yes
Search Suggestion Count? 2
Show Results Count for Each Suggestion? Yes
Enable Search Recommendations? Yes
Search Recommendations Count? 5

I feel like I'm missing something very simple... any suggestions?

A: Copy these two template files to your theme
- enterprise/default/template/search/suggestions.phtml
- enterprise/default/template/search/recommendations.phtml

And make sure that these are specified in the catalogsearch.xml file
 <catalogsearch_result_index translate="label">
       ......
        <reference name="content">
            <block type="core/text_list" name="additional" translate="label">
                        <label>Additional Info</label>
                        <block type='enterprise_search/suggestions' name='search_suggestions' template="search/suggestions.phtml"></block>
                        <block type='enterprise_search/recommendations' name='search_recommendations' template="search/recommendations.phtml"></block>
                    </block>
            ........
        </reference>
    </catalogsearch_result_index>

Note: as a quick test, you can switch to the default enterprise theme and see if the (Solr)  suggestions and recommendations show up in the search results page. If so, the above changes should definitely work for your current theme.


text:
Q: Lock multiple rows using CTE and FOR UPDATE In one session, I trying to lock multiple rows in "users" table, and get "status" column for user WHERE id = 2.
do $$
declare user_status int;
begin
    WITH t(id, status) AS(
        SELECT id, status FROM users WHERE id in( 2,4,7,6) order by id FOR UPDATE
    )
    SELECT status FROM t WHERE id = 2 INTO user_status;

    -- just run transaction for a while
    FOR i in 1..2000000000 loop
    end loop;

end;
$$ language plpgsql

while this transaction is running, I run in another session this query:
UPDATE users SET some_col = some_col WHERE id = 6;

I expected that row WHERE id = 6 should locked by first transaction, but this is not true, because UPDATE in  second session runs immediately (not waiting for ending transaction in first session).
What I'm misunderstood ?
P.S.
If in first transaction, instead of CTE use:
perform id, status FROM users WHERE id in( 2,4,7,6) order by id FOR UPDATE;

Then lock works as expected.

A: I think this is due to the way that PL/pgSQL's SELECT INTO works under the hood.
The apparent underlying cause is mentioned in the docs:

if a locking clause is used in a cursor's query, only rows actually
  fetched or stepped past by the cursor will be locked.

...and this effect flows through to any CTE in the query, where rows will only be fetched (and therefore locked) when the outer query needs them.
This is pretty easy to demonstrate. First, some setup:
CREATE TABLE t (x INT);
INSERT INTO t VALUES (1),(2),(3);

This query will lock all rows, as expected:
WITH cte AS (SELECT x FROM t WHERE x IN (1,2,3) FOR UPDATE)
SELECT x FROM cte WHERE x = 1

However, this will produce the behaviour you observed, locking only the first record:
DECLARE c CURSOR FOR
  WITH cte AS (SELECT x FROM t WHERE x IN (1,2,3) FOR UPDATE)
  SELECT x FROM cte WHERE x = 1;
FETCH NEXT FROM c;

My guess is that a SELECT INTO in PL/pgSQL operates in much the same way; as mentioned in the docs, if the query returns multiple rows, then the first row is assigned to the target variable, and the rest are ignored (so there is never a need for it to fetch more than one record).
This statement, however, will lock all rows in t:
DO $$
DECLARE i INT;
BEGIN
  WITH cte AS (SELECT x FROM t WHERE x IN (1,2,3) FOR UPDATE)
  SELECT x FROM cte WHERE x = 1 INTO STRICT i;
END
$$ LANGUAGE plpgsql;

Note the use of SELECT INTO STRICT. The STRICT keyword causes an error to be thrown if multiple rows are returned by the query. But in order to discover that a second row was returned, PL/pgSQL must attempt to fetch it, which causes the CTE query to fetch the remaining records (locking them in the process).
All of this is a non-issue most of the time in a PL/pgSQL function, as you'd typically fetch all records from a FOR UPDATE query, and pass them along to whoever is actually updating them. On the other hand, if you want a query's side-effects but aren't interested in its output, then (as you observed) you can use PERFORM, which will run a query to completion, but discard the results.
In the rare case where you need to (i.e. lock) all rows, while only returning a subset of them, you'll probably need to write your own loop.


text:
Q: Group values of a chosen column into a list when creating a dictionary from a pandas data frame with a non-unique index I have a dataframe that looks like his
_____________________
|col1 | col2 | col3 |
---------------------
| a   | b    | c    |
| d   | b    | c    |
| e   | f    | g    |
| h   | f    | j    |
---------------------

I want to get a dictionary structure that looks as follows
{
    b : { col1: [a,d], col2: b, col3: c},
    f : { col1: [e, h], col2: f, col3: [g, j]}
}

I have seen this answer. But it seems like overkill for what I want to do as it converts every value of the key inside the nested dictionary into a list. I would only like to convert col1 into a list when creating the dictionary. Is this possible?

A: Use custom lambda function for return unique values in list if there is multiple them else scalar in lambda function:
d = (df.set_index('col2', drop=False)
       .groupby(level=0)
       .agg(lambda x: list(set(x)) if len(set(x)) > 1 else list(set(x))[0])
       .to_dict('index'))
print (d)
{'b': {'col1': ['d', 'a'], 'col2': 'b', 'col3': 'c'},
 'f': {'col1': ['h', 'e'], 'col2': 'f', 'col3': ['j', 'g']}}

If order is important use dict.fromkeys for remove duplicates:
d = (df.set_index('col2', drop=False)
       .groupby(level=0)
       .agg(lambda x: list(dict.fromkeys(x)) if len(set(x)) > 1 else list(set(x))[0])
       .to_dict('index'))
print (d)
{'b': {'col1': ['a', 'd'], 'col2': 'b', 'col3': 'c'},
 'f': {'col1': ['e', 'h'], 'col2': 'f', 'col3': ['g', 'j']}}


text:
Q: Hide widgets/plugins from dashboard I have two plugins in the dashboard, SEO Wordpress and Custom Content Type Manager, and for security reasons I want to hide these from dashboard. How to do that?
I tried to hide the SEO Wordpress with this:
// Remove Admin Dashboard menus
 function wp_admin_dashboard_remove_menus() {
     global $menu;
     $restricted = array(('Comments'), __('Users'), __('Updates'), __('wpseo_dashboard'));
     end ($menu);
     while (prev($menu)){
         $value = explode(' ',$menu[key($menu)][0]);
         if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){
             unset($menu[key($menu)]);
         }
     }
 }

 add_action('admin_menu', 'wp_admin_dashboard_remove_menus');

Tried many combinations like:
__('wpseo')
__('wp-seo')
__('wp_seo')

But the SEO menu did not hide.

A: Wordpress SEO
If you want to remove the admin menu:

you can do that with:
function hide_wpseo() {
       remove_action('admin_menu', 'zeo_options_menu');
}
add_action( 'init', 'hide_wpseo');

where it will be removed for all users.
WordPress SEO by Yoast
To hide the admin menu:

and the admin menu bar:

one can use:
function hide_yoastseo() {
    remove_action('admin_bar_menu', 'wpseo_admin_bar_menu',95);
    remove_menu_page('wpseo_dashboard');
}
add_action( 'admin_init', 'hide_yoastseo');

where it will be hidden for all users.
Custom Content Type Manager
Here one can hide the admin menu:

from all users with:
function hide_cctm() {
    remove_menu_page('cctm');
}
add_action('admin_init', 'hide_cctm');

A: Do you want to hide it for a specific kind of user like an author? If so, you can use the Advanced Access Manager plugin http://wordpress.org/extend/plugins/advanced-access-manager/
With this plugin you can decide what the user(group) has access to in the backend and also what permissions he/she has.

A: For removing plugin's menu from multisite dashboard
foreach($GLOBALS[ 'menu' ] as $key => $value) {

    remove_menu_page($value[2]);

}

For adding menu use add_menu_page();


text:
Q: Save html to a new directory automatically - Rmarkdown I have created a .RMD file that can be used to analyze different data sets. However, I am not able to automate the way to export this data in an html that contains a different name depending on the embedded dataset. For example, if I analyze the data set "Data1.csv", I would like to create a folder called "Data1" and put inside all the files resulting from running the script, and the generated html with the name "Data1.html". But if I then load the "Data2.csv" file, I would like to generate a new folder called "Data2" and a new html (Data2.html) that is saved in the "Data2" folder. Does anyone know if it's possible to do this in rmarkdown?
Thanks!


text:
Q: Is Coldfusion more than a presentation technology? I've been looking recently at Coldfusion for an upcoming job. My background is in ASP.net/MVC and JSP/Servelets.
From what I can tell, Coldfusion is mostly a presentation technology that interfaces with a business layer implemented in some other technology. For the trivial cases, it also looks like you can go straight from the markup to the database much like PHP.
I know this is probably a simplistic view of the product. So what more does it do and what is the business case for using Coldfusion over more heavily hyped web technologies like ASP.net/JSP?

A: You can definitely write your business layer in ColdFusion, and as you say you can extend that with easy hooks to java and .net objects.
The business case for ColdFusion is that it is a rapid application development platform - the speed that you as a developer can get things done is just insane. There is a lot of built-in functionality, from MS Exchange integration, charting, Excel generation, all the way through to a Hibernate ORM implementation (new in CF9).
There are a few popular, mature MVC frameworks (Model-Glue, Coldbox, Fusebox, onTap, etc) that you can work with, or you can run up your own framework using a pattern that suits your style.
What might be confusing you is that you can choose to write the presentation layer and business layer in ColdFusion tags, and that might be why you think it's not a powerful option for the business layer. CF tags wrap a lot of functionality in an easy to use syntax, but with CF9 you have the option to write ColdFusion Components (CFCs) completely with a script based syntax - that might help you distinguish between presentation (tags) and business logic (script).
The developer edition is free to try, so you really only are losing some time if you give it a go, and I highly recommend you check it out.

A: Riding on Antony's suggestions, he forgot to mention another MVC framework, ColdFusion on Wheels! We're rapidly approaching a 1.0 release by next month and have an active community developing a slew of plugins. With built a ORM that follows Rails' design, it's easy to pick up. Check it out and give us some feedback.


text:
Q: Not able to figure out why state is empty while writing unit tests in Jest I've a react component which I'm trying to unit test via Jest.
My component looks like this:
export class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            expandModal: false
        };
        this.setExpandModal = this.setExpandModal.bind(this);
    }

    setExpandModal(expandModal) {
        this.setState({expandModal});
    }

    render() {
        const {expandModal} = this.state;
        return (
            <Container>

                    <Modal
                        show={expandModal}
                        onHide={() => this.setExpandModal(false)}
                    >
                        <Modal.Header>
                            <Modal.Title> Title </Modal.Title>
                        </Modal.Header>
                        <Modal.Body>

Some body!

                        </Modal.Body>

                <Row>
                    <Col>
                        <Button id={"show-modal-button"}
                            onClick={() => this.setExpandModal(true)}
                        >Show Modal
                        </Button>
                    </Col>
                </Row>

            </Container>
        )
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

My test file:

it("closing modal sets state to false", function () {
    const wrapper = mount(<Provider store={store}>
        <MyComponent/>
    </Provider>
    );

    const button = wrapper.find("#show-modal-button").first();
    button.simulate("click");

    const modal = wrapper.find(Modal);
    expect(modal.prop("show")).toBe(true);
    modal.invoke("onHide")();
    expect(wrapper.state("expandModal")).toBe(false);
});

I get an error saying that state shouldn't be null or undefined. When I log inside MyComponent it shows the state does get updated, but I'm not able to figure out why my tests aren't able to get
the updated state. I tried using wrapper.update() but that didn't help either.


text:
Q: How to hit Web Service Based on WSDL Here is the WSDL
http://cc93161263da499cb8f0e0e0b2bcc5a9.cloudapp.net/Service1.svc?wsdl
How can I get to the GetHello service
I tried
http://cc93161263da499cb8f0e0e0b2bcc5a9.cloudapp.net/Service1.svc/GetHello
But I receive a bad request error....
Any thoughts...

A: Easiest would be to use VS to generate a client proxy based on the WSDL (Add a Service Reference to your project).
Regarding the error: it could be because you're not passing in an input parameter... looks like there is a blank sequence.  Or that your browser is sending in accepts parameters that don't match what the server expects (soap).
See this for command line generation without VS:
http://cc93161263da499cb8f0e0e0b2bcc5a9.cloudapp.net/Service1.svc?help


text:
Q: How to fix bizarre incorrect Laravel routing? I am building a simple website in Laravel 6. I used the built in Laravel artisan tools to create authentication routes and views.
After logging in, a user should be redirected to /home. However, every now and then Laravel will redirect to /js/popper.js.map
I have no idea why Laravel is doing this! I have scoured error logs, to no avail. I am using Bootstrap, but I never explicitly told Laravel to import or use Popper. I have no idea why it specifically wants to go this specific file?? I've had this problem for weeks.
Sometimes running php artisan config:cache and cache:clear help, but not always. Furthermore, it sometimes will happen on my remote server, or on local, but often not at the same time, making it very hard to debug.
I have declared the Auth routes with the built in Laravel Auth. Like so:
php artisan ui bootstrap
And in web.php:
Auth::routes();
I expect logging in to redirect to /home, which then redirects to welcome/red (part of my software). Instead, it gets stuck at js/popper.js.mapand 404s. Logging in WORKS, and I can access authenticated content. But it's a bad user experience to get stuck in a 404 page for no reason.
Does anyone have any clue where Laravel is getting the idea to redirect to /js/popper.js.map? Thank you!!!!

A: I've never had this issue. Maybe you could start with a simple controller and view? Without any assets and packages loaded? From that point add packages and assets one by one. You should find your bug. And did you write any tests? That should help a lot!
And I assume this popper.js file is loaded by a npm package? Maybe it helps to uninstall it?


text:
Q: Wrong area calculation with geosphere:: areaPolygon? I have used geosphere::areaPolygon() with success many times but now I have encountered an issue.
I have a polygon sp2 containing another polygon sp1. So sp2 should have larger area than sp1. When I calculate each area with areaPolygon(), I get the opposite result.
areasp1 = 10133977
 areasp2 = 9858811
I used gSymdifference to find the symmetrical different polygon sp3, which has
areasp3 = 275165.4
sp1 : red dashed line
sp2 : black line
sp3 : green dotted line

Code I used:
library(sp)
library(geosphere)
library(rgeos)
library(raster)

s1 <- data.frame(lon= c(130.4327, 129.85127, 121.00775, 84.9176, 60.40123,
58.97929, 58.55841, 94.95237),lat= c(30.25074, 29.83075, 23.7992, 28.25964,
36.89905, 37.72305, 52.58793, 43.47459))

s2 <- data.frame(lon= c(130.4327, 129.85127, 121.00775, 54.35377, 58.55841,
94.95237),lat= c(30.25074, 29.83075, 23.7992, 31.61798, 52.58793, 43.47459))

sp1 <- SpatialPolygons(list(Polygons(list(Polygon(s1)),1)))
crs(sp1) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

sp2 <- SpatialPolygons(list(Polygons(list(Polygon(s2)),1)))
crs(sp2) <-CRS ("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")

areasp1 <- areaPolygon(sp1)/10^6    # to get area in square km
areasp2 <- areaPolygon(sp2)/10^6

sp3 <- gSymdifference(sp1,sp2,checkvalidity = TRUE)
areasp3 <- areaPolygon(sp3)/10^6

All polygons were tested for self-intersections or other issues with gIsValid(), so it has nothing to do with the problem mentioned here.
Any idea on why sp1 has larger area than sp2?
Note: If you sum areasp2 + areasp3, it almost equals areasp1. I don't know if this is by chance.

A: This is nice illustration of how things aren't always what they seem when you treat angular coordinates as if they were planar. Your plot assumes straight line connections between nodes. That would be reasonable if the coordinates were planar. But they are not, and that makes all the difference in this case.
Below I redraw the plot with the raw data and after adding vertices following the shortest distance between the nodes. You can see that object 2 is much smaller than it seems.
library(raster)
library(geosphere)

s1 <- cbind(lon= c(130.4327, 129.85127, 121.00775, 84.9176, 60.40123, 58.97929, 58.55841, 94.95237),lat= c(30.25074, 29.83075, 23.7992, 28.25964, 36.89905, 37.72305, 52.58793, 43.47459))
s2 <- cbind(lon= c(130.4327, 129.85127, 121.00775, 54.35377, 58.55841, 94.95237),lat= c(30.25074, 29.83075, 23.7992, 31.61798, 52.58793, 43.47459))
sp1 <- spPolygons(s1, crs="+proj=longlat +datum=WGS84")
sp2 <- spPolygons(s2, crs="+proj=longlat +datum=WGS84")

# add nodes on shortest path
mp1 <- makePoly(sp1, interval=100000)
mp2 <- makePoly(sp2, interval=100000)

# background countries for map
library(maptools)
data(wrld_simpl)
w <- crop(wrld_simpl, extent(mp2) + 40)

plot(w, col='light gray')
points(s2, pch=20, cex=3)
points(s1, pch=20, cex=2, col='gray')

lines(sp2, col='red', lwd=3)
lines(sp1, col='blue', lwd=1)
lines(mp2, col='red', lwd=4, lty=2)
lines(mp1, col='blue', lwd=2, lty=2)

legend("bottomright", c('sp1', 'mp1', 'sp2', 'mp2'), col=rep(c('blue', 'red'), each=2), lwd=rep(c(2,3), each=2), lty=c(1, 2))

You can perhaps better appreciate this by projecting the coordinates to a planar reference system.
library(rgdal)
crs <- CRS("+proj=ortho +lat_0=40 +lon_0=90 +a=6370997 +b=6370997 +units=m")
ww <- spTransform(w, crs)
sp1x <- spTransform(sp1, crs)
sp2x <- spTransform(sp2, crs)
mp1x <- spTransform(mp1, crs)
mp2x <- spTransform(mp2, crs)

par(mai=c(0,0,0,0))
plot(ww, col='light gray')
lines(sp2x, col='red', lwd=3)
lines(sp1x, col='blue', lwd=1)
lines(mp2x, col='red', lwd=4, lty=2)
lines(mp1x, col='blue', lwd=2, lty=2)

The shortest route between Isfahan and Taipei does not go across Nepal.


text: Q: MongoDB and PostgreSQL audit I am new to Database Administration and have been asked to prepare data for an audit for both Mongodb and PostgreSQL, and I'm not sure where to begin.  Is there some sort of Checklist or a way to have the full information for the audit ?


text:
Q: Debugging Program I am nearly done with my program. Problem is, I have having some slight trouble with the debugging with the pointers. I would like some help on how I can fix it. Note that I do require all of my function prototypes sadly. (Assignment would have been much easier if I could do everything in main though...)
#include <stdio.h>
#include <stdlib.h>

#define STUDENTS 5

int getData(int *student, char *pass, int *hw1, int *hw2, int *hw3, int *hw4,
             int *hw5, int *hw6, int *hw7, int *mid1, int *mid2, int *final,
             int *extra);
float calcAvg(float *total);
float printTable(int student, float total);

int main(void)

{
    int student[STUDENTS];
    char pass[STUDENTS];
    int hw1[STUDENTS], hw2[STUDENTS], hw3[STUDENTS], hw4[STUDENTS], hw5[STUDENTS], hw6[STUDENTS], hw7[STUDENTS];
    int mid1[STUDENTS], mid2[STUDENTS];
    int final[STUDENTS];
    int extra[STUDENTS];
    float total[STUDENTS];

    getData(student, pass, hw1, hw2, hw3, hw4, hw5, hw6, hw7,
            mid1, mid2, final, extra);
    calcAvg(total);
    printTable(student, total);

system("pause");
return 0;
}

int getData(int *student, char *pass, int *hw1, int *hw2, int *hw3, int *hw4,
             int *hw5, int *hw6, int *hw7, int *mid1, int *mid2, int *final,
             int *extra)
{
    FILE *fpIn;
    int i;

    fpIn = fopen("data.txt", "r");
    if (!fpIn)
    {
        printf("File does not exist.");
        system("pause");
        exit (101);
    }

    for (i=0; i<STUDENTS; i++)
    {
        fscanf(fpIn, "%d", &student[i]);
        fscanf(fpIn, "%c", &pass[i]);
        fscanf(fpIn, "%d %d %d %d %d %d %d", hw1[i], hw2[i], hw3[i], hw4[i], hw5[i], hw6[i], hw7[i]);
        fscanf(fpIn, "%d %d", mid1[i], mid2[i]);
        fscanf(fpIn, "%d %d", final[i], extra[i]);
    }

    return;
}

float calcAvg(float *total)
{
    int hwtotal[STUDENTS], midtotal[STUDENTS];
    int i;

    for (i=0; i<STUDENTS; i++)
    {
        hwtotal[i] = hw1[i]+ hw2[i]+hw3[i]+hw4[i]+hw5[i]+hw6[i]+hw7[i];
        midtotal[i] = mid1[i]+mid2[i];
        total[i] = (hwavg[i]+midavg[i]+final[i]+extra[i])/3;
    }

    return total;
}

float printTable(int student, float total)
{
    int i;

    printf("==== ======= =======\n");
    printf(" ID   Score   Grade\n");
    printf("==== ======= =======\n");

    for(i=0; i<STUDENTS; i++)
    {
        printf("%d .1f  ", student[i], total[i]);

        if (total>90)
        printf("A\n");
        else if(total>80);
        printf("B\n");
        else if (total>70);
        printf("C\n");
        else if (total>60);
        printf("D\n");
        else
        printf("F\n");
    }

    return;
}

A: I suggest you create an struct to encapsulate all the information of a student instead of having different arrays for each data you are storing.
struct{
   int studentId;
   char pass;
   int hw[7]
   int mid[2];
   int final;
   int extra;
   float total;
} student;

 student mystudents[STDENTS];

Whatever your problem is, it will be easier to detect with more compact data structures that will ease also if must make any changes.

A: Well, you didn't describe your problem, but it looks like this part may cause issues.
int getData(...) {
    ...
    fscanf(fpIn, "%d %d %d %d %d %d %d", hw1[i], hw2[i], hw3[i], hw4[i], hw5[i], hw6[i], hw7[i]);
    fscanf(fpIn, "%d %d", mid1[i], mid2[i]);
    fscanf(fpIn, "%d %d", final[i], extra[i]);
    ...
}

You are passing ints to fscanf which expects int *s. You did the right thing earlier with
fscanf(fpIn, "%d", &student[i]);
fscanf(fpIn, "%c", &pass[i]);


text:
Q: fopen() seems not work when I create a daemon process Here is my main source code:
int main(int argc, char *argv[]) {
    [...]

    if (become_daemon(0) == -1) {
        exit(EXIT_FAILURE);
    }

    while (main_loop == LOOP_CONTINUE) {
        [...]

        if (log_data(date_temp, data_processed) < 0) {
            [...]
        } else {
            [...]
        }
        sleep(measure_rate);
    }
    [...]
}

Here my functions definitions:
int become_daemon(int flags) {
    int maxfd, fd;

    switch (fork()) {
      case -1:
        return -1;
      case 0:
        break;
      default:
        exit(EXIT_SUCCESS);
    }

    if (setsid() == -1)
        return -1;

    switch (fork()) {
      case -1:
        return -1;
      case 0:
        break;
      default:
        exit(EXIT_SUCCESS);
    }

    if (!(flags & BD_NO_MASK0))
        umask(0);

    if (!(flags & BD_NO_CHDIR))
        chdir("/");

    if (!(flags & BD_NO_CLOSE_FILE)) {
        maxfd = sysconf(_SC_OPEN_MAX);
        if (maxfd == -1)
            maxfd = BD_MAX_CLOSE;

        for (fd = 0; fd < maxfd; fd++)
            close(fd);
    }

    if (!(flags & BD_NO_REOPEN_STD_FDS)) {
        close(STDIN_FILENO);

        fd = open("/dev/null", O_RDWR);

        if (fd != STDIN_FILENO)
            return -1;
        if (dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO)
            return -1;
        if (dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO)
            return -1;
    }
    return 0;
}

int log_data(char *date, double array_data[DATA_NUM]) {
    FILE *file;

    if ((file = fopen(DATALOG_FILE, "a")) == NULL)
        return -1;

    fprintf(file, "%s ; %.2f ; %.2f ; %.2f ; %.2f ; %.2f ; %.2f\n",
            date, array_data[0], array_data[1], array_data[2],
            array_data[3], array_data[4], array_data[5]);

    fclose(file);

    return 0;
}

and here is my problem:
when I compile my code with the become_daemon() function active and then I  execute the program, the file DATALOG_FILE (it's a define for "xxxxxx.txt") it's not created. If I compile without the become_daemon() function call, the program works fine and the file is created.
I even noticed that if I add the line
sudo /my/folder/program

in the rc.local to run it at the boot, it starts like I want but, even in these case, it does not create the file DATALOG_FILE.
I'm newbie with daemon process so can anyone tell me the cause of this behavior?

A: As Ctx mentioned in his comment, the function become_daemon may change the current directory to /.  If DATALOG_FILE is a relative filename, such as "xxxxxx.txt" as you write in the question, the daemon will fail to create it in the system root directory, unless it has root privileges.
Either do not change the current directory by passing BD_NO_CHDIR as an argument to become_daemon or make DATALOG_FILE an absolute path.


text:
Q: My video goes off the screen, but stays within it's UIView I have a UIView that has an aspect ratio of 16:9 with constraints set up accordingly. However, the video stays within the UIView but half of it goes off the screen. Anyone know how to fix this? Just to clarify I am trying to create a video inside a UIView.
import Foundation
import UIKit
import AVKit
import AVFoundation

class WallPush: UIViewController {

@IBOutlet weak var videoView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textView: UILabel!

var player: AVPlayer?

override func viewDidLoad() {
    super.viewDidLoad()

    // Load video resource
    if let videoUrl = Bundle.main.url(forResource: "WallPush", withExtension: "mp4") {

        if #available(iOS 10.0, *) {
            player?.playImmediately(atRate: 1.0)
        } else {
            // Fallback on earlier versions
        }
        // Init video
        self.player = AVPlayer(url: videoUrl)
        self.player?.isMuted = true
        self.player?.actionAtItemEnd = .none

        // Add player layer
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
        playerLayer.frame = videoView.bounds

        // Add video layer
        self.videoView.layer.addSublayer(playerLayer)

        // Play video
        self.player?.play()

        // Observe end
        NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
    }
}

// MARK: - Loop video when ended.
@objc func playerItemDidReachEnd(notification: NSNotification) {
    self.player?.seek(to: CMTime.zero)
    self.player?.play()
}

}

A: You need to put the line inside
override func viewDidLayoutSubviews() {
   super.viewDidLayoutSubviews()
   playerLayer.frame = videoView.bounds
}

Also inside viewDidLoad set
self.videoView.clipsToBounds = true

and declare
var playerLayer:AVPlayerLayer!

then
playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect

 class WallPush: UIViewController {

    @IBOutlet weak var videoView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var textView: UILabel!

    var player: AVPlayer?

    var playerLayer:AVPlayerLayer!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Load video resource
        if let videoUrl = Bundle.main.url(forResource: "WallPush", withExtension: "mp4") {
            print("File exists")
            if #available(iOS 10.0, *) {
                player?.playImmediately(atRate: 1.0)
            } else {
                // Fallback on earlier versions
            }
            // Init video
            self.player = AVPlayer(url: videoUrl)
            self.player?.isMuted = true
            self.player?.actionAtItemEnd = .none
            videoView.clipsToBounds = true
            // Add player layer
            playerLayer = AVPlayerLayer(player: player)
            playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
            playerLayer.frame = videoView.bounds  // you can comment it

            // Add video layer
            self.videoView.layer.addSublayer(playerLayer)

            // Play video
            self.player?.play()

            // Observe end
            NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
        }
        else {
            print("File not exists")
        }
    }

    override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      playerLayer.frame = videoView.bounds
    }

    // MARK: - Loop video when ended.
    @objc func playerItemDidReachEnd(notification: NSNotification) {
        self.player?.seek(to: CMTime.zero)
        self.player?.play()
    }

}


text:
Q: Cocos2d and Pyglet installation non-functional After installing both by moving them into the Lib folder of my python installation, I get this error when trying to import cocos.
Traceback (most recent call last):
  File "C:/Users/test/PycharmProjects/Testing/main.py", line 1, in <module>
    import cocos
  File "C:\Python34\lib\cocos\__init__.py", line 69, in <module>
    import os, pyglet
  File "C:\Python34\lib\pyglet\__init__.py", line 276
    print '[%d] %s%s %s' % (thread, indent, name, location)
                   ^
SyntaxError: invalid syntax

A: You are using Python 3, but attempting to use Python 2's print statement. In Python 3 the print statement was changed to a print function. Try:
print('[%d] %s%s %s' % (thread, indent, name, location))

You can also use a newer way to format strings in Python 3:
print('{:0d} {}{} {}'.format(thread, indent, name, location))


text:
Q: How can I get my python script to read all values from a config file? I have a couple of config files. One with some team names and the other with positions. Each one of my users will upload a file with teams and positions on them. The teams and positions must match what's in the config files otherwise an error will print. I can get the script to read only one value from each config file. It doesn't read the rest of the values. How can I get it to read all of the values in the config files?
Here are the two config files:
for teams:
    [Teams]
    teams = Barcelona, Bayern, Inter, Chelsea
for positions:
[Positions]

positions = striker, midfielder, defender, goalkeeper

Here is a sample text file:
Teams   Positions   User ID
Barcelona   goalkeeper  BCTG-F
Barcelona   striker BCTG-F
Bayern  defender    BCTG-F
Bayern  striker    BCTG-F
Inter   striker    BCTG-F
Inter   midfielder  BCTG-F
Chelsea midfielder  BCTG-F
Chelsea goalkeeper  BCTG-F

Here is the script:
#!usr/bin/python

from subprocess import *

import sys
import ConfigParser
import os
import csv
from sys import argv
script, user_id, team_file = argv

def main():

    #get the actions

    def teamCalls():
        actions = ConfigParser.SafeConfigParser()
        actions.read('/etc/nagios/ingestion/team.cfg')
        for section_name in actions.sections():
            for name, value in actions.items(section_name):

                return '%s' %(value)

    teamCalls()

   #get the object types

    def positionTypes():
        objects = ConfigParser.SafeConfigParser()
        objects.read('/etc/nagios/ingestion/position.cfg')
        for section_name in objects.sections():
            for name, value in objects.items(section_name):

                return '%s' % (value)

    positionTypes()

    # checking path to file and user id
    try:
            f = csv.reader(open(team_file, "rb"), delimiter='\t')
    except:
            logging.error('No such file or directory. Please try again')
    else:
            for line in f:
                for row in f:
                    if user_id != row[2]:
                        print ("User ID is incorrect")
                    elif teamCalls() != row[0]:

                        print ("Wrong team")
                    elif positionTypes() != row[1]:
                        print ("Position not valid")

                    else:
                        print row

    finally:
        print "all error checks done!"

main()

sys.exit(0)

A: You have "return" on the inner most statement of your loops.  This will cause it to return immediately, without looping through the rest of the values.  If you want a list of values, you could do something like:
calls = []
for section_name in actions.sections():
    for name,value in actions.items(section_name):
       calls.append(str(value))  # same as '%s' % (value)
return calls

A: How about that?
for line in open('team.cfg','r'):
    list_fu = [ column for column in line.split() ]
    print(list_fu)
Output:
['Teams', 'Positions', 'User', 'ID']
['Barcelona', 'goalkeeper', 'BCTG-F']
['Barcelona', 'striker', 'BCTG-F']
['Bayern', 'defender', 'BCTG-F']
['Bayern', 'striker', 'BCTG-F']
['Inter', 'striker', 'BCTG-F']
['Inter', 'midfielder', 'BCTG-F']
['Chelsea', 'midfielder', 'BCTG-F']
['Chelsea', 'goalkeeper', 'BCTG-F']

if you want to read in those positions, you should now the column of the list EG -> Positions, so it is 1. now you catch the Teams and User with if conditions:
for line in list_fu[1]:
    if line == 'goalkeeper':
        print(line) #do what you want to do


text:
Q: Aggregate result in mongoDB with calculation I'm working under MongoDb database and I have this collection :
What I have ?
{
Name : "David",
Type : "First",
Score : 1.66
}

{
Name : "David",
Type : "Second",
Score : 0.66
}

{
Name : "Naim",
Type : "First",
Score : 0.33
}

{
Name : "Naim",
Type : "Second",
Score : 0.10
}

{
Name : "Joe",
Type : "First",
Score : 1.10
}
{
Name : "Joe",
Type : "Second",
Score : 2
}

What I want ?
I want to aggregate result in this way :
{
Name : "David",
Type : "First",
Score : 1.66 / ( 0.33 + 1.10 ) // first scores for other documents
}

{
Name : "David",
Type : "Second",
Score : 0.66 / ( 0.10 + 2 ) // second scores for other documents
}

And the same for other Names ...
Please How can I achieve the above ?

A: As this looks like an easy solution for sql world (where we have CTE expressions), then using mongo we could utilise $lookup phase to simulate CTE.
First we calculate sum per test group, then join results on source, and using some arithmetic operations in $project phase, we calculate result.
db.dp.aggregate([{
            $group : {
                _id : "$Type",
                "SumScore" : {
                    $sum : "$Score"
                }
            }
        }, {
            $lookup : {

                from : "dp",
                localField : "_id",
                foreignField : "Type",
                as : "lookUp"
            }
        }, {
            $unwind : "$lookUp"
        }, {
            $project : {
                _id : 0,
                "Name" : "$lookUp.Name",
                "Type" : "$_id",
                "Score" : {
                    $divide : ["$lookUp.Score", {
                            $subtract : ["$SumScore", "$lookUp.Score"]
                        }
                    ]
                }
            }
        }
    ])

and the output:
{
    "Name" : "David",
    "Type" : "First",
    "Score" : 1.16083916083916
}

{
    "Name" : "Naim",
    "Type" : "First",
    "Score" : 0.119565217391304
}

{
    "Name" : "Joe",
    "Type" : "First",
    "Score" : 0.552763819095477
}

{
    "Name" : "David",
    "Type" : "Second",
    "Score" : 0.314285714285714
}

{
    "Name" : "Naim",
    "Type" : "Second",
    "Score" : 0.037593984962406
}

{
    "Name" : "Joe",
    "Type" : "Second",
    "Score" : 2.63157894736842
}


text:
Q: Proving a mapping from a higher dimension to a lower dimension is continuous? How does one show a mapping is continuous from a higher dimension to a lower dimension. For example:
Let f : $\mathbb{R}^2$ $\rightarrow$ $\mathbb{R}$, (x,y) $\rightarrow$ x. How would you show this is continuous.
My attempt was to use the definition of continuous:
That is: f is continuous at $x_0 \in$ its domain if and only if for every $\epsilon$ > 0, there exists a $\delta$ > 0 such that for all x $\in$ its domain A, d(x,$x_0$) < $\delta$ implies $\gamma$(f(x),f($x_0$)) < 0.
So set y = $y_0$ and then the proof should be vascuous. However, I feel that there is something wrong with this approach.

A: Let $z_0=(x_0,y_0)$ be an arbitrary point in the domain. Let $\epsilon>0$.
We need to exhibit $\delta>0$ such that for all $z=(x,y)$ with $d(z,z_0)<\delta$ we have $d(f(z),f(z_0))<\epsilon$. Here we have the Euclidean metric on $\Bbb R^2$, i.e., $d(z,z_0)=\sqrt{(x-x_0)^2+(y-y_0)^2}$ and the standard metric on $\Bbb R$, i.e., $d(f(z),f(z_0))=|x-x_0|$.
As $$\sqrt{(x-x_0)^2+(y-y_0)^2}\ge \sqrt{(x-x_0)^2}=|x-x_0|$$
we see that we can simply pick $\delta=\epsilon$.

A: You have $$0 \le \vert x \vert \le \sqrt{x^2 +y^2}.$$ Now take $\epsilon > 0$, for $x^2 + y^2 \le \epsilon^2$ you have $0 \le \vert x \vert \le \epsilon$ allowing you to conclude that $\delta = \epsilon^2$ is convenient for the $\epsilon$-$\delta$ proof.


text:
Q: How to register a variable in one role and use it in another one in Ansible? I am trying to register a variable in a role and then use it in another one.
Here are the different files I'm using :
playbook.yml
---
- hosts: hostsgroup1
  [...]
  roles:
    - role1
- hosts: 127.0.0.1
  connection: local
  roles:
    - role2

role1/tasks/main.yml
- name: Example 1
  [...]
- name: Example 2
  shell:
    qm agent {{ VM_id }} network-get-interfaces |grep ip-address |grep '172.20' |grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'
  register: var_role1

role2/tasks/main.yml
- name: Adding server to bastion
  ansible.builtin.debug:
    msg : Test {{ var_role1.stdout }}

For the information, the qm agent command gives me an IP address and I want to use it in the second role. But obviously, for now it displays an error when I execute the playbook :
fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: \"hostvars['proxmoxhosts']\" is undefined\n\nThe error appears to be in '/root/ansible/roles/bastion_add/tasks/main.yml': line 3, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n# tasks file for bastion_add\n- name: Adding server to bastion\n  ^ here\n"}

To summarize, I want to use var_role1, registered in role1, in role2.

A: set_fact should do the trick.
- name: Example 2
  shell:
    qm agent {{ VM_id }} network-get-interfaces |grep ip-address |grep '172.20' |grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'
  register: var_role1
- set_fact:
    var_role1: "{{ var_role1.stdout }}"


text:
Q: Usage of the pipe " | " in a less calculation So I have found the following codepen that i am using within a project i am currently working on.
I have implemented the code for the most part, however I am not familiar with the usage of the LESS preprocessor and so am trying to convert the styles to SCSS instead.
I am only struggling to convert the following line of code from LESS to SCSS:
transform: rotate(unit(`(Math.random()*8*(Math.random()-0.5)|0+1)*0.25`, turn));

Specifically the area of the line i am stuggling with is the usage of the | operator between the -0.5) | 0+1
Can anybody explain to me what the purpose of this is and how i may go about converting is to a SCSS fiendly alternative since my SCSS linter throws an error at this line.
Thanks in advance.


text:
Q: Regex to match a string based on particular character count It is not a duplicate question, other questions are about the repetition of a regex and my question is how can we get/limit a particular character count in regex for validation, I am looking for a regex to match a string only when the string has the count of character ' as 1.
Example:
patt = #IDontKnow
s = "Shubham's"
if re.match(patt, s):
    print ("The string has only ONE '")
else:
    print ("The String has either less or more than ONE ' count")

A: Why not just use .count()?
s = "Shubham's"
if s.count("\'") == 1:
    print ("The string has only ONE '")
else:
    print ("The String has either less or more than ONE ' count")

A: I guess what you are looking for is this:
import re
pat = "^[^\']*\'[^\']*$"
print (re.match(pat, "aeh'3q4'bl;5hkj5l;ebj3'"))
print (re.match(pat, "aeh3q4'bl;5hkj5l;ebj3'"))
print (re.match(pat, "aeh3q4bl;5hkj5l;ebj3'"))
print (re.match(pat, "'"))
print (re.match(pat, ""))

Which gives output:
None
None
<_sre.SRE_Match object; span=(0, 21), match="aeh3q4bl;5hkj5l;ebj3'">
<_sre.SRE_Match object; span=(0, 1), match="'">
None

What "^[^\']*\'[^\']*$" does?
^ matches the beginning of string
[^\']* - * matches 0 or more characters from set defined in []. Here, we have a set negated using ^. The set is defined as one character - ', which is escaped so it looks \'. Altogether, this group matches any number of any characters except '
\' - matches one and only character '
$ - matches end of the string. Without it partial matches would be possible which could contain more ' characters. You can compare with above:
print (re.match("^[^\']*\'[^\']*", "aeh'3q4'bl;5hkj5l;ebj3'"))

<_sre.SRE_Match object; span=(0, 7), match="aeh'3q4">


text:
Q: EF TPT inheritance mapping issue with one to one relationship I'm trying to configure a one to one relationship between entities which both have an inheritance hierarchy.
For the sample, let's considered the following first inheritance chain :
[Table("A")]
public abstract class A
{
    public Guid ID { get; set; }
    ...
}

[Table("AA")]
public class AA : A
{
    ...
}

[Table("AB")]
public class AB : A
{
    ...
}

Then, considered this second inheritance chain :
[Table("B")]
public abstract class B
{
    public Guid ID { get; set; }
}

[Table("BA")]
public class BA : B
{
    ...
}

[Table("BB")]
public class BB : B
{
    ...
}

Add a one to one relationship between AA and BA with AA as principal entity :
[Table("AA")]
public class AA : A
{
    ...
    public BA BAChild { get; set; }
    ...
}

[Table("BA")]
public class BA : B
{
    ...
    public AA Parent { get; set; }
    ...
}

public class AAConfiguration : EntityTypeConfiguration<AA>
{
    public AAConfiguration()
    {
        this.HasRequired(o => o.BAChild)
            .WithRequiredPrincipal(o => o.Parent);
    }
}

Add a one to one relationship between AB and BB with AB as principal entity :
[Table("AB")]
public class AB : A
{
    ...
    public BB BBChild { get; set; }
    ...
}

[Table("BB")]
public class BB : B
{
    ...
    public AB Parent { get; set; }
    ...
}

public class ABConfiguration : EntityTypeConfiguration<AB>
{
    public ABConfiguration()
    {
        this.HasRequired(o => o.BBChild)
            .WithRequiredPrincipal(o => o.Parent);
    }
}

I also want that EF generates tables for entities A and B so I have added and registered the following empty EntityTypeConfiguration :
public class AConfiguration : EntityTypeConfiguration<A>
{

}

public class BConfiguration : EntityTypeConfiguration<B>
{

}

If you run the code like this you will get a bug during index creation (saw Unhandled Exception after Upgrading to Entity Framework 4.3.1)
So let's do some tricky code and register a custom MigrationSqlGenerator derived from SqlServerMigrationSqlGenerator to avoid index creation based on my business naming rule :
public class Configuration : DbMigrationsConfiguration<DataContext>
{
    public Configuration()
    {
        ...
        this.SetSqlGenerator("System.Data.SqlClient", new CustomSqlServerGenerator());
        ...
    }
}

public class CustomSqlServerGenerator : SqlServerMigrationSqlGenerator
{
    protected override void Generate(CreateIndexOperation createIndexOperation)
    {
        if (createIndexOperation.Columns.Count() == 1 && createIndexOperation.Columns.Any(o => o == "ID"))
            return;

        base.Generate(createIndexOperation);
    }
}

public class DataContext : DbContext
{
    static DataContext()
    {
        Database.SetInitializer<DataContext>(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
    }

    ...
}

So now it's time to generate the database, to make it, I use the following code :
...
DataContext dataContext = new DataContext();
dataContext.Database.Initialize(true);
...

And now if you look at the generated database you will saw that both table BA and BB has a foreign key for the table AB and that there is no foreign key between BA and AA !?!
I am probably missing something but I can't see what's wrong with this sample.
What can be done to generate the database properly ?

A: After doing some deep search throughout reflector it seems that this behavior is an EntityFramework bug.
I've located the problem in System.Data.Entity.ModelConfiguration.Configuration.Mapping.ForeignKeyPrimitiveOperations in the following function :
    private static void UpdatePrincipalTables(DbDatabaseMapping databaseMapping, DbTableMetadata toTable, bool removeFks, EdmAssociationType associationType, EdmEntityType et)
    {
        ...
    }

When EntityFramework loads the model, the DbDatabaseMapping instance is loaded with the base types and the foreign key constraints are added to the base types metadatas.
EntityFramework also store an instance of EdmAssociationType in the annotations of the foreign key constraint to maintain all the required informations to generate the correct constraint.
Latter, when the derived types are added and configured in the DbDatabaseMapping instance, EntityFramework tries to update the related end of the associations to move the foreign key constraints on the derived tables.
To identify the foreign key constraints to update the following selector is used where tableInfo.Value is an IEnumerable containing the dependent columns for the foreign key :
fk => fk.DependentColumns.SequenceEqual<DbTableColumnMetadata>(tableInfo.Value);

Unfortunately, in my case for the relation between AA and BA and for the relation between AB and BB the column "ID" is used.
So, both of them are updated a first time to replace the principal table metadata by AA metadata and a second time by AB metadata.
As a consequence, both of the foreign key are generated with AB as principal table !
I think that the EdmEntityType passed in the function parameters should be used in the selector to be compared to the entity type of the relationship end stored in the foreign key constraint annotations.


text:
Q: Ld magically overrides statically linked symbols For a few days we are dealing with very strange problem.
I can't understand how it even happens - when a third-party (MATLAB) program uses our shared library, it somehow overrides some of our symbols (boost, to be precise) with it's own. Those symbols are statically linked and (!!) local.
Here is the deal - we use boost 1.47, MATLAB has boost 1.40. Currently, library call segfaults on a call from OUR library to their boost (regex).
So, here is the magic:

*

*We have no library dependencies, ldd:

    linux-vdso.so.1 =>  (0x00007fff4abff000)
    libpthread.so.0 => /lib/libpthread.so.0 (0x00007f1a3fd65000)
    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f1a3fa51000)
    libm.so.6 => /lib/libm.so.6 (0x00007f1a3f7cd000)
    libgomp.so.1 => /usr/lib/libgomp.so.1 (0x00007f1a3f5bf000)
    libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f1a3f3a8000)
    libc.so.6 => /lib/libc.so.6 (0x00007f1a3f024000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f1a414f9000)
    librt.so.1 => /lib/librt.so.1 (0x00007f1a3ee1c000)

*

*No Cxx symbols (our public symbols are POC C for binary compatibility) are exported from our library, nm:

nm -g --defined-only libmysharedlib.so

addr1 T OurCSymbol1
addr2 T OurCSymbol2
addr3 T OurCSymbol3
...

*

*Still, it uses their boost. HOW? Stacktrace (paths cut):

[  0] 0x00007f21fddbb0a9 bin/libmwfl.so+00454825 fl::sysdep::linux::unwind_stack(void const**, unsigned long, unsigned long, fl::diag::thread_context const&)+000009
[  1] 0x00007f21fdd74111 bin/glnxa64/libmwfl.so+00164113 fl::diag::stacktrace_base::capture(fl::diag::thread_context const&, unsigned long)+000161
[  2] 0x00007f21fdd7d42d bin/glnxa64/libmwfl.so+00201773
[  3] 0x00007f21fdd7d6b4 bin/glnxa64/libmwfl.so+00202420 fl::diag::terminate_log(char const*, fl::diag::thread_context const&, bool)+000100
[  4] 0x00007f21fce525a7 bin/glnxa64/libmwmcr.so+00365991
[  5] 0x00007f21fb9eb8f0 lib/libpthread.so.0+00063728
[  6] 0x00007f21f3e939a9 libboost_regex.so.1.40.0+00342441 boost::re_detail::perl_matcher, std::allocator > >, boost::regex_traits > >::match_all_states()+000073
[  7] 0x00007f21f3eb6546 bin/glnxa64/libboost_regex.so.1.40.0+00484678 boost::re_detail::perl_matcher, std::allocator > >, boost::regex_traits > >::match_imp()+000758
[  8] 0x00007f21c04ad595 lib/libmysharedlib.so+04855189 bool boost::regex_match, std::allocator > >, char, boost::regex_traits > >(__gnu_cxx::__normal_iterator, __gnu_cxx::__normal_iterator, boost::match_results, std::allocator > > >&, boost::basic_regex > > const&, boost::regex_constants::_match_flags)+000245
[  9] 0x00007f21c04a71c7 lib/libmysharedlib.so+04829639 myfunc2()+000183
[ 10] 0x00007f21c01b41e3 lib/libmysharedlib.so+01737187 myfunc1()+000307

It's known, that MATLAB does dlopen with RTLD_NOW flag only.
People, think with me please.
Now i'm desperate not to even fix this, but to simply understand ld&elf behavior.
edit:
Small additional question: how i understood, without special linker options, symbols in linux .so libraries are never linked by address? So even statically linked local symbols are resolved in runtime?

A: Check out the -Bsymbolic option for ld.
If -Bsymbolic is specified, then at the time of creating a shared
object ld will attempt to bind references to global symbols to definitions
within the shared library.  The default is to defer binding to runtime.
This may be clearer with an example.
Say example.o contains a reference to a global function defined in
global.o,
$ nm example.o | grep ' U'
     U _GLOBAL_OFFSET_TABLE_
     U globalfn
$ nm global.o | grep ' T'
00000000 T globalfn

and two shared objects, normal.so and symbolic.so, are built as
follows:
$ cc -fPIC -c example.c
$ cc -c global.c
$ rm -f archive.a; ar cr archive.a global.o
$ ld -shared -o normal.so example.o archive.a
$ ld -Bsymbolic -shared -o symbolic.so example.o archive.a

Disassembling the code for normal.so shows that the call to
globalfn is actually going through the procedure linkage table, and
thus the final destination of the call is determined at runtime.
$ objdump --disassemble normal.so
...snip...
00000194 <example>:
...snip...
 1a6:   e8 d9 ff ff ff          call   184 <globalfn@plt>
...snip...
$ readelf -r normal.so

Relocation section '.rel.plt' at offset 0x16c contains 1 entries:
Offset     Info    Type            Sym.Value  Sym. Name
00001244  00000207 R_386_JUMP_SLOT   000001b8   globalfn

Whereas in symbolic.so, the call always invokes the definition of
globalfn within the shared object.
$ objdump --disassemble symbolic.so
...snip...
0000016c <shared>:
...snip...
 17e:   e8 0d 00 00 00          call   190 <globalfn>
...snip...
$ readelf -r symbolic.so

There are no relocations in this file.

A:
Here is the deal - we use boost 1.47, MATLAB has boost 1.40. Currently, library call segfaults on a call from OUR library to their boost (regex).

You are invoking undefined behavior, which is a "Doctor, it hurts when I do this" kind of situation. The Matlab executable already contains external functions for class boost::re_detail::perl_matcher< elided >. When Matlab loads your shared library the dynamic linker sees that your shared library defines those exact same symbols in a way that conflicts with the existing definitions. Undefined behavior.
The solution is to build a version of your library for use with Matlab that uses the same version of Boost as does Matlab.


text:
Q: racism VS the racism
There are other reasons for the racism: the legacy of fascism and
  the continuing adulation of Benito Mussolini; the tangible insecurity,
  even sense of inferiority, of many Italians; widespread economic
  misery for at least the last decade; and a political class that is
  absurdly ignorant. But perhaps the most interesting explanation for
  racism comes from an Italian mate of mine who's an armchair anthropologist.

I know that notions like racism do not take a definite article unless that notion is well referred to in a context. Then why is the first occurrence of racism in this fragment preceded by the, and the second one is not? If, on the one hand, the first occurrence of racism is about the racism in Italy, the second one seems to me to be about the racism in Italy, as well. On the other hand, if racism was used notionally, then both occurrences of the word should have been preceded by no the. Either way, racism in this fragment, whether it is about racism in general or the racism in Italy, should have been used uniformly. So my question is: why wasn't it?

A: The use of the definite article the here indicates that the thing in question (racism) has been defined and scoped previously. In this case, the headline of the article is "Why is Italy still so racist?", and the first paragraph of the article contains examples of racist behavior in Italy. When the second paragraph says "[t]he racism isn't restricted to right or left," therefore, it should be understood as referring specifically to racism in Italy, the subject of the article, rather than to racism as a general phenomenon. Other uses of "the racism" throughout the article, such as the one you mention, serve a similar function.
To look at it another way, consider the difference between

The Smiths own two Toyotas, but Mr. Smith says he doesn't care for the cars.

and

The Smiths own two Toyotas, but Mr. Smith says he doesn't care for cars.

One is specific, the other is unspecific.

A: I would guess that particular instances or types of racism in Italy have already been mentioned prior to the beginning of the excerpt - is this correct? If so, it is this racism that is being addressed with "the racism". Later, the writer is referring to racism in general (but still in Italy), not just the particular type/instances of racism referred to previously.

A: In the first case, "the" has been used to indicate to the (high)magnitude of racism in Italy (to emphasise the gravity of "racism" in Italy). In the second case, there is no need to reiterate the same idea again (once the idea of the magnitude of racism is conveyed to readers, it is implied that racism refers to "the racism" only-if the editors start becoming pedantic (fuss over perfection) news won't be able to reach us on time). I am in no way insinuating that racism has been wrongly used. Both the cases refers to racism in Italy. "The" is used like an adjective in the first case like "The great Gatsby". "The" distinguishes racism in Italy from racism in other parts of the world and suggests it has superior form of racism than rest of the world.


text:
Q: Regression F-test without the raw data How can I perform an F-test in regression (H0: all coefficient are zero) without having the original data?
Y=XB+eps
I have the X'X, b, and e'e and I know the n and k of course.

A: I found the answer in the Greene's econometrics book, page 159.


text:
Q: Blur all the objects(Images,div,text..) that comes behind a div tag Need your help.
I created a static semi-opaque banner which stays at the top of a website. When a user scrolls the website the entire container objects goes underneath the banner. I want all the objects (images, text..etc) getting blury effect as it goes underneath the banner.
Thanks

A: This isn't possible with CSS nor jQuery. You might be able to do something with IE's filters, however that's IE only (of course), and will invalidate your CSS.
Currently, there is no way to do this, although something might come along in CSS 4 or something.
The Chrome nightly builds support some filters, however there isn't an alpha blur filter (yet, at least).

A: The only way you're going to be able to do this is by getting fancy with some CSS and javascript.  CSS doesn't support blur directly, but you can emulate it with text-shadow.  Images can also be blurred with a little jquery/css/javascript magic, but will be problematic because you can't partially blur an image (what happens when only part of the image is under the banner?).  It could probably be done by layering your images and keeping track of their position on screen, but all of this seems like a lot of work for a very small return.
So, assuming you've decided to give all of this a shot, you're going to have to use javascript to determine which parts of the page have passed under the banner and apply the style to those parts.  The difficulty of this task will scale with the complexity of your page layout.  In a best case scenario, your banner and content container are both 100% the width of the html body.  At this point, it would be fairly trivial to write some kind of scanner that traverses the dom every time you page scroll to find elements that the blur should be applied to.  However, best-case-scenario is rarely the case at hand, at which point I'd recommend abandoning the effort to pursue something with a greater ROI.


text:
Q: I lost current head branch in git When I switch from Develop branch to a previously submitted, the head branch is my current branch,but the branch is not shown in my branch list
(CMD: git branch).
When I finished some work,I don't be careful switch directly to Develop branches,oh my God,I lost these changes, how can I find just the part of change?

A: You can use git reflog to identify where your working copy was previously.  Once you've identified the relevant commit, you can just do git checkout <commit> to get back to it.

A: Use the reflog to find out what happened and then recover to that point

git reflog
You can always use the reflog as well.
git reflog  will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.
Every time the HEAD is modified there will be a new entry in the reflog
git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

How to find and restore added content (even if it was not commited )
Use the git fsck to find out about all the lose object (dangling) and then you can check them out with the git cat-file -p <sha-1> and restore them.

A: git reflog
git checkout HEAD@{...}
Thank you all.


text:
Q: Python PIllow Tkinter - How to edit a photo twice without losing the previous change? How do I edit a photo without losing previous edits? Below is my code.
After uploading a photo and pressing the blur button, the photo blurs, but if I then press rotate, the blurring of the photo disappears. How do I keep the result of both effects?
Do I have to save the photo to a separate file after using each function?
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter.filedialog import askopenfilename,asksaveasfilename
from PIL import Image, ImageTk, ImageFilter, ImageEnhance, ImageOps
import os

my_w = Tk()
my_w.geometry("1000x1000")  # Size of the window
my_w.title('Photo Editing Tool')

def upload_image():
    global img_path, img
    img_path = filedialog.askopenfilename(initialdir=os.getcwd())
    img = Image.open(img_path)
    img.thumbnail((350, 350))
    img = ImageTk.PhotoImage(img)
    canvas2.create_image(300, 210, image=img)
    canvas2.image=img

def rotate_image():
    global img_path, img
    img = Image.open(img_path)
    img.thumbnail((350, 350))
    img = img.rotate(90)
    img = ImageTk.PhotoImage(img)
    canvas2.create_image(300, 210, image=img)
    canvas2.image = img

def blur():
    global img_path, img
    img = Image.open(img_path)
    img.thumbnail((350, 350))
    img = img.filter(ImageFilter.BLUR)
    img = ImageTk.PhotoImage(img)
    canvas2.create_image(300, 210, image=img)
    canvas2.image = img

canvas2 = Canvas(my_w, width="600", height="420", relief=RIDGE, bd=2)
canvas2.place(x=15, y=150)

btn_select = Button(my_w, text="Select Image", bg='white', fg='black',
              font=('ariel 15 bold'), relief=GROOVE, command=upload_image)
btn_select.place(x=100, y=595)

btn_blur = Button(my_w, text="Blur Image", bg='white',fg='black',
                    font=('ariel 15 bold'), relief=GROOVE, command=blur)
btn_blur.place(x=250, y=595)

btn_rotate = Button(my_w, text="Rotate Image", bg='white',fg='black',
                    font=('ariel 15 bold'), relief=GROOVE, command=rotate_image)
btn_rotate.place(x=400, y=595)

my_w.mainloop()

A: the reason why the previous change is lost is because each of your functions is reading the image again from disk, and while saving it back to disk temporarily is what some image processing applications do to prevent loss of work on power outage, you can simply work from memory for the application by hand.

*

*define a variable to hold the image, in you case it is img

*when user selects image the image will be loaded from disk and saved in that variable

*when user applies an effect, it will be applied to the image in memory, the image won't be read from disk again.

*before drawing make another variable the PhotoImage from img and draw it to screen, but don't overwrite img while drawing.

*if you add a save button, it only have to save img as it will already be in memory.

img = None
img_path = None

def upload_image():
    global img_path, img
    img_path = filedialog.askopenfilename(initialdir=os.getcwd())
    img = Image.open(img_path)
    img.thumbnail((350, 350))
    photo_img = ImageTk.PhotoImage(img)
    canvas2.create_image(300, 210, image=photo_img)
    canvas2.image = photo_img

def rotate_image():
    global img
    img = img.rotate(90)
    photo_img = ImageTk.PhotoImage(img)
    canvas2.create_image(300, 210, image=photo_img)
    canvas2.image = photo_img

def blur():
    global img
    img = img.filter(ImageFilter.BLUR)
    photo_img = ImageTk.PhotoImage(img)
    canvas2.create_image(300, 210, image=photo_img)
    canvas2.image = photo_img


text:
Q: Mysql PHP Query select I want to order desc some rows from mysql table by a numberic value .
Such as: SELECT * FROM table ORDER BY ABS(row1) DESC.
Table format:

ID | Type | Value
1  | 2 | 42
2  | 1 | 52
3  | 2 | 67
4  | 2 | 50
5  | 1 | 15
6  | 1 | 27
7  | 3 | 48
8  | 3 | 23

And i want to get the following result - to sort by value DESC but first show rows with type 2 and DESC and after that the type 1,3,4 (...) rows DESC:

ID | Type | Value
3  | 2 | 67
4  | 2 | 50
1  | 2 | 42
2  | 1 | 52
7  | 3 | 48
6  | 1 | 27
9  | 3 | 23
5  | 1 | 15

A: you can sort by two or more fields
SELECT * FROM table ORDER BY ABS(row1), row2, row3 DESC

A: This is the order by you want:
order by `type` = 2 desc,
         value desc

The expression type = 2 returns a boolean value, which is equivalent to 1 when true and 0 when false.  Your example doesn't have negative values, so I don't see a need for abs().


text:
Q: object segmentation with bwlabel I have a binary image and I am interested to do segmentation only in the characters that appear in the horizontal central line, because applying bwlabel on the whole image returns 80 objects to me, but I am interested the only in characters whose pixels appear in the center line.
if I apply bwlabel to the central subimg line, I get 9 objects, of these I have to discard the first character that is on the left, of the remaining 9-1, I have to select the N (f.e N=6) those that have the largest area ( sorting and selection).
I did something like:
% Ib1 = binaryImage;

off = height / 2;
Ib2 = Ib1 (off-2: off + 2, :);
[Ietiq, NumObj] = bwlabel (Ib2);

stats = regionprops (Ietiq, 'Area', 'Centroid');
areas_matlab = cat (1, stats.Area);
centroid_matlab = cat (1, stats.Centroid);
areas_matlab = sort (areas_matlab, 'descend');

I don't know how to select only the largest N objects and segment these objects, detected by the horizontal center line (only a part of the pixels that make up the character) on the initial image Ib1.
thanks to those who will be able to help me

A: Matlab's 'sort' function has a second argument that provide an array of the elements' indices describing the arrangement of the sorted elements. You can slice it by N to get the desired N largest connected components out of regionprops.
it should look like this :
[areas_matlab, ii] = sort (areas_matlab, 'descend')
N=6;
max_n_stats=stats(ii(1:N));

EDIT:
To visualize the result - add the 'PixelIdxList' feature to regionprops function call and draw the selected characters:
Ib22 = zeros(size(Ib2));
for ii=1:N
    Ib22(max_n_stats(ii).PixelIdxList) = ii;
end

Ib11 = zeros(size(Ib1));
Ib11(off-2: off + 2) = Ib22;


text:
Q: Importing an image file, adding it to an ArrayList, and then displaying the images sequentially I'm trying to import an image file using JFileChooser add the image to an ArrayList. Then finally have display the images sequentially on a JPanel when a button is pressed.  Does anyone know how I could do this?  I'm new to java.
Thanks!

A: Break it down into steps.
Task 1: Import an image file using JFileChooser.
Get the file object chosen
Use ImageIO.read(file) to get a buffered image.
Task 2: Add image to an array list
List<BufferedImage> images = new ArrayList<BufferedImage>()
images.add(image);

Task 3: Display an image in a JPanel
JPanel p = new JPanel();
JButton button = new JButton();
ImageIcon icon = new ImageIcon(images.get(0));
button.setIcon(icon);

p.add(button);

Task 4: Adding buttons that advance through your images
JButton advance = new JButton();
advance.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    advanceImage();
  }
};


text:
Q: bash script - print from line N to EOF I want to be able to print the number of lines from bash as such:
Line number (as counted from the top) -> end of the file
It seems tail will only count lines from the bottom.
Does anyone know how to do this? Thanks.
I've tried the following
# Where $1 is the file I'm reading in

# Get line number of error:
LINENUM=$( grep -n "$LAST_ERROR_DATE" $1 | egrep $LOG_THRESHOLD | grep $LAST_HOUR: | sed 's/:/ /g' | awk '{print $1}' | head -n 1 )

echo $LINENUM

# This returns 995

# Print everything from linenumber downwards
MESSAGE=$( awk 'NR >= $LINENUM' $1 )

This works when I manually pop in 995 to awk instead of $LINENUM, it doesn't seem to read in my bash variable. Any ideas?

A: Use tail -n +X filename to print from the Xth line to end of file.

A: Single quotes '' mean, "use this exact string." They do not substitute variable names with their values. So that's why you have to manually write in 995. Does that help?

A: Use sed -n 'N,$p' filename to print from the Nth line to the end of file.

A: womble's answer is the best one, but to solve your problem with the variable in the last line, you can use awk's variable-passing feature:
MESSAGE=$( awk -v linenum=$LINENUM 'NR >= linenum' $1 )

A: alternate:
line=10
file=/path/to/file
sed -n $line,\$p $file


text:
Q: Php object not converting to array Actually i am not able to convert php object to array and specially when i have other access specifier.
for example:
<?php

class Foo
{
    public $bar = 'barValue';
    protected $baz = 'bazValue';
    private $tab = 'tabValue';
}

$foo = new Foo();

$arrayFoo = (array) $foo;

echo "<pre>";
var_dump($arrayFoo);

and output is:
array(3) {
  ["bar"]=>
  string(8) "barValue"
  ["*baz"]=>
  string(8) "bazValue"
  ["Footab"]=>
  string(8) "tabValue"
}

so i am not able to get the key with its name, it automatic added * (for protected) and class name (for private),

A: You can use function mentioned in comments for get_object_vars PHP documentation:
function obj2array ( &$Instance ) {
    $clone = (array) $Instance;
    $rtn = array ();
    $rtn['___SOURCE_KEYS_'] = $clone;

    while ( list ($key, $value) = each ($clone) ) {
        $aux = explode ("\0", $key);
        $newkey = $aux[count($aux)-1];
        $rtn[$newkey] = &$rtn['___SOURCE_KEYS_'][$key];
    }

    return $rtn;
}


text:
Q: Null pointer exception when onPageFinished() called in Android? When a webpage is called through webview, null pointer exception is being thrown on onPageFinished().  The problem persists only on Android 2.3, its working fine on Android 4.1. This is my code:
    public class StoreLocatorActivity extends Activity {

    // Declare WebView
    WebView storeLocator;
    final StoreLocatorActivity activity = this;

    boolean homeUrl = false;

    // Declare MenuItems
    MenuItem homeItem;
    MenuItem locationsItem;
    MenuItem preQualifyItem;
    MenuItem productsItem;
    MenuItem logOutItem;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
                Window.PROGRESS_VISIBILITY_ON);
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.activity_store_locator);

        setTitle("");

        // Changes to ActionBar
        /*ActionBar bar = getActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.LTGRAY));
        bar.setDisplayShowHomeEnabled(false);// This prevent icon from being
                                                    // displayed on ActionBar
*/
        callHome();
        //logOutItem.setVisible(false).setEnabled(false);
    }

    public void callHome() {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);

        storeLocator = (WebView) findViewById(R.id.storeLocator);
        storeLocator.setWebViewClient(new WebViewClient());
        //storeLocator.getSettings().setJavaScriptEnabled(true);
        // storeLocator.getSettings().setBuiltInZoomControls(true);
        storeLocator.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                progressDialog.show();
                progressDialog.setProgress(0);
                activity.setProgress(progress * 1000);

                progressDialog.incrementProgressBy(progress);

                if (progress == 100 && progressDialog.isShowing())
                    progressDialog.dismiss();
            }
        });

        storeLocator.loadUrl(getResources().getString(R.string.home));
        //storeLocator.loadUrl("http://192.168.0.24/EMG/Login.aspx");

        storeLocator.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {

                if (url.equals(getResources().getString(R.string.accounts))||url.equals(getResources().getString(R.string.accountsalt))) {
                    homeUrl = true;
                    System.out.println("in here!!!!!!");
                    logOutItem.setVisible(true).setEnabled(true);
                    preQualifyItem.setVisible(false).setEnabled(false);

                } else
                    logOutItem.setVisible(false).setEnabled(false);
                System.out.println("Changed url is " + url);
                super.onPageFinished(view, url);

            }
        });

    }

Menu ITems instantiation:
 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_store_locator, menu);
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    homeItem = menu.findItem(R.id.home);
    locationsItem = menu.findItem(R.id.location);
    preQualifyItem = menu.findItem(R.id.preQualify);
    productsItem = menu.findItem(R.id.products);
    logOutItem = menu.findItem(R.id.logOut);
    // logOutItem = menu.findItem(R.id.logOut);

    return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case R.id.home:

        locationsItem.setIcon(R.drawable.locations72);
        preQualifyItem.setIcon(R.drawable.prequalify72);
        productsItem.setIcon(R.drawable.products72);
        // logOutItem.setVisible(true);

        item.setIcon(R.drawable.homeb);

        final ProgressDialog homeDialog = new ProgressDialog(this);
        homeDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        homeDialog.setCancelable(false);

        storeLocator = (WebView) findViewById(R.id.storeLocator);
        storeLocator.setWebViewClient(new WebViewClient());
        //storeLocator.getSettings().setJavaScriptEnabled(true);
        // storeLocator.getSettings().setBuiltInZoomControls(true);
        storeLocator.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                homeDialog.show();
                homeDialog.setProgress(0);
                activity.setProgress(progress * 1000);

                homeDialog.incrementProgressBy(progress);

                if (progress == 100 && homeDialog.isShowing())
                    homeDialog.dismiss();
            }
        });
...........................................

This is exception:
05-02 14:06:42.632: E/AndroidRuntime(320): Uncaught handler: thread main exiting due to uncaught exception
05-02 14:06:42.672: E/AndroidRuntime(320): java.lang.NullPointerException
05-02 14:06:42.672: E/AndroidRuntime(320):  at com.emg.emgstorelocator.StoreLocatorActivity$2.onPageFinished(StoreLocatorActivity.java:117)
05-02 14:06:42.672: E/AndroidRuntime(320):  at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:242)
05-02 14:06:42.672: E/AndroidRuntime(320):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-02 14:06:42.672: E/AndroidRuntime(320):  at android.os.Looper.loop(Looper.java:123)
05-02 14:06:42.672: E/AndroidRuntime(320):  at android.app.ActivityThread.main(ActivityThread.java:4363)
05-02 14:06:42.672: E/AndroidRuntime(320):  at java.lang.reflect.Method.invokeNative(Native Method)
05-02 14:06:42.672: E/AndroidRuntime(320):  at java.lang.reflect.Method.invoke(Method.java:521)
05-02 14:06:42.672: E/AndroidRuntime(320):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-02 14:06:42.672: E/AndroidRuntime(320):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-02 14:06:42.672: E/AndroidRuntime(320):  at dalvik.system.NativeStart.main(Native Method)

Unable to figure out reason for exception.


text:
Q: anyway to configure a URL prefix for prestosql web UI Given prestosql cluster started and listens to localhost:8080, I found it redirects request to http://localhost:8080/ui/
> curl -v http://localhost:8080/
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0
> Accept: */*
> Referer:
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 303 See Other
< Date: Thu, 02 Jul 2020 14:07:10 GMT
< Location: http://localhost:8080/ui/
< Content-Length: 0

Is there anyway to support a prefix like /prestosql so that it can redirect request from /prestosql to /prestosql/ui instead of /ui/?
The scenario is about using a gateway in front of prestosql then routing requests via URL rewrite. E.g., Nginx/HAProxy or Istio virtual service.

A: It is not possible and would require quite some work, since Presto's UI HTML and javascript code and expects various resources available at /ui/... path.
See previous discussion at https://github.com/prestosql/presto/issues/3706


text:
Q: How to query subcollection inside transaction in firebase? I have a subcollection named requests inside my root collection tradeRequests
I want to query my requests subcollection using transactions in firebase
This code below will fail because Transaction.get() requires its first argument to be a DocumentReference
const getOne = (itemID) => db.runTransaction(async (transaction) => {
  const tradeRequestItemRef = tradeRequestsRef.doc(itemID);
  const requestsRef = tradeRequestItemRef.collection('requests');

  const rawTradeRequestItem = await transaction.get(tradeRequestItemRef);

  if (!rawTradeRequestItem) return null;

  // something like this ???
  // But this line will break everything
  // Error: Transaction.get() requires its first argument to be a DocumentReference
  const rawRequests = transaction.get(requestsRef);

  return {
    ...normalizeData(rawTradeRequestItem),
    requests: normalizeData(rawRequests),
  };
});

A: As explained in the doc on "Transaction serializability and isolation" for Firestore, the mobile/web SDKs (iOS, Android, Web, C++) use optimistic concurrency controls.
The doc explains that:

The transaction keeps track of all the documents you read inside the
transaction ... and completes its write operations only if none of
those documents changed during the transaction's execution. If any
document did change, the transaction handler retries the transaction.
If the transaction can't get a clean result after a few retries, the
transaction fails due to data contention.

So the risk of having too many data contention failures when keeping track of all the documents returned by a Query is considered too high, therefore the mobile/web SDKs do not give the possibility to execute a Query in a Transaction.

On the other hand, the Admin SDKs use pessimistic concurrency controls, therefore you can execute a query within a Transaction and place a  pessimistic lock on all the documents returned by the Query. So one solution is to use a Callable Cloud Function (which uses the Admin SDK) and call this Cloud Function from your Client.
More concretely, you would use, in your Cloud Function, the get() method from the Node.js Server SDK for Google Cloud Firestore, which can be passed a Query and will hold a pessimistic lock on all returned documents.

A: In the web and mobile client SDKs, you can't transact on the results of a query within that same transaction. You can only get() each document individually using a DocumentReference.  So, what you can do instead is perform the query first, then get() each individual document reference from that query in the transaction to make sure it is being operated on atomically.
// query for requests before the transaction
const requests = await db.collection("requests").get()

await db.runTransaction(async transaction => {
    // get each document individually again in the transaction
    const requestsInTransaction = []
    for (const doc of requests.docs) {
        const requestInTransaction = await transction.get(doc.ref)
        requestsInTransaction.push(requestInTransaction)
    }

    // Work with each document as needed...
    return whatever_you_want
})

Note that if the results of the original query change during the transaction, any new or removed documents will not be seen by the transaction.


text:
Q: replacing failed HDD in Lacie 2big I have a Lacie 2big Network, 2 x 1 TB in mirror. One of them failed 3 days ago. It produces a clicking sound, the Raid status shows endless "Synchronizing".
If I buy a new HDD, same type, and replace in the failed slot, will the new empty drive synchronize with old functioning drive?
Or do I have to reformat the whole unit after replacing 1 drive? I want to know if I am going to lose the data on the functioning drive in the process?

A: I'm assuming you're doing RAID 1, if you replace the drive with the exact model as as the other drive - it will rebuild the array and clone the data from the existing hard drive.


text:
Q: Establishing a persistent connection in Android For one of the screens in my android application, I need to listen to server indeterminately - ie; I have few fields in the screen whose values change continuously so long the screen is kept open. The values to be updated will be provided by the server continuously. I understand that normal http connection would not be a solution here. Also, I do not wish to make continuous http requests owing to performance reasons. What is the best way out in order to accomplish this.Is GCM Cloud Connection Server a good solution for my requirement. Or are there better solutions? Please advise.
Any help is much appreciated.

A: I think there are a two options.  If you don't own the server yourself I would start a service to run in the background and bind to it.  The service would poll the server at some time interval depending upon how often you want the values to update.  The activity would then receive periodic updates and update the views.  Given that the information that you're updating is really not all that large, updates every 30s to a minute wouldn't take a toll on performance at all since all of the work would be done in an asynchronous task.
Using an AlarmManager to accomplish this.
If you own the server then you could implement the GCM model, and only send updates when data changes.  This is assuming that every user of the app would get the same set of updates of course.
Introduction to GCM

A: Keeping screen on could be battery consuming. If you own the server the changes can be pushed to the app using the GCM service.
As far as I understand, GCM bundles push messages from several server trying to push the messages together and hence is an optimised way to communicate.
Alternatively, you can bring up a server which can keep polling the original server and push the changes to the app through GCM.


text:
Q: Repeat Column data on each Page I want to Repeat my Column data on each page when i export on PDF
I am using RDLC Reporting my report generated in Landscape now i want to show my Student Name Column data on each page or multiple page..
is there any solution ?


text:
Q: AttributeError: 'NoneType' object has no attribute 'geq' I am trying to do a multiprocessing in a python script by importing the below module
from multiprocessing import Process,Manager,Queue

I am trying to run the scripts in the list [1.py,2.py] . During execution one script is successful and other fails both have some dataframe to read .Not sure why it fails .Function used inside the script :
func1 :
f=df.where((df[a] >= dat1) & (df[b] <= dat2)) .

df : is a dataframe
I want these scripts to be run one by one and not exit out after one script is succesfull . Any Examples or pointers


text:
Q: Convert English to logic How to write the following sentence using propositional logic:
Only monkeys properly appreciate the value of art.
Is this good:
Let $M(x)$ be '$x$ is a monkey' and $A(x)$ be '$x$ properly appreciates the value of art', where the domain of $x$ is the set of all animals.
In this case, $\forall x\ A(x) \rightarrow M(x)$ or $\forall x\ A(x) \iff M(x)$?

A: You seem right, but you may want to formulate it as follows to reflect the nature of the question: If $x$ properly appreciates art, then $x$ is a monkey AND if $x$ is not a monkey, then $x$ does not appreciate art, but this latter statement is just the contrapositive of the previous statement which takes the form $(\forall x)(A(x)\to M(x))$. Thus, I do not see any issue with your formulation.