text:
Q: I need to pass some data through some components React I'm doing a broker simulator and I need to pass the data (side,price,volume,timestamp) into different tab, which is like grandparent's brother. The problem is I have no idea, how to transport data that far
Modalbuy.js
import React from "react";
import "./modal.css";

const Modalbuy = ({active, setActive,price}) => {

    return (

 setActive(false)}>

 e.stopPropagation()}>
            Make order

BUY {price}

            <input placeholder="Volume">{volume}</input>

              <button onClick={() =>{this.props.addData("BUY", price, volume,)}}>Ok</button>
              <button>Cancel</button>

    )
}

export default Modalbuy;

Select.js
import React, {useState} from "react";
import './select.css'
import Modalbuy from "../popup/Modalbuy"
import Modalsell from "../popup/Modalsell"
import { useEffect } from "react";

const Select = () => {

    const [value, setValue] = useState("");

    const [usdrub, setUsdrub] = useState(Math.random() * (64-61) + 61);
    useEffect(() => {
      const interval = setInterval(() => {
        setUsdrub(Math.random() * (64-61) + 61);
      }, 10000);
      return () => clearInterval(interval);
    }, [])

    const [rubusd, setRubusd] = useState(Math.random() * 2);
    useEffect(() => {
      const interval = setInterval(() => {
        setRubusd(Math.random() * 2);
      }, 10000);
      return () => clearInterval(interval);
    }, [])

    function changeSelect(event) {
        setValue(event.target.value)
    }
    const [modalBuyActive, setModalBuyActive] = useState(false)
    const [modalSellActive, setModalSellActive] = useState(false)

    function addData(side, price, volume, timestamp) {
        this.setState({side:side, price:price, volume:volume, timestamp:timestamp})
    }

    return (

        <select value = {value} onChange={changeSelect}>
         <option>Choose instrument</option>
        <option name="USD/RUB" value={usdrub}>USD/RUB</option>
        <option name="RUB/USD" value={rubusd}>RUB/USD</option>
        </select>

 <button className="Buy" type="btn" onClick={() => setModalBuyActive(true)}>BUY {value + 1} </button>

<button className="Sell" type="btn"  onClick={() => setModalSellActive(true)}>SELL {value}</button>

          <Modalbuy active={modalBuyActive} setActive={setModalBuyActive} price={value + 1} addData={addData}/>
          <Modalsell active={modalSellActive} setActive={setModalSellActive} price={value}/>

    )
}

export default Select

Trading.js
import React from "react";
import Timer from "./Timer";
import Select from "./select_curr/Select";

const Trading = () => {
    return (

        <Timer/>
        <Select/>

    )
}

export default Trading;

Page.js
import React from 'react'
import { Tabs, TabList, TabPanel, Tab } from 'react-re-super-tabs'
import CustomTab from './customTab'
import Trading from '../trading/Trading.js'
import Table from '../archive/table'

const Page = () => {
  return (

    <Tabs activeTab='about'>
      <TabList>
        <Tab component={CustomTab} label='Trading' id='trading' />
        <Tab component={CustomTab} label='Archive' id='archive' />
      </TabList>
      <TabList>
        <TabPanel component={Trading} id='trading' />
        <TabPanel component={Table} id='table' />

      </TabList>
      </Tabs>

  )

}

export default Page;

So I need to make a table in Table.js and import there data I got from module dialogue

A: To summarize the way I understand your problem, The component Modalbuy need to share data with your component Table.
Here are some way I can advise you.
1. The common Parent manage the state
const Page = () => {
  const [yourData, setYourData] = useState([])
  return (
    [...]
    <TabPanel component={props=>(<Trading {...props} value={yourData} onChange={setYourData} />)} id='trading' />
    <TabPanel component={props=>(
)} id='table' />
    [...]
  )
}

This implies intermediate component are in charge to follow those new props to Modalbuy
2. Using Redux librairy
Redux is basicly a librairy to help you to define a global state for your app. You define actions your components can call to transform this global state. On the other way, components can subscribe to that state to be refreshed when a change happen.
Don't hesitate to have a look to tutorials https://react-redux.js.org/tutorials/quick-start
3. Using React Context
export const YourDataContext = React.createContext({})
const Page = () => {
  const [yourData, setYourData] = useState([])
  return (
    <YourDataContext.Provider value={{yourData, setYourData}}>
    [...]
    </YourDataContext.Provider>
  )
}

const Modalbuy = ({active, setActive,price}) => {
  const { yourData, setYourData } = React.useContext(YourDataContext)
  [...]
})

You define a context YourDataContext. You share a value to this context, here we create a state and passing the getter/setter. All child of the Provider can access the attribute value with the hook React.useContext(YourDataContext)


text:
Q: Routing a Heterogeneous Fleet of Vehicles I know it is possible to solve a VRP problem using OptaPlanner. I would like to know if it is possible to route a Heterogeneous Fleet of Vehicles using OptaPlanner.

A: Yes, it's been done before.
Just change the (Vrp)Vehicle class accordingly. Currently it already has a capacity, so you can already model vehicles with different capacities. But it's trivial to add other properties (such as maximumSpeed, driverLicenseLevelRequirementEnum, safeAgainstRobberyBoolean, ...).
Then simply use those properties in your new/existing score constraints.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Write a program that can pause/resume the existing running program I need to write a program that will halt the existing running program in the system and prompt for a question. After answering the question the running program will continue. [This halt will occur after a fixed interval of time.]
I need to implement the pause/resume feature.

*

*Is it feasible?

*If yes then what would be the approach?

Note: Please ask for any clarification, If I am unable express my problem statement.


text:
Q: OpenSearch Dashboards with Podman gets the wrong unexposed IP I have a machine X with a lot of IPs, podman-compose with OpenSearch and OpenSearch Dashboards links the images to the wrong (unexposed) IP. I tried to force the IP but if I do so, podman-compose would break. How can I do so?
I tried to add an IPv4 in the docker-compose.yml, I tried to modify the images and force the right IP whenever I found 0.0.0.0, but it keeps breaking.

A: Docker / Podman container IPs are not accessible from external clients.
You need to expose TCP or UDP ports from your container to the host system and then clients will connect to :.
The host port and the container port do not need to be the same port.
i.e. you can run multiple web server containers all using port 80 however you will need to pick unique ports on your host OS that are not used by other services to port-map to the containers.  i.e 80->80, 81->80, 8080->80 etc.
Once you create the port definitions in your container configuration Podman will handle the port forwarding from the host to the container.
You might need to open the ports on the host firewall to allow clients to connect. 0.0.0.0 is another way of representing the local host.
Let say your host is 10.1.1.20 and your OpenSearch Dashboards container is 172.16.8.4 and your dashboard web app is configured to listen on port 5001/TCP.
You will need a ports directive in your docker-compose.yml file to map the host port 5001 to the container port 5001 similar to the below.
containers:
opensearch-dashboard:
ports:
- "5001:5001"
As long as port 5001 is permitted on your host firewall, the client should be able to connect using https://10.1.1.20:5001/


text:
Q: Handling jQuery AJAX failures with statusCode I'm trying to globally detect and react to a certain statusCode, using jQuery's statusCode function. However, when a specific call fails, it seems be hitting both the original error and THEN the statusCode. Why is this happening? Can it just hit the statusCode first?
Here is my ajaxSetup:
$.ajaxSetup({
    statusCode: {
            412 : function(data) {
               alert('do something!');
            }
     }
});

And here is a sample instance:
$.ajax({
     type: "GET",
     url: 'a_url.json',
     dataType: 'json',
     data : {
          'id': dnaRefTOID
     },
     success: function(data) {
          alert('success');
     },
     error : function(xhr, status, error) {
           alert(xhr.statusText);
     }
 });

What I'm seeing is that the call is hitting 'error' before hitting statusCode. I want it to hit statusCode and statusCode always. This example is obviously spread across many ajax calls, so I don't want to use an if statement in each error or else it defeats the point of using statusCode.
Does anyone have any ideas?

A: As far as I know you can't achieve that without changing jQuery itself.
You could do something like this:
$(document).ajaxError(function(event, jqxhr, settings, exception) {
   if (jqxhr.status == 412) {
      //handle status code 412 here
   }
});


text:
Q: Using Plists in other environments Are Pists limited to be used on a OSX and iOS system?
I am thinking of the architecture of my app and one of many ways to import data into an iPhone app is via a Plist and you can save to it as well.
Now if say that plist is able to be exported away from the app in it's raw format, will it be accesible by say Android or Windows Phone format? Or will it need to be converted?
The way I understand it is that a Plist is a XML format right?
I am probably wrong, but that is what I can make up of the file when I look at it.
Cheers

A: A property list, as explained in the Property List Programming Guide, is any of these things:

*

*a string

*a blob of binary data

*a date

*an integer

*a floating-point number

*a Boolean value

*an array of property lists

*a dictionary whose keys are strings and whose values are property lists

There are two common ways to serialize a property list.
One is the XML format, which you are aware of.  This format is sort of documented on the plist(5) man page.
The other is a binary format, which is much more compact and faster to encode and decode.  It is not officially documented anywhere, but its format is described in the comments and code of CFBinaryPlist.c, which is included in the open source release of Apple's Core Foundation framework.
If your data doesn't use dates or binary blobs, you may find it easier to use JSON than an XML plist.  Starting in iOS 5 and OS X 10.7 (Lion), Apple provides the NSJSONSerialization class to serialize and deserialize JSON, and there are JSON libraries for just about every platform and language under the sun.

A: You are right. Plist is actually an xml formatted file with a plist header and can be parsed by any xml parser. Since xml can be used in variety of environments, plist can do the same thing. Just change its suffix to xml and you can do whatever you want.


text:
Q: Text formatting in different versions of Python I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another.
In python < 2.6, it's done like this:
n = 3
print "%s * %s = %s" % (n, n, n*n)

whereas in python >= 2.6 the best way to do it is:
n = 3
print "{0} * {0} = {1}".format(n, n*n)

But how about when you want the script to be runned in any python version?
What's better, to write python<2.6 code to assure instant compatibility or use the python>=2.6 code that is going to be the way it's used in the future?
Is there any other option to write code for the actual python versions without loosing compatibility with olders?
Thanks

A: str.format() was introduced in Python 2.6, but its only become the preferred method of string formatting in Python 3.0.
In Python 2.6 both methods will still work, of course.
It all depends on who the consumers of your code will be. If you expect the majority of your users will not be using Python 3.0, then stick with the old formatting.
However, if there is some must-have feature in Python 3.0 that you require for your project, then its not unreasonable to require your users to use a specific version of the interpreter. Keep in mind though that Python 3.0 breaks some pre 3.0 code.
So in summary, if you're targeting Python 3.0, use str.format(). If you're targeting Pyhon <3.0, use % formatting.

A: What about the good old tuple or string concatenation?
print n, "*", n, "=", n*n
#or
print str(n) + " * " + str(n) + " = " + str(n*n)

it's not as fancy, but should work in any version.
if it's too verbose, maybe a custom function could help:
def format(fmt, values, sep="%%"):
   return "".join(str(j) for i in zip(fmt.split(sep), values) for j in i)

#usage
format("%% * %% = %%", [n, n, n*n])

A: You should have a look at the string.Template (link for 3.1) way to format a string, the API is stable across all versions >=2.5.
I think that concatenation is the simple way to achieve portability for both old and new Python versions. Obviously it's slow, verbose and less pythonic than alternatives.


text:
Q: How to cache ResponseEntity in spring boot I am trying to cache ResponseEntity in spring boot but unable to find a proper way to implement the same.
There are few examples where
        return ResponseEntity.ok()
            .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
            .body(body);

But my problem here is that I am using an external library that returns
ResponseEntity<Resource>

and I wanted to cache that response. so it should be like
ResponseEntity<Resource> getResource() {

       ResponseEntity<Resource> resource = getResourceFromExternalFunction();
       // wanted to cache this resource
       return cachedResource
}

If I apply above technique for my code, it would be like
ResponseEntity<Resource> getResource() {

       ResponseEntity<Resource> resource = getResourceFromExternalFunction();
       return ResponseEntity.ok()
            .cacheControl(CacheControl.maxAge(20, TimeUnit.SECONDS))
            .body(resource );
}

it would return
ResourceEntity<ResourceEntity<Resource>>

which is not expected. Can some one help here please

A: Always be on the look out for SpringBoot libraries that already exist before you try and reinvent the wheel. Lucky for you, the Spring community already has such a caching library which should make your life much easier, you can find a tutorial on it here:
Baeldung: A Guide to Caching in Spring


text:
Q: Why doesn't the const lvalue reference to an array compile below? The const lvalue reference int(const& crb)[3] = b; doesn't compile. Why?
#include<iostream>

int a = 1;
int b[3] = { 1, 2, 3 };

int main(){
    int& ra = a;             // Ok
    int const& cra = a;      // Ok

    int(&rb)[3] = b;         // Ok
    int(const& crb)[3] = b;   // Doesn't compile
}

Error message emitted by g++:
error: expected primary-expression before 'int'
int(const& crb)[3] = b;
^~~

A: Reference is always constant, you can't change reference. int const (& crb)[3] = b; here we have reference to array of const int, we can also write  const int (& crb)[3] = b; It would be the same.
Pointers have a difference, pointer can be changed
const int *p; - here it is pointer on const int
int const *p; - here it is const pointer on int
const int const *p; - here it is const pointer on const int


text:
Q: Probability of wearing a coat & having it snow. I haven't been able to solve this, could you please help?
Steve has lived in Boston for a long time. From experience, he knows that each day has a 5%
chance to be snowy. Steve looks ahead to the next 10 days.
Steve decides that, without checking the weather, he will wear his heavy coat to work 3 of
those days. What is the probability Steve will wear his coat on at least one snowy day?
Thank you

A: The $7$ days on which Steve does not wear his heavy coat on are irrelevant. He has chosen the three days on which he will wear his heavy coat, and on each of these three days, there is a $5\%$ chance of snow.
The probability that it will snow on at least one of these days is $1$ minus the probability that it will snow on none of these days. This is $$1-0.95^3 = 0.142625 = \boxed{\,14.2625\%\,\,}$$


text:
Q: .NET library for use with XBRL or XLINK Does anyone know of a good .NET library I can use to process XBRL or XLINK documents?

A: Gepsio: XBRL Document Object Model for .NET

A: I would go for Altova XML library instead

A: There is the GEPSIO Open Source project.
However, GEPSIO doesn't support all XBRL specifications, just XBRL 2.1 (and even this seems incomplete).
There is another commercial XBRL .NET API available at that supports all specifications: The AMANA XBRL Engine
Please see official list of "Tools and services" on xbrl.org.


text:
Q: Get active panel in a jquery accordion I´m struggling with getting the active panel in a jquery accordion.
Given the equivalent of a select-element:
<select data-bind="options: Tasks, optionsText: 'TaskName', value: SelectedTask"></select>

where Tasks = ko.observableArray(); initialized by a db-call.
What I want to achieve is to set SelectedTask to the chose panel in my jQuery UI accordion.
My accordion in created by a knockout-loop:

Data-binding "SelectedTask" to any of the header elements in the template fails, making me think I have to do this in the accordion code, for instance in a "click" event. I´m able to defining the click-event, but how do I set "SelectedTask" to the item that has been clicked?

A: If you only care about setting the selectedTask to an accordion panel that is opening, then consider the beforeActivate event handler on the jqAccordion.

If the accordion is currently collapsed, ui.oldHeader and ui.oldPanel will be empty jQuery objects. If the accordion is collapsing, ui.newHeader and ui.newPanel will be empty jQuery objects.

I don't like this wording as it's kind of confusing, but basically, $(ui.newHeader)[0] is truthy when the panel is about to be expanded and $(ui.oldHeader)[0] is truthy when the panel is about to be collapsed.  And we only care about setting selected if it's about to expand (you could set selected to null if it's about to collapse but that's a preference call).
So in your CustomBinding, add this to your accordion options:
$(element).accordion({
    beforeActivate: function (event, ui) {
        if ($(ui.newHeader)[0]) {
            bindingContext.$root.SelectedTask(ko.contextFor($(ui.newHeader)[0]).$data);
            // I think this is equivalent to:
            // viewModel.SelectedTask(ko.contextFor($(ui.newHeader)[0]).$data);
        }
    }
});

Let me know if this works.  This is kind of a shot in the dark (untested), but I think it should.


text:
Q: Difference between 'study on' and 'study into' In the sentences

This is the only study on/into the effect of X in aquatic birds.
The studies on/into aquatic birds have been carried out on species A and B.

Which word do we use?
Learner's Dictionary defines 'on' as:

used to indicate the subject of something
  •   a book on [=about] North American birds
  •   a discussion on current events

and 'into' as:

relating to or concerning (something)
  •   an investigation into the causes of the accident

Am I right in thinking that 'into' is used in these contexts when the study is about the result of an action (based on Google searching for both usages)?
i.e. 'study on birds' and 'study into the effect of X'. Or can they be used interchangeably?

A: You can't reliably predict which preposition will be used in any particular context from its dictionary definition—see my Answer here. You have to learn, word by word, which particular preposition each verb, adjective or noun 'selects' or 'licenses' to express a particular meaning or relationship.
For instance, the verb study casts its field or topic as a direct object—we studied the effect of X on aquatic birds. When transitive verbs are nominalized, their direct objects are most often cast as preposition phrases headed by of:

A study of the effect of X ...

Nominal study also licenses on PPs:

A study on the effect of X ...

But of would be preferred if you went on to use an on PP as complement of a different word, with a different sense:

A study of the effect of X on Y ...

Study does not license into PPs as complements, either as a noun or as a verb. You would find an into PP following study only as an adjunct or complement of another consituent:

We studied into the night ... here into the night is not a complement of study but an adjunct locating the action in time.

The verb investigate likewise casts its field or topic as a direct object—we investigated the effect of X on aquatic birds—and its nominal derivative investigation likewise licenses of PPs:

An investigation of the effect of X ...

Investigation, however, also licenses into PPs:

An investigation into the effect of X ...

Here investigation is metaphorically treated like a process of digging into a formless mass to find the relevant information, as if with a probe or shovel.
The into construction tends to be used mostly in contexts where investigation designates the process of investigating—we are conducting an investigation into the effect of X. It is unusual to find into used when investigation designates the outcome—in the title of a paper, for instance, where the results are reported.
Often the nominal derivative will license the same prepositions as its mother verb. But this doesn't usually run backwards, from the noun to the verb. For instance, we never say:

* We studied on the effect of X ...
  * We investigated into the effect of X ...

These are not hard and fast "rules", but they reflect 'standard' formal usage.


text:
Q: Closest facilities using Pgr_Withpoint I am trying to calculate the shortest path's distance from certain locations to their closest schools,
I used the Pgr_WithPointsCost Function to get the result from one location to its 10 closest destinations (One to Many), But I can't use the (many to many) scripts since Pgr_WithPointsCost will calculate the shortest distance between every point of the source and every target point. The problem is my data set is huge and when I launch the script it crashes.
This is the script I used to calculate the distance

A: There is a handy function currently in pgRouting's develop branch coined dijkstraNear. This will help you compute many to many.
pgr_dijkstraNear(Edges SQL, Start vids, End vids [, directed] [, cap], [global])
RETURNS SET OF (seq, path_seq, start_vid, end_vid, node, edge, cost, agg_cost)
OR EMPTY SET


text:
Q: Neural network when not to shuffle? So for the MLP regressor in sklearn there is the option to shuffle. And I assume it means that before dividing into batches the data is shuffled and thus at each iteration the batches are different from the batches in the previous iteration?
Now, I did read about why to shuffle but are there also instances when not to shuffle? I thought probably with time-series data? Because you destroy the temporal ordering?

A: Shuffling does not harm. It helps with the gradient updates. For time series data, we prepare the data such that the entries of previous time instants are fed into RNNs in order, i.e. $X, y$, where $X$ contains the previous time instants' targets or features. Shuffling is applied for different data samples, i.e. $(X_1,y_1), (X_2,y_2) ...$
Each libraries' shuffling logic can be different. In MLPRegressor, it says

Whether to shuffle samples in each iteration

So, in each iteration (probably epoch), the data is shuffled. So, at every epoch, the batches will be different.


text:
Q: Difference between a uniform stable and a uniform attractive solution Consider the following time-varying system:
$\dot{x} = f(x,t)$
The solution of this system which starts from the point $x_0$ at time $t_0 \geq 0$ is denoted as $x(t;x_0,t_0)$ with $x(t_0;x_0,t_0)=x_0$. The solution $x(t;x_0,t_0)$ of above system is:

*

*Uniform stable, if for each $\epsilon >0$ there exists a $\delta(\epsilon)>0$ such that:
$|\tilde{x}_0-x_0|<\delta  \Rightarrow  |x(t;\tilde{x}_0,t_0)-x(t;x_0,t_0)|<\epsilon, \forall t \geq t_0$

*Uniform attractive, if there exist an $r>0$ and, for each $\epsilon >0$, a $T(\epsilon)>0$ such that:
$|\tilde{x}_0-x_0|<r  \Rightarrow  |x(t;\tilde{x}_0,t_0)-x(t;x_0,t_0)|<\epsilon, \forall t \geq t_0+T$

I find it very difficult to understand the differences between these definitions.

A: Let us interpret the initial datum $\tilde{x}_0$ as a perturbation of $x_0$. The "uniform stable" condition means that, if the perturbation is small enough, then the solution with perturbed data stays near the original solution at all times.
On the other hand, the "uniform attractive" condition means that there exists an attractive region, namely the ball $B(x_0, r)$. Every time the perturbed datum lies in this region, the corresponding solution is asymptotically close to the original. This means that, if we go far enough in the future, the two solutions are as close as we want.
Note that the "uniform stable" condition does not imply that the solution with perturbed data is asymptotically close to the original. An example that might be illuminating is a simple harmonic oscillator
$$
\begin{cases}
\dot{v}+\omega^2 x=0 \\
\dot{x}=v.
\end{cases}
$$
Here $x$ can be interpreted as the position and $v$ as the velocity of a mass point attached to a spring. Clearly, the initial condition $(x_0, v_0)=(0,0)$ gives rise to the stationary solution $(x, v)=(0,0)$, corresponding to the point being motionless. But a small perturbation $(\tilde{x}_0, \tilde{v}_0)$ will give rise to the oscillating solution
$$
(\tilde{x}(t), \tilde{v}(t))=\left( \tilde{x}_0\cos(\omega t)+\frac{\tilde{v}_0 \sin(\omega t)}{\omega} , -\omega \tilde{x}_0 \sin(\omega t)+\tilde{v}_0 \cos(\omega t)\right),
$$
which is close to $(0,0)$ if $\sqrt{ \tilde{x}_0^2+\tilde{v}_0^2 }$ is small enough, but is not asymptotic to $(0,0)$ since it keeps oscillating.
Therefore the initial datum $(0,0)$ is for this system uniform stable but not uniform attractive.

A: Your notion of uniform attractive is also known as asymptotic stability. The notion of uniform stability is often called just the stability (or Lyapunov stability). In my experience, the notations in italics are much more widespread.
The difference between these stabilities lies in the behaviour of the solutions. In the case of stability, your solution changes by at most a constant for a sufficiently small change of initial data.
In the case of asymptotic stability, if the change of initial data is suffciently small, then the distance between the solutions tends to zero (some sort of convergence).
You can try to look at the system
$$\dot x(t)=\begin{pmatrix}0&1\\-1&0\end{pmatrix}x(t)$$
The zero solution is stable (in fact, you can prove that $\|x(t)\| = \|x(0)\|$), but not asymptotically.
However, in the case of
$$\dot x(t)=\begin{pmatrix}-2&1\\0&-2\end{pmatrix}x(t)$$ you have asymptotical stability of zero solution. Whatever the initial data, the solution converges to zero as $t\to\infty$.


text:
Q: How to sync scroll with multiple UIScrollViews? I have 2 UIScrollViews displaying an image each (overview and zoom mode). I can scroll in both views already individually, now I want to keep the centerpoint of both views in sync.
I guess when one of the views is creating events, I need to forward them also to the other view, just can't find out which functions are relevant. Any hints?
edit: If parallel live scrolling is not possible, I want to at least sync after a scroll event.

A: This is not specific to the requirement here but helps in syncing scrollViews among different classes.
To sync scrollViews between different classes, use NSNotificationCenter to observe for a particular notification.
When scroll occurs then within the -scrollViewDidScroll: delegate method, use NSNotificationCenter to post the notification (with userInfo contents as scrollView.contentOffset.x & scrollView.contentOffset.y)
Example:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSMutableDictionary *userInfo = [[NSMutableDictionary alloc]init];
[userInfo setObject:[NSNumber numberWithFloat:scrollView.contentOffset.x]
          forKey:@"offsetX"];
[userInfo setObject:[NSNumber numberWithFloat:scrollView.contentOffset.y]
          forKey:@"offsetY"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"scrollSync"
                                      object:nil
                                      userInfo:userInfo];
}

Register for this notification in the same class or anyother class and perform the -setContentOffset: method on the scrollView/s you want synced.
.
Example on Adding Observer (either in didLoad or init or anywhere suitable to you in as many classes as you like):
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(handleNotification:)
                                      name:@"scrollSync" object:nil];

.
Example of the Selector Method
-(void)handleNotification:(NSNotification *)sender
{
float newX = [[sender.userInfo objectForKey:@"offsetX"] floatValue];
float newY = [[sender.userInfo objectForKey:@"offsetY"] floatValue];

[myOtherScrollView setContentOffset:CGPointMake(newX,newY)];
}

A: Check out the functions

*

*-setContentOffset:animated:

*-contentOffset

*-zoomScale

*-setZoomScale:animated:

*-zoomToRect:animated:
You can link this together in the delegate method -scrollViewDidScroll:, which is constantly called while the user is scrolling.


text:
Q: Laravel Facade not being loaded I started with a fresh installation of Laravel and then did the following...
I filled in the config/workbench.php file with my info: -
return array('name' => 'My Name', 'email' => 'fullysick@email.com');

I ran the artisan command: -
php artisan workbench dicksmith/curl --resources

Everything reported success.  It installed dependencies etc.
I populated the app.php file with the necessary service provider and alias information.  My code can be seen here -> http://paste.laravel.com/wFj
I'm struggling to think why it may not be loading through the Facade accessor.
Any ideas?

A: Problem solved.
I just needed to have the Facades directory located inside the package.
A stupid, stupid, stupid, stupid mistake on my behalf.  2 days lost... I feel sheepish.


text:
Q: Postfix daemon connects and immediately disconnects periodically Postfix's smtpd(daemon used to receive mail) flaps/(connects/disconnects) every 30 seconds with the connection from localhost.
May 24 17:33:03 ---- postfix/smtpd[8397]: connect from localhost[127.0.0.1]
May 24 17:33:03 ---- postfix/smtpd[8397]: disconnect from localhost[127.0.0.1] ...
...
...
May 24 17:33:34 ---- postfix/smtpd[8397]: connect from localhost[127.0.0.1]
May 24 17:33:34 ---- postfix/smtpd[8397]: disconnect from localhost[127.0.0.1] ...

Postfix seems to be working correctly and I am not seeing any faults.

A: Monit connects to check if Postfix (amongst other applications) to see if it is alive. Resulting in the connect and disconnect in the log.
Stop monitoring Postfix with Monit to verify.


text:
Q: how to send request on my flask app google colab How do I send a request from localhost to my google colab app? I want to test the functions of deepface api, because my computer is so bad for this, but i have a CORS trouble...
I still tested this code on my computer, the error with CORS was also present, but the code below helped fix this problem
import argparse
import time
import uuid
import tensorflow

from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
from flask_ngrok import run_with_ngrok
from deepface import DeepFace

tf_version = int(tensorflow.__version__.split(".")[0])

if tf_version == 2:
    import logging

    tensorflow.get_logger().setLevel(logging.ERROR)

if tf_version == 1:
    graph = tensorflow.get_default_graph()

app = Flask(__name__)
run_with_ngrok(app)

# Service API Interface
@app.route('/')
def index():
    return '
Hello, world!
'

@app.route('/analyze', methods=['POST'])
def analyze():
    global graph

    tic = time.time()
    req = request.get_json()
    trx_id = uuid.uuid4()

    print(req)
    if tf_version == 1:
        with graph.as_default():
            resp_obj = analyzeWrapper(req, trx_id)
    elif tf_version == 2:
        resp_obj = analyzeWrapper(req, trx_id)

    toc = time.time()

    resp_obj["trx_id"] = trx_id
    resp_obj["seconds"] = toc-tic

    return resp_obj, 200

def analyzeWrapper(req, trx_id=0):
    resp_obj = jsonify({'success': False})

    print(req)
    instances = []
    if "img" in list(req.keys()):
        raw_content = req["img"]  # list

        for item in raw_content:  # item is in type of dict
            instances.append(item)

    if len(instances) == 0:
        return jsonify({'success': False, 'error': 'you must pass at least one img object in your request'}), 205

    print("Analyzing ", len(instances), " instances")

    detector_backend = 'opencv'
    actions = ['emotion', 'age', 'gender', 'race']

    if "actions" in list(req.keys()):
        actions = req["actions"]

    if "detector_backend" in list(req.keys()):
        detector_backend = req["detector_backend"]

    try:
        resp_obj = DeepFace.analyze(instances, actions=actions)
    except Exception as err:
        print("Exception: ", str(err))
        return jsonify({'success': False, 'error': str(err)}), 205

    return resp_obj

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

I'm trying to do this:
app = Flask(__name__)
CORS(app, support_credentials=True)
run_with_ngrok(app)

and this:
def _corsify_actual_response(response):
    response.headers.add("Access-Control-Allow-Origin", "http://localhost:8080")
    return response

and a few more options, but none helped:(
Pls help
P.S. my JS post:
axios
        .post('http://b3a6-35-237-77-168.ngrok.io/analyze', {})
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });


text:
Q: Developer tool shows CSS I can't locate in order to edit This is probably a newb problem that's very easy to fix.
Here is my site
I'm trying to change the background color of the menu wrap: The box around the words INFO.
Using Chromes Developer tools I was able to find that the Background color is coming from CSS line 43
This is my problem
body #menu_wrap, #topmenu ul li ul li{ background:#302F2F url("http://blergh.us/wp-content/themes/theron-lite/images/transblack.png") repeat!important;}

The CSS rule however is not there when I try to edit. Instead I find this garbage:
#menu_wrap{width:1000px; float:left; background:#7d928f url(images/menu_wrap.png) repeat;}
#topmenu{text-align:center;}
.menu-header{margin:auto; padding:0; display:block;}
#topmenu ul{ margin:0; padding:0;}
#topmenu ul li{list-style-type:none; display:inline-block; position:relative; margin-top:0px;padding:25px 15px;}
#topmenu li a{ font-size:18px; color:#fff;}
#topmenu ul > li:hover{  background:#7d928f url(images/transblack.png) repeat;}
#menu-icon{display:none;}

Where is my CSS hiding?

A: If you use google chrom right click inspect element. On the css panel Matched CSS rules it shows blergh.us which is your home page.
This means
body #menu_wrap, #topmenu ul li ul li{ background:#302F2F url("http://blergh.us/wp-content/themes/theron-lite/images/transblack.png") repeat!important;}

Is on the page.
Just right click on your home. Look at the last style tag right above
   </head>
You will find your style
<style type="text/css" id="custom-background-css">
body.custom-background { background-color: #ffffff; background-image:   url('http://blergh.us/wp-content/uploads/2013/06/DAMASK.jpg'); background-repeat: repeat; background-position: top center; background-attachment: scroll; }

A: Looks like you're setting the background of the list item which is overriding the background
body #menu_wrap, #topmenu ul li ul li{ background:#302F2F url("http://blergh.us/wp-content/themes/theron-lite/images/transblack.png") repeat!important;}

change it to this
#topmenu ul li ul li{ background:#302F2F url("http://blergh.us/wp-content/themes/theron-lite/images/transblack.png") repeat!important;}

A: The problem is in Theme Functions (functions.php).
body #menu_wrap, #topmenu ul li ul li{ background:#302f2f url("<?php echo get_template_directory_uri(); ?>/images/transblack.png") repeat!important;}

Change here #302f2f with your color.

A: All the answers above are correct, however they don't really answer your question. The CSS is to be found on the client-side HTML, that's correct. But how do you edit it?
I am assuming you are running a Wordpress site (can't access the link you posted, but from the CSS you posted it is clear). Wordpress allows plug-ins to run server-side. These plug-ins can dynamically add CSS to any given page. It is likely that the CSS in your qquestion is injected by a plug-in.
To figure out which plug-in is generating that CSS, you can try disabling each plug-in one at a time. When you see the CSS isn't imported anymore, you have found the guilty one.


text:
Q: how to implement group by via distinct I have a table that contains two columns: col1 | col2. I want to select where col2 is opposition empty and col1 and only one row of duplicate rows
My thable:
// tablename [col1=integer | col2=varchar]
+-------+-------------+
| col1  |    col2     |
+-------+-------------+
|  1    |  anything1  |
|  2    |             |
|  3    |  anything3  |
|  3    |  anything3  |
|  4    |  anything4  |
|  5    |  anything5  |
|  5    |  anything5  |
|  6    |             |
|  7    |  anything7  |
+-------+-------------+

I want this output:
// newtablename
+-------+-------------+
| col1  |    col2     |
+-------+-------------+
|  1    |  anything1  |
|  3    |  anything3  |
|  4    |  anything4  |
|  5    |  anything5  |
|  7    |  anything7  |
+-------+-------------+

My query:
select * from tablename where col2 <>'' group by col1

Now I want to know, How can I implement above query via distinct (instead of group by) ?

A: Do you mean:
select distinct col1,col2
from tablename
where col2 <>''
order by col1


text:
Q: ASP.net authentication Im a CS major and I just got done designing an ASP.net site, and for the site I needed a login authentication system... I didn't want to use SQLMembershipProvider as I really wanted to learn how to make one on my own... Anyways this is what I came up with, and I was wondering if anyone can give me some feedback, tips, or advice.
Thanks in Advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Cryptography;

/// <summary>
/// Summary description for PwEncrypt
/// </summary>
public class PwEncrypt
{
    public const int DefaultSaltSize = 5;

    private static string CreateSalt()
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buffer = new byte[DefaultSaltSize];
        rng.GetBytes(buffer);
        return Convert.ToBase64String(buffer);
    }

    public static string CreateHash(string password, out string salt)
    {
        salt = CreateSalt();
        string saltAndPassword = String.Concat(password, salt);
        string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword, "SHA1");
        hashedPassword = string.Concat(hashedPassword, salt);
        return hashedPassword;
    }
       public static string CreateHashAndGetSalt(string password, string salt)
    {

        string saltAndPassword = String.Concat(password, salt);
        string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword, "SHA1");
        hashedPassword = string.Concat(hashedPassword, salt);
        return hashedPassword;
    }

    public static bool comparePassword(string insertedPassword, string incUserName, out string newEncryptedPassword, out string originalPassword)
    {
        databaseInteraction DBI = new databaseInteraction();
        string actualPassword ="";
        string salt = "";

        DBI.getSaltandPassword(incUserName, out salt, out actualPassword);
        string hashedIncPassword = PwEncrypt.CreateHashAndGetSalt(insertedPassword, salt);
       // hashedIncPassword = string.Concat(hashedIncPassword, salt);
        newEncryptedPassword = hashedIncPassword;
        originalPassword = actualPassword;
        if (newEncryptedPassword == originalPassword)
        {

            return true;
        }

        else { return false; }

    }

A: Suppose we have a table for accounts like this

Then you can create some helper class that returns an account object
private static Account GetByName(string accountName, bool activatedOnly = false)
{
    using (var context = new DBEntities())
    {
        return context.Accounts.FirstOrDefault(s =>
            s.AccountName == accountName &&
            s.IsApproved == activatedOnly);
    }
}

public static Account Get(string accountName, string password)
{
    var account = GetByName(accountName, true);
    if (account != null)
        if (!Cryptographer.IsValidPassword(password,
                                           account.PasswordSalt,
                                           account.PasswordKey))
            return null;
    return account;
}

I'm using EntityFramework but it's not important here. The main idea is show that you don't need to get the whole list of accounts (especially if you have a big list of users).
My Cryptographer class looks like
public class Cryptographer
{
    private const int keyByteLength = 20;
    public static void Encrypt(string password,
                               out byte[] salt,
                               out byte[] key)
    {
        using (var deriveBytes = new Rfc2898DeriveBytes(password,
                                                        keyByteLength))
        {
            salt = deriveBytes.Salt;
            key = deriveBytes.GetBytes(keyByteLength);
        }
    }
    public static bool IsValidPassword(string password,
                                       byte[] salt,
                                       byte[] key)
    {
        using (var deriveBytes = new Rfc2898DeriveBytes(password, salt))
        {
            byte[] newKey = deriveBytes.GetBytes(keyByteLength);
            return newKey.SequenceEqual(key);
        }
    }
}

Of cource you can implement the algorithm of your own.


text:
Q: Easily Editing XAML Color Resources in Visual Studio From the XAML designer in Visual Studio it is possible to place your cursor into the Color attribute of a Brush element and easily access the color Editor.
<SolidColorBrush x:Key="MyBrush" Color="#FF4B4B4B" />

In the above case, if you place the cursor before in the # in the XAML, then you can access the color from the properties view shown in the image below, it is easily accessed under the "Appearance" section.

That works great, the issue is only when one would like to do the same with a Color resource that is defined like this instead.
<Color x:Key="MyBrushColor">#FF4D7BBF</Color>

In the above case, placing the cursor in front of the # apparently does NOT cause Visual Studio to display the color editor anywhere in the properties view.

A: Right after I posted this, I see how to do it, hope this helps someone else.

*

*Place the cursor in the Color element.

*Right-click on the "Color" box in the Properties View and select Edit Resource...


text:
Q: More efficient way to get the start and the end points of a line (arcpy)? I am collecting start and end points for a large polyline feature class in a file geodatabase. I am using arcpy, ArcGIS 10.3, Python 2.7.3 64-bit and a 10.3 compressed file geodatabase with just one feature class (and no other objects).
One accesses the geometry properties with the SHAPE@ token which gives access to the geometry of the line (namely firstPoint and lastPoint).
with arcpy.da.SearchCursor(fc, ["OID@", "SHAPE@"],query) as search_cur:
        allLinesList = [[row[0],(row[1].firstPoint.X,row[1].firstPoint.Y),
                         (row[1].lastPoint.X,row[1].lastPoint.Y)]
                            for row in search_cur]

Reading 1 million line features (note that my lines consist of only two vertices, start and end) takes ca 5 minutes. I have tried using for loop iterating a cursor instead of comprehension and iterating features in chunks of several hundred thousands with no significant difference in time.
Do you know any other faster way to read XY of the start and end points of the lines?

A: Write a proxy class in managed C++ if this is an option for your. Realistically, you might need to perform the kind of operation that takes longer in .NET or Arcpy (large iterations of small operations).You have the choice to write a proxy class in managed C++ where you can place ArcObjects code that heavily uses the interop layer.
Once you expose this code as public methods, you can call the methods from your C# or VB .NET and even from arcpy using comtypes. Since the interop layer is only required when you call the methods of this proxy class, the execution time can be greatly reduced. For example a method for creating a line feature with 1 million records takes 30 seconds with .NET, but using managed C++, it takes 5 seconds (6 times faster).
A Proxy class is the ultimate choice where you can get the most out of ArcObjects. This is what Arcpy data access module does to improve performance.


text:
Q: How can someone have 101 reputation on multiple SE sites? I came across this account and noticed that it has got a reputation of exactly 101 on more than 20 Stack Exchange platforms, even without posting any question or answer (see image below).
At first I thought it's due to the first days of SE when there hasn't been such strict reputation gaining rules as today. But then I saw that this is even true for accounts that have been created only half a year ago.

So, am I missing something here like "Take this online introduction tour and gain 101 reputation"?
I'm asking because for me it takes quite a long time to gain enough reputation to become a productive member (voting, commenting, editing,..) on SE, especially when joining a new platform.

A: This is most probably due to the association bonus. When you have 200+ reputation on any SE site, you get a bonus of 100 on each new site you register an account on (and that is linked to the 200+ site's account, of course), in addition to the 1 reputation point you normally get upon registering anyway. So this results in the very common pattern of 101 reputation you see.


text:
Q: Automate a report from SharePoint list I am new to SharePoint online I need a help to create a report on SharePoint list which need to capture new data from a list on daily basis and send to a person.
The report format is in excel/ any other in Office 365

A: You could export SharePoint list data to csv file by PowerShell with CSOM.
http://www.sharepointdiary.com/2016/03/export-list-items-to-csv-in-sharepoint-online-using-powershell.html
Then, send reminder email to user.
http://www.sharepointdiary.com/2016/11/sharepoint-online-powershell-to-send-email.html
Run PowerShell script as windows task scheduler daily.
https://blog.netwrix.com/2018/07/03/how-to-automate-powershell-scripts-with-task-scheduler/


text:
Q: when take photo get - java.lang.Throwable: file:// Uri exposed through ClipData.Item.getUri() The Exception is:
file:// Uri exposed through ClipData.Item.getUri()
java.lang.Throwable: file:// Uri exposed through ClipData.Item.getUri()
    at android.os.StrictMode.onFileUriExposed(StrictMode.java:1618)
    at android.net.Uri.checkFileUriExposed(Uri.java:2341)
    at android.content.ClipData.prepareToLeaveProcess(ClipData.java:808)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:7926)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1506)
    at android.app.Activity.startActivityForResult(Activity.java:3832)
    at android.app.Activity.startActivityForResult(Activity.java:3783)
    at android.support.v4.app.FragmentActivity.startActivityFromFragment(Unknown Source)
    at android.support.v4.app.Fragment.startActivityForResult(Unknown Source)
    at me.chunyu.ChunyuDoctor.Utility.w.takePhoto(Unknown Source)
    at me.chunyu.ChunyuDoctor.Dialog.ChoosePhotoDialogFragment.takePhoto(Unknown Source)
    at me.chunyu.ChunyuDoctor.Dialog.ChoosePhotoDialogFragment.access$000(Unknown Source)
    at me.chunyu.ChunyuDoctor.Dialog.b.onClick(Unknown Source)
    at me.chunyu.ChunyuDoctor.Dialog.ChoiceDialogFragment.onClick(Unknown Source)
    at android.view.View.performClick(View.java:4848)
    at android.view.View$PerformClick.run(View.java:20270)
    at android.os.Handler.handleCallback(Handler.java:815)
    at android.os.Handler.dispatchMessage(Handler.java:104)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5643)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

My code is here:
public static void takePhoto(Fragment fragment, int token, Uri uri) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (uri != null) {
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    }
    fragment.startActivityForResult(intent, token);
}

I searched the similar problems and solutions.
And modify the code as follow:
public static void takePhoto(Fragment fragment, int token, Uri uri) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    if (uri != null) {
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    }
    fragment.startActivityForResult(intent, token);
}

But it is also not work.
It happend on Android 5.1 While work well on Android 4.3.
Is there anyone meet the same problem?
Ask for some advance.
Waiting online...

A: Besides the solution using the FileProvider, there is another way to work around this. Simply put in Application.onCreate() method. In this way the VM ignores the file URI exposure.
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
 StrictMode.setVmPolicy(builder.build());

A: The reason of this error is that file:// uri scheme no more supported because the security is exposed.
https://code.google.com/p/android/issues/detail?id=203555
And We can not use file:// uri any more after with targetSDK 'N'.
https://commonsware.com/blog/2016/03/14/psa-file-scheme-ban-n-developer-preview.html
So, answer is right. Anyone who use file:// have change content:// to provide kinds of local files.

A: To sum up :
file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24 (Android Nougat)
You have to Change your code if you plan to support api 24+
two links :
https://developer.android.com/training/camera/photobasics.html
https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en

A: I have already resolved this problem.
First, this problem occurred because StrictMode prevents passing URIs with a file:// scheme.
So there are two solutions:

*

*Change StrictMode. See similar problem and its code.
But for our apps, it is not realistic to modify the Android source code.

*Use another URI scheme, instead of file://. For example, content:// related to MediaStore.
So I chose the second method:
private void doTakePhoto() {
    try {
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
        mCameraTempUri = getActivity().getContentResolver()
                .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        takePhoto(this, RequestCode.REQCODE_TAKE_PHOTO, mCameraTempUri);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void takePhoto(Fragment fragment, int token, Uri uri) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    if (uri != null) {
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
    }
    fragment.startActivityForResult(intent, token);
}

Also, there is another solution.

A: So, I was actually reading about this, and it seems the correct solution to handle this is the following:
String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

static final int REQUEST_TAKE_PHOTO = 1;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                                                  "com.example.android.fileprovider",
                                                  photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

Notice there is a note that google says to create a "content://" file instead of a "file://" based resource.
This is from google:
Note: We are using getUriForFile(Context, String, File) which returns a content:// URI. For more recent apps targeting Android N and higher, passing a file:// URI across a package boundary causes a FileUriExposedException. Therefore, we now present a more generic way of storing images using a FileProvider.
Also, you will need to setup the following:
Now, you need to configure the FileProvider. In your app's manifest, add a provider to your application:
<application>
   ...
   <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>
    ...
</application>

Note: (Taken from google's site) Make sure that the authorities string matches the second argument to getUriForFile(Context, String, File). In the meta-data section of the provider definition, you can see that the provider expects eligible paths to be configured in a dedicated resource file, res/xml/file_paths.xml. Here is the content required for this particular example:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

If you would like more information: read up here
https://developer.android.com/training/camera/photobasics.html


text:
Q: how to set various level ROW INDEX on a data table? I have a C# data table with below sample data,

Now, I am trying to add 3 more columns as row number (starts with zero in descending order) on 3 different level "Category" ("Grand_Total", "Overall_Total" and "PROJ_TOTAL"), here is I'm trying to achieve,

I able to add ONLY one column "G_T_I" with total number of rows in datatable logic, but not able to figure out the logic to crack other 2 columns "O_T_I" and "P_T_I".
Please help/suggest?
class Program
{
    static void Main(string[] args)
    {
        // Get the DataTable.
        DataTable table = GetTable();

        //get new data table
        DataTable newTable = GetNewTable();

        for(int i = table.Rows.Count - 1; i > -1; i--)
        {
            var gTotalIndex = (table.Rows.Count - i) - 1;
            newTable.Rows.Add(i, table.Rows[gTotalIndex]["Category"], table.Rows[gTotalIndex]["Name"], table.Rows[gTotalIndex]["PROJID"], table.Rows[gTotalIndex]["Type"], table.Rows[gTotalIndex]["Amt"]);
        }

    }

    static DataTable GetNewTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("G_T_I", typeof(int));
        table.Columns.Add("Category", typeof(string));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("PROJID", typeof(string));
        table.Columns.Add("Type", typeof(string));
        table.Columns.Add("Amt", typeof(decimal));
        return table;
    }

    static DataTable GetTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Category", typeof(string));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("PROJID", typeof(string));
        table.Columns.Add("Type", typeof(string));
        table.Columns.Add("Amt", typeof(decimal));

        table.Rows.Add("NEW_PROJ", "ABC", "100", "Acost", 10);
        table.Rows.Add("SAME_PROJ", "", "", "Bcost", 20);
        table.Rows.Add("PROJ_TOTAL", "", "100 Total", "", 30);
        table.Rows.Add("NEW_PROJ", "", "200", "Acost", 40);
        table.Rows.Add("PROJ_TOTAL", "", "200 Total", "", 40);
        table.Rows.Add("OVERALL_TOTAL", "ABC Total", "", "", 70);
        table.Rows.Add("NEW_PROJ", "PQR", "300", "Acost", 10);
        table.Rows.Add("SAME_PROJ", "", "", "Bcost", 10);
        table.Rows.Add("PROJ_TOTAL", "", "300 Total", "", 20);
        table.Rows.Add("OVERALL_TOTAL", "PQR Total", "", "", 20);
        table.Rows.Add("GRAND_TOTAL", "", "", "", 90);

        return table;
    }
}

A: try this :
  using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the DataTable.
            DataTable table = GetTable();

            //get new data table
            DataTable newTable = GetNewTable();

            for (int i = table.Rows.Count - 1; i > -1; i--)
            {
                var gTotalIndex = (table.Rows.Count - i) - 1;
                newTable.Rows.Add(i,null,null, table.Rows[gTotalIndex]["Category"], table.Rows[gTotalIndex]["Name"], table.Rows[gTotalIndex]["PROJID"], table.Rows[gTotalIndex]["Type"], table.Rows[gTotalIndex]["Amt"]);
            }

            var oTotal = 0;
            for (int i = newTable.Rows.Count - 1; i > -1; i--)
            {
                if (newTable.Rows[i]["Category"].ToString() == "GRAND_TOTAL")
                    continue;
                if (newTable.Rows[i]["Category"].ToString() == "OVERALL_TOTAL")
                {
                    oTotal = 0;
                    newTable.Rows[i]["O_T_I"] = oTotal;
                    oTotal++;
                }
                else
                {
                    newTable.Rows[i]["O_T_I"] = oTotal;
                    oTotal++;
                }
            }

            var pTotal = 0;
            for (int i = newTable.Rows.Count - 1; i > -1; i--)
            {
                if (newTable.Rows[i]["Category"].ToString() == "GRAND_TOTAL" || newTable.Rows[i]["Category"].ToString() == "OVERALL_TOTAL")
                    continue;
                if (newTable.Rows[i]["Category"].ToString() == "PROJ_TOTAL")
                {
                    pTotal = 0;
                    newTable.Rows[i]["P_T_I"] = pTotal;
                    pTotal++;
                }
                else
                {
                    newTable.Rows[i]["P_T_I"] = pTotal;
                    pTotal++;
                }
            }

        }

        static DataTable GetNewTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("G_T_I", typeof(int));
            table.Columns.Add("O_T_I", typeof(int));
            table.Columns.Add("P_T_I", typeof(int));
            table.Columns.Add("Category", typeof(string));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("PROJID", typeof(string));
            table.Columns.Add("Type", typeof(string));
            table.Columns.Add("Amt", typeof(decimal));
            return table;
        }

        static DataTable GetTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Category", typeof(string));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("PROJID", typeof(string));
            table.Columns.Add("Type", typeof(string));
            table.Columns.Add("Amt", typeof(decimal));

            table.Rows.Add("NEW_PROJ", "ABC", "100", "Acost", 10);
            table.Rows.Add("SAME_PROJ", "", "", "Bcost", 20);
            table.Rows.Add("PROJ_TOTAL", "", "100 Total", "", 30);
            table.Rows.Add("NEW_PROJ", "", "200", "Acost", 40);
            table.Rows.Add("PROJ_TOTAL", "", "200 Total", "", 40);
            table.Rows.Add("OVERALL_TOTAL", "ABC Total", "", "", 70);
            table.Rows.Add("NEW_PROJ", "PQR", "300", "Acost", 10);
            table.Rows.Add("SAME_PROJ", "", "", "Bcost", 10);
            table.Rows.Add("PROJ_TOTAL", "", "300 Total", "", 20);
            table.Rows.Add("OVERALL_TOTAL", "PQR Total", "", "", 20);
            table.Rows.Add("GRAND_TOTAL", "", "", "", 90);

            return table;
        }
    }
}


text:
Q: ASP.NET application and user it is running under I have multiple applications on a IIS server. How can I set one particular application to run as user 'appuser' and all uploaded files to be saved by as  this user. ASP.NET

A: Every single IIS application run under some so-called application pool. The application pools have default identity (App Pool Identity in newer IIS, NETWORK SERVICE in older IIS). You can also set application pool to have custom identity by specifying user credentials.
However it seems like an overkill to run application under specific user if the only thing you require is to set specific owner for files being created - so I'd rather just force file owner after the file was created instead of changing application pool identity.
See Getting / setting file owner in C#
how to do that.
UPDATE
If you have to write to folder which is restricted to (yourspecialusername) I recommend this approach:
1) Dump file to temp files folder
2) Copy your file to shared folder under the (yourspecialusername) - see - Start a .Net Process as a Different User
3) Wait for Process in 2) to exit and delete temp file


text:
Q: Accessing Google Sheets API with Python and keep getting dailyLImitsExceededUnreg error I keep getting the following error when trying to access the Google Sheets API.  It was working before hand, but now this keeps happening. I've checked the quotas, I've recreated the projects and the credentials files, and I've made sure that the Google Sheets API and Google Drive API are enabled.  I've included these scope items:
DEFAULT_SCOPES = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
I'm currently using Google.oauth2 module since the oauth2client module has been deprecated.
Could someone please help me out with this? Please let me know if you need more info.
Traceback (most recent call last):

  File "<filepath>", line 19, in <module>
    cleaned_results = spud.parse_update(search_results)
  File "<filepath>", line 91, in parse_update
    latest_data = Spud.sheet_manager.get_column()
  File "<filepath>", line 49, in get_column
    worksheet = self._get_worksheet(worksheet_number)
  File "<filepath>", line 33, in _get_worksheet
    spreadsheet = self.client.open(self.sheet_name)
  File "<filepath>", line 123, in open
    self.list_spreadsheet_files()
  File "<filepath>", line 96, in list_spreadsheet_files
    res = self.request('get', url, params=params).json()
  File "<filepath>", line 79, in request
    raise APIError(response)
gspread.exceptions.APIError: {
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}


text:
Q: How can I just print a single object and not it's children? My goal is to allow users to modify the elements of an object that are within a list of other objects. To first do this, I need to search for the element "name" so that I can identify the specific object with that name that needs to be modified. My code does the job to a point, however, I have 3 objects, and 2 of those objects are "nested" within one. So I'm in the predicament whereby if I search for the parent object, it shows me the result of the parent object and it's child objects and if I search for the child object, it returns null. How can I fix this so that it only returns the specific object with the element name that I searched for? I'd like to treat each of them individually.

*

*The format of the xml cannot be changed for this, since the structure is what I'm limited to

I'm not sure if the problem came about with how I originally parsed the xml file into java objects

Main class
public class Main {
    public static void main(String[] args) throws IOException, JAXBException {

        File file = new File("items.xml");
        Scanner scan = new Scanner(System.in);

        JAXBContext context = JAXBContext.newInstance(Items.class);
        Unmarshaller un = context.createUnmarshaller();
        Items itemData = (Items) un.unmarshal(file);

        List<Item> items = itemData.getItem();

        System.out.println("'\n\n------------- Options ---------------");
        System.out.println("\n1. Search Items by Group");
        System.out.println("\n2. Modify Movie");
        int choice = scan.nextInt();
        scan.nextLine();

        if (choice == 2){
            System.out.println("\nEnter the name of the movie you would like to modify: ");
            String search = scan.nextLine();

            Optional<Item> item = items.stream()
                    .filter(x -> x.getName().equals(search))
                    .findFirst();

            System.out.println(item.toString());

        }

        else{
            System.out.println("You entered an invalid option!");
        }
    }
}

Item class
public class Item {
    private String dataType;
    private String name;
    private int data;
    private String group;
    private Items items;

    @XmlElement
    public String getDataType(){
        return dataType;
    }
    public void setDataType(String dataType){
        this.dataType = dataType;
    }

    @XmlElement
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }

    @XmlElement
    public int getData(){
        return data;
    }
    public void setData(int data){
        this.data = data;
    }

    @XmlElement
    public String getGroup(){
        return group;
    }
    public void setGroup(String group){
        this.group = group;
    }

    public Items getItems() {
        return items;
    }

    public void setItems(Items items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return
                "\n\tDataType: " + dataType +
                "\n\tName: " + name +
                "\n\tData: " + data +
                "\n\tGroup: " + group +
                "\n\tItems: " + items + "\n";
    }
}

Items class
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement(name = "items")
public class Items {
    private List<Item> item;

    @XmlElement(name = "item")
    public List<Item> getItem(){
        return item;
    }

    public void setItem(List<Item> itemList){
        this.item = itemList;
    }

    @Override
    public String toString() {
        return "\n" + item ;
    }
}

XML File
<items>
      <item>
            <dataType>Number</dataType>
            <name>Rush Hour</name>
            <data>1</data>
            <group>Comedy</group>
      </item>
      <item>
            <dataType>Number</dataType>
            <name>Harry Potter</name>
            <data>2</data>
            <group>Fiction</group>
            <items>
                  <item>
                        <dataType>Number</dataType>
                        <name>Harry Potter and the Goblet Of Fire</name>
                        <data>3</data>
                        <group>Fiction</group>
                  </item>
                  <item>
                        <dataType>Number</dataType>
                        <name>Harry Potter and the Chamber of secrets</name>
                        <data>4</data>
                        <group>Fiction</group>
                  </item>
            </items>
      </item>
      <item>
            <dataType>Number</dataType>
            <name>Men In Black</name>
            <data>5</data>
            <group>Action</group>
      </item>
      <item>
            <dataType>Number</dataType>
            <name>Coming to America</name>
            <data>6</data>
            <group>Comedy</group>
      </item>
</items>

A: You can modify your code to search the nested item as well. Please take help from below code:
            Optional<Item> item = items.stream()
                .map(x->{
                    if(x.getItems()==null){
                        return Collections.singletonList(x);
                    }
                    x.getItems().getItem().add(x);
                    return x.getItems().getItem();
                })
                .flatMap(Collection::stream)
                .filter(x -> x.getName().equals(search))
                .peek(x-> x.setItems(null))//Peek exists mainly to support debugging
                .findFirst();

which will help to search elements in 2 levels nested object.
When you search Harry Potter and the Chamber of secrets then it will give a single item of Harry Potter object mapping that name.
Optional[
    DataType: Number
    Name: Harry Potter and the Chamber of secrets
    Data: 4
    Group: Fiction
    Items: null
]


text:
Q: Set styles to last element in ListView with sections I have a problem with ListView styling. My ListView has sections. So I need to separate sections by some empty space. I see decision in adding marginBottom style to last element in every section. With css it would be done with :last pseudo-class. Has React Native some alternatives to do this?
Some pseudo code for example:
var dataSource =  new React.ListView.DataSource({
    rowHasChanged: (a, b) => a !== b,
    sectionHeaderHasChanged: (a, b) => a !== b,
    getRowData: (dataBlob, sectionId, rowId) => dataBlob[rowId],
    getSectionHeaderData: (dataBlob, sectionId, rowId) => dataBlob[sectionId]
});

//test data
var sectionIds = ["clients", "properties"];
var rowIds = [["clients_1", "clients_2"], ["properties_1"]];
var dataBlob = {
    clients_1: {
        type: "client",
        title: "Andrew Chinn",
        addInfo: "xxx xxx xxx",
        image: ""
    },
    clients_2: {
        type: "client",
        title: "Karl Chinn",
        addInfo: "xxx xxx xxx",
        image: ""
    },
    properties_1: {
        type: "property",
        title: "Karl Chinn",
        addInfo: "xxx xxx xxx",
        image: ""
    }
};

const renderSectionHeader = (data) => {
    return (
        <SomeTestHeader {...data}/>
    );
};

const renderRow = (data) => {
    return (
        <SomeTestComponent {...data}/>
    );
};

var Test extends React.Component {
    render() {
        <View>
            <ListView
                dataSource={dataSource.cloneWitRowsAndSections(dataBlob, sectionIds, rowIds)}
                renderRow={renderRow}
                renderSectionHeader={renderSectionHeader}
            />
        </View>
    }
}

A: You can do this in your renderRow method :
renderRow = (rowData, sectionId, rowId) => {
  var indexSection = _.findIndex(this.state.sectionIds, function(o) {return o === sectionId});
  if (rowId == _.last(this.state.rowIds[indexSection])) {
    return (
      <View style={{backgroundColor: 'red'}}>
        <Text>{rowId}</Text>
      </View>
    );
  } else {
    return (
      <View style={{backgroundColor: 'blue'}}>
        <Text>{rowId}</Text>
      </View>
    );
  }
};

You can do the same for your sections with sectionId. I've set up an example here.

A: ListView exposes a function called renderSeparator which renders a view/component between sections, use it to render the separator you want.
Your other option is just to give marginTop value to the view you're rendering in the renderSectionHeader


text:
Q: Javascript: Benchmarking to get operations per second capabilities of PC Is it somehow possible, to figure out client PC CPU capabilities? I want my app to load only 25% of CPU or even 10% of CPU, but how much operations i should set, to avoid overloading it's CPU?
Have anyone tried to implement something like that?
For example 10 seconds Benchmark, how much operations fail etc.
Thanks :)

A: Make the code throttle itself dynamically. Run a bit of work and check how long time it took, then do a timeout based on that time.
Something like:
function work() {
  var t0 = new Date().getTime();
  // do some part of the work
  var ms = new Date().getTime() - t0;
  window.setTimeout(work, ms * 10);
}

You can also use the time to decide how much work to do in the next iteration.

A: You can't access the CPU via JavaScript.
JavaScript is running in your browser, and no browser delivers functionality for manipulating the CPU or any task control.
This is some javascript benchmark thing, but not that what you really want I think.

*

*http://www.webkit.org/perf/sunspider/sunspider.html


text:
Q: Elif giving invalid syntax python? This is the code i have been using but it is not working as it says that the elif statement is invalid syntax. Can anyone help me because i am a beginner in python.
age = int(input('How old are you?: '))
if age <= 16:
    print ('You are too young to enter this section of the program!')
else:
    age >= 16
    print ('Welcome to the advanced section of the program!')

elif: password = int(input('please enter the password to enter the elite members section: ')):
    if password == ('muffin'):
        print ('Well done for unlocking the secret part of the program')
    else:
            print ('You shall not pass!')

A: elif needs a condition (ie elif 7 > 5: ....) also an elif cannot follow an else and must follow an if or elif condition
in your case your elif has no condition ,so python does not know what to do
your elif also follows your else Im not sure what you actually expect it to do ...

A: Your elif has no conditional. Else if...what?
else:
    age >= 16

This looks like an attempt at an elif. Should this really be
elif age >= 16:

That'd make sense based on your if.
Additionally, elif goes before else. If you are using elif, it needs to occur after the if but before the else:
if ...
elif ...
else ...

A: As stated above, be sure to have a condition for your elif statement as well as place it between your if and else.  You may also run into an issue with your statements when a user's age is 16 as both your if and else technically qualify at this point.


text:
Q: Problems when using composer require with Magento/Framework in Magento 2.4.2 Using Magento 2.4.2
Composer 2.2.17
I am trying to install Mollie Payments in Magento 2.4.2. Using Composer version 2.2.17.
After running composer require mollie/magento2, i get the following problems:

One of the problems is that Magento/Framework doesn't match with the requirements.
Is there any way to solve this specific issue?
Also, what is the role of Laminas\DependencyPlugin....? Could this be a potential source of the problems?


text:
Q: copy lines from a text file to another i have two text files
file1 has the following lines
line1
line2
hello-hai-1
hello-2-hai
3-hai-hello
hello

and file 2 has
line4
line3
hello-hai-5
hello-7-hai
6-hai-hello
hai
hello-4

what i want to do is copy all the lines which contain both hello and hai in file2 and overwrite it on those lines in file1, the no. of lines may or may not be equal. but all the hello-hai lines are together in both files
the current code i use is
setlocal enabledelayedexpansion
for /f "tokens=1*delims=:" %%i in ('^<file2 essentials\findstr.exe /n "hello"') do set "#%%i=%%j"
(for /f "delims=" %%i in (file1) do (
    set "line=%%i"
    if not "!line!"=="!line:hello=!" (
    if not "!line!"=="!line:hai=!" (
        if not defined flag (
            for /f "tokens=1*delims==" %%a in ('set "#"') do echo(%%b
            set "flag=true"
        )
        ) else echo !line!
    )  else echo(!line!
))>output.txt

this copies all hello lines over the hello-hai lines in file1, i want to know how to add the word hai to the search in first file

A: @echo off
setlocal EnableDelayedExpansion

rem Find lines with both strings in file2
set i=0
for /F "delims=" %%a in ('findstr "hello" file2 ^| findstr "hai"') do (
   set /A i+=1
   set "file2[!i!]=%%a"
)

rem Merge file1 with the found lines in file2
set i=0
(for /F "delims=" %%a in (file1) do (
   set "line=%%a"
   if "!line:hello=!" neq "!line!" (
      if "!line:hai=!" neq "!line!" (
         set /A i+=1
         for %%i in (!i!) do echo !file2[%%i]!
      ) else (
         echo !line!
      )
   ) else (
      echo !line!
   )
)) > output.txt

EDIT: New version added
Previous solution achieve a line-by-line replacement that works even if the matching lines are not together in any file (file merge), but requires that the number of matching lines be the same in both files. The new simpler version below works  in the way requested by the OP:
@echo off
setlocal EnableDelayedExpansion
(for /F "delims=" %%a in (file1) do (
   set "line=%%a"
   if "!line:hello=!" neq "!line!" (
      if "!line:hai=!" neq "!line!" (
         if not defined flag (
            findstr "hello" file2 | findstr "hai"
            set flag=true
         )
      ) else (
         echo !line!
      )
   ) else (
      echo !line!
   )
)) > output.txt

A: Try this:
@echo off &setlocal
set "tf1=%temp%\~%random%1"
set "tf2=%temp%\~%random%2"
set "tf3=%temp%\~%random%3"
set "tf4=%temp%\~%random%4"
set "pt=hello"
set "pu=hai"
<file1 findstr /lin "%pt%">"%tf1%"
<"%tf1%" findstr /li "%pu%">"%tf2%"
<file2 findstr /li "%pt%">"%tf3%"
<"%tf3%" findstr /li "%pu%">"%tf4%"
for /f "usebackqdelims=:" %%i in ("%tf2%") do (
    if not defined st set "st=%%i"
    set "fi=%%i"
)
set /a st-=1
<file1 (
for /l %%i in (1,1,%st%) do (
    set "line="
    set/p "line="
    setlocal enabledelayedexpansion
    echo(!line!
    endlocal
))>"%tf1%"
<file1>"%tf3%" more +%fi%
copy /a "%tf1%"+"%tf4%"+"%tf3%"=output.txt>nul
del "%temp%\~*"
type output.txt

output is:

line1
line2
hello-hai-5
hello-7-hai
6-hai-hello
hello

A: @ECHO OFF
SETLOCAL
SET searching=Y
(
FOR /f "delims=" %%i IN (file1.txt) DO (
 ECHO %%i|FIND "hello"|FIND "hai" >NUL
 IF ERRORLEVEL 1 (ECHO(%%i) ELSE (
  IF DEFINED searching TYPE "file2.txt"|FIND "hello"|FIND "hai"
  SET "searching="
 )
)
)>output.txt
TYPE output.txt
GOTO :EOF

Here's a version without tempfiles. It simply reproduces lines from file1 that don't contain BOTH of the target strings. When BOTH are found in the same line, it outputs all of those lines in file2 that contain both strings. The searching flag is used to ensure that the file2 lines are only output once.
It won't reproduce blank lines or lines that begin ;. Could be made to do so if required.


text:
Q: Что такое "федеративные таблицы" в Mysql? Что такое "федеративные таблицы" в Mysql?

A: Очень грубо говоря - ссылка на таблицу в mysq_BD1 на удалённую mysql_BD2. Пример создания:
CREATE TABLE `your_table` (   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,   `column1` enum('insert','update','delete') NOT NULL,   `column2` int(10) unsigned NOT NULL,   `column3` int(10) unsigned NOT NULL,  PRIMARY KEY (`id`) ) ENGINE=FEDERATED DEFAULT CHARSET=utf8 CONNECTION='mysql://your_user:your_password@your_host:3306/your_db/your_table';

Подробная инфа: http://dev.mysql.com/doc/refman/5.7/en/federated-storage-engine.html


text:
Q: Where can I find an automatic day-night color balance adjuster similar to f.lux/Redshift that works with multiple monitors? I tried f.lux, and I like what it does (automatically adjust the color balance of your monitors depending on time of day), but it seems to work on only 1 of my monitors.
Can I configure it to work on all of them? If not, what other apps can I use that do?
I'm currently running Ubuntu 10.04 LTS with 2 NVIDIA Quadro NVS 420s connected to 4 DELL 2007FPs.

A: I had the same problem with -m vidmode but when I used -m randr instead, both monitor changed.
For example, I use:
gtk-redshift -l 49.2:-123.1 6500:3700  -b 0.7 -g 0.8 -m randr -v

A: I tried Redshift, and was able to get it to affect all monitors by running multiple instances targeting specific screens.
Basically I have something like this in a script:
#!/usr/bin/zsh

for i in {0..3}
do
   redshift -m vidmode:screen=$i -t 5500:4000 &
done

There are probably much better ways to accomplish what I need to do, but this seems to work for now.


text:
Q: utf-8 coding problems using python pyodbc to connect to a Sybase Database in a Docker container When I create a connection using pyodbc
connectionString = ('DRIVER='+driver+';SERVER='+server+';PORT='+port+';UID='+username+';PWD='+password+';DATABASE='+db_environment)
db_connection_dw = pyodbc.connect(connectionString)
cursor = db_connection_dw.cursor()
cursor.execute(sql_query_string)
print(cursor.fetchone())

I get weird results regarding fields of type CharField that contains specials characters.
For example I get 'M\x8adic' instead of 'Mèdic'
Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONIOENCODING=utf-8

ADD devartodbcase_amd64.deb /tmp/devartodbcase_amd64.deb
RUN apt-get clean && \
    apt-get update && \
    apt-get install -y locales locales-all && \
    locale-gen ca_ES.UTF-8 && \
    apt-get install -y gettext libgettextpo-dev g++ unixodbc unixodbc-dev libaio1 && \
    cd /tmp/ && dpkg -i devartodbcase_amd64.deb

ENV LANG ca_ES.UTF-8
ENV LC_ALL ca_ES.UTF-8

COPY ./requirements.txt /requirements.txt
RUN pip install --upgrade pip==20.0.2 && pip install -r /requirements.txt

RUN mkdir /app
WORKDIR /app
COPY ./app/ /app

requirements.txt
Django==2.2.7
djangorestframework==3.10.3
django-filter==2.2.0
psycopg2==2.8.4
pyodbc==4.0.28

numpy==1.18.1
pandas==1.0.1

python-decouple==3.3
dj-database-url==0.5.0

django-widget-tweaks==1.4.5

SQLAlchemy==1.3.13

Is the problem caused by the driver configuration, the Dockerfile configuration?
Thanks in advance

A: You should set connection encoding since DB client get results in some default DB server encoding that could not properly interpreted in your script. You could do it after getting connection with db_connection_dw.setencoding("utf-8"). See following manual https://github.com/mkleehammer/pyodbc/wiki/Unicode


text:
Q: Error: Failed to lookup view "students/addEdit.hbs" in views directory I am going to built an application in NodeJS using MongoDB.
But I have an issue while inserting data in the database
please help me why this error occur.
Error: Failed to lookup view "students/addEdit.hbs" in views directory "D:\Projects\NodeJS\views"
    at Function.render (D:\Projects\NodeJS\node_modules\express\lib\application.js:580:17)
    at ServerResponse.render (D:\Projects\NodeJS\node_modules\express\lib\response.js:1012:7)
    at D:\Projects\NodeJS\controllers\studentController.js:8:9
    at Layer.handle [as handle_request] (D:\Projects\NodeJS\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\Projects\NodeJS\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\Projects\NodeJS\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\Projects\NodeJS\node_modules\express\lib\router\layer.js:95:5)
    at D:\Projects\NodeJS\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\Projects\NodeJS\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Projects\NodeJS\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (D:\Projects\NodeJS\node_modules\express\lib\router\index.js:174:3)
    at router (D:\Projects\NodeJS\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (D:\Projects\NodeJS\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\Projects\NodeJS\node_modules\express\lib\router\index.js:317:13)
    at D:\Projects\NodeJS\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (D:\Projects\NodeJS\node_modules\express\lib\router\index.js:335:12)

Below is my code for server.js
require('./models/db');

const express=require('express');
const path=require('path');
const exphbs=require('express-handlebars');
const bodyparser=require('body-parser');

const studentController=require('./controllers/studentController');
//const stdController=require('/controllers/stdController')

var app=express();
app.use(bodyparser.urlencoded({
    extended:true
}))

app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views'));
app.engine('hbs', exphbs({extname:'hbs', defaultLayout:'mainLayout', layoutsDir: __dirname+'/views/layouts/'}));
app.set('viee engine', 'hbs');

app.listen(4000, ()=>{
    console.log('Express server started at port:4000');

})
app.use('/student', studentController);

A: it's student/addEdit.hbs
not students/addEdit.hbs


text:
Q: Torsion-freeness of the group $\langle a, b \mid a b^m = ba^n\rangle$ For integers $m$ and $n$ let $K(m,n)$ be the group $\langle a, b \mid a b^m = ba^n\rangle$. Is there a special name for this group? Is there a complete characterization of those pairs $(m,n)$ for which the group is torsion-free? Or bi-orderable (in the sense of Rolfsen: http://www.math.ubc.ca/~rolfsen/papers/luminynotes/lum.pdf)?

A: These groups are torsion-free groups with a single defining relation, which implies that they are right-orderable. I do not know if they are bi-orderable though.
A one-relator group is a group with a presentation of the form $\langle X; S\rangle$ where $X$ is some set (possibly infinite) and $S$ is an arbitrary word. Your groups are clearly one-relator groups, and they are torsion-free because every one-relator group has torsion if and only if the relator $S$ is a proper power of some other element $R$ in $F(X)$, that is, $S\equiv R^n$ for $n>1$. This follows from the fact that you can always use HNN-extensions and free products with amalgamation to write such a group in terms of another one-relator group where the relator has strictly shorter length. This gives you an induction step. This induction idea is called Magnus' method, after Wilhelm Magnus, and Lyndon and Schupp's book goes into this interpretation of Magnus' method a wee bit, but they prefer Magnus' original (rather messy) approach. If you want a neat proof, look up the paper The Freiheitsstatz and its extensions of Fine and Rosenberger. This is in a book though, so you could look up the paper of McCool and Schupp entitled One-relator groups and HNN-extensions.
These groups are locally-indicable because they are torsion-free one-relator groups (see the paper On locally indicable groups, 1982, by Jim Howie), that is, every finitely-generated subgroup maps into the infinite cyclic group. This means that they are right-orderable (see the paper A note on group rings of certain torsion free groups, 1972, by Burns and Hale). I do not know if they are bi-orderable though.
EDIT: I have just looked over the notes you link too, and you should realise that my last paragraph is expanded on in the notes.

A: Proposition 5.18 from Lyndon, Schupp, Combinatorial Group Theory,  Springer, 1977:
If $G = \langle X; r=1\rangle$ and $r$ is not a proper power, then $G$ is torsion free.


text:
Q: How can I populate one dataset from other two datasets? SAS I have a dataset final with variable A B C D E of which A,B,C are numeric and D,E are character.I want to delete the data from dataset final and populate it with new data from dataset One and dataset Two.
Dataset One has variables A B C and dataset Two has D and E.
Example:
FINAL
 A B C D E
 1 2 3 a b
 4 5 6 c d

I want to delete the old content.Then IT should look like
FINAL
     A B C D E

I have data set One and Two as
One
    A B C
    0 2 4
    1 2 3
    7 6 4

Two
    D E
    x y
    p q

I want to update FINAL with One and Two content like
FINAL
    A B C D E
    0 2 4 x y
    1 2 3 p q
    7 6 4

A: I think you want merge (documented here):
data final;
   merge one two;
run;

This is a bit more painful using proc sql.


text:
Q: NodeJS async callback not succeeding? I'm trying to implement a scraper using async.map feature to iterate over an array, do some logic and then map them to different values.
async.map($('.listing tr').toArray(), GetLink, function(err, results) {
    if (err) throw err;
    console.log(results);
});

It uses the cheerio module to loop through all table rows to get their links, then completes some logic on them (gets the information from the page it is linked).
var GetLink = function(tablerow, callback) {
    var nameElement = $(tablerow).children().first().find('a');
    var link = nameElement.attr('href');

I then use the 'got' module (a faster/more barebones version of request) to get the pages html.
    got(link, function(error, html, resp) {
        if (!error)
            callback(null, html); // Sends the HTML back as an array result.
    }
}

However the async.map callback [function (err, results)] is never ran even though callback is a valid function from that scope.
Any information would be appreciated.

A: Such is the way with stack overflow.. you spend a long time trying to fix it yourself, and as soon as you post a question, you figure it out.
The issue was that sometimes there was an error in the got method, which meant that a callback wasn't being run. Therefore I changed:
if (!error)
    callback(null, html);

to
if (!error)
    callback(null, html);
else
    callback(null, null);

Without a guaranteed callback supplied in the logic method, the async.map callback will never be run.


text:
Q: Compare two columns in one Table and use result in if condition? I'm trying to solve problem which will compare BEFORE INSERTING columns values partnerCode and partnerCodeOwner1 with username in the table below, If partnerCode and partnerCodeOwner1 values same with username should error message And insert shouldn't be completed!
May be problem while comparing? Any syntax error??
PHP version 7.0
My attemp below but incorrect!
  $user_check_query = "SELECT * FROM refer";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);

    if ($user['username'] === $user['partnerCodeOwner1']) {
      array_push($errors, "You can't add item to yourself");
    }

    if ($user['username'] === $user['partnerCode']) {
      array_push($errors, "You can't add item to yourself");
    }

if (count($errors) ==0) {
//Start inserting
}

Example in table
table: refer
      ID      randomfield    username      partnerCode    partnerCodeOwner1
    +-------+ ------------+-------------+-----------------+-----------+
    |   1   | A45scdv     |  John       |  Not same       |    John   |
    +-------+-------------+-------------+-----------------+-----------+
    |   2   | das654d     | Alex        |  Alex           | Not same  |
    +-------+-------------+-------------+-----------------+-----------+


text:
Q: How can I play sound when my activity starts public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    View view = findViewById(R.id.textView1);
    view.setOnTouchListener(this);

    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) {
            loaded = true;
        }
    });
    soundID = soundPool.load(this, R.raw.dog_bark, 1);

 }
;
@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {

        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        float actualVolume = (float) audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        float maxVolume = (float) audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = actualVolume / maxVolume;

        if (loaded) {
            soundPool.play(soundID, volume, volume, 1, 0, 1f);
        }
    }
    return false;
}
}

I tried this way, but the sound is being played on touch event. I want the sound to be played automatically when my activity starts. But it should stop after a loop is completed and start again on touch event. Please help.

A: Use this in the activity where you wanna hear the music
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();

A: public class CommonMethod {
public static MediaPlayer player;
public static void SoundPlayer(Context ctx,int raw_id){
        player = MediaPlayer.create(ctx, raw_id);
        player.setLooping(false); // Set looping
        player.setVolume(100, 100);

        //player.release();
         player.start();
    }
}

//you can use this method for stopping the player.
CommonMethod.player.stop();

A: If it because you are just loading the sound on onCreate() and play it on touch!
Try soundPlay.play() in onCreate instead!

A: you can play the sound in a runnable and post it in onCreate method.
View view = findViewById(R.id.textView1);
view.post(new Runnable() {

            @Override
            public void run() {
                if (loaded) {
                    soundPool.play(soundID, volume, volume, 1, 0, 1f);
                }
            }
        });

A: Put your onTouch() method's code into OnStart() method of your Activity, so that when activity is started, then Your sound plays.

A: If your activity name is MainActivity
MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.sound);
play.start();

Place this in the onCreate method


text:
Q: Filtering pandas DataFrame by values in a list There is a pandas dataframe:
  df = pd.DataFrame({'c1':['a','b','c','d'],'c2':[1,2,3,4]})

c1  c2
0   a   1
1   b   2
2   c   3
3   d   4

And a pandas Series:
list1 = pd.Series(['b','c','e','f'])

Out[6]:
0    a
1    b
2    c
3    e

How to create a new data frame that contains rows where c1 is in list1.
output:
c1  c2
0   b   2
1   c   3

A: You can use df.isin:
In [582]: df[df.c1.isin(list1)]
Out[582]:
  c1  c2
1  b   2
2  c   3

Or, using df.loc, if you want to modify your slice:
In [584]: df.loc[df.c1.isin(list1), :]
Out[584]:
  c1  c2
1  b   2
2  c   3

A: Using query
In [1133]: df.query('c1 in @list1')
Out[1133]:
  c1  c2
1  b   2
2  c   3

Or, using isin
In [1134]: df[df.c1.isin(list1)]
Out[1134]:
  c1  c2
1  b   2
2  c   3

A: Both @JohnGalt's and @COLDSPEED's answers are more idiomatic pandas.  Please don't use these answers.  They are intended to be fun and illustrative of other parts of the pandas and numpy api.
Alt 1
This is utilizing numpy.in1d which acts as a proxy for pd.Series.isin
df[np.in1d(df.c1.values, list1.values)]

  c1  c2
1  b   2
2  c   3

Alt 2
Use set logic
df[df.c1.apply(set) & set(list1)]

  c1  c2
1  b   2
2  c   3

Alt 3
Use pd.Series.str.match
df[df.c1.str.match('|'.join(list1))]

  c1  c2
1  b   2
2  c   3

A: For the sake of completenes
yet another way (definitely not the best one) to achieve that:
In [4]: df.merge(list1.to_frame(name='c1'))
Out[4]:
  c1  c2
0  b   2
1  c   3