Modelling congestion games in python without tons of for loop

Question: In the bidirected triangle network as shown below, 4 agents $\{s1,s2,s3,s4\}$ have their own destination $\{t1,t2,t3,t4\}$. I am trying to model this problem with a python script without any game theory library as a challenge.

Since the cost of most of the edges (except edge $vu$ and $wu$) depend on the number of agents using it, I need to know all the strategy for all agents before getting the final cost of each edge.
So my algorithm outlines as:

Loop the strategy of agent 1, add cost to the edges he used
Inside the previous loop, loop the strategy of agent 2, add cost to the edges he used
Inside the previous loop, loop the strategy of agent 3, add cost to the edges he used
Inside the previous loop, loop the strategy of agent 4, add cost to the edges he used
After knowing all their strategy, add calculate the cost for each agent
Before exploring alternative strategy, remove 1 cost on the edge that has given up by the agent who's changing his strategy.
Repeat step 1-6

Shown below is my python script, but you can see I have 1 for loop for 1 agent. It would be difficult for me to try 10 agents in the future. Anyway to improve the algorithm?
# Initializing Paraemeters
agent_dict = {
    'agent1': [['uv'], ['uw','wv']],
    'agent2': [['uw'], ['uv','vw']],
    'agent3': [['vw'], ['vu','uw']],
    'agent4': [['wv'], ['wu', 'uv']],
}

# Variables
uv = 0
uw = 0
wv = 0
vw = 0

path_to_cost = {
'uv': uv,
'uw': uw,
'wv': wv,
'vw': vw,
'vu': 0,
'wu': 0
}

cost_list = []
strategy_set = []

for path1 in agent_dict['agent1']:

    for edge1 in path1: # Step 1
        if edge1 == 'vu' or edge1 == 'wu':
            pass
        else:
            path_to_cost[edge1]+=1

    for path2 in agent_dict['agent2']: # Step 2
        for edge2 in path2:
            if edge2 == 'vu' or edge2 == 'wu':
                pass
            else:
                path_to_cost[edge2]+=1

        for path3 in agent_dict['agent3']: # Step 3
            for edge3 in path3:
                if edge3 == 'vu' or edge3 == 'wu':
                    pass
                else:
                    path_to_cost[edge3]+=1

            for path4 in agent_dict['agent4']: # Step 4
                for edge4 in path4:
                    if edge4 == 'vu' or edge4 =='wu':
                        pass
                    else:
                        path_to_cost[edge4]+=1

                # Step 5
                cost1 = [path_to_cost[x] for x in path1]
                cost2 = [path_to_cost[x] for x in path2]
                cost3 = [path_to_cost[x] for x in path3]
                cost4 = [path_to_cost[x] for x in path4]
                social_cost = sum(cost1) + sum(cost2) + sum(cost3) + sum(cost4)
                cost_list.append(social_cost)
                strategy_set.append([path1,path2,path3,path4])
                print('agent1 is using {}, agent2 is using {}, agent3 is using {}, and agent4 is using {}'.format(path1,path2,path3,path4))
                print('agent1 costs {}, agent2 costs {}, agent3 costs {}, agent4 is using {}'.format(cost1,cost2,cost3,cost4))
                print('Social cost = {}\n'.format(social_cost))

                        # Step 6: Resetting cost for each agent for next trial
                for edge4 in path4: # resetting agent 4 strategy
                    if edge4 == 'vu' or edge4 =='wu':
                        pass
                    else:
                        path_to_cost[edge4]-=1

            for edge3 in path3:
                if edge3 == 'vu' or edge3 == 'wu':
                    pass
                else:
                    path_to_cost[edge3]-=1

        for edge2 in path2:
            if edge2 == 'vu' or edge2 == 'wu':
                pass
            else:
                path_to_cost[edge2]-=1

    for edge1 in path1:
        if edge1 == 'vu' or edge1 == 'wu':
            pass
        else:
            path_to_cost[edge1]-=1

My 2nd attempt to the problem using S0AndS0's suggestions
from points import Point
points = {
          'u': Point(address = 'u', neighbors = {'v': 0, 'w': 0}),
          'v': Point(address = 'v', neighbors = {'u': 0, 'w': 0}),
          'w': Point(address = 'w', neighbors = {'u': 0, 'v': 0}),
        }

# Strategy 1 u-v (if choice == 'v')
agent1_pos = 'u'
agent1_target = 'v'

agent2_pos = 'u'
agent2_target = 'w'

agent3_pos = 'v'
agent3_target = 'w'

agent4_pos = 'w'
agent4_target = 'v'

choice_a1 = agent1_target
points[agent1_pos]['neighbors'][choice_a1]+=1

choice_a2 = agent2_target
points[agent2_pos]['neighbors'][choice_a2]+=1

choice_a3 = agent3_target
points[agent3_pos]['neighbors'][choice_a3]+=1

choice_a4 = agent4_target
points[agent4_pos]['neighbors'][choice_a4]+=1

edge_cost = lambda base_cost, drivers: base_cost * drivers # no information about the driver along the edges

Comment: Nice question. Not sure if it is suitable here, but I am interested in answering this problem.

1) It appears that this algorithm is not invariant to the order of the loops i.e. are you expecting to obtain the same answer if you start with `agent4` first?
2) code can be cleaned up in terms of python.
3) try to think of a data structure you can create before running the algorithm.
I will take a look.
Comment: I have been playing with the itertools product but due to the nature of the loops and the dict update this is not possible. Recursion may help but I feel the way the algorithm is structured the recursion would be difficult. One last point can you confirm the last decrement loop for strat 1 since it does not seem to follow the same pattern as the increment loops.
Comment: I have doubled checked this algorithm, there was some bug in the loop indentation. After fixing it, my algorithm is now invariant.
For point number (3), I was also thinking about the possible data structure that I can create, but currently haven't come up with anything better yet.
Comment: I will give it a go later - but you could also try to use the networkx python library. This will allow you to create the network it self with edges and weights. Then you will be traversing the graph with provided paths. Explain briefly why you are nesting the strategies? I assumed the strategies would be independent?
Comment: I will check out networkx. Actually I also want to avoid using so many for loops. But I cannot think of a better way to do it. Nested loop is the only simple thing I can think of at the moment.
Comment: The decrement loops for edges have already aligned with the increment loops for edges, so that if anyone has given up their edge, the cost will decrease. Can you tell me more in what way you don't think that it follows the same pattern?

Also, thanks for suggesting the itertools product, I think with this function, I can come up another algorithm to model this game without tons of for loops.
Comment: _Close_; `u_to_v = points[agent1_pos]['neighbors'][choice_a1]`, then `edge_cost(u_to_v, 1)` (`1` is number of drivers going from $u$ to $v$), with the current cost set to that pair it should return `0`... I'd advise setting non-`0` costs if you're going to use multiplication X-) `Agents` can go into a structure too eg `{'name': 'Bob', 'address'...}`, consider states you want questioned about an agent. Between here and a related [question](https://math.stackexchange.com/q/2389734/657433)'s examples I bet you could write a class that picks a direction from those that have not yet been visited.
Answer:
Note from the future, if this is your first time here know that this has been made apart of a Git Pages hosted documentation series with tips on various aspects split out to separate posts, and source code examples are just a git clone away. Those wondering why scripts where moved, they're frozen in time (with some git magics) to ensure that the examples here work long into the future, and oh the sweet syntax highlighting; all in all allowing room for more content or answers.
Links to scripts maybe downloaded by clicking the Raw button then Ctrl^s to save it as a regular text file.

The following portions are what I'll attempt to aid with as I'm on a similar path...

I am trying to model this problem with a python script without any game theory library as a challenge.
...
It would be difficult for me to try 10 agents in the future. Anyway to improve the algorithm?

... however, unfortunately helping with the tons of for loops I cannot, but I can help in spreading'em out such that cyclomatic complexity checker tools don't flag down what you're trying to accomplish, and code profilers can then give meaningful output for determining where libraries such as numpy are a good fit.
Looking through your code, I think you're on the right track with using dictionaries for some of this, well that is if you're dedicated to minimal library use; which I think is totally a legit way of learning.
The next step seems to be to use Python's OOP (Object Oriented Programing) tendencies, and __doc__ strings to your advantage; first step you've already completed by getting some code that produces your desired output. Because you've stated this is a challenge I'll not be posting a complete answer, but I'll provide some code to illustrate what I mean.

Or in other words, maybe a good idea to get a snack and drink... this is about to get verbose,

# Nodes/Points
The current graph looks sorta like the following when unwrapped, note I'm just drawing a sketch to better frame what the code'll be covering.
$$
  \color{#000}{\fbox{ w }}{
  \color{#2E8B57}{ \xleftarrow[]{\color{#000}{X}} }}
  \color{#00A}{ \fbox{ u } }{
  \color{#2E8B57}{ \xrightarrow[]{\color{#000}{X}} }}
  \color{#000}{\fbox{ v }}
\\
  \color{#000}{\fbox{ u }}{
  \color{#FF0000}{ \xleftarrow[]{\color{#000}{O}} }}
  \color{#00A}{ \fbox{ v } }{
  \color{#2E8B57}{ \xrightarrow[]{\color{#000}{X}} }}
  \color{#000}{\fbox{ w }}
\\
  \color{#000}{\fbox{ v }}{
  \color{#2E8B57}{ \xleftarrow[]{\color{#000}{X}} }}
  \color{#00A}{ \fbox{ w } }{
  \color{#FF0000}{ \xrightarrow[]{\color{#000}{O}} }}
  \color{#000}{\fbox{ u }}
$$
Points (the items from the middle column above and defined in the following linked to class) are only concerned with where it is (address), and the costs to each of it's neighbors's addresses. The cheapest (of routes) method (defined within the Point class) calculates the returned value at call time so that neighbors can be added, removed, or modified at any other time.
Link to points/__init__.py

a customized dictionary that'll be used in the following section.
Note for those not Python savvy, don't worry to much about it as the file is less than one hundred lines long (including comments, tests, and __doc__ strings), and really just serves as someway of organizing a portion of the problem space to be modeled.

To the mathematically educated, I'd really like to see how to write a similar model through pure math, so feel free to edit this section here with something beautiful.

If ya saved the above to a file path such as points/__init__.py, importing could look like...
from points import Point

Initializing a similarly shaped three pointed graph with bi-directional traveling costs between each point's neighbors could look like...
X = 0.2
O = 0.7

points = {
    'u': Point(address = 'u', neighbors = {'v': X, 'w': X}),
    'v': Point(address = 'v', neighbors = {'u': O, 'w': X}),
    'w': Point(address = 'w', neighbors = {'u': O, 'v': X}),
}

Getting the information back out would then look like...
help(points['w'])
# ... prints triple quoted block from class
#     AKA the `__doc__` string ;-)

points['w']['neighbors']
# -> {'u': 0.7, 'v': 0.2}

for name, point in points.items():
    neighbors = point['neighbors']
    print("{name} cheapest routes -> {route}".format(
        name = name,
        route = point.cheapest(neighbors)))
# -> u cheapest routes -> {'w': 0.2, 'v': 0.2}
# -> w cheapest routes -> {'v': 0.2}
# -> v cheapest routes -> {'w': 0.2}

The cheapest of routes differ between points u and v, and so far the information of all possible routes are preserved, because this class inherits from the dict class, that's what the class Point(dict) did, it's possible to dump it's saved/current state via...
print(points)
# -> {'u': {'address': 'u',...}, 'v': {'neighbors': {'u': 0.7, ...}, ...}, ...}

Bellow is a sketch of Point's super relationship with the dict class

$$
\color{#CD8C00}{\fbox{ dict }{
  \color{#00A}{\xleftarrow[]{
\color{#000}{\text{super}_{\left(key\_word\_args\right)}}
  }}
  \over{
\xrightarrow[\color{#000}{\text{returned value}}]{}
  }
}}
\color{#00A}{\fbox{ Point }}
$$
Essentially with one class we can model the graph portion of the graph (minus the agents and something to coordinate iterating states through time), plus it abstracted three for loops and other logic to a something that can be questioned reliably. Utilizing this methodology of splitting things into manageable chunks on the rest of the challenges will make adding more agents, changing algorithms, and even mutating the graph much simpler.

This is probably a good time for an intermission before diving into the next section, it'll be there once the above has been digested.

# Customizing Points (updates)

If the cost of each edge depends on the number of agents using it, what X and O should I pass it to the 'neighbors' dictionary?

I believe that the total cost is a result of a function that takes points['w']['population']s travel plans for instance (a property that'll be updated iteratively) and cost (X, or Y depending upon Point). And not to get too lost in the details but both X and O could be functions.
Here's two quick examples of how that could look in Python using lambdas...

Masking saved cost states

edge_cost = lambda base_cost, drivers: base_cost * drivers

travel_estimate = points['w']['neighbors']['u']
# ... > `O` ... > 0.7
edge_cost(base_cost = travel_estimate, drivers = 2)
# -> 1.4

What I'm asking of edge_cost might also be able to be expressed as $ e{\left( c, d \right)} = d \times c $, though one gotcha (if I remember correctly), is that $\text{`pythonLambda`} {\ne} {lambda}$, because a Python lambda can be asked to do things that don't quite translate cleanly the other-way-round.

Differing execution/calculations of X and O, or in this case first and business class tickets.

first = lambda base_cost: base_cost + 0.5
business = lambda base_cost: base_cost + 0.2

customers = {
    'bob': {'name': 'Bob', 'ticket': business},
    'alice': {'name': 'Alice', 'ticket': first}}

for key, customer in customers.items():
    print("{name} ticket cost -> {cost}".format(**{
        'name': customer['name'],
        'cost': customer['ticket'](base_cost = 0.4)
    }))
# -> Bob ticket cost -> 0.6
# -> Alice ticket cost -> 0.9

These states a Point for the most part totally doesn't care about from it's frame of reference as a destination that agents leave. At most in the second of the last to examples it would only care about getting it's output by feeding a first class function call. One way to look at is maybe a Point could be like a dispatcher (a stationary agent) who keeps a roaster of other agents in town and maybe picks up calls (_if they must, and it's not a Monday_), from agents about recent traveling conditions after arriving at a neighbor. Defined this way a Point could intentionally give bad information to another agent.

Maybe $v$ has never gotten along with $S_{1}$ and will happily low-ball any travel cost estimates given to that agent, maybe $S_{1}$ doesn't figure this out till the end n of a pay periods when their gas cost vs. compensation are not as they expected. How $v$'s' and $S_{1}$'s personalities cause them to mess with one another I think are within the scope of a Point.

If you wish to question an edge I think it maybe helpful to re-frame an edge (define a class) as the points that are populated on an edge, so that things can be asked about those on an edge. This isn't to say that an edge must contain every point between, computers and $\infty$ usually don't mix, but instead an edge could have a way of calculating things like distances between agents or their destination.

But it seems to me that the point class can only model edges with a constant cost?

Sorta; it depends upon how you use those values or choose to update them. I took some care trying to model only part of the problem because covering everything in one post can cause readers to feel a bit like Joel Miller; which is not my intent, I'd rather hope code be seen as another way to break a problem down to the atomic level if need be.
Think of Point as a starting point for organizing questions about it's state, the using of those states and final calculations are still a bit further up the stack as far as code execution depth if you want fine-grain control. Suppose in the future you want to model the rising and falling travel of costs based on hour of day or number of iterations of a parent's loop. These and other things can be done within another class that either imports or inherits the Point class.
Inheriting a Point to model something based on construction hours for example could look something like...
$$
\color{#CD8C00}{\fbox{ dict }{
  \color{#00A}{\xleftarrow[]{
\color{#000}{\text{super}_{\left(key\_word\_args\right)}}
  }}
  \over{
\xrightarrow[\color{#000}{\text{returned value}}]{}
  }
}}
\color{#00A}{\fbox{ Point }{
  \color{#2E8B57}{\xleftarrow[]{
\color{#000}{\text{super}_{\left(key\_word\_args\right)}}
  }}
  \over{\color{#00A}{
\xrightarrow[\color{#000}{\text{returned value}}]{}
  }}
}}
\color{#2E8B57}{\fbox{ Construction }}
$$

Above is just a sketch to show an overview of the relationships that are being built with the code linked bellow

Link to points/construction.py

which contains the Construction class a customized Point found in points/__init__.py.

By having the Construction class inherit from Point we gain the super powers of pre-processing cheapest within the scope of Construction.cheapest method. Yes that also means there's now some for loop stacking, but the this is just an example of using the scope stacking that Python almost expects of authors, while also addressing one way to have changing cost calculations done by a point.

In other-words, to those yelling at their monitor, right now the focus is optimizing for developer's time and not code execution time; releasing pandas or other libraries and optimizing code can wait till the problem is fleshed-out from components with well defined inputs and outputs.

Importing the Construction point if saved under points/construction.py could then look like...
from points.construction import Construction

Adding a fourth point c to the points dictionary defined previously might then look like...
points.update({
    'c': Construction(
        address = 'w',
        neighbors = {'v': O, 'w': X},
        current_hour = 6,
        hours = {9: 0.1, 10: 0.3,
                 11: 0.4, 13: 0.6,
                 14: 0.7, 15: 0.85,
                 16: 0.3, 17: 0.2}
        )})

City planners kinda dropped the ball by having construction on both out-bound routs, but that kinda models life.

... and updating points['c']'s neighbors could look like...
Z = 0.1
for address in points['c']['neighbors'].keys():
    points[address]['neighbors'].update({'c': Z})

Which then would require some adjustments to the for loop that was being used to iterate over points such as...
hours_start = 1
hours_end = 24
hours_step = 1
days = 2

day_count = 0
for i in range(hours_start, (hours_end * days) + 1, hours_step):
    for address, point in points.items():
        # ... This `try`/`except` syntax is known as
        #     "asking forgiveness" _dig_ into previous
        #     edits for a "asking permission" version ;-)
        try:
            current_hour = point['current_hour']
        except KeyError:
            current_hour = 'NaN'
        else:
            if current_hour >= hours_end:
                point['current_hour'] = hours_start
                day_count += 1
            else:
                point['current_hour'] += hours_step

        finally:
            cheapest_routs = point.cheapest()
            print("{d} {h} {p} cheapest routes -> {r}".format(
                d = day_count, h = current_hour,
                p = address, r = cheapest_routs))

Indeed I've just nested even more loops, so when you're ready, I've addressed one way of mitigating this overall problem on a somewhat related question using Iterators that allow for further unwrapping of loops into their own classes; instances of which are iterable with next() method calls. Right now what is important to grasp from the adjusted model is that we now have a way to consistently mask the initialized cost values within a point based off some other state that is updated. And that regardless of if a Point is a normal point or special point like Construction, the cheapest of routs methods are what is called by what ever process asking the questions of points.
# ... Example _snippets_ of output
0 6 c cheapest routes -> {'w': 0.2}
0 NaN u cheapest routes -> {'w': 0.2, 'v': 0.2}
0 NaN w cheapest routes -> {'c': 0.1}
0 NaN v cheapest routes -> {'c': 0.1}
0 7 c cheapest routes -> {'w': 0.2}
# ...
1 12 c cheapest routes -> {'w': 0.2}
1 NaN u cheapest routes -> {'w': 0.2, 'v': 0.2}
1 NaN w cheapest routes -> {'c': 0.1}
1 NaN v cheapest routes -> {'c': 0.1}
1 13 c cheapest routes -> {'w': 0.8}
# ...

Okay I think it's time for another pause for digestion, hopefully these pointers have helped ya plan out a course.

Agent hints

My 2nd attempt to the problem using S0AndS0's suggestions...

You're really close! There are many ways to handle abstracting this part of the problem, I've left some hints within the comments of the question and the answer, but here's just a bit more...
agents = {
    'Bob': {
        'name': 'Bob',
        'address': 'u'},
    'Alice': {
        'name': 'Alice',
        'address': 'u'},
}

# ... having the `points` agree
#     with agents `address`...
for agent in agents.values():
    agent_addr = agent['address']
    points[agent_addr]['population'].append(agent['name'])

... then having Bob go on a random adventure could look a bit like...
from random import randint

for _ in range(5):
    agent = agents['Bob']
    here = points[agent['address']]

    option_limit = len(here['neighbors'].keys()) - 1
    direction = randint(0, option_limit)
    # ... for example `randint(0, 2)` -> `1`
    #     could be a lookup for `w` bellow...
    chosen_addr = here['neighbors'].keys()[direction]
    # ... remember `neighbors` are `{addr: cost}` pairs,
    #     so above is really pulling a random `addr`
    base_cost = here['neighbors'][chosen_addr]

    there = points[chosen_addr]

    here['population'].remove(agent['name'])
    there['population'].append(agent['name'])
    agent['address'] = there['address']

    print("{name} paid {paid} to get from {here} to {there}".format(
        name = agent['name'],
        paid = base_cost,
        here = here['address'],
        there = there['address']))

Output may look similar to...
Bob paid 0.2 to get from u to v
Bob paid 0.7 to get from v to u
Bob paid 0.2 to get from u to v
Bob paid 0.7 to get from v to u
Bob paid 0.2 to get from u to w

Those last few lines with heres population remove some name, theres populated append some name, and agents reassignment address are what updates the object states. Figuring out how ya want to store states in a more efficient manor can be the challenge after getting something that works for the problem you want modeled.
Now with these tips it's getting really close to a solution which is something that I've been trying to dance about so that there's still a challenge left. So I'm going to call this answer's version complete so there's at least some space left for answers on other aspects.

I'll encourage readers once more to make use of the downloads (perhaps first), and the full repo via forking that's been setup for answering questions on a similar path. Questions specific to the code likely should be opened as Issues so that the question here is more about the problem as a whole.

Hope this all helps in making the task of modeling even more complexity something that is within reach.
Comment: Most welcome! Here's just a few more tips with `Agents`...If ya check the `Point` class you'll find a `population` `list`'s been waiting for your needs, and was originally there for _registering_ an `Agent`s `name`. _Quick-n-dirty_ example; suppose `agents = {'bob': {'name': 'Bob'}, 'alice': {'name': 'Alice'}...}`, then _sign_ `Bob` _into_ $u$ could look like `points['u']['population'].append(agents['bob']['name'])`, and to _move_ Alice along $w$ to $v$ could look like `points['w']['population'].remove(agents['alice']['name'])` then `points['v']['population'].append(agents['alice']['name'])`.
Comment: Thanks for providing such a detail answer. But it seems to me that the point class can only model edges with a constant cost? If the cost of each edge depends on the number of agents using it, what 'X' and 'O' should I pass it to the 'neighbors' dictionary?
It's definitely towards the direction I want to go, I will try running the code once I am in front of my computer.
Comment: You're welcome and glad it seems to be of use, I've updated the answer with details and more code that may address some of your questions (side note, check the `diff` of the original `Point` script to see what changed). `X` and `O` are just _place holders_ at this point to make sure that there's something functional to play around with and see that things are working as expected. Adding more layers of complexity, as you'll hopefully see in the new code examples, is totally possible while maintaining code readability and organized file paths.
Comment: Thanks for your fantastic answer. This is what I am going to do in the future. But before expanding to a complete work, I would like to solve the agent sustainability issue first. After trying your `Point` class, it does make the code more readable, but to fully calculate all possible strategies by different agents and their outcome respectively, I still need to do it case by case (see my updated code above). I am not sure if I am using your code correctly. It seems the `Point` class can only store the node information, but for my problem, the population along each edge is needed.


Brightness is not adjusting in the image

Question: I am trying to achieve this result

but what I am trying is
Mat out = imread ("F:\\image.jpg");
Mat img2 = Mat(out.size(),out.type());
cv_Gamma(out,image ,0.7);
blending_overlay(image , out , image);

and this give me the following result

and the original image is

It looks that there is a lack of brightness in my image but when I increase the brightness it still not give the required result
Edit
Blending Overlay
void blending_overlay(Mat& img1 , Mat& img2 , Mat& out)
{

Mat result(img1.size(), CV_32FC3);
for(int i = 0; i < img1.size().height; ++i){
    for(int j = 0; j < img1.size().width; ++j){

        for (int c=0 ; c<img1.channels();c++){
            float target = (float)img1.at<uchar>(i, 3*j+c)/255.0 ;
            float blend =  (float)img2.at<uchar>(i, 3*j+c)/255.0 ;
            if(target > 0.5){
                result.at<float>(i, 3*j+c) = ((1 - (1-2*(target-0.5)) * (1-blend)));

                }
            else{
                result.at<float>(i, 3*j+c) = ((2*target) * blend);
                }
        }
    }
}
result.convertTo(out,CV_8UC3,255);
}

In fact I have tried every blending mode, what I understand about this is that I may multiply with a linear gradient which come from yellow to white, but how to make that gradient is not understandable for me. Any algorithm regarding this scenario would also be appreciated.
Comment: I don't see `blending_overlay` in the OpenCV documentation. Is that a function you defined? If so, we'll need to see that source too.
Comment: Now that you've changed the BGR values from your original question, it doesn't look like there's a lack of brightness. Can you give us some context? Where did `blending_overlay` come from and why do you think it should be able to reproduce the first image? Do you want a different algorithm? Do you just want help coming up with better BGR values for your overlay? Are you using trial and error to determine your BGR values?
Comment: blending overlay is functionality of Photoshop and it uses for blending 2 images , well because of lightening i think it may merge and discover the same result , Well i just want to get the above result , doesn't matter much which way to follow
Comment: Well i get the close result when i overlay the 2 same input images by using gamma with them , cv_Gamma is the function in @Andry answers
Comment: If you're using Photoshop to generate the "desired" image, you should tell us what steps you're using in Photoshop. Many functions will translate directly to other platforms.
Comment: No my desired result is not from photoshop , its from photo editing app , and I just want that type of result , its just for comparing , i want to learn how to edit only certain part of the image like in above 1st image
Answer: It seems that you need gamma correction.
Take a look here:
http://subokita.com/2013/06/18/simple-and-fast-gamma-correction-on-opencv/
and the source of link above (with source/result pictures):
http://imagingsolution.net/program/opencv/gamma-correction/
Comment: Well am not getting the required result with it , btw why we use LUT ?
Comment: We use LUT for fast value transformation ecaluation. We have precomputed values in LUT, and then take it from lookup table instead of time consuming evaluation of gamma correction formula.
Comment: i tried it in every way its not solving the problem
Comment: To solve the problem you need more complex function then exponential. You can use spline (CatmulRom http://www.codeproject.com/Articles/30838/Overhauser-Catmull-Rom-Splines-for-Camera-Animatio ) for instance. Then you'll have much more control on color mapping.
Comment: You'll get somethin like this: http://laurashoe.com/2010/04/01/wild-tone-curve-moves-in-lightroom-3-beta-2/
Comment: did it automatically adjust `Highlights` , `Light` , `Darks` and `shadows` ? or do it need to made them on my own
Comment: Computer does not know what do you want. If you can formulate your desired result in the form of some kind of target function (representing quality of result in scalar form) , then you can get parameters that minimizes/maximizes your target function.
Comment: Can we draw that curve in opencv without using c++ interface of .net ? like in the link ?
Comment: Yes, you can draw it in separate window using OpenCV functions, you can draw it using WinAPI GDI+ functions, you can use Qt GUI design tools etc.
Comment: your answer my solve not my problem but it take me very close to my solution


innerHTML nav (main content appears with nav content)

Question: First off, I've no background in html at all, just fiddling around with my little knowledge of the basic stuffs .. so, sorry if my question is stupid.
I have a problem with innerhtml while doing up my blog template; when I manage to get through with the navigation, the blog content is seen with the nav content. (You can view it at my blog here) It's kind of frustrating because it feels like there's left that I've not tried. My basic code is like this:

ABOUT

        Content...

    <blogger>....</bloger>

Thanks in advance!
Comment: Sorry, but i dont get the problem here. http://jsfiddle.net/8zoobzen/ working fine i think.
Answer: I'm not sure what your problem is but I think the main thing would be that if you had multiple sections, your links would only work once (as the element you are trying to target gets deleted after the first link click).
To solve this, move the target blocks (ie the about element) outside the main element.  Also I would change the main element into a div as if any of the content within about has a p tag, you will end up with nested ps which is invalid content

        Content...

Example Fiddle
Comment: `` acts as the main "box" for the content right? (I used p because it's easier to identify actually). My problem is that the main page content is still there when I click the nav ``. What I wanted to do was to hide the main page content when I click on a nav.
Comment: yep, it should do.  when the links are clicked, it will populate the "main" box with the content of the div that is targeted in the onclick event
Comment: It's so weird because it works on my other blog. Hmm, I'll try to figure it out. Thanks!


Using a variable inside the Math.random function

Question: I am working on a piece of code which make an array full of numbers with the amount of numbers i want, but instead of this beeing static with 16 numbers i tried to change 16 to a variable but the math.floor/randome cant read it it only spits out Not a number wierdly enough.
EDIT: with 16 put in it works, but i cant use a variable (declared in the same function ofc)after i console.log the variable it shows it as a number but then my browser freezes
Is There anyone who knows how to change this
while(arr.length < pictures.length) {
    var randomenumber = Math.floor((Math.random()* 16));
    if(arr.indexOf(randomenumber) > -1) {
        continue;
    }
    arr[arr.length] = randomenumber;
}

//cheat sheet
for(var i = 0; i < arr.length ; i++) {
    document.write(arr[i]);
    document.write("
");
}

Answer: You will need to parse it in integer using parseInt.
var num = 16;
var randomenumber = Math.floor((Math.random() * parseInt(num)));

Answer: I don't see any issues if you use var length = 16 and Math.floor((Math.random() * length)).
Working snippet:

var arr = [], length = 16;

while(arr.length < length) {
    var randomenumber = Math.floor((Math.random() * length));
    if(arr.indexOf(randomenumber) > -1) {
        continue;
    }
    arr[arr.length] = randomenumber;
}

//cheat sheet
for(var i = 0; i < arr.length ; i++) {
    document.write(arr[i]);
    document.write("
");
}


conditions for two automorphisms of a covering space be homotopic?

Question: If $X\rightarrow Y$ is a covering space, and $\sigma\ne\tau\in Aut(X/Y)$. Under what assumptions on $X,Y,\sigma,\tau$ would $\sigma,\tau$ be homotopic?
Edit: I'm specifically interested in the case where $X$ has nontrivial fundamental group. Even more specifically, I'm interested in the case where $X,Y$ are fibrations of elliptic curves over $S,T$ respectively, and $X\rightarrow Y$ is the pullback of a covering $S\rightarrow T$.
Answer: If $X$ is contractible, then $\sigma$ and $\tau$ are certainly homotopic. If $X$ is the universal cover, this happens if and only if $\pi_i(Y) = 0$ for $i \geq 2$; that is, $Y$ is a $K(G, 1)$ (Eilenberg-MacLane space). For every group $G$, there exists a space $K(G, 1)$, so there are many such example.
If $G = \mathbb{Z}$, $K(G, 1) = S^1$ which has contractible universal cover $\mathbb{R}$. More generally, if $G = \mathbb{Z}^n$ then $K(G, 1) = (S^1)^n$ which has contractible universal cover $\mathbb{R}^n$. Other examples of spaces with contractible universal cover are compact oriented surfaces which are connected sums of tori.
Comment: @AnubhaV At the very least, you cannot say anything by making assumptions about $\pi_1(X)$ alone. The nontrivial deck transformation (the antipodal map) with respect to $S^n \to \Bbb{RP}^n$ is homotopic to the other deck transformation (the identity) if and only if $n$ is odd.
Comment: can you say any stronger statement which only depends on the relation between $\sigma$ and $\tau$ and $\pi_1(X)$... I dont know much anout this kind of result..but still this result looks very weak to me...can it be possible to generalize this problem??? thankyou in advance.


Suppose that y1 = 8.3, y2 = 4.9, y3 = 2.6, y4 = 6.5 is a random sample of size 4 from the two parameter uniform pdf,

Question: Suppose that $y_1 = 8.3, y_2 = 4.9, y_3 = 2.6, y_4 = 6.5$ is a random sample of size 4 from the two-parameter uniform pdf,
$f_y(y;\theta_1,\theta_2) = \frac{1}{2\theta_2}, \theta_1 - \theta_2 \le y \le \theta_1 + \theta_2$
Use the method of moments to calculate $\theta_{1e}$ and $\theta_{2e}$
So I understand how to solve the question when it comes to one parameter. Where we essentially solve for $E(y)$. But I'm not sure how to go about solving for two parameters.
Comment: Then why not start by showing how to find the MOM (method-of-moments) estimator for $\theta_1$ in this problem?
Answer: This is not the usual parameterization of a uniform distribution, so looking at standard references may not be immediately helpful,
Begin by showing That $E(X) = \theta_1$ and $Var(X) = \theta_2^2/3.$
Then, for the given sample, find $\bar X = 0.375$
and $S^2 = 6.3825.$ Computations in R:
<code>x = c(8.3, 4.1, 2.6, 6.5)
mean(x); var(x)
[1] 5.375
[1] 6.3825
</code>
Finally, set
$E(X) = \mu = \theta_1 = \bar X$ and
$Var(X) = \sigma^2 = \theta_2^2/3 = S^2.$
Solve for $\theta_1, \theta_2$ in terms of data
to get numerical MOM estimates $\hat\theta_1, \hat\theta_2,$ respectively. Obviously, $\hat\theta_1 - \bar X =5.375.$ What is $\hat\theta_2 ?$
Note: Later you may study maximum likelihood estimates. Sometimes MOM (method-of-moments) estimators are the same as MLEs (maximum likelihood estimators), and sometimes not. When sampling from the uniform distribution of this problem, there are differences between the two kinds of estimators.


Can't get text to center?

Question: I have a div wrapped around a couple span's and using JS to make the span's fade in and out (for testimonials). Everything works, except I can't get the span text to center within the div. Here's the relevant code:
HTML -

    Hi
    Goodbye

And here's the slideshow CSS -
.slideshow {
width:940px;
height:64px;
background-image:url(../images/quotes.png);
}

Can anyone tell me what I'm doing wrong? Oh and yes I've tried text-align:center; with no luck.
[Edit] I'd like to add I've also tried adding in !important with no change.
Comment: I'm sorry for the wait David had to walk my younger brother to the bus. Here's the fiddle link: http://jsfiddle.net/v7EuF/
Comment: no worries. Thanks for adding the link (I'd suggest editing into your question, too, so any late-comers don't get left out if they miss the comments).
Answer: I tested your code and just added
.slideshow {
    text-align: center;
}

and the text centered just fine.
Maybe you've got a typo, or a css definition somewhere else that overrides your text-align?
Edit
I did an "inspect-element" of the fiddle posted and here are the css definitions i got:

    Hi
    Goodbye

element.style {
    color: #333;
    display: block;
    font-family: 'Lucida Grande', 'Lucida Sans Unicode', Calibri, Arial, sans-serif;
    font-size: 12px;
    height: 15px;
    left: 0px;
    opacity: 1;
    position: absolute;
    top: 0px;
    width: 52px;
    z-index: 3;
}

I would say the "display: block" is your problem.
Comment: It, perhaps obviously, should work. But it doesn't in his situation (which I think is the point @David Dorward makes in his comment to his own answer). It's also why I asked the OP to post a live demo somewhere, so we could try and find out what it is, elsewhere, that's causing his problem(s).
Comment: Yes I tested the above code and it worked fine, so it has to be somewhere else. I've included a fiddle link (http://jsfiddle.net/v7EuF/) that reproduces the same problem.
Comment: If that element is set to `display: block;` then adding `margin: 0 auto;` should probably work, rather than trying to fight the plug-in that appears to be adding the extra styles.
Answer: You need to apply text-align: center to the containing
, and not do anything that causes the s to be rendered as a block (such as floating them). Absolute positioning would also pull elements out of normal flow so they wouldn't be influenced by text-align.

Update : Now a working example has been provided, we can see what is going on. The span elements are being absolutely positioned by the plugin:
$slides.css({position: 'absolute', top:0, left:0}).hide()

Looks like you will need to rethink the layout logic the plugin is using.
Comment: Did he not say he tried that? And he is not floating anything. And why the upvotes???
Comment: @Yehonatan — no, he said he was using `text-align: center`, but not where, and he didn't say he wasn't floating anything. Whatever is causing the problem isn't in the code that is being shown.
Comment: @David He didn't say that he had his computer plugged in either.
Comment: What else would cause `` to be rendered as a block? I'm not floating anything. And I tried adding `text-align: center` to `.slideshow` ... no luck.
Comment: @Matt Untsaiyi you can use the css property "display: block" to display almost any element as a block element. This is a very common thing to do. If you want to make double sure the spans are displayed inline you could add "display: inline", but normally this should not be neccessary.
Comment: He didn't say it was absolutely positioned either — but it was.
Comment: I'm stuck. I've tried adding `left:50%` to `$slides.css` and although it centers, the slide is broken and all my ``s appear at once.

Can't get text to center?


Como Ordenar Em R

Question: Como fazer para ordenar os números na linguagem r
dados = order(dados, decreasing = F)
dados

Aqui so ordena a posição...
Queria saber um método de ordenar os números que estão na lista dados: dados = c(8,6,5,4,1,3,7)
Answer: Você pode utilizar o sort
dados = c(8,6,5,4,1,3,7)
dados = sort(dados, decreasing = F)
dados

Saída
1 3 4 5 6 7 8

Como Ordenar Em R


mean/plotting in R studio with imported data from excel

Question: I imported a csv file from excel and I'm trying to find the mean and do a histogram plot.  The data set is N1.  I'm used mean(N1) and I get the following
N1 <- structure(list(V1 = c(13.56535447, 10.98573126, 9.819271544, 6.87414882, 8.303223126, 9.478439048)), .Names = "V1", row.names = c(NA, 6L), class = "data.frame")
mean(N1)
[1] NA
Warning message:
In mean.default(N1) : argument is not numeric or logical: returning NA

What am I doing wrong.  I the name and data is there because I can get the max and min but I can't get the mean or histogram plot.
Data example:
dput(head(N1))

N1 <- structure(list(V1 = c(13.56535447, 10.98573126, 9.819271544, 6.87414882, 8.303223126, 9.478439048)),
.Names = "V1", row.names = c(NA, 6L), class = "data.frame")

Comment: Are you trying to measure the average of all your dataset all a particular column? try this: `mean(N1$coloumn, na.rm = true)`
Comment: Right now we cannot know what is wrong with your data. I assume you imported the column names or anything not numeric within your data column(s), so R does not acknowledge the vector as numeric. Please provide a data example by pasting either the output of `dput(N1)` (if your data is small) or `dput(head(N1))` (if your data is large), so we can see what might be causing your error.
Comment: dput(head(N1))
structure(list(V1 = c(13.56535447, 10.98573126, 9.819271544,
6.87414882, 8.303223126, 9.478439048)), .Names = "V1", row.names = c(NA,
6L), class = "data.frame")
Answer: You are calling mean on a data.frame, what you want is the mean of its only column. So mean(N1$V1) should solve your problem.


Java InputStream . Is there is Correct And Efficient way?

Question: I am working on Bluetooth Application on Android. This inputStream is from connection socket. I want to read bytes upto certain length.
First way I tried  :
byte[] data = new byte[lengthtoread];
for (int i = 0; i < data.length; i++)
    data[i] =(byte) mmInStream.read() ;

I have found that it is been too slow.
Sencond way:
   byte[] data = new byte[lengthtoread];
   mmInStream.read(data, 0, lengthtoread);

In this I found that its not reading data completely when length to read is too large
Anyone please help me out ??
Comment: how did you realize it(in second approach)? what is the value of `lengthtoread`? what is the target file size?
Comment: lengthtoread is large sometimes near about upto 90000 more or less
Comment: so why do you want to read all at a time? it's not a good idea, try to buffer data
Comment: what is the reliable size of buffer ??
Comment: it dependents buddy, it dependents on target environment, you need small in small devices like a J2ME application, but it may be huge in servers, also it dependents on data rate, if data rate is slow, keep buffer small, and for any fetched data do the business, sometimes it dependents to business, for example each task need at least 4096 bytes, I cannot say *how much is good*, it dependents buddy :)
Answer: Using only standard API, the DataInputStream class has a method called readFully that fills a byte array from the stream:
byte[] data = new byte[lengthtoread];
DataInputStream in = new DataInputStream(mmInStream);
in.readFully(data);

Don't forget to close the streams when you are done with them!
Answer: What, exactly, are you trying to do?
If it's to read all the bytes from a file, then do this:
Files.readAllBytes(Paths.get("filename.txt"));
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes%28java.nio.file.Path%29
Comment: Its inputstream from bluetooth connection not from file. I want to some bytes only
Answer: Yes: use Jakarta Commons IOUtils. This class contains fully-debugged utility methods for reading and writing streams.
If you want to read the entire stream, use IOUtils.toByteArray(). However, be aware that you might run out of memory when doing this. Usually it's better to process a piece of a stream at a time.


Aceder arquivo da Maquina Virtual pelo SQLite Browser

Question: O meu arquivo .db esta no SDCARD do emulador, só que como eu faço para abrir com o SQLite Browser esse arquivo que esta lá dentro ? Ou pegar esse arquivo que esta na pasta SDCARD e colocar na minha Area de trabalho ?
Exemplificando:
Meu arquivo está salvo na pasta SDCARD do meu emulador, eu quero de algum jeito que eu pegue esse arquivo e coloque em minha área de trabalho, eu não sei se existe uma pasta em minha maquina física compartilhada com a da maquina virtual (emulador), ou seja, eu so quero transferir de uma para a outra, para poder pegar esse arquivo e abrir pelo SQLite Browser, pois quando eu vou em Abrir Banco de Dados, ele abrirá da minha maquina física e não da virtual
Comment: Você precisa exportar seu banco via DDMS `/data/data/com.seuDominio/databases/ seu banco`
Comment: eu tirei do /data/data e coloquei no sdcard, só que agora eu queria abrir pelo SQLite Browser
Comment: Abre seu SQLite > open database > escolhe seu arquivo
Comment: ele esta no SDCARD da Maquina virtual, eu queria tirar da mv e colocar na minha maquina física, não achei uma pasta que fique os arquivos do SDCARD na maquina fisica
Comment: Essa VM, seria seu Emulador?
Comment: sim, o emulador é o bluestack
Comment: http://pt.stackoverflow.com/a/71852/10315 essa resposta do @FelipeDouradinho te atende perfeitamente
Comment: ele atende a minha pergunta anterior perfeitamente, mas não essa, note que são perguntas diferentes
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/25415/discussion-between-wellington-avelino-and-gabriel-santana-bonatto).
Answer: Para exportar seu banco.db faça os seguintes passos:

DDMS > File Explorer > data/data/seu dominio/databases

Após chegar até onde fica seu arquivo banco.db selecione o mesmo e clique em pull a file from the device o botão é um disquete no canto superior direito.
Depois é só selecionar onde deseja salvar seu arquivo e abrir com o SQLite Browser


Best practice for custom module variable names?

Question: I've gotten into the habit of doing pretty robust configuration panes for my modules now, and I'm finding the variable names & management to be quite the pain.
I have variables like mymodule_section_subvar_varname_type_context and I not only loose track of the order of the elements in my variable names but I feel as if having a variable name that long is a design flaw.
I've been considering using a serialized array in a variable mymodule_section_settings in conjunction with a set of functions that make it easy to maintain that array but I'd love some input in what (if any) best practices have been established outside of prefixes and/or examples of modules that we trust and what they are doing for large sets of variables.
Thanks!
Comment: Also, I'd like to consider updates in this as well (which is why I am leaning towards a serialized array) so making changes to the variable names doesn't orphan data and add extra work for additional upgrade path functionality/tests
Answer: It is possible to use a Drupal variable to contain an array; that is what Drupal core modules do too (see book_type_is_allowed()).
It is possible to use a single Drupal variable to contain different settings used by a module into an array. With the form #tree attribute is still possible to use system_settings_form() to save the array into a Drupal variable without writing any additional code. Serializing the de-serializing the code is automatically done by the Drupal core functions that handle Drupal variables (see  the code of variable_set()).
The question is then: when should a single Drupal variable be used to contain different settings? I would use a single variable for settings that are used by a function, or a group of functions; if the array contains values used by (for example) 10 different functions, but those functions access a single value (or a couple of values) from that array, then I would not use a single persistent variable for the settings.
Comment: Do you / anyone know how this type of scenario will react within Features and/or Strongarm? I'd hate to lock out those modules and the users who cherish the mobility those modules can bring.
Comment: I don't see any reasons why Features would have any problem with a Drupal variable that contains an array. Somebody else could report you in details if it is completely true, or not.
Comment: yes, I understand this may be a tad out of scope of this question - but want to make sure this standard works for everyone :) I'll report after I try a few things.
Answer: If a set of settings are related then putting them in an array makes sense. For example if you are doing several variable_get's sequentially. It gives you some flexibility as well as being potentially a little faster.
However this will make it difficult for other programs to edit your settings manually via something like drush vset or strongarm. In these cases long variable names can actually be helpful.


How to programmatically update node title?

Question: I would like to programmatically update some fields including the title of a node, when this node is saved.
To do so I am using a hook
function MY_MODULE_node_update($node) {
    $node->title = "Something new an beautiful";
    $node->filed_what_ever = "Something";
    field_attach_update('node', $node);
}

The problem is, that the title is not updated, I assume, that's because of the fact it isn't a field an the Drupal sense.
But I can not use
node_save($node);

instead, because that brings me in an infinite loop: the function hook_node_update() is called by the function node_save()... So what would be a clean why to do this?
Comment: You should probably use a hook that gets called earlier in the node updating process. I think adding a custom submit handler in a hook_form_alter(), that changes the node title before save, might work.
Answer: To do this, you have to use hook_node_presave().
It's called before saving the node to the database. (both new nodes and edits).
Note that you must make sure that you are saving sanitized and formatted data.
Comment: Does that mean, with hook_node_presave() I just can set or alter the fields as I wish, and than they will be saved without having to call field_attach_update() or node_save() again?
Comment: exactly! You don't need to return the node. it will be passed by reference so go ahead and make the changes.
Comment: The only way to change programmatically the node title is in the hook_node_presave?
Comment: @AdrianCidAlmaguer with the context of original question about using a hook_node_update, you will have to use the presave hook or save the node yourself.


Utilização apenas de um atributo de uma entidade

Question: Estou construindo uma API Rest para cadastro de Cidades e Clientes. O meu problema seria em relação à classe Cliente que possui como atributos dados pessoais do cliente e uma Cidade, que seria a cidade de residência relacionada à entidade Cidade.
A entidade Cidade:
package com.desafio.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table(name = "cidade")
public class Cidade {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "cidade", nullable = false)
    private String nomeCidade;
    @Column(name = "estado", nullable = false)
    private String estado;

}

A entidade Cliente:
package com.desafio.model;

import java.time.LocalDate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table(name = "cliente")
public class Cliente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "nome_cliente")
    private String nomeCliente;
    @Column(name = "sexo")
    private String sexo;
    @Column(name = "data_nascimento")
    private LocalDate dataNascimento;
    @Column(name = "idade")
    private Integer idade;

    @ManyToOne
    private Cidade cidade;

}

O problema principal é que, no momento em que o Cliente vai fazer o cadastro, logo gerar um POST, no campo onde deveria ter apenas o nome da cidade, solicita todo o objeto Cidade, inclusive o ID.
O Json esperado fica da seguinte forma:
{
  "cidade": {
    "estado": "string",
    "id": 0,
    "nomeCidade": "string"
  },
  "dataNascimento": "string",
  "id": 0,
  "idade": 0,
  "nomeCliente": "string",
  "sexo": "string"
}

Gostaria de saber o que pode ser feito, para que eu tenha um relacionamento entre as 2 entidades, porém capturando apenas o nome da cidade para a classe Cliente.
Answer: Separar as responsabilidades entre os domínios de sua controladora e base de dados.
Respondi uma pergunta similar a esta aqui um tempo atrás que engloba o seu dilema, especificamente neste trecho:

Para separar a responsabilidade da entidade de banco ser a mesma a ser requisitada/retornada ao cliente, contendo tanto anotações relacionadas à persistência quanto anotações relacionadas à parse (@Table e @JsonIgnore por exemplo).

Para o seu caso, você tem a necessidade de customizar o objeto de requisição enviado pelo seu cliente, e está utilizando a sua entidade de banco de dados para isso. Com o decorrer do tempo, a manutenção do seu código vai ficar mais complexa, visto que sua API vai evoluir, e com isso mais dados serão incluídos na requisição, validações deverão ser realizadas...
Uma solução seria adotar a criação de um objeto de Request e Response para suas operações, com isso você ganharia a flexibilidade de possuir uma classe com apenas os dados que lhe interessam nessa requisição (eliminando campos e estruturas, ou adicionando campos e validações), e não corre o risco de suas propriedades de requisição/resposta mudarem quando houver qualquer alteração em seu banco de dados.


Azure API call: response contains html page

Question: I created an API app that is hosted in Azure and protected by the Active Directory (when I open the url in a browser, I get redirected to a login page from microsoft).
Now I have an angular app that should get the data from the api. I protected the angular app with the Actice Directory, too. In this manner I want to get a token which I can use for authentication.
API call:
const auth = btoa("[my username]:[my password]");

var token;
if((window.location.href).indexOf('/') != -1) {
  var queryString = (window.location.href).substr((window.location.href).indexOf('/') + 1);
  token = (queryString.split('='))[1];
  token = decodeURIComponent(token);
}

$http.defaults.headers.common['Authorization'] = 'Basic ' + auth;
$http.defaults.useXDomain = true;
$http.defaults.headers.common['x-ms-token-aad-id-token'] = token;
delete $http.defaults.headers.common['X-Requested-With'];

var erg = $http.get('http://[app name].azurewebsites.net/api/contacts')
.success(function (data, status, headers, config) {
      $scope.loggedIn = "LOGGED IN";
      $scope.responseData = data;
})
.error(function (data, status, header, config) {
      console.log("ERROR");
});

I had to open Chrome with disabled 'same origin policy'.
The data that was returned:
<title>Working...</title>

    <form method="POST" name="hiddenform" action="https://[app name].azurewebsites.net/.auth/login/aad/callback"><input type="hidden" name="id_token" value="eyJ0[...]NBw" />
        <input type="hidden" name="state" value="/api/contacts#" />
        <input type="hidden" name="session_state" value="fdbe7ee3-[...]-b12663d39846" />

Script is disabled. Click Submit to continue.
<input type="submit" value="Submit" />
    </form>

How can I get the JSON data that the API should actually return? What can I do with this html snippet?
Comment: You should check this tutorial: https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-angular/. You need to authenticate with Azure AD first to get an access token to call your API. And you should never have your password in front-end JavaScript..
Comment: Have you tried to use https://github.com/AzureAD/azure-activedirectory-library-for-js to get the token and leverage it to call your resource protected by AAD
Comment: Yes, I tried it. I get the token (in the url...), but I can't access the API. Actually I don't know where I should put the token.
Comment: Hi @chocolatecake, do you have any update for now?
Comment: Hi Gary Liu. The update: I can get a bearer token (I think this is what I need) when I send a request with a java application. With my web application it doesn't work because of CORS policy.
Answer: You can follow the sample in https://github.com/AzureAD/azure-activedirectory-library-for-js to integrate adal in your SPA. The SDK has implemented the functionalities acquiring access token from AAD. And also will intercept the http requests in Angularjs and add the authentication header.
You can refer to http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/ & http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ for further understanding of adal for js.
And to make sure your SPA can call your APIs in server. You can try following configurations in Angualrjs config section:
app.config(['$locationProvider', 'adalAuthenticationServiceProvider', '$httpProvider', function($locationProvider, adalAuthenticationServiceProvider, $httpProvider) {
            $locationProvider.html5Mode(true).hashPrefix('!');
            $locationProvider.html5Mode(true).hashPrefix('!');
            var endpoints = {
                "http://garycors.azurewebsites.net": "bce85948-9ea4-4738-b1e6-972f3d30f4da",
                // "http://garycors.azurewebsites.net": "90e54701-ff93-414c-b7ee-c2d9b01417f3",
            };
            adalAuthenticationServiceProvider.init({
                    tenant: "<tenant_id>", // Optional by default, it sends common
                    clientId: "<client_id>",
                    cacheLocation: 'sessionStorage'
                },
                $httpProvider // pass http provider to inject request interceptor to attach tokens
            );
            $httpProvider.interceptors.push('httpRequestInterceptor');
    }]);

 app.factory('httpRequestInterceptor', function () {
          return {
            request: function (config) {

              config.headers['Authorization'] = 'Bearer ' + sessionStorage.getItem("adal.idtoken");

              return config;
            }
          };
        });

Any further concern, please feel free to let me know.


How to update value in different table sql

Question: I have some questions, I have 2 tables, Table a and table b.
This is what Table a looks like:

ID
INFROMATION
STATUS

1
Detail Inf
0

--
-----------
------

And this is what table b looks like:

ID
SEQ
ITEM NAME
STATUS

1
1
Item A
0

1
2
Item B
1

1
3
Item C
2

My question is: how to update a.Status and set value to 2 with condition if all values in b.status are 2 and a.id = b.id
And of course if Table b.status contains a value of 0 or 1 and a.id = b.id, then column a.status is set to 1.
Appreciate your help.
Thank you
Answer: The status in the A table appears to be derived from the state of the B table, and, as such, I would actually suggest not doing this update.  Instead, when you want to view the aggregate status, use an appropriate select query:
SELECT
    ID,
    INFORMATION,
    CASE WHEN NOT EXISTS (SELECT 1 FROM TableB b WHERE b.ID = a.ID AND b.STATUS <> 2)
         THEN 2 ELSE 1 END AS STATUS
FROM TableA a;

The logic here is that if, for a given ID in the A table, we can't find any record in the B table whose status isn't 2, then we label the overall status as 2, otherwise we label as 1.
Answer: I'll run 2 query
UPDATE A
SET A.STATUS = 2
FROM A
JOIN B ON A.ID = B.ID
WHERE B.STATUS = 2

UPDATE A
SET A.STATUS = 1
FROM A
JOIN B ON A.ID = B.ID
WHERE B.STATUS <> 2


Find the total number of selections of r things from n different things when each thing can be repeated unlimited number of times?

Question: Find the total number  of selections of r things from n different things when each thing can be repeated unlimited number of times ?
I know that the formula is $$ n+r-1\choose r  $$
But how do we get this formula ?
How the problem stated above is equivalent to choosing $r$ things from $n+r-1$ things?
Answer: The method of 'stars and bars' comes in handy here.
For instance if you are selecting $r=9$ things from $n=4$ different types.  Then any sequence of $3$ bars and $9$ stars represents a selection, where the bars are separators between the types, and stars are items selected.  For instance
$**|****|***| $
represents selecting two things of type 1, four of type 2, three of type 3, and none of type 4.
Thus there are ${12}\choose{9}$ possible ways to make the selection.
Answer: Modifying the above solution a little bit to give a better perspective to solution.
For instance if you are selecting $r=9$ things from $n=4$ different types. Then any sequence of 3 bars and 9 stars represents a selection, where the bars are separators between the types, and stars are items selected. For instance
∗∗|∗∗∗∗|∗∗∗|
represents selecting two things of type 1, four of type 2, three of type 3, and none of type 4.
Thus we have to decide where to place bars and then the partitions created will automatically be the combinations.
we have 12 empty positions have we have 3 bars thus solution is $^{12}C_3$ which is same as $^{12}C_9$


MapView rotation / orientation issue

Question: I am working on MapActivity that have some extra fields in top, bottom and side of the the map. These all View component is available in a single main.xml file. For both orientation i have layout-land and for portrait directory also, both folder containing main.xml with same ids.
I have use android:ConfigChaneg in androidManifest.xml, and i overrides the method onConfigChange(Configuration newConfig)
<code>@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.main);
    }
    else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        setContentView(R.layout.main);
    }
}
</code>
But now when screen is rotating / changing orientation then getting Exception. MapActivity can have only one MapView how to solve this problem,  Please guide me.
Thanks in advance....
Answer: here if you want to fix in one mode screen you may fix screen in Manifest file
in activity add attribute android:screenOrientation="portrait"
or here when your onConfigurationChanged here start all process again in both mode
Comment: you need to both Orientation ?

MapView rotation / orientation issue


Why is config for my view going to config/local?

Question: We use config_split to slice off parts of the site config to other config folders (local, dev, stage, etc). This more or less works as expected.
I have one view which always exports to config/local even though there is nothing I can see in the config_split configuration which is suggesting it do this.
Any ideas why it fails to export to the correct folder (config/sync)?
Answer: As is usually the case, 30 min after posting I figure it out.
My issue was caused by the "Include dependent configuration" option being enabled for the split configuration.


Keras/Tensorflow: Train multiple models on the same GPU in a loop or using Process

Question: I have multiple models to train in Keras/Tensorflow at a stretch one after the other without manually calling train.py, so I did:
for i in range(0, max_count):
    model = get_model(i)   # returns ith model
    model.fit(...)
    model.save(...)

It runs fine for the i=0 (and in fact runs perfectly when run separately). The problem is that when the second time model is loaded, i get ResourceExhaustedError OOM, so I tried to release memory at the end of for loop
del model
keras.backend.clear_session()
tf.clear_session()
tf.reset_default_graph()
gc.collect()

none of which individually or collectively works.
I looked up further and found that the only way to release GPU memory is to end the process.
Also rom this keras issue

Update (2018/08/01): Currently only TensorFlow
  backend supports proper cleaning up of the session. This can be done
  by calling K.clear_session(). This will remove EVERYTHING from memory
  (models, optimizer objects and anything that has tensors internally).
  So there is no way to remove a specific stale model. This is not a bug
  of Keras but a limitation of the backends.

So clearly the way to go is to create a process everytime I load a model and wait for it to end and then create another one in a fresh process like here:
import multitasking
def train_model_in_new_process(model_module, kfold_object, x, y, x_test, y_test, epochs, model_file_count):
    training_process = multiprocessing.Process(target=train_model, args=(x, y, x_test, y_test, epochs, model_file_count, ))
    training_process.start()
    training_process.join()

but then it throws this error:
  File "train.py", line 110, in train_model_in_new_process
    training_process.start()
  File "F:\Python\envs\tensorflow\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "F:\Python\envs\tensorflow\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "F:\Python\envs\tensorflow\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "F:\Python\envs\tensorflow\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "F:\Python\envs\tensorflow\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
TypeError: can't pickle module objects
Using TensorFlow backend.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "F:\Python\envs\tensorflow\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "F:\Python\envs\tensorflow\lib\multiprocessing\spawn.py", line 115, in _main
    self = reduction.pickle.load(from_parent)
EOFError: Ran out of input

I really can't utilize the information presented in the error to see what I was doing wrong. It is clearly pointing at the line training_process.start(), but I can't seem to understand what's causing the problem.
Any help to train models either using for loop or using Process is appreciated.
Answer: Apparently, Multiprocessing doesn't like modules or more precisely importlib modules. I was loading models from numbered .py files using importlib
model_module = importlib.import_module(model_file)

and hence the trouble.
I did the same inside the Process and it was all fine :)
But I still could NOT find a way to do this without Processes, using fors. If you have an answer, please post it here, you're welcome. But anyway, I'm continuing with processes, because processes are, I believe, cleaner in a way that they are isolated and clears all the memory allocated for that specific one when done.


Harmonizing Bourrée in E minor

Question: Out of interest and just to give myself practice in part-writing, I've been trying to harmonize the popular Bach Bourrée in E minor from his lute suite. It only has two voices, so there is a lot of ambiguity. The main part I'm having trouble with is the very beginning.
First I'm not sure to give the alto and tenor quarter or eighth notes. Either way I can't create a harmonic progression that sounds good and doesn't distract from the melody.

Anybody got ideas on how to fill in this anacrusis? Or any advice on completing the four-part harmony from then on.
Comment: Just put a rest under the anacrusis?
Comment: so if Bach was harmonized this for, say, a string quartet, do you think he would've done that? I've only seen him leave out voices for songs on the lute, like this.
Comment: J.C.F. Bach has parts come in sequentially http://imslp.org/wiki/6_String_Quartets,_Op.1_%28Bach,_Johann_Christoph_Friedrich%29 in a string quartet; other arrangements of J.S. Bach's work do the same; so I'd say that it is at least period appropriate.
Answer: First of all, I think it's important to keep in mind that harmony is written for something. I'm going to follow the sort of academic rules of part-writing in my answer, but if this were for "real life" purposes, it would be worth subjecting a lot of those assumptions to the test of what makes the best music (and the most idiomatic music for whatever you're writing for). I think there could be a lot of musical merit, for example, to using only two voices in the pick-up bar, and possibly even to not always treating the two voices given as "bass" and "soprano."
Within the bounds of formal part-writing, though, the place to begin has to be harmonic analysis. That answers the question of quarter-notes vs eighth-notes right away: all of the eighth notes in this excerpt can be analyzed as passing tones, so they aren't a part of the functional harmony. The harmonic rhythm here is definitely the quarter-note. Of course, once you've written a harmonization in quarter-notes, you may want to add non-harmonic tones to your lines for musical interest, or you may want to use them strategically to smooth out voice-leading — this comes back to what the arrangement is for. (If we were going outside of academic part-writing, you might even want to consider using a primary harmonic rhythm longer than the quarter-note, but the quarter-note will do well for study purposes.)
When that's established, the first thing you'll want to do is harmonize the E-minor i chord on the first beat of the first full bar. That i chord is, from the perspective of functional harmony, the real "landing point" for the beginning of the piece. The function of the pickup bar is to propel us to the i chord on the downbeat, so the best strategy is to first figure out where we're going, and then work out the most elegant way to get there.
Of course, there is no one right answer for how to harmonize that i chord, but I'm going to go with e2 e4 b4 g5 (if you enter that into Wolfram Alpha you'll see the notation).
Once we've established that i chord on the down-beat, we can go back to the pickup bar and and analyze how it is propelling the music forward to the down-beat. Since we know that we're headed to a i chord in E-minor, the best analysis for the harmony of the pickup bar seems to be as a i^6 chord (i.e. a i chord in first inversion). If you exclude the second eighth-notes of each pair as passing tones, you'll also see that the soprano and bass voices are in fact exchanging pitch-classes from the pickup to the down-beat.
The goal, then, should be to fill in the harmony in the i^6 chord in a way that:

is unintrusive; and
helps to keep forward momentum toward the down-beat (i)

How to achieve those goals is again a matter of taste, but in my example solution, I'd again give the tenor e4 and the alto b4. That way, the alto and tenor will stay on the same note from the pick-up to the down-beat, which lets the movement in the bass and soprano shine through while still establishing the four-voice texture.
Hopefully this example both helps you through the pick-up bar and demonstrates the strategy to use in the rest of the piece: start by identifying (and harmonizing) the most structurally/functionally important moments, then fill in the details to achieve smooth, elegant, effective voice-leading.
Answer: Do not treat the eight notes as passing notes. The notes on the downbeat, no matter what their duration is, establish the harmonic progression here with a few exceptions in the second part that add a little tension.
From looking at the sheet superficially you can tell, that this is composed in counterpoint. The pickup bar and the first downbeat establish that beyond doubt to the listener. Upper and lower voice move in different directions, both in a straight, mirrored line. So in the first beat, e-minor key becomes obvious.
Then, realise what the basic mode here is. What minor is that piece in? It is in harmonic minor. The H-7 on the third downbeat in the first bar makes that unmistakably clear.
So the chord progression becomes:
e-min / emin a-min B-7 a-min /
That's a i-iv-V and leaves no doubt. It continues with:
G-maj B-7 e-min D-7 /  G-maj
The D-7 modulates briefly to G-Major, but Bach doesn't follow that route and returns to E-harmonic minor:
/ G-maj a-min B-7 a-min / G-maj H-7 e
The second half of the first part starts out just the same, but this time, Bach fools us and actually stays in G-major:
e-min / emin a-min H-7 a-min / G-maj H-7 e-min D-7 /  G-maj a-min H-7 a-min / G-maj a-min D-7 G-maj / G-maj
That ends in a ii-V-I pattern, BTW. Bach chose that probably just to make sure, there is no doubt of the new mode reached.
The second part then sets out in G-major to take the listener on a walk on the wild side with continuous modulation. That ride of course ends in firmly established e-harmonic minor.

Harmonizing Bourrée in E minor


how to do nodejs hot deployment in nodeclipse , enide studio, express server?

Question: I am debugging an application in nodeclispe/ enide studio. I wish to change js files on the go while the express server is running, instead of doing a server restart. HOw can I do that?
Answer: Since you are debugging an application the best you can do is use the module nodemon, this module watches your folder for files change when a file changes the application is automatically redeployed.
To install nodemon use this command, install it globally:

npm install nodemon -g

To execute from CLI you use

nodemon --debug app.js

PS: Have in mind that when i say redeployed the memory of the process is flushed and do not use nodemon under production environment.


Proving that grassmannians are smooth manifolds

Question: I'm trying to show that real grassmannians $G(k, n)$ are smooth manifolds of dimension $k(n-k)$.
The problem is set in this way:
Identify the set of all real matrices with $n$ rows and $k$ columns with $\mathbb{R}^{kn}$. Then consider the following equivalence relation on $\mathbb{R}^{kn}$:
$M_1 \sim M_2$ if and only if there exists $L \in GL(k,\mathbb{R})$ such that $M_1=M_2L$. Then define $G(k, n)=\mathbb{R}^{kn}/ \sim$. $G(k, n)$ becomes a topological space whose topology is the quotient topology.
Now, for each subset of $J$ of $\{1, \ldots, n\}$ consisting of $k$ indices, consider the matrix $M_J$ obtained from $M \in \mathbb{R}^{kn}$ taking only the the $k$ rows whose indices are in $J$ and consider the set
$$U_J=\{[M]\in G(k, n): detM_J \neq 0\}. $$
Finally, for each $J$, define the map from $U_J$ to $\mathbb{R}^{k(n-k)}$ given by
$$\phi_J([M])= (MM^{-1}_J)_{J^c}$$
where $J^c$ denotes the complement of $J$ in $\{1, \ldots, n\}$.
I think I've managed to show that this map is a homeomorphism, but I'm in trouble when I hace to prove that transitions map between the charts are smooth, i.e. for each $J_1,J_2$ the composition $\phi_{J_1} \circ \phi_{J_2}^{-1}$ is smooth.
Any help would be greatly appreciated.
Comment: So write out the case $k=2$, $n=4$ carefully, if you have thought through tge notation for $k=1$. Also, you're missing an inverse in your composition.
Comment: Have you tried working out some explicit examples (start with $k=1$ and then go to $k=2$)?
Comment: For $k=1$ I can understand how the thing is working, because in that case $G(k,n)$ is just the $n-1$ dimensional projective space. For $k=2$ the situation becomes more complicated, and I find myself a little bit confused.
Comment: That's true, thank you for pointing it out.
Answer: Let $X\in\mathbb{R}^{(n-k)k}$. I will first denote $[M]=\phi_{J_2}^{-1}(X)$ and rewrite $\phi_{J_1}([M])$ as follow:
\begin{align}
\label{comp:1}
\phi_{J_1}([M])&=(MM_{J_1}^{-1})_{J_1^c} \\
&=M_{J_1^c}M_{J_1}^{-1} \\
&=M_{J_1^c}\cdot\frac{1}{\det M_{J_1}}\text{adj}(M_{j_1})
\end{align}
In case it is not clear, the second step is justified by noting that $M_J$ can be obtained from $M$ by a pre-multiplication of the $k\times n$ matrix $E_J$, whose $j$-th column is equal to the standard basis column vector $e_r\in\mathbb{R}^k$ if $j=i_r\in J$ and is equal to $0$ otherwise. For example, if $n=7$, $k=3$ and $J=(1,4,6)$, then
\begin{align}
E_j=\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1 & 0
\end{pmatrix}
\end{align}
Then $M_J=E_JM$ as you can check easily. Thus
\begin{align}
(MM_{J_1}^{-1})_{J_1^c}&=E_{J_1^c}(MM_{J_1}^{-1}) \\
&=(E_{J_1^c}M)M_{J_1}^{-1} \\
&=M_{J_1^c}M_{J_1}^{-1}
\end{align}
which justified the second step.
By rewriting $\phi_{J_1}([M])$ in this way, it is clear that each entry of $\phi_{J_1}([M])$ is a rational function of entries of $M$. In particular, the denominator of this rational function is equal to $\det M_{J_1}$, which is nonzero since $[M]\in U_{J_1}$. Therefore, each entry of $\phi_{J_1}([M])$ depends smoothly on the entries of $M$.
Note that the whole computation does not depend on the choice of the representative of the equivalence class $[M]$. So we may choose the representative $M$ to be a convenient one. When you were proving the surjectivity of $\phi_{J_2}$, I believe you have already seen how to obtain such $M$ from $X$: Simply inserting back the row vectors $(0 \cdots 1 \cdots 0)$ to the position indexed by $J_2$. For example, when $n=4$, $k=2$ and $J_2=\{1,3\}$, if
\begin{align}
X=\begin{pmatrix}
a & b \\
c & d
\end{pmatrix}
\end{align}
then
\begin{align}
M=\begin{pmatrix}
1 & 0 \\
a & b \\
0 & 1 \\
c & d
\end{pmatrix}
\end{align}
Thus entries of $M$ are either $0$, $1$ or entries of $X$. Hence by choosing such $M$, it follows that
\begin{align}
\phi_{J_1}([M])=\phi_{J_1}\circ\phi_{J_2}^{-1}(X)
\end{align}
is a matrix whose entries depend smoothly on the entries of $X$. This proves the smoothness of $\phi_{J_1}\circ\phi_{J_2}^{-1}$.


Decode statement in SQL results in ORA-00936: missing expression

Question: Trying to figure out why this decode isn't working.  I just want to create a column that would separate the above line into <5 and >=5 and give them a corresponding answer.  I really can't seem to see why it is not working, I keep getting ORA-00936: missing expression.
SELECT a.account_id "Account ID",
   a.first_name ||' '|| a.last_name "Name",
   b.date_and_time_created "Date Created",
   c.date_and_time_ordered "Date Ordered",
   c.date_and_time_ordered - b.date_and_time_created "Days Ordered After Created",
   DECODE ((c.date_and_time_ordered - b.date_and_time_created), <5, 'No Reminder Needed',
                                                              >=5, 'Reminder Needed', ' ') "Reminder"
FROM shopper a
   JOIN shopping_cart b ON a.account_id = b.shopper_account_id
   JOIN orders c ON a.account_id = c.shopper_account_id

Comment: rewrite it as a case statement
Answer: the problem causes due to usage of < > = within a decode statement , use this instead :
SELECT a.account_id "Account ID",
   a.first_name ||' '|| a.last_name "Name",
   b.date_and_time_created "Date Created",
   c.date_and_time_ordered "Date Ordered",
   c.date_and_time_ordered - b.date_and_time_created "Days Ordered After Created",
   (case when ( c.date_and_time_ordered - b.date_and_time_created  <  5 ) then 'No Reminder Needed'
         when ( c.date_and_time_ordered - b.date_and_time_created  >= 5 ) then 'Reminder Needed'
         else ' '
     end ) "Reminder"
FROM shopper a
   JOIN shopping_cart b ON a.account_id = b.shopper_account_id
   JOIN orders c ON a.account_id = c.shopper_account_id

Comment: Thank you, had to fix a small error with the parentheses in the CASE, (extra close parentheses on the line with the second WHEN clause), but other than that thank you!
Comment: you're welcome, thank you i removed extra parathesis that i forgot to remove carelessly.
Answer: Or, if you insist on DECODE (though, I don't know why would you want to do that as CASE is much more appropriate here), you could use SIGN function, such as
SELECT DECODE (
          SIGN ( (c.date_and_time_ordered - b.date_and_time_created) - 5),
          -1, 'less than 5',
          'greater than or equal to 5')
          result
  FROM ...


How to include / exclude filter statement in R httr query for Localytics

Question: I can successfully query data from Localytics using R, such as the following example:
r <- POST(url = "https://api.localytics.com/v1/query,
           body=list(app_id=<APP_ID>,
                     metrics=c("occurrences","users"),
                     dimensions=c('a:URI'),
                     conditions=list(day = c("between", "2020-02-11", "2020-03-12"),
                                     event_name = "Content Viewed",
                                     "a:Item URI" = "testing")
           ),
           encode="json",
           authenticate(Key,Secret),
           accept("application/json"),
           content_type("application/json"))
stop_for_status(r)

But what I would like to do is create a function so I can do this quickly and not have to copy/paste data.
The issue I am running into is with the line "a:Item URI" = "testing", where I am filtering all searches by the Item URI where they all equal "testing", but sometimes, I don't want to include the filter statement, so I just remove that line entirely.
When I wrote my function, I tried something like the following:
get_localytics <- function(appID, metrics, dimensions, from = Sys.Date()-30,
                           to = Sys.Date(), eventName = "Content Viewed",
                           Key, Secret, filterDim = NULL, filterCriteria = NULL){

  r <- httr::POST(url = "https://api.localytics.com/v1/query",
                  body = list(app_id = appID,
                              metrics = metrics,
                              dimensions = dimensions,
                              conditions = list(day = c("between", as.character(from), as.character(to)),
                                                event_name = eventName,
                                                filterDim = filterCriteria)
                              ),
                  encode="json",
                  authenticate(Key, Secret),
                  accept("application/json"),
                  content_type("application/json"))
  stop_for_status(r)
  result <- paste(rawToChar(r$content),collapse = "")
  document <- fromJSON(result)
  df <- document$results
  return(df)
}

But my attempt at adding filterDim and filterCriteria only produce the error Unprocessable Entity. (Keep in mind, there are lots of variables I can filter by, not just "a:Item URI" so I need to be able to manipulate that as well.
How can I include a statement, where if I need to filter, I can incorporate that line, but if I don't need to filter, that line isn't included?
Answer: conditions is just a list, so you can conditionally add elements to it. Here we just use an if statement to test of the values are passed and if so, add them in.
get_localytics <- function(appID, metrics, dimensions, from = Sys.Date()-30,
                           to = Sys.Date(), eventName = "Content Viewed",
                           Key, Secret, filterDim = NULL, filterCriteria = NULL){

  conditions <- list(day = c("between", as.character(from), as.character(to)),
                     event_name = eventName)
  if (!is.null(filterDim)  & !is.null(filterCriteria)) {
    conditions[[filterDim]] <- filterCriteria)
  }

  r <- httr::POST(url = "https://api.localytics.com/v1/query",
                  body = list(app_id = appID,
                              metrics = metrics,
                              dimensions = dimensions,
                              conditions = conditions),
                  encode="json",
                  authenticate(Key, Secret),
                  accept("application/json"),
                  content_type("application/json"))
  stop_for_status(r)
  result <- paste(rawToChar(r$content),collapse = "")
  document <- fromJSON(result)
  df <- document$results
  return(df)
}


Discrete math equivalence classes

Question:
Let $A$ be a finite set of size $k$ and $R$ a relation on the power set $P(A)$ defined by $R=\left\{(A,B) : |A|=|B|\right\}$

Show that $A$ is an equivalence relation.
Let $a \in A$. What is the size of the equivalence class of $\{a\}$?
Let $a, b$ be two different elements of $A$. What is the size of the equivalence class of $\{a, b\}$?

I'm having a lot of trouble with this problem. It says the relation is on the power set, but then I'm finding the size of the equivalence class of elements within $A$, and then of $(a,b)$? I'm honestly completely lost and don't have any base to build off of. I think I'm a bit confused on the concept of the size of equivalence classes in general.
Comment: $\{a\}$ and $\{a,b\}$ are elements of $P(A)$.  The ordered pair $(a,b)$ occurs nowhere in the problem.
Answer: Informally, under this equivalence relation two subsets are equivalent when they have the same size.
Thus, the equivalence class of $\{a\}$ consists of all subsets of $A$ with cardinality/size equal to one. Thus the size of this equivalence class is $k=|A|$.
The equivalence class of $\{a, b\}$ consists of all two element subsets of $A$. Thus the size of this equivalence class is $\binom{k}{2}=\frac{k(k-1)}{2}$.
Answer: You mean to prove that $R$ is an equivalence relation. There are three criteria that must be followed in order to prove $R$ is an equivalence relation,

Reflexive
Symmetric
Transitive

To get you started, with generic sets $B,C,D \in \mathcal{P}(A)$, see that we always have $$|B| = |B|$$ so $R$ is reflexive. This would mean $(B,B) \in R$  for some $B \subseteq A$
To show it's symmetric, it  requires you to show that if $|B| = |C|$, then $|C| = |B|$.
To show it's transitive, it requires you to show if $|B| = |C|$, and$ |C| = |D|$, then |B| = |D|$

Discrete math equivalence classes


How to identify method subscribe has executed in Ionic 2 using Angularfire2

Question: I am trying to get data from Firebase in my Ionic2 project using Angular2. Following is the code.
  getNextItem(): string[] {

    this.af.database.object(`/user/${uid}/data`)
    .subscribe(value =>{
      this.item = value;
    });
    return this.item;
  }

In this case, my item is always empty as the subscribe method executes after my method is complete. I also can not return the item from inside the subscribe method.
So how will I be able to get the data and how to identify when subscribe method has executed?
Answer: Would you not have to create a new Promise maybe?
return new Promise(resolve => {
   this.af.database.object(`/user/${uid}/data`).subscribe(resolve => {
         this.item = resolve;
   });
 });

havent tried this code so not sure it works.
I generally write something like this
getDataByUser(fbPath: string, userId: string) {
    return new Promise(resolve => {
        this.af.database.list(`${fbPath}/${userId}/data`)
            .subscribe(res => resolve(res));
    })
}


A weakly bounded operator family on a Banach space is also uniformly bounded

Question: Given $X$ a Banach space, to say $\{A_i\}_{i\in I}$, a family of bounded linear operators from $X$ to another normed space $Y$, is weakly bounded is to say that, fixing any $x\in X$ and $y^*\in Y^*$, the numerical set $\{y^*(A_i x)\}_{i\in I}$ is bounded. Now the result to prove is: a weakly bounded family must also be uniformly bounded, i.e., $\{\|A_i\|\}$ is bounded.
This is apparently a corollary of Banach-Steinhaus Theorem (aka uniform boundedness principle, UBP). I think proof by contradiction is the right track, but I've been stuck on the proper choice of $y^*$. My hunch is that we need to vary $y^*$ rather than just comstructing a specific one to violate the weak boundedness.
Any help is appreciated.
Comment: Hint: First show that if $y^\ast (A) $ is a bounded set for ever $y^\ast$, then $A \subset Y $ is bounded.
Comment: @PhoemueX that's exactly the difficult part.
Comment: @PhoemueX it still boils down to finding *one* $y^*$ such that $y^*(A)$ is unbounded when $A$ is unbounded.
Comment: Use the embedding of $Y $ into its bidual and the uniform boundedness principle.
Comment: @PhoemueX Thanks! This is in effect an answer already.
Answer: As I hinted at in the comments, one way to show this is as follows:

One uses the isometric embedding of $Y$ into its bidual to show that if $A \subset Y$ is such that $y^\ast (A) \subset \Bbb{K}$ is bounded for each $y^\ast \in Y^\ast$, then $A$ is a bounded set. Note: This does not even use completeness of $Y$, just that of $Y^\ast$.
Using the predecing point and the given assumptions, we conclude that for every $x \in X$, the set $\{A_i x \,:\, i \in I\}$ is bounded in $Y$. Now, another application of the uniform boundedness principle yelds the claim. This uses completeness of $X$.


How to Disable Spring Security Filters

Question: I have a situation where I have a RESTful service which is using a pre-authenticated token for authentication. I've implemented my own preAuth filter, and that's working great. My issue is that some requests sent to my service include BasicAuthorization which isn't for my application. (I wish they didn't, and they shouldn't, but they do and I can't control that.)
Now, it seems that Spring Security automatically makes a BasicAuthorization filter, but that filter is catching these irrelevant authentication headers, and then throwing the error:
Error 401 No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken

So I want to turn off the filters I'm not using in Spring Security, but I can't figure out how. I know I could create dummy filters and replace the auto filters, or I could just delete all basic Auth headers before the application enters the filter chain, but those both seem like hacks.
When I looked in the spring security filter documentation I found the part that shows you how to add a FilterChainProxy, but it seems like I'm having to manually create all the beans for spring security that way. Specifically I got to the part where you need an AccessDecisionManager, but I thought that is what my
<http use-expressions="true" create-session="stateless"
        authentication-manager-ref="authenticationManager">

        <intercept-url pattern=[etc ...]

stuff was for, and I still want to use that. Anyone have any suggestions?
Comment: Does the rest of your spring security config look like the Siteminder Example Configuration here? http://static.springsource.org/spring-security/site/docs/3.0.x/reference/preauth.html
Comment: This is strange... I thought that BasicAuthenticationFilter is not registered if you don't have ``. Is your example accurate?
Comment: Actually, I dont see the line  in your  element...   hopefully adding that would make your filter get called first.
Comment: @samlewis It's actually not an issue of the pre-auth filter not being called first. It's an issue of a method that requires no authentication attempting to authenticate with an HttpBasicAuth auth header, and that throwing an exception, even though I don't want authentication on that method. An alternative solution would be to set that specific request as `security:none` (or however that is), and then put my pre-auth filter in front of the basic filter in the order, but again that sounds like a bit of a hack to me.
Comment: After looking into it for a while, it turns out my example was incomplete. I was using [baeldung's spring security with a REST service guide](http://www.baeldung.com/2011/11/20/basic-and-digest-authentication-for-a-restful-service-with-spring-security-3-1/) and foolishly included `` from that. So ... sorry for the bad question.
Answer: After looking into it for a while, it turns out my example was incomplete. I was using baeldung's spring security with a REST service guide and foolishly included <http-basic /> from that. So ... sorry for the bad question.

How to Disable Spring Security Filters


Given any two angle values, find angle of incidence or difference

Question: I want to find the angle of incidence or simply the difference between some ray and some surface, given their respective angles in some coordinate system. No need for further definition, it's just a question about angle differences.
As far as I can tell, the angles can have any values on the real number line (like -10000 or + 999999). (I can bring them in the [0,360] range or any other range, but that counts as 1 computational step, and at the end I want the computationally simplest process. So a computational process that would not require bringing both angles to a range first, but say, only bringing their difference to a range would be one step simpler)
I just want to know if they are rather parallel (angle between the two is close to zero, they almost go in the same direction) or rather perpendicular (almost 90° from one another). Therefore an answer that is either negative or greater than 90° has no usable meaning for me.
What is the simplest way to get there in all input situations ? I mean, with the least computation steps.
NB : Angle to normal ("angle of incidence" in physics) or the complement to 90° of that are all the same to me, since at the end I am guaranteed a result between 0 and 90° I can always take the complement to 90°.
Best I can muster so far :

Take the difference between the angles
Bring to [0,360]
If larger than 90, take complement to 180. Else, finished.
Take absolute value.
Go to 3.

Actually you only need to go through 3. twice maximum, given 2.
Example :

Red is given as 350°. Green is given as -210° degrees. The expected result is 20°.

Difference is -210-350 = -560°.
Mod 360° : 160°
Larger than 180° : take 180-160 = 20°.
Take absolute value : 20° (unchanged).
Go to 3.
Smaller than 180° : finished.
Comment: Sorry, but I don't understand **at all** what you attempt to explain, and I must not be alone. Please, be much more precise. And give graphical examples.
Comment: How is your surface defined ? By an implicit equation ? Do you need to find the angle with the **normal** (orthogonal) vector at the surface where the ray hits the surface ? What is the point of mentionning huge angle values as -10000 or +999999, knowing that we reduce them modulo 360 in order to work on [0,360] or preferably on [-90,90]... Besides why 2 angles in your title ? How are they related ?
Comment: Thanks for the added information. I discover that it is a 2D (not 3D) issue. Suggestion : if $\alpha, \beta$ are your two angles, brought back in a reasonable range $[-180°,+180°]$ for example, take the minimum value among all absolute values $d_{p,q}:=|(\alpha+p*180°) - (\beta+q*180°)|$ where $p, q$ take a certain number of integer values "in the good range".
Answer: The easiest way to calculate the angle between two lines who can be described as vectors, is based on:
$$\overrightarrow{a} \cdot \overrightarrow{b} = ||\overrightarrow{a}|| \cdot ||\overrightarrow{b}|| \cdot \cos(\alpha)$$
Where $\alpha$ is the angle between $\overrightarrow{a}$ and $\overrightarrow{b}$.
Comment: Okay I see, I mean I really only get two angles at input but I guess I could simulate vectors. And this has all the guarantees needed ? For examples if I end up calling $arccos$ it will have the image range [0,$\pi$] and I need [0,$\frac{\pi}{2}$]. I could just take the complement to $\pi$ then I guess.
Comment: Okay if my two angles are called $\beta$ and $\gamma$ and their desired difference is $\alpha$ then this devolves into $\alpha = arccos(cos(\beta-\gamma))$ and $cos$ and $arccos$ are the ones doing the job of guaranteeing ranges.
Indeed if I simulate the two vectors to be $(cos\beta, sin\beta)$ and $(cos\gamma, sin\gamma)$ then the dot product is $cos\beta cos\gamma + sin\beta sin\gamma$ which is $cos(\beta-\gamma)$. On the other side of the equation we have both vector norms equal to one and only $cos\alpha$ left.
Comment: @Dominique I am sorry but this is not an answer, just a comment.


First order non linear equation

Question: $$(1+y)y' + (1-2x)y^2 = 0$$
I thought of using bernoulli equation but i cant bring it to the form
$$y' + P(x)y = F(x) y^n$$
My attempt
$$(1+y)y' + (1-2x)y^2 = 0$$
$$\frac{dy}{dx} = (2x-1)\left(y-1 + \left(\frac{1}{y}+1\right)\right)$$
Should i continue?
Answer: This equation is separable.  Put all the $y$s on the left, and all the $x$s on the right, then integrate them separately.
Comment: ok thanks ill trry it!

First order non linear equation