text:
Q: std::async analogue for specified thread I need to work with several objects, where each operation may take a lot of time.
The processing could not be placed in a GUI (main) thread, where I start it.
I need to make all the communications with some objects on asynchronous operations, something similar to std::async with std::future or QtConcurrent::run() in my main framework (Qt 5), with QFuture, etc., but it doesn't provide thread selection. I need to work with a selected object (objects == devices) in only one additional thread always,
because:

*

*I need to make a universal solution and don't want to make each class thread-safe

*For example, even if make a thread-safe container for QSerialPort, Serial port in Qt cannot be accessed in more than one thread:

Note: The serial port is always opened with exclusive access (that is, no other process or thread can access an already opened serial port).

*Usually a communication with a device consists of transmit a command and receive an answer. I want to process each Answer exactly in the place where Request was sent and don't want to use event-driven-only logic.

So, my question.
How can the function be implemented?
MyFuture<T> fut = myAsyncStart(func, &specificLiveThread);

It is necessary that one live thread can be passed many times.

A: Let me answer without referencing to Qt library since I don't know its threading API.
In C++11 standard library there is no straightforward way to reuse created thread. Thread executes single function and can be only joined or detachted. However, you can implement it with producer-consumer pattern. The consumer thread needs to execute tasks (represented as std::function objects for instance) which are placed in queue by producer thread. So if I am correct you need a single threaded thread pool.
I can recommend my C++14 implementation of thread pools as tasks queues. It isn't commonly used (yet!) but it is covered with unit tests and checked with thread sanitizer multiple times. The documentation is sparse but feel free to ask anything in github issues!
Library repository: https://github.com/Ravirael/concurrentpp
And your use case:
#include <task_queues.hpp>

int main() {
    // The single threaded task queue object - creates one additional thread.
    concurrent::n_threaded_fifo_task_queue queue(1);

    // Add tasks to queue, task is executed in created thread.
    std::future<int> future_result = queue.push_with_result([] { return 4; });

    // Blocks until task is completed.
    int result = future_result.get();

    // Executes task on the same thread as before.
    std::future<int> second_future_result = queue.push_with_result([] { return 4; });
}

A: If you want to follow the Active Object approach here is an example using templates:
The WorkPackage and it's interface are just for storing functions of different return type in a vector (see later in the ActiveObject::async member function):
class IWorkPackage {
    public:
        virtual void execute() = 0;

        virtual ~IWorkPackage() {

        }
};

template <typename R>
class WorkPackage : public IWorkPackage{
    private:
        std::packaged_task<R()> task;
    public:
        WorkPackage(std::packaged_task<R()> t) : task(std::move(t)) {

        }

        void execute() final {
            task();
        }

        std::future<R> get_future() {
            return task.get_future();
        }
};

Here's the ActiveObject class which expects your devices as a template. Furthermore it has a vector to store the method requests of the device and a thread to execute those methods one after another. Finally the async function is used to request a method call from the device:
template <typename Device>
class ActiveObject {
    private:
        Device servant;
        std::thread worker;
        std::vector<std::unique_ptr<IWorkPackage>> work_queue;
        std::atomic<bool> done;
        std::mutex queue_mutex;
        std::condition_variable cv;
        void worker_thread() {
            while(done.load() == false) {
                std::unique_ptr<IWorkPackage> wp;
                {
                    std::unique_lock<std::mutex> lck {queue_mutex};

                    cv.wait(lck, [this] {return !work_queue.empty() || done.load() == true;});
                    if(done.load() == true) continue;

                    wp = std::move(work_queue.back());
                    work_queue.pop_back();
                }

                if(wp) wp->execute();
            }
        }
    public:

        ActiveObject(): done(false) {
            worker = std::thread {&ActiveObject::worker_thread, this};
        }

        ~ActiveObject() {
            {
                std::unique_lock<std::mutex> lck{queue_mutex};
                done.store(true);
            }
            cv.notify_one();
            worker.join();
        }

        template<typename R, typename ...Args, typename ...Params>
        std::future<R> async(R (Device::*function)(Params...), Args... args) {
            std::unique_ptr<WorkPackage<R>> wp {new WorkPackage<R> {std::packaged_task<R()> { std::bind(function, &servant, args...) }}};
            std::future<R> fut = wp->get_future();
            {
                std::unique_lock<std::mutex> lck{queue_mutex};
                work_queue.push_back(std::move(wp));
            }
            cv.notify_one();

            return fut;
        }

        // In case you want to call some functions directly on the device
        Device* operator->() {
            return &servant;
        }

};

You can use it as follows:
ActiveObject<QSerialPort> ao_serial_port;
// direct call:
ao_serial_port->setReadBufferSize(size);
//async call:
std::future<void> buf_future = ao_serial_port.async(&QSerialPort::setReadBufferSize, size);

std::future<Parity> parity_future = ao_serial_port.async(&QSerialPort::parity);

// Maybe do some other work here

buf_future.get(); // wait until calculations are ready
Parity p = parity_future.get(); // blocks if result not ready yet, i.e. if method has not finished execution yet

EDIT to answer the question in the comments: The AO is mainly a concurrency pattern for multiple reader/writer. As always, its use depends on the situation. And so this pattern is commonly used in distributed systems/network applications, for example when multiple clients request a service from a server. The clients benefit from the AO pattern as they are not blocked, when waiting for the server to answer.
One reason why this pattern is not used so often in fields other then network apps might be the thread overhead. When creating a thread for every active object results in a lot of threads and thus thread contention if the number of CPUs is low and many active objects are used at once.
I can only guess why people think it is a strange issue: As you already found out it does require some additional programming. Maybe that's the reason but I'm not sure.
But I think the pattern is also very useful for other reasons and uses. As for your example, where the main thread (and also other background threads) require a service from singletons, for example some devices or hardware interfaces, which are only availabale in a low number, slow in their computations and require concurrent access, without being blocked waiting for a result.

A: It's Qt. It's signal-slot mechanism is thread-aware. On your secondary (non-GUI) thread, create a QObject-derived class with an execute slot. Signals connected to this slot will marshal the event to that thread.
Note that this QObject can't be a child of a GUI object, since children need to live in their parents thread, and this object explicitly does not live in the GUI thread.
You can handle the result using existing std::promise logic, just like std::future does.


text:
Q: System setting to stop WiFi from dropping connection? My WiFi connection is frequently dropping.  Are there any system settings to help with the problem?

A: A generic way to try to fix things is to increase the mac80211 kernel module parameters having to do with disconnections.  From modinfo -p mac80211:

max_nullfunc_tries:Maximum nullfunc tx tries before disconnecting (reason 4). (int)
  max_probe_tries:Maximum probe tries before disconnecting (reason 4). (int)
  beacon_loss_count:Number of beacon intervals before we decide beacon was lost. (int)
  probe_wait_ms:Maximum time(ms) to wait for probe response before disconnecting (reason 4). (int)

You can go to the directory /sys/module/mac80211/parameters and do cat [parameter] to see the current value of a parameter and (as root) do echo [value] > [parameter] to (non-persistently) set a parameter to a particular value.
To persistently/permanently set the parameters you can create a file in /etc/modprobe.d like this:
options mac80211 max_nullfunc_tries=16
options mac80211 max_probe_tries=20
options mac80211 beacon_loss_count=28

redpajama_set_name: RedPajamaStackExchange


text:
Q: css clip-path partial circles I am trying to replicate this clipping in css and finding it impossible to get partial cricles and multiple instances of a clip path.

Basically I am wanting to get the curved bottom top edges (ignore the pink box).
I thought something like,
clip-path: circle(50%, 50%) but not that is clip path that runs too far down the element and is large of a circle.
I thought about maybe absolute :before & :after elements but that feels hacky?

A: I don't know, if you can do this with css clip-path property, but you can use background-image as svg vector. Make SVG with rounded sides, and fill property with that background image.
<svg width="502" height="162" viewBox="0 0 502 162" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M501.5 162V0.5C305.81 41.1562 196.035 41.1985 0.5 0.5V162C196.015 122.401 305.709 122.384 501.5 162Z" fill="url(yoururl.svg)"/>
</svg>

That svg looks like this:

       <svg id="svg" viewBox="0 0 502 162" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <path d="M501.5 162V0.5C305.81 41.1562 196.035 41.1985 0.5 0.5V162C196.015 122.401 305.709 122.384 501.5 162Z" fill="green"/>
    </svg>

You can use this <svg>, copy this to new file, replace url attribute on <path> element, change style of the container to this:
background: url(yourfile.svg);
background-size: cover;


text:
Q: Asterisk console command for getting logged sip users? Is there any direct console command for getting logged sip users in a particular context

A: asterisk -rx "sip show peers"

asterisk -rx "sip show users"

Unfortanly users and contexts are DIFFERENT entities, so no way bind user to context or get that info.


text:
Q: Python: Multiprocessing is using an undesired value for use in a function Apologies for the ambiguous title, I'm not sure how to concisely describe my problem.
For simplicity I have written a very short test code which demonstrates the problem I'm having. I am trying to use multiprocessing to create a large data set to be used with plt.imshow to make a heat map.
The test code is as follows (and ignore the fact I am only using a pool of 1, as I said this is just for demonstration purposes):
import numpy as np
import multiprocessing

G_list = [1,2,3]
r = 6

def test(G):
    D = np.cos(G)
    E = r*2
    return G, D, E

pool = multiprocessing.Pool(1)

r_list = []
for i in range(5):
    r += 1
    r_list.append(r)
print r_list

for i in range(len(r_list)):
    r = r_list[i]
    output = pool.map(test,G_list)
    print output

The intention of this code was to calculate the values of D and E for the three values of G in G_list, except I want it to do this for a range of values for r. Since pool.map() does not accept a function with multiple inputs, I tried to simple put the pool.map() command inside a for loop which varies r.
The result, however, is this:
[7, 8, 9, 10, 11]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]
[(1, 0.54030230586813977, 6), (2, -0.41614683654714241, 6), (3, -0.98999249660044542, 6)]

As you can see, G is being varied by pool.map() as expected, but the r value is the same each loop despite the fact it is being changed with each loop right before pool.map() is called. My question is, how do I prevent pool.map() using the value of r globally defined at the top, and make it use the value I am changing it to each loop?
Python 2.7, many thanks!

A: Since test can only accept one input, make the input a tuple.
Then inside of test, unpack the tuple into separate variables:
def test(task):
    G, r = task

Now, when calling pool.map, pass a list of tuples as the second argument:
tasks = [(G, r) for r in r_list for G in G_list]
output = pool.map(test, tasks)

import numpy as np
import multiprocessing

def test(task):
    G, r = task
    D = np.cos(G)
    E = r*2
    return G, D, E

if __name__ == '__main__':
    pool = multiprocessing.Pool(1)

    G_list = [1,2,3]
    r = 6
    r_list = [r+i for i in range(1, 6)]

    tasks = [(G, r) for r in r_list for G in G_list]
    output = pool.map(test, tasks)
    print(output)

The list comprehension r_list = [r+i for i in range(1, 6)] is equivalent to
r_list = []
for i in range(1, 6):
    r_list.append(r+i)

Similarly, the list comprehension tasks = [(G, r) for r in r_list for G in G_list] is equivalent
to
tasks = []
for r in r_list:
    for G in G_list:
        tasks.append((G, r))


text:
Q: Livechart: How to show every X value I'm using "Basic Stacked columns" to show the state and the number  of tasks in every phase of the project.
I want to show x value for each column and in the annotation I want to show"Phase value" (for exemple Phase 4)

this is my code:
String[] Statuts = { "A faire", "En cours", "interrompue", "Terminée", "Annulée" };

        int j = 0;
        string[] numPhases;
        foreach (string st in Statuts)
        {
            double[] valeurSerie = new double[5];
            string sql_Statut = "SELECT distinct Phases.RefPhase ,COALESCE(nb, 0)  AS nb  " +
              " FROM Phases LEFT JOIN " +
              " (SELECT RefPhase, count(*) AS nb " +
              " from Taches  where IDprojet = '" + idprojet + "'  and statut = '" + st + "' group by RefPhase) Taches " +
              " On Phases.RefPhase = Taches.RefPhase";//find for each phase the number of the state of tasks

            SqlCommand cmd3 = new SqlCommand(sql_Statut, connexion.OpenConnexion());
            DataTable dt3 = new DataTable();
            dt3.Load(cmd3.ExecuteReader());
            connexion.CloseConnexion();
            numPhases=new string[dt3.Rows.Count];
            int i = 0;
            foreach (DataRow dr in dt3.Rows)
            {

                valeurSerie[i] = (double)(int)dr["nb"];

                cartesianChart1.Series[j].Values.Add(valeurSerie[i]);

                if (j == 0)
                {

                    numPhases[i] = dr["RefPhase"].ToString();//number of each phase
                }
                      i++;
            }
            if (j == 0)
            {
                cartesianChart1.AxisX.Add(new LiveCharts.Wpf.Axis //phases
                {
                    Title = "Phases",
                    Labels = numPhases,
                    LabelFormatter = value => "Phase " + value,//****this is NOT SHOWN Why?*****
                    ShowLabels = true,//**** this dont't work why?****
                    Separator = DefaultAxes.CleanSeparator
                });
            }
                j++;

        }

        cartesianChart1.AxisY.Add(new LiveCharts.Wpf.Axis
        {
            Title = "Taches",
            LabelFormatter = value => value + ""
        });

    }

A: Just set the Seperator of your X-Axis to 1.
Can be done very easily in the xaml part:
<lc:CartesianChart x:Name="Chart" Series="{Binding SeriesCollection}" >
    <lc:CartesianChart.AxisX>
        <lc:Axis Title="{Binding XTitle}" Labels="{Binding XLabels}" LabelsRotation="-45" FontSize="15">
            <lc:Axis.Separator>
                <lc:Separator Step="1"/>
            </lc:Axis.Separator>
        </lc:Axis>
    </lc:CartesianChart.AxisX>
</lc:CartesionChart>

lc is my LiveChart NameSpace.


text:
Q: WTforms: Error "field not present" Hi I have  a form class which looks like below:-
class UserCreateForm(wtf.Form):
    name=wtf.TextField('Name',validators=[validators.Required(),username_check])
    email=wtf.TextField('Email')
    userimage=wtf.FileField(u'Upload Image',validators=[checkfile])

The custom validator function " checkfile" looks like this:-
def checkfile(form,field):
   if field.data:
      filename=field.data.lower()
      ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
      if not ('.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS):
            raise ValidationError('Wrong Filetype, you can upload only png,jpg,jpeg,gif files')
  else:
      raise ValidationError('field not Present') # I added this justfor some debugging.

However I find that even though I browse a file in the template and
click submit , it always raises the error "field not present". I am a
little confused here . Is field.data not the right way to check for
the presence of filenames

A: Solved this finally , had to replace field.data in the validator with field.file and then access its attributes using field.file.filename.


text:
Q: react-redux: why do I get _this.props.incrementCounter is not a function? Just starting with react/redux. Trying to implement a Counter component hookedup to a action:
export class Counter extends Component {
    constructor(props) {
        super(props);
      }

    handleClick = () => {
        this.props.incrementCounter();
    }

    render() {
        return (
            <div onClick={this.handleClick}>
                hello this is counter:{this.props.counter}
            </div>
        )
    }
}

const mapStateToProps = (state) => ({
    counter: state
})

export default connect(mapStateToProps, { incrementCounter })(Counter)

This is part of the index.js:
ReactDOM.render(<Provider store={store}>
    <App />
</Provider>, document.getElementById('root'));

However when I run the app I get an error when clicking on the 'hello' div?
Error:
_this.props.incrementCounter is not a function
Why am I getting this error, looks like the props are not passed down properly?
For more code see : github

A: you need to use a function as second parameter, like:
connect(mapStateToProps, dispatch => ({ incrementCounter }))(Counter)


text:
Q: Ultimate Website Testing String I've been grappling with the fraught area of escaping user (text) input for web pages.  The ultimate goal is to have user input displayed and stored exactly as typed in, without breaking anything.
To that end I have been using the following test string :
'"_$%^&*()+=-£{}[]/n/<>\@~;|,.?#:!&``"'
It seems to work well (even Stack Overflow or Twitter is not immune, hence the back ticks).  My question is, will this string capture most escaping problems, for example going from a web page via Ajax and to a database and back again?
In fact how do I display this string in Stack Overflow without the back ticks?
Is there a better one, e.g. say one that will highlight encoding problems too?

A: When I'm testing, I'm using something like this

a'b<'>",!"/%$?$&?%(()%/"!"/&?%$/"&$/"?%&?-f¯Ñ112üêù

This is generally sufficient to highlight encoding issues, at least from what I can see.

A: Including a mathematical symbol such as unicode x2202 might be useful too.

A: That seems like it should be all of them.  The smartest thing to do would be to (depending on the language you're using) use a library that has been well tested, that can sanitize user input. Just ask around what other websites use.

A: See here: http://gendoh.com/2511063
The post itself is written in Korean, but you could see what makes difference between several given patterns. (V1 to V3 are for generic web apps while V4 and V5 is for javascripts.)


text:
Q: Screens HTML element sizes I got xd.adobe link from the designer to implement it as web pages, so I'm taking the same px sizes that exist in adobe and putting them to my web page HTML elements, but what I noticed is the HTML elements look more zoomed-in in bigger screen, so if the screen is matching the screen sizes in xd.adobe the webpages will be identical otherwise it will be bigger, I read one of the solution is to stop using px and start using %, but will not be applicable because the project will be finished after a couple of days.

A: If you are trying to convert the px to any other sizing units, than I would suggest that you do so using rem unit. Basically rem unit is relative to the size of html root tag.
To further understand it I recommend you to go through this site.
Link
Here is an example of conversion:

* {
  font-size: 16px;
}

h1 {
  font-size: 50px;
}

#first {
  font-size: 12px;
}

My First Heading

My first paragraph.

My second paragraph.

And its equivalent css in rem:

* {
  font-size: 16px;
}

h1 {
  font-size: 3.125rem;
}

#first {
  font-size: 0.75rem;
}

My First Heading

My first paragraph.

My second paragraph.


text:
Q: Single word for non-domestic errands Is there a single word that describes non-domestic errands like filing taxes, paying credit card bills, printing job related documents, filing an application for a driving license, etc.?
For example, if I were to dedicate my entire week to do only the above type of tasks, I would like to say this:
"My entire next week is dedicated to ________."
I need a single word that fills the blank above.

A: All of the exemplified tasks are forms of paperwork, which is defined by Collins English Dictionary—Complete & Unabridged 12th edition (©2014) defines it as meaning:

clerical work, such as the completion of forms or the writing of reports or letters

Similarly the American Heritage Dictionary 5th edition (©2016) defines it as meaning:

Work involving the handling of reports, letters, and forms.

Most of what you describe involves filling out forms. I am sure I do not need to prove that to you since you already know you will be be filling out tax forums alone for days to come. Paying the bills which still counts since the bill traditionally came in the mail as a paper letter, and printing documents is part of the handling. It specifically relates to clerical work and paper, so any common household chores are excluded by definition, and perhaps any task which does not at least have a historical relationship with paper.
Raking, mowing the lawn, watering the plants, doing the dishes, mopping the floor, vacuuming and dusting are all categorically ruled out as candidates, so nobody will mistakenly think that your week is dedicated to that sort of task.
Dedicated to paperwork is a perfectly valid collocate too, for example, in the United States Congressional Record of 1999 you can see the following sentence:

How many of those staff could be better utilized in classrooms across the district instead of spending their time dedicated to paperwork?

You might also see some cop movies where officers who prefer to be on-the-beat decry being knees deep in paperwork, although specific examples do not come to mind right now.

A: Just for completeness (although I agree the two previous answers have good merit) I am proposing

"My entire next week is dedicated to administration."

However I would normally out of context use lbf's suggested quality description
"My entire next week is dedicated to administrative chores." or

"My entire next week is dedicated to household administration."

A:
"My entire next week is dedicated to chores."

chore TFD

*

*A routine or minor duty or task.

And:
chore noun [ C ]. Cambridge Dictionary

a job or piece of work that needs to be done regularly:
A chore is also something that is difficult and unpleasant:

Chores are not just for kids around the home.  As in:
By the time he'd finished all the chores and gotten home, it was mid-afternoon.
An errand may work:

A short trip taken to perform a specified task, usually for another

but In AmE, this can imply a task at others behest.

A: There is in current BrE a very simple two syllable word that conveys simultaneously tedium and necessity: it is "admin". I know it is an abbreviation of a longer word but my point is that the longer word fails to convey the emotion.

A: "I am getting some paperwork done" or "I am doing some paperwork" could be a casual way to describe the tasks you have mentioned as examples. Certainly, buying groceries or watering plants dont count as paperwork so no one would think you are doing these domestic chores.


text:
Q: How to limit number of attempts someone has to provide username/password credentials for a webpage with htpasswd? I've enabled htpasswd on a webpage.  Is there a way I can limit the number of attempts a user has to enter the correct username/pass credentials before they have to do a hard refresh of the page?

A: Not with basic authentication, you'll need to go to a different authentication module in order to do it.  I was just reading up on mod_auth_pamacea which allows you to use the PAM libraries and all of their goodness with .htpasswd.  You could setup a separate service for your http authentication and then use pam_tally.so to limit the number of login attempts.  Here are a couple of links for your reading pleasure:
The Linux-PAM System Administrators' Guide
mod_auth_pamacea Documentation
I'm sure there are other auth modules that will allow the same functionality, to me this is the closest you'll come to mod_auth_basic.


text:
Q: Macros as default param for function argument I'm writing logger file. I'd prefer to use macros __FUNCTION__ there. I don't like the way like:
Logger.write("Message", __FUNCTION__);

Maybe, it's possible to make something like:
void write(const string &message, string functionName = __FUNCTION__)
{
   // ...
}

If not, are there any ways to do that stuff not by hands (I mean passing function name)?

A: You could do something like that by wrapping it all in a macro:
#define log(msg) Logger.write(msg, __FUNCTION__)

The downside is that you will need to have Logger in scope when using this macro.

A: You can finally do it without macros magic in c++20:
void write(std::string_view message, const std::source_location& location =
                                         std::source_location::current()) {
  std::cout << "Message= " << message
            << ", Function=" << location.function_name();
}

int main() {
  write("Hello world!");
}

A: Macros work just by text substitution - the preprocessor puts the macro definition in place of its name. You can't have "intelligent" macros like the one you suggest.
There is no support for what you want in standard C++.


text:
Q: ASP.NET MVC - Change tabs AJAX RenderAction I'm Spanish so my English is bad. I hope my next explanation is clear.
In this moment I have this code:

        @{Html.RenderAction("Name", "Name2", new {ser ="ser1", s1 = s1, s2 = s2});}

        @{Html.RenderAction("Name", "Name2", new {ser ="ser2", s1 = s1, s2 = s2});}

The fact is that, in this moment, when the page is loaded, al the content is loaded and the page is very slow. How can I change this with AJAX? I want that when the page is loaded it only has the content of the first tab loaded and when the second tab is clicked, it loads the content of that tab.
Finnally, if I return to the first tab, it has to be loaded because of the first time and it doesn't have to loaded it again.
Thank you!

A: jquery ui tabs has an option for that out of the box (see link).
However, there were some issues with the ajax loading and, a quick look at the above link, shows there are still some issues (eg it showed tab 4 when I clicked tab1 then 3 quickly and 3 (the ajax one) always reloads).
I recommend you look at the beforeActivate event (or similar)
Set each tab so that it knows if it's loaded or not and load when it's activated.
Use a simple $.ajax call or $("#div").load(...) to get the content, eg:
$("#table-ser2").load("@Url.Action("Name", "Name", ... ");


text:
Q: Problem with for loop and creating list of list I have an numpy array called expected which is a list of a list of a list.
expected =  [[[45.0, 10.0, 10.0], [110.0, 10.0, 8.0], [60.0, 10.0, 5.0], [170.0, 10.0, 4.0]], [[-80.0, 20.0, 10.0], [97.0, 15.0, 12.0], [5.0, 20.0, 8.0], [93.0, 10.0, 8.0], [12.0, 5.0, 15.0], [-88.0, 10.0, 10.0], [176.0, 10.0, 8.0]]]

I want to put it through a loop without having to hardcode so its applicable to different lengths of list.
When the loop runs for the first time i want it to solve this:
horizontal_exp = expected[0][0][1]*expected[0][0][2]
*np.cos(np.deg2rad(expected[0][0][0]))

Then the next loop to be like this:
horizontal_exp = expected[1][1][1]*expected[1][1][2]
*np.cos(np.deg2rad(expected[1][1][0]))

And the following loop to be like this:
horizontal_exp = expected[2][2][1]*expected[2][2][2]
*np.cos(np.deg2rad(expected[2][2][0]))

and so on until it finished the different sections of rows.
I don't understand why the 'i' never worked??
In the end I want horizontal expected to be a list of a list
e.g.
expected = [ [12,21,23,34], [12,32,54,65,76,87,65] ] # These are not the values I'm just giving an example

where the [12,21,23,24] corresponds to the [[45.0, 10.0, 10.0], [110.0, 10.0, 8.0], [60.0, 10.0, 5.0], [170.0, 10.0, 4.0]]
and the [12,32,54,65,76,87,65] corresponds to the [[-80.0, 20.0, 10.0], [97.0, 15.0, 12.0], [5.0, 20.0, 8.0], [93.0, 10.0, 8.0], [12.0, 5.0, 15.0], [-88.0, 10.0, 10.0], [176.0, 10.0, 8.0]]
I'm unsure how to do this, I know you have to append it with a for loop but how do you separate it into a list of a list??
horizontal_expected = []
for i in list(range(len(expected[i]))):
    horizontal_exp = expected[i][i][1]*expected[i][i][2]
    *np.cos(np.deg2rad(expected[i][i][0]))

    horizontal_expected.append(horizontal_exp)
    print(horizontal_expected)

A: The reason why you don't see the desired output is that, even though you have nested list expected, you are iterating only through the nested lists. You first need to iterate through the outer lists and then iterate through the nested lists internally:
import numpy as np
expected = [ [[45.0, 10.0, 10.0], [110.0, 10.0, 8.0], [60.0, 10.0, 5.0], [170.0, 10.0, 4.0]], [[-80.0, 20.0, 10.0], [97.0, 15.0, 12.0], [5.0, 20.0, 8.0], [93.0, 10.0, 8.0], [12.0, 5.0, 15.0], [-88.0, 10.0, 10.0], [176.0, 10.0, 8.0]] ]
horizontal_expected = []
for i in range(len(expected)):
    tmp_list = []
    for j in range(len(expected[i])):
        horizontal_exp = expected[i][i][1]*expected[i][i][2]*np.cos(np.deg2rad(expected[i][i][0]))
        tmp_list.append(horizontal_exp)
    horizontal_expected.append(tmp_list)
print(horizontal_expected)

The output of that is a list of lists:
>>> print(horizontal_expected)
[[70.71067811865476, 70.71067811865476, 70.71067811865476, 70.71067811865476], [-21.936481812926527, -21.936481812926527, -21.936481812926527, -21.936481812926527, -21.936481812926527, -21.936481812926527, -21.936481812926527]]

As you can see, it holds a value for each of the lists in the input, but the value is the same. This is due to the way that your equation was set up.
You want the indices to be updated based on the level of the loop:
horizontal_exp = expected[i][j][1]*expected[i][j][2]*np.cos(np.deg2rad(expected[i][j][0]))
The full working code would look like this:
import numpy as np
expected = [ [[45.0, 10.0, 10.0], [110.0, 10.0, 8.0], [60.0, 10.0, 5.0], [170.0, 10.0, 4.0]], [[-80.0, 20.0, 10.0], [97.0, 15.0, 12.0], [5.0, 20.0, 8.0], [93.0, 10.0, 8.0], [12.0, 5.0, 15.0], [-88.0, 10.0, 10.0], [176.0, 10.0, 8.0]] ]
horizontal_expected = []
for i in range(len(expected)):
    tmp_list = []
    for j in range(len(expected[i])):
        horizontal_exp = expected[i][j][1]*expected[i][j][2]*np.cos(np.deg2rad(expected[i][j][0]))
        tmp_list.append(horizontal_exp)
    horizontal_expected.append(tmp_list)
print(horizontal_expected)

And the output:
>>> print(horizontal_expected)
[[70.71067811865476, -27.361611466053496, 25.000000000000007, -39.39231012048832], [34.72963553338608, -21.936481812926527, 159.39115169467928, -4.186876499435507, 73.36107005503543, 3.489949670250108, -79.80512402078594]]


text:
Q: Error message "Call to a member function query() on a non-object" In the following code, I am trying to check if the username entered has been used or not by counting the username.
<?php
$hostname = 'aaa';
$username = 'bbb';
$password = 'ccc';
$prefix = "";
$dbna = 'ddd';
$username11 = $_POST['username'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbna", $username, $password);
$nRows = $pdo->query("SELECT count(Username) FROM Users WHERE Username ='$username11'")->fetchColumn();
if($nRows)
{
echo 'The username '.$username11.' is already in use.    ';
}
else
{
echo 'OK';
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

The error is:
Fatal error: Call to a member function query() on a non-object in /home/check.php on line 10

I looked for the solution for this error but I couldn't find it.

A: $pdo->query

should be:
$dbh->query


text:
Q: Trying to implement HTML Template into first Django project. Movies not showing I am following along an online Python tutorial and I am have to create an HTML template in which creates a table for the end user to see the movies in the inventory. I have followed the teachers instructions step-by-by step but when I refresh the browser page, it only shows the class attributes that I listed in the HTML. The code that I wrote is below:
index.html file:

            Title
            Genre
            Stock
            Daily Rate

        {% for movie in movies %}

                {{ movie.title }}
                {{ movie.genre }}
                {{ movie.number_in_stock }}
                {{ movie.daily_rate }}

        {% endfor %}

and the views.py file:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Movie

def index(request):
    movies = Movie.objects.all()
    return render(request, 'index.html', {' movies': movies})

Here is what results on my web browser:
enter image description here
If someone knows why this is not working, any help would be awesome!

A: You seem to have a space where you are passing the context:
return render(request, 'index.html', {' movies': movies})

You need to replace ' movies' with 'movies', otherwise the variable will not be available with the correct name while rendering the template.

A: As the other user @le.chris mentioned, you seem to have a space where you are passing the context.
This would be the right context : return render(request, 'index.html', {' movies': movies}).
However, in your views file, I highly suggest having Class-based views, start by importing the ListView in this case and create a post_list.html or specify a template_name and since you are using movies as your context object, you also need to specify that in the context_object_name attribute. Maybe like this :
class MovieListView(ListView):
    model = Movie
    template_name = 'appname/index.html' #appname is the name of your app
    context_object_name = 'movies'
    ordering = # optional
    paginate_by = 3

in your urls.py file of the app :
path('', MovieListView.as_view(), name='movie-index') #adjust the name as you please


text:
Q: Reading a text file in iOS using std C++ After reading a lot of related SO questions, I am still wondering:
Is it possible to read a (text) file in iOS using only std C++ in a cpp file on iOS?

A: Yes it is possible.
Your source file should be a .mm file and to get the path of the file you should use Objective-C classes. The path will likely be an NSString which is convertable to an std::string.


text:
Q: Create file in JUnit test case in Android I am developing my test project to unit test my Android project.
In my test case, I would like to create a file in my computer e.g. under /Users/MyUserName/Documents/ & write some test result into this file. Is it possible?? How to do it??
protected void setUp() throws Exception {
        super.setUp();

        File myTestResult = CREATE_FILE_IN_MY_COMPUTER();

}

A: Nope. Not like that at least. All test code runs within the phone/emulator and as such has no direct access to your computer's file system.
You'd probably have to write a webservice that runs in your machine to which your tests send data via HTTP or similar.
More importantly, what are you trying to achieve?


text:
Q: historical weather data from python noaa_sdk api and generator? I am trying to get historical weather data using the python noaa_sdk for the noaa api.  I am using the following code from an example:
from noaa_sdk import noaa

n = noaa.NOAA()
observations = n.get_observations('08205','US', start='2017-07-04', end='2018-07-06')
for observation in observations:
    print(observation)
    break

But when I do and include the start and end dates, I don't get a 'print(observation)' response.
I think it has to do with the generator and yield in the get_observations() function but I can't figure it out.  If I don't put in the start and end dates, it works...any idea what I am doing wrong?

A: thanks for letting me know. Please use the latest version 0.1.14.
In the future, please go to:
https://github.com/paulokuong/noaa/issues
adding issue.
It is due to the inconsistent structure of the json response from NOAA.
thanks again.


text:
Q: Have two Minecraft players coexist at separate times in the same local server There's only one computer in the house. My brother and I play Minecraft on it using the same account. Up to this day, I play on my world, and he plays on his own (which just so happens to be the same seed, thereby the same world).
I want to know if it's possible to turn this world into a local server (or just recreate a world and make it into a server) and then have make it so that he can log into it and build things. Then he logs out, and I log into that same server, and see the progress he's made, and make my own. In essence, we wouldn't be playing at the same time, but we would coexist in the same server. Is that possible? If so, how?

A: The simplest way I can think of to do this is having 2 player.dat files which you switch out each time one of you plays.  Of course, this would be a bit of a pain to do manually, but writing a script to switch quickly shouldn't be too hard.
This would be done in a singleplayer world with the same minecraft account.

A: When your done playing, put your inventory into a chest, and when you when you come back, take it out again.

A: Download the server jar, turn  online-mode  to false and login.

You won't have the same inventories, provided the world on the server is a new world.


text:
Q: Navbar switch between pages Bootstrap 3.1.1 Keep hitting a big issue on an altered website template using bootstrap 3.1.1. Need the Navbar to link both to parts of the page that's open, and to other parts on different pages of the site. Navbar as is switches to the parts of the same page just fine, but won't switch to the parts of the other pages.  I cannot work out why, everything seems to be correct?
I confuse easily, alas

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Description

Home

/

Description a

/

Description b

/

Description c

/

Description d

/


text:
Q: Topological properties such that if the subspace has P then the whole space also has P Is there any topological Property $P$ if it is satisfied on a subspace topology $N$ of a topological space $X$, then it must be satisfied on a topological space $X$. Thanks.

A: Do you consider having a nontrivial open set to be a topological property? $N \not = \emptyset$ implies $X \not = \emptyset$, so $N$ having a nontrivial open set implies that $X$ does too. You could cook up other "properties" like this that satisfy your answer, but in a boring way. (Like that $X$ contains a property $P$ subspace.)
But in general I don't think so - if I can write $X$ as the disjoint union of $N$ and $M$, then most properties I can think of have to be satisfied by $N$ and $M$ in order to be satisfied by $X$ (the separation axioms, for instance). For others (such as connectedness), this is not enough.
But the upshot is that if you hand me a property that a space $N$ has and a space $M$ doesn't, then I think $N \dot \cup M$ is unlikely to have that property. This is especially so if that property can be characterized locally, or by some global characteristic - like that a space being compact implies that every closed set is compact.
I would like to be proved wrong though.

A: Not first-countable. Not second-countable. Not Hausdorff. Not regular. Not completely regular. Not T0. Not T1. Not metrizable.
In general, if $\mathfrak{P}$ is a topological property inherited by subspaces, then the topological property not-$\mathfrak{P}$ is of the kind sought.

A: Recall that a topological property is called hereditary if the following holds: If $X$ has the property P and $N$ is subspace of $X$, then $N$ also has the property P.
If you take any hereditary property P, the negation of it $\neg P$ will fulfill the conditions you ask in your post.
In fact, the property $P$ is hereditary if and only if $\neg P$ has fulfills the requirements from your post.

In some contexts, results of this type are might be called reflection theorems. However, as the two formulations are equivalent, they can be formulated as in your post, or dually. Quite often some additional condition is given on the subspace.
The following quote is from Encyclopedia of General Topology; Edited by: Klaas Pieter Hart, Jun-iti Nagata and Jerry E. Vaughan, Elsevier, 2003, p.16.

Generally speaking, a reflection theorem is a theorem of the form "if a set (or a space) $X$ has a property $P$, then there is a subset (or a subspace) $Y$ of a small size (in some sense) satisfying $P$.


text:
Q: How does a wind farm prevent the fastest spinning turbine from driving the slowest one? Just what the title says.
On a wind farm spread across several score hectares, I assume, the wind-speed wouldn't be uniform. The faster spinning turbines would probably induce more electricity than the slower ones ...
Assuming the output from the farm is ganged at some point, how is the output from the faster spinning turbines prevented from interfering with the slower ones? It wouldn't be just a matter of putting a diode, would it?

A: You are forgetting that each turbine is connected to the grid, which is much larger than any one turbine.  Each generator on the grid runs synchronously.  Unless the turbines have variable transmissions, each turbine spins at the same rate.  The one with more wind will have more torque, and hence more power, at the fixed speed.  As long as there is positive torque on the generator shaft, the generator will be pushing power onto the grid.  Some turbines will be pushing more power than others, but since the grid is essentially a infinite sink at this level, they aren't pushing each other.

A: Old, turbines were hooked directly to the net, so the generator would be synced to the line frequency, that was what would synchronize the turbines and keep them from over speeding.
Modern windmills contain two switch mode converters:

*

*The first converter takes the energy from the generator and charges a capacitor bank to the highest possible voltage.

*The second converter takes the energy from the capacitor bank and dumps it into the net, at the right phase and frequency and at the highest possible current.
If the network is disconnected for some reason, then the second converter is unable to discharge the capacitor and the voltage will rise (for a very short time, milliseconds) and the first converter will be unable to keep the load on the generator and the windmill will start to over speed.
Once an over speed situation starts (or anything else unplanned) the controller will hit the air brakes (typically hydraulic rams with a huge reservoir which are used to turn the wings out of the wind), this braking is so powerful that the entire tower bends violently, both back-to-front because the load goes off the wings and the tower snaps back upright and from the torque introduced from mechanical and electrical braking.


text:
Q: Divide string into pairs I want to divide text into pairs.

*

*Input: text = "abcde"

*Goal Output: result = ["ab", "cd", "e_"]

*Current Output: result = ['ab', 'abcd']
My current code looks like this. But I do not know how I do that now. Anyone has a tip for me?
def split_pairs(text):
    result = []
    if text is None or not text:
        return []
    pair = ""
    for i in range(len(text)):
        if i % 2 == 0:
            pair += text[i]
            pair += text[i+1]
        else:
            result.append(pair)
    return result

A: You could use a list comprehension to zip together the even values with the corresponding odd values. And using itertools.zip_longest you can use the fillvalue argument to provide a "fill in" if there is a length mismatch.
>>> from itertools import zip_longest
>>> s = 'abcde'
>>> pairs = [i+j for i,j in zip_longest(s[::2], s[1::2], fillvalue='_')]
>>> pairs
['ab', 'cd', 'e_']

A: You should reset your "pair" variable once appended to "result"
def split_pairs(text):
result = []
if text is None or not text:
    return []
pair = ""
for i in range(len(text)):
    if i % 2 == 0:
        pair += text[i]
        pair += text[i+1]
    else:
        result.append(pair)
        pair = ""
return result

A: You could also use a list comprehension over a range with 3rd step parameter and add ljust to add _. This will also work nicely for more than just pairs:
>>> s = "abcde"
>>> k = 2
>>> [s[i:i+k].ljust(k, "_") for i in range(0, len(s), k)]
['ab', 'cd', 'e_']

A: I am not if your code needed to be in the format you originally wrote it in, but I wrote the below code that gets the job done.
def split_pairs(text):
    if len(text) % 2 == 0:
        result = [text[i:i+2] for i in range(0, len(text), 2)]
    else:
        result = [text[i:i+2] for i in range(0, len(text), 2)]
        result[-1]+="_"
    return result

A: The issue here is that the "pair" variable is never reinitialized to "".
Make sure you make it an empty string in your else block.
def split_pairs(text):
    result = []
    if text is None or not text:
        return []
    pair = ""
    for i in range(len(text)):
        if i % 2 == 0:
            pair += text[i]
            pair += text[i+1]
        else:
            result.append(pair)
            pair = ""  # Make sure you reset it
    return result

If you want to have a "_" at the end (in case of an odd number of character), you could do like the following:
def split_pairs(text):
    result = []
    if text is None or not text:
        return []
    pair = "__"  # Setting pair to "__" by default
    for i in range(len(text)):
        if i % 2 == 0:
            pair[0] = text[i]
            if i < len(text):  # Avoiding overflow
                pair[1] = text[i+1]
        else:
            result.append(pair)
            pair = "__"  # Make sure you reset it
    if pair != "__":  # Last bit
        result.append(pair)
    return result


text:
Q: How do I put strings on a UIImageView using Objective-C (iOS) I'm planning a simple drawing app for the iOS.
As i want to be able to put user defined strings with various fonts, sizes, styles (bold, italic and such) and in different colors. But I'm having no idea how this should be done. Please help me.

A:
As i want to be able to put user defined strings with various fonts,
  sizes, styles (bold, italic and such) and in different colors.

The easiest way to do that would be to place some UILabels on top of the image view. You can then set the text, size, font, color, etc. of each label as you like.
Another way is to create your own UIView subclass that draws both the image and whatever text you want.

I'm planning a simple drawing app for the iOS....But I'm having no
  idea how this should be done.

Start by developing a real understanding of how the view system works, how to create your own view classes, and how to draw in views. Apple provides plenty of documentation on these topics; a good starting point would be the View Programming Guide.


text:
Q: HTML/JS How to input text and have it appear on screen So, all I'm trying to do is have an input box into which the user types text, and when it is submitted the text appears on screen. I think I am nearly there, but I'm having a problem: the text appears on screen for a split-second and then disappears. Below is the relevant HTML:

    <form onsubmit="f()">
        <input type="text" id="input" placeholder="Enter text" autocapitalize="off" />
        <input type="submit" id="submitbutton">
    </form>

And the internal JavaScript:

Like I said, the entered text appears for a split-second and then disappears. Any thoughts on how to fix this would be greatly appreciated. I'm sorry if this is a foolish question, but I am only a beginner, and this is my first experience with input boxes. I have searched this forum and other regions of the Web and cannot find any helpful content.

A: Your problem is that your event is onsubmit, after executing f(), the page is reloading. To avoit that, add an event parameter to your f function and call preventDefault(); on it.
Also instead of adding event Handler to your object througt html attributes, prefer using addEventListener on your html object.
Here is a code sample without jQuery:

Note: You need to add an ID (like id="yourform") to your form element.
Also in order to avoid some loading issues, add your script tag to the end of your page, before .
Edit:
My bad, I wrote document.getElementById("yourform").addEventListener("click", f);
 instead of document.getElementById("yourform").addEventListener("submit", f);

A: If all you want is to make the text appear, there is no need to create a form to submit. Just remove the form and put the f() function to the button's onclick event. Your javascript function is okay.

function f() {
  var t = document.getElementById("input").value;
  document.getElementById("outputtext").innerHTML = t;
}

  <input type="text" id="input" placeholder="Enter text" autocapitalize="off" />
  <button onclick="f()" type="button" id="submitbutton">Click Me!</button>

A: When you submit the form, it displays the output and then the page gets reloaded. Thats why you see it just for a split second. Possible solution would be to include a return false at the end of your f () function definition.

A: Another jQuery alternative: instead of calling an onsubmit method, just use a click function:
<-- jQuery CDN -->

HTML

    <form>
        <input type="text" id="input" placeholder="Enter text" autocapitalize="off" />
        <input type="submit" id="submitbutton">
    </form>

A: You can use the jquery submit function here. Try this one below.
HTML:
<form id="target" action="destination.html">
  <input type="text" value="Hello there">
  <input type="submit" value="Go">
</form>

  Trigger the handler

Script:
$(function() {
  $( "#target" ).submit(function( event ) {
      alert( "Handler for .submit() called." );
      event.preventDefault();
    });
});

Note: load first the jquery cdn before the  tag.

A: What .....no....no.no
All you do is do want is text to appear on screen but it will disappeare because you need php inventory where it would be stored so the text it will disappeare always when you reload site so what you need is action button just put button on left and that make it like protected


text:
Q: How to apply LinedResource to XSLT in C# method? I have one XSLT file that takes elements from XML and gives HTML output i use
XslCompiledTransform()

to convert XSLT to html output in C# method. The output is then converted to HTML Email Message Body and sent to the client dynamically.
I have some images embedded in the html everything works fine as long as my site at some domain. But when i test it from my Development Machine the images doesn't get sent to the client.
To overcome this i am using a class called
LinkedResource();

which helps to embed images in html. I works fine if you are writing custom html inside your html body. But in my case my html is being generated by XSLT.
Can anyone tell me how can i apply this (linedresource) to XSLT so that the html produced will contain the images.
SO far i have tried something like this:
           var logoImageResource =new LinkedResource("C:\\MyProject\\Images\\logo.png")
                    {
                    ContentId = "logoId",
                    TransferEncoding = TransferEncoding.Base64
            };

And my XLST file has used the ContentId like this:
 <img src="cid:logoId" alt="logo"/>

Till now it doesn't work for me. Any help really appreciated.

A: Using linkedresource statement before doing XSLT transformation worked fine.


text:
Q: How can I convert only an hour (Not date) in a string from UTC to localtime in flutter? I am making use of an API which states the following:

NOTE: All times are in UTC and summer time adjustments are not included in the returned data.

So I retrieved the data as follows:
String time = "3:52:59 PM";

I want to get that time as the phone localtime, so according to a similar question for dates it would be as follows:
final convertedTime = DateTime.parse(time).toLocal();
print(convertedTime.toString());

But this produces an error:

Invalid date format

I guess this issue comes because date time expects a date and not just hours, but I am not able to find anything else for just hours in import 'package:intl/intl.dart';
How can I make this conversion, for example for GMT+1 taking into account the summertime, or any other timezone of the phone?
In my example the expected time would be:
String time = "4:52:59 PM";

A: If you know the received time is in UTC and the date are "today" in UTC time, we can do something like this:
void main() {
  print(parseHoursInUtc('3:52:59 PM')); // 2021-01-21 15:52:59.000Z
}

RegExp _timePattern =
    RegExp(r'(?<hour>\d+):(?<minute>\d+):(?<second>\d+) (?<amPm>AM|PM)');

// timeString must be of the format "3:52:59 PM"
DateTime parseHoursInUtc(String timeString) {
  final match = _timePattern.firstMatch(timeString);

  final hour = int.parse(match.namedGroup('hour'));
  final minute = int.parse(match.namedGroup('minute'));
  final second = int.parse(match.namedGroup('second'));
  final isPm = match.namedGroup('amPm') == 'PM';

  final now = DateTime.now().toUtc();
  return DateTime.utc(
      now.year, now.month, now.day, isPm ? hour + 12 : hour, minute, second);
}

The methods returns a DateTime in UTC mode which you can convert to local time with toLocal().
You can then use the intl package to create a DateTimeFormat which prints the time as you want it like this:
import 'package:intl/intl.dart';

void main() {
  print(DateFormat.jms().format(parseHoursInUtc('3:52:59 PM').toLocal())); // 4:52:59 PM
}

RegExp _timePattern =
    RegExp(r'(?<hour>\d+):(?<minute>\d+):(?<second>\d+) (?<amPm>AM|PM)');

// timeString must be of the format "3:52:59 PM"
DateTime parseHoursInUtc(String timeString) {
  final match = _timePattern.firstMatch(timeString);

  final hour = int.parse(match.namedGroup('hour'));
  final minute = int.parse(match.namedGroup('minute'));
  final second = int.parse(match.namedGroup('second'));
  final isPm = match.namedGroup('amPm') == 'PM';

  final now = DateTime.now().toUtc();
  return DateTime.utc(
      now.year, now.month, now.day, isPm ? hour + 12 : hour, minute, second);
}

I am in Denmark which are CET (UTC+1) right now (and with now I mean outside DST).

A: To get the time of any date in flutter you can use:
DateFormat("hh:mm aaa").format(DateTime.now()))

result: 5:40 p.m


text:
Q: Suggestion for books in Pertubation theory with an emphasis on the theory As the title suggest I am looking for another good coverage of the theory of Pertubation theory.
Currently I am working through Murodock's book: Pertubations: Theory and Methods.
But I am rest assure that the field should have more theory than what is covered in Murdock's, also open theorywise problems are fine by me.
Most books that i found only have technical examples without looking at the theory, I am sure there are technical theorywise books in this field but not sure where to look.
I am asking for regular and singular pertubations, also if you have theoretical books on pertubation theory of PDEs, since Murdock's only deals mainly on ODEs and algebraic polynomials.
Thanks!


text:
Q: Prove or disprove that R is an equivalence relation A relation R is defined on Z by xRy if x · y ≥ 0. Prove or disprove the following:

(a) R is reflexive

(b) R is symmetric

(c) R is transitive

(a) If xRx then x*x >= 0 for all x in Z. This is true because (-a)(-a) = a, for all a in Z.

(b) If xRy then we want yRx for all x,y in Z. This is true because ab = ba for all a, b in Z.

(c) Now I am stuck because I know that "If xRy and yRz we want that xRz. This is true because ..." but how do I say that multiplication is transitive.

A: HINT: Is $-1\,R\,0$? Is $0\,R\,1$? Is ... ?

A: Suppose $x*y \ge 0$ and $y*z\ge 0$.
Case 1:  $x < 0$.  $x*y \ge0 \implies $\frac 1x x*y \le \frac 1x *0$ so $y \le 0$.
Case 1a: $y < 0$ then $y*z \ge 0 \implies z \le 0$.  So $x < 0$ and $z\le 0$ so $x*z \le 0$.  So far so good.
Case 1b: $y = 0$ then $y*z \ge 0$ means $y*z=0$ and $z$... could be anything.
If $z\le 0$ we would have $x*z \le 0$.
But if $z > 0$ we would have $x< 0$ and $z > 0$ so $x*z < 0$ and that fails transitivity.
Counter example:
Let $- 1 R 0$ because $-1*0 \ge 0$.  And $0 R 1$ because $0*1 \ge 0$.  But $-1 \not R 1$ because $-1*1 < 0$.
So not transitive.


text:
Q: Hovering on blurred video, how to unblur a part of it After searching for a long time for an answer, here is my question:
How can I reveal a part of a html5 video that is blurred when I hover on it?
Here is some code for HTML:

    <video autoplay muted controls>
        <source src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm">
        <source src="https://dl.dropboxusercontent.com/s/bch2j17v6ny4ako/movie720p.mp4">
    </video>

Here is some code for CSS:
.container { position: relative; }
#soblurme {
    position: absolute;
    border: 1px solid white;
    pointer-events: none;
    width: 50px;
    height: 50px;
    left: 70px;
    top: 20px;
    /*-webkit-backdrop-filter: blur(0);*/
    /*backdrop-filter: blur(0);*/
    -webkit-filter: blur(0%);
    filter: blur(0%);
}

video {
    width: 50%;
    cursor: none;
    filter: blur(7px) opacity(1);
}

Here is some code for JS:
// just make the div follow the mouse
const mouse = {
    x: 0,
    y: 0,
    dirty: false
};
const blurme = document.getElementById('soblurme');
document.querySelector('.container')
    .addEventListener('mousemove', (evt) => {
        mouse.x = evt.offsetX;
        mouse.y = evt.offsetY;
        // recently all UI events are already debounced by UAs,
        // but all vendors didn't catch up yet
        if( !mouse.dirty ) {
            requestAnimationFrame( move );
        }
        mouse.dirty = true;
    });

function move() {
    blurme.style.left = (mouse.x - 25) + 'px';
    blurme.style.top = (mouse.y - 25) + 'px';
    mouse.dirty = false;
}

So, being it blurry, I would like to hover and reveal a part around the pointer so you can see through the blurred div.


text:
Q: Parameter Count Mismatch CreateEndSessionUrl - IdentityModel I'm new to C#. I'm using .NET IdentityModel with AWS Cognito User Pools and attempting to get logout to work. CreateEndSessionUrl sets post_logout_redirect_uri but Cognito requires logout_uri. I'm attempting to use the extra parameter but getting a Parameter Count Mismatch.
Here is my code:
StringDictionary cognitoParameters = new StringDictionary();
cognitoParameters.Add("client_id", OAuthConfiguration.ClientId);
cognitoParameters.Add("logout_uri", OAuthConfiguration.EndsessionEndpointPath);

var endsessionEndpoint = OAuthConfiguration.Authority.TrimEnd('/') + "/" + OAuthConfiguration.EndsessionEndpointPath;
var requestUrl = new RequestUrl(endsessionEndpoint);
var endSessionUrl = requestUrl.CreateEndSessionUrl(
   idTokenHint: HttpContext.Current.GetToken(OidcConstants.ResponseTypes.IdToken),
   postLogoutRedirectUri: OAuthConfiguration.Host,
   state: null,
   extra: cognitoParameters
);

The CreateEndSessionUrl documentation says "The extra parameter can either be a string dictionary or an arbitrary other type with properties. In both cases the values will be serialized as keys/values." I assume I'm creating the string dictionary incorrectly somehow.
The error I get is:
Message: Parameter count mismatch.

Exception type: System.Reflection.TargetParameterCountException
Stack trace:
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at IdentityModel.Internal.ValuesHelper.ObjectToDictionary(Object values)
at IdentityModel.Client.RequestUrlExtensions.CreateEndSessionUrl(RequestUrl request, String idTokenHint, String postLogoutRedirectUri, String state, Object extra)
at Indice.Kentico.Oidc.EndSessionOidcHandler.EndSession()
at Indice.Kentico.Oidc.EndSessionOidcHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Can someone help me understand how to properly format and include the extra parameter? I actually don't need the idTokenHint, postLogoutRedirectUri, or state if they can be excluded.

A: I figured out that I needed to create a Dictionary instead of a StringDictionary:
IDictionary cognitoParameters = new Dictionary<string,string>() {
  { "client_id", OAuthConfiguration.ClientId },
  { "logout_uri", OAuthConfiguration.Host.TrimEnd('/') + "/SignOut.ashx" }
};

It is working now.


text:
Q: Plotly Indicator Chart - Auto Margin I'm struggling to get the Plotly Indicator chart to "auto-margin".

Currently I have to do the following manually to get the outer labels to fit in the chart:
layout.margin = {
   t: 10,
   r: 10,
   b: 10,
   l: 10
}

There does not seem to be any "auto margin" setting for the indicator chart.  I've tried it at multiple places in the data, layout and axis objects with no success.
Any ideas ?


text:
Q: Masonry is not a function I am trying to use masonry in my application. Following is my component template.
<template>

{{team.name}}

                                {{team.title}}

</template>

I get the following error whenever the view is getting rendered.
TypeError: $container.masonry is not a function

Can you please let me know what I am doing wrong here ?

A: You can get vue component DOM element by this.$el. So you can do the following:
$(this.$el.querySelector('.team')).masonry({
                            columnWidth: '.member',
                            itemSelector: '.member'
                          });

But remember this is valid as long as your component is not a Fragment Instance i.e. it has a single root HTML tag.

You many need to put following script line in index.html, so that it loads properly.


text:
Q: R - New column in data frame with aggregated value based on three conditions Suppose I have the data frame:
df <- data.frame(Year = rep(1:3, each = 5)
                 , Terminal = c(1,1,1,1,1,1,2,2,2,2,2,2,2,1,2)
                 , day = c (1,1,1,1,1,1,2,2,2,2,2,2,2,1,2)
                 , Capacity = sample(1:15))

and trying to get a columnb "X" that is a sum of capacity for the same year, day and terminal.
Original df

Outcome:

I use below codes to do the calculations:
aggregate(Capacity ~ Terminal + Year + day , data=df, FUN=sum)

and
as.data.table(df)[, sum(Capacity), by = .(Terminal, Year, day)]

but when I try to create the new column it only prints either 1 or 2 value and not the sum. Also it gives the below warring. The code I have for the X is df["X"] <- aggregate(Capacity ~ Terminal + Year + day , data=df, FUN=sum)
Warning message:
In [<-.data.frame(*tmp*, "X", value = list(Terminal = c(1, 1,  :
  provided 4 variables to replace 1 variables

A: The aggregate returns a summarised output and not create a new column.  We can use mutate from dplyr
library(dplyr)
df %>%
   group_by(Year, day, Terminal) %>%
   mutate(X = sum(Capacity))

For the data.table approach we need to assign := to create a new column
as.data.table(df)[, X := sum(Capacity), by = .(Terminal, Year, day)]

Or with ave from base R
df$X <- with(df, ave(Capacity, Year, day, Terminal, FUN = sum))


text:
Q: How to use the Null assertion operator with instance fields I'm having trouble understanding how to type promote an object's field if it is nullable. Let's say I had the following Comment class and tried to access its one nullable field:
class Comment {
  final String? text;
  Comment(this.text);
}

void main() {
  final comment = Comment("comment");

  if (comment.text!= null) {
    String text = comment!.text;
  }
}

The Dart compiler would give me an error for trying to assign a nullable variable to a non-nullable variable. From what I've gathered from looking into this topic, it's impossible to have type promotion with instance variables because instance variables can be modified which can then break the sound null-safety. I've seen the Null assertion operator (!.) being used in these circumstances, however it doesn't seem to work with fields, only with methods.
With dart null-safety, how should I go about assigning a nullable field such as String? to a non-nullable variable (String). To the same effect, how should I go about passing a nullable field to a function that requires a non-null argument.

A: You can fix it in different ways:

*

*Use local variable (recommended)
final local = comment.text; // <-- Local variable
if (local != null) {
  String text = local;
}

*Use ?. and provide a default value
String text = comment?.text ?? 'Default value';

*Use Bang operator !
if (comment.text != null) {
  String text = comment.text!; // <-- Bang operator
}

Note: Bang operator can result in a runtime error if the text was null.


text:
Q: Jquery length property always returning 0 I have some form elements added via ajax in to a table as below.

        <input id="cde[0]" name="cde[0]" class="required" value="30-09-2015">
        <input type="hidden" id="cddbe[0]" name="cddbe[0]" value="2015-09-30">

        <input id="cqtye[0]" name="cqtye[0]" class="required number" value="30">

        <input id="cremarke[0]" name="cremarke[0]" value="remarks 1">

There may be many rows of elements like this in the table.
I am trying to find if an element exists before getting its value using jquery.length property as below
var nor=$('#commite tr').size()-2;
var c="cqtye["+nor+"]";
if($('#'+c).length){
  console.log("element exists");
}

But .length is always false. When I check length for elements outside the table it is returning 1. But on elements inside this table it is always 0.
This table is inside a div and bith div and table have unique Ids.
Can some one guide me how to check if an element exists in this case.

A: As you are using [] i.e. meta-characters in ID, these needs to be escaped.
Use
var c="cqtye\\["+nor+"\\]";

Docs

To use any of the meta-characters ( such as  !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.

$(function() {
  var nor = $('#commite tr').length;
  var c="cqtye\\["+nor+"\\]";
  if ($('#' + c).length) {
    snippet.log("element exists");
  }
})

      <input id="cde[0]" name="cde[0]" class="required" value="30-09-2015">
      <input type="hidden" id="cddbe[0]" name="cddbe[0]" value="2015-09-30">

      <input id="cqtye[0]" name="cqtye[0]" class="required number" value="30">

      <input id="cremarke[0]" name="cremarke[0]" value="remarks 1">

A: You need to escape the css meta character while creating jquery selector or use name value selector instead:
if($("[id='"+c+"']").length){
   console.log("element exists");
}


text:
Q: Gem::LoadError: Specified 'mysql' for database adapter, I am trying to run rake db:setup for my old rails project and it is throwing the following error.
`rake aborted!
Gem::LoadError: Specified 'mysql' for database adapter, but the gem is not loaded. Add `gem 'mysql'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).

Caused by:
Gem::LoadError: mysql is not part of the bundle. Add it to your Gemfile.

Tasks: TOP => db:setup => db:schema:load_if_ruby => db:create
(See full trace by running task with --trace)`

this is my ruby version ruby 2.3.8p459 (2018-10-18 revision 65136) [x86_64-linux]
my rails version Rails 4.2.7.1
and mysql version mysql  Ver 14.14 Distrib 5.5.56, for linux-glibc2.5 (x86_64) using readline 5.1
Thank you

A: Try adding line that specifies that the adapter is mysql2 (and not mysql)
adapter: mysql2

Instead of
adapter: mysql

in your config/database.yml file
If just the above does not work then update your Gemfile and explicitly add activerecord-mysql2-adapter dependency there:
gem 'mysql2'
gem 'activerecord-mysql2-adapter'


text:
Q: start oracle weblogic server when system starts I want to set Oracle weblogic server 10.3.6 to start automatically when my Ubuntu machine starts.
At this moment, I start it from this sh file manually
Oracle > MiddleWare > user_domains > base_domain > bin > startWebLogic.sh

A: There are many ways to start a process like this... you can use cron or you can use a service in /etc/init.d ... not sure which one you are looking for.
For a super simple /etc/init.d example:

*

*Create /etc/init.d/weblogic_start

*

*Add the following:
su – user -c "/path/to/script/startWebLogic.sh &"
This will start Weblogic every time the machine boots. See other questions like: Start JBoss 7 as a service on Linux


text:
Q: Need to update pricing in a spreed sheet from a separate sheet. Excel 2016 I have 2 sheets.
One 'Content' has Product Code in A11-A2912 and Price E11-E2912, and some fields are blank.
The new data is in a separate sheet 'New Price Data' with Product Code in A1-A1409 and Price in B1-B1409. The Product Codes in 'New Price Data' are in numerical order but they aren't in 'Content'.
I need to compare Product Codes and update Price data in 'Content" with data from "New Price Data'
I hope this is clear enough
I know this would of already been answered somewhere but I couldn't find anything I could translate to my problem.

A: Here's how you can update the prices in column E.

*

*Insert a new column F to the Content sheet.

*Put this formula in F11, and Fill Down column F to beside the last price in column E (F11:F2912).

=IFNA(VLOOKUP(A11,'New Price Data'!$A$1:$B$1409,2,FALSE),IF(E11=0,"",E11))

*Select F11 to the end of the data (F11:F2912), and Copy.

*Select E11. Use Paste Special to copy Values.

*Delete column F.

For each row in the Content sheet, VLOOKUP checks A1:B1409 in the New Price Data sheet. If VLOOKUP finds the Product Code from column A in the Content sheet, it returns the matching price from the New Price Data sheet. If VLOOKUP can't find the product, it returns #NA.
IFNA looks at the return from VLOOKUP. If the return is not #NA, IFNA returns the VLOOKUP result, otherwise it returns the old price from column E. IF preserves fields that are blank, otherwise column F would be zero where column E is blank.

A: I could be wrong, but am pretty sure you're going to have to use VBA, unless you want to format the "content" sheet as a table and then sort it in order of product code. Then you can just make the values in the price column of the content sheet equal the values in the price column of the "new price data" sheet.
Yep, I was wrong.


text:
Q: Conditional probability with randomness There are 10 children and 10 presents prepared for them. There is one present for each child. Each present has a child's unique name. The children are asked to take turns to take their presents. Out of excitement, the first child picks a present at random and runs away with it. The other 9 children are reminded to carefully check their names. If they can't find their present, they are allowed to take any one at random. They all follow the instruction. What is the probability that the child to pick the last present will pick a present which has her name on it?
Here is my attempt :
For simplicity's sake let us say there are only 3 kids and 3 presents :
P( k3=p3)= p(k1≠p3)*p(k2≠p3 | k1≠p2)
Where P( k3=p3) is probability of 3rd kid getting the third present which is meant for her. And similarly the inequality would mean not getting it.
If the above approach is right the answer to the original question would be ~0.39.
But I am not sure if this is the right way to solve this problem .

A: The last child will get the present with her name on it, $P_{10}$, iff the present with the name of the first child, $P_1$,  is picked before $P_{10}$.
This has probability $1/2$ by symmetry.


text:
Q: Prove $f_x(0,0) , f_y(0,0)$ exist Let $f(x,y)= (xy)^{1/3}$
Using definition of the partial derivatives, prove $f_x(0,0), f_y(0,0)$ both exist.
Show that the directional derivative for $f$ in any direction other than $i$ or $j$ does not exist at the origin.

A: I assume that for $t\in{\mathbb R}$ the expression $t^{1/3}$ is defined as $\ {\rm sgn}(t)\>|t|^{1/3}$.
It follows that $${f(x,0)-f(0,0)\over x}=0\qquad(x\ne0)\ ,$$
which implies $f_x(0,0)=0$; and similarly $f_y(0,0)=0$.
Let $u:=(\cos\phi,\sin\phi)$ be a fixed unit vector. Then by definition the directional derivative of $f$ at $(0,0)$ in direction $u$ is given by
$$\eqalign{D_uf(0,0)&=\lim_{t\to 0+}{f(t\cos\phi,t\sin\phi)-f(0,0)\over t}=
\lim_{t\to 0+}{t^{2/3}|\cos\phi\>\sin\phi|^{1/3}\over t}\cr &=\lim_{t\to 0+}{|\cos\phi\>\sin\phi|^{1/3}\over t^{1/3}}\ ,\cr}$$
if the limit on the right hand side exists. But when $\phi$ is not an integer multiple of ${\pi/2}$ this limit does not exist.


text:
Q: DevOps yaml pipeline define location I'm trying to add a submodule to my Azure DevOps yaml pipeline.
I Added the step to checkout the submodule.
steps:
  - checkout: self
    submodules: true

The only side effect I'm having now is that it's moving the entire build repository to a subfolder (the name of the repository).
I'm trying to find out how to set the root back to the build directory back again. I tried setting the path below the submodule in the checkout step. I just can't seem to find where I need to set this paramter and how it's called.
I was reading about the variables over here:
https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml
I was reading about the azure git repos over here: https://learn.microsoft.com/en-us/azure/devops/pipelines/repos/azure-repos-git?view=azure-devops&tabs=yaml
None of these resources say how to fix this.
Can anyone help me with this?

A: If a path is specified for a checkout step, that path is used, relative to (Agent.BuildDirectory).
If you are using default paths, adding a second repository checkout step changes the default path of the code for the first repository. For example, the code for a repository named tools would be checked out to C:\agent\_work\1\s when tools is the only repository, but if a second repository is added, tools would then be checked out to C:\agent\_work\1\s\tools. If you have any steps that depend on the source code being in the original location, those steps must be updated.
See: Checkout path and Checkout for more details. Please check it and kindly let me know the result.


text:
Q: CSS3 Height 100% I don't know how to ask/write this, so feel free to update the name or point me to the correct question/title.
I am designing a cross html5-css3 site, and trying to make it look the same for every (common) browser.
This is what I have:
http://www.pojotlan.com/example1/
It works fine with Firefox 14.0.1, Chrome 21.0.1180.6 and Safari 5.1.7, this, with (file:estilo.css) #contenido line height is used to make it fit in Safari and Chrome.
this is the short version of the included 3 css files...
html {height:100%;}
body {height:100%;}
div#Tabla {display:table; height:100%;}
div.row.main {display:table-row-group; height:auto; min-height:100%;}
div#main {display: table-cell; position: relative; height:auto; min-height:100%;}
div#contenido {display:inline-block; position: relative;
               height:100%; min-height:100%; line-height:100%;}
section {height:auto; min-height:100%;}

if I change its position to absolute, i got the same look on  Chrome 21.0.1180.6 and Safari 5.1.7, Opera 12.
as you can see, #contenedor wont fit 100% height on Opera and IE. How can I fix this?
I'm really new to css styling and stuff, so I don't get what is wrong.
Thank you in advance :)
ps. yes, maybe I am messing everything with css display:table and stuff, but thats where google sent me... haha xD so, yes, you can basically tell me to start again without tables. (I am trying that already, with less results.)

A: I couldn't make it as I were, so this is what I did.
CSS File:
body, html {border: 0px; margin: 0px; padding: 0px;
height:100%; position:relative; width:100%;}
#head
{
 position:absolute;
 background-color: #98a;
 height: 100px;
 width:100%;
 top:0px;
}

#footer
{
 position:absolute;
 background-color: #e46;
 width:100%;
 height:20px;
 bottom:0px;
}

#content
{
 position:absolute;
 background-color: #dee;
 height:auto;
 top:100px;
 bottom:20px;
 width:100%;
}

body:

#head

#footer

#content

The important part, was that content is absolute, and top/bottom.
so, this is all.
thank you :D

A: You may try to use the min-height IE hack :
body, html {
  min-height:100%;
  height:auto !important;
  height:100%;
}

Hope this helps!


text:
Q: PHP syntax highlighter - objecto DOM não actualiza o HTML Tenho estado a desenvolver um código para fazer syntax highlighting, mas o código está a falhar a actualizar o HTML.
O código é extenso, e infelizmente todo ele é necessário.
Tenho um ficheiro principal chamado highlight.php:
<?php

final class highlight {

    private static $langs = array();
    private static $exts = array();
    private static $default_replace = array(
            'tag'=>'span',
            'text'=>'$1'
        );

    static function highlight_string($lang, $code) {
        if(isset(self::$langs[$lang]))
        {
            $lang_defs = &self::$langs[$lang];

            $dom = new DOMDocument('1.0', 'utf-8');

            $element = $dom->createElement('code', $code);

            $element->setAttribute('class','highlight '.$lang);

            $dom->appendChild($element);

            foreach($lang_defs as $k=>&$lang_def)
            {
                $html = '';

                while($child = &$element->firstChild)
                {

                    if($child->nodeType === 3)
                    {

                        if(!isset($lang_def['replace']))
                        {
                            $lang_def['replace'] = self::$default_replace;
                        }

                        switch(gettype($lang_def['replace']))
                        {
                            case 'string':
                                $html .= preg_replace(
                                        $lang_def['match'],
                                        $lang_def['replace'],
                                        $child->nodeValue
                                    );
                                break;
                            case 'array':
                                $html .= preg_replace(
                                        $lang_def['match'],
                                        '<' . $lang_def['replace']['tag'] .
                                        ' class="' . $lang_def['class'] . '">' .
                                            $lang_def['replace']['text'] .
                                        '</' . $lang_def['replace']['tag'] . '>',
                                        $child->nodeValue
                                    );
                                break;
                            case 'object':
                                $html .= preg_replace_callback(
                                        $lang_def['match'],
                                        $lang_def['replace'],
                                        $child->nodeValue
                                    );
                                break;

                        }
                    }
                    else
                    {
                        $html .= $child->nodeValue;
                    }

                    $element->removeChild($child);

                }

                if($html)
                {
                    $fragment = $dom->createDocumentFragment();

                    $fragment->appendXML(isset($lang_def['patch'])?$lang_def['patch']($html):$html);

                    $element->appendChild($fragment);

                    if($element->nodeValue == $code)
                    {
                        trigger_error('Syntax highlight failed on the rule no. '.$k.', for the language '.$lang,E_USER_WARNING);

                        return false;
                    }

                    echo '
',htmlentities($dom->saveXML()),'
',var_dump($element);
                }
            }

            //removes the xml declaration
            return trim(
                    str_replace(
                        '<?xml version="1.0" encoding="utf-8"?>',
                        '',
                        $dom->saveXML()
                    ),
                    "\r\n"
                );

        }
        else
        {
            return false;
        }
    }

    static function highlight_file($file) {

        if(@is_file($file))
        {
            if(preg_match('@(?P<file>.*)\.(?P<ext>[^\.]*)$@', $file, $name) && isset(self::$langs[$name['ext']]))
            {
                return self::highlight_string(self::$langs[$name['ext']], file_get_contents($file));
            }
        }
        else
        {
            return false;
        }
    }

    static function add_lang($lang, $defs){
        switch(gettype($defs)){
            case 'string':
                $defs = (array)include($defs);
                if( $defs === array() )
                {
                    return false;
                }
            case 'array':

                self::$langs[$lang] = $defs['lang'];

                foreach( $defs['exts'] as $ext)
                {
                    self::$exts[$ext] = $lang;
                }

                break;
            default:
                return false;
        }
        return true;
    }

    static function lang_loaded($lang) {
        return isset(self::$langs[$lang]);
    }

};

Este é o ficheiro onde está a falha. Constantemente corre a função trigger_error().
A função corre quando o código html é o mesmo que o código original, indicando que a função falhou.
As definições são carregadas em ficheiros à parte, um exemplo para o ficheiro sql.php:
<?php
    return array(
        'exts'=>array('sql'),
        'lang'=>array(

            array(
                'class'=>'string',
                'match'=>'/([bn]?"(?:[^"]|[\\"]")*"|[bn]?\'(?:[^\']|[\\\']\')*\')(?=[\b\s\(\),;\$#\+\-\*\/]|$)/'
            ),
            array(
                'class'=>'comment',
                'match'=>'/((?:\/\/|\-\-\s|#)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*(?:\*\/|$))/',
                'patch'=>function($html){
                    //step one: try to fix the spans
                    $html = preg_replace(
                            '/((?:\/\/|\-\-\s|#)[^\r\n]*|\/\*(?:[^*]|\*[^\/])*(?:\*\/|$))/',
                            '$1',
                            $html
                        );

                    //step 2: fix single-line comments (-- and #)
                    $html = preg_replace_callback(
                            '/((?:#|-- |\/\/)(?:.|<\/span>([^<])<\/span>)*)([\r\n]|$)/',
                            function($matches){
                                return ''.
                                    //cleans up all spans
                                    preg_replace(
                                            '/<\/?span(?: class="[^"]+")?>/',
                                            $matches[1].$matches[2],
                                            ''
                                        ).''.$matches[3];
                            },
                            $html
                        );

                    //step 3: fix multi-line comments
                    return preg_replace_callback(
                            '/(\/\*(?:[^*]|\*[^\/])+(?:\*\/(?:<\/span>)?|$))/',
                            function($matches){
                                return ''.
                                    //cleans up all spans
                                    preg_replace(
                                        '/<\/?span(?: class="[^"]+")?>/',
                                        $matches[1],
                                        ''
                                    ).'';
                            },
                            $html
                        );
                }
            ),
            array(
                /*
                 * numbers aren't that 'regular' and many edge-cases were left behind
                 * with the help of @MLM (http://stackoverflow.com/users/796832/mlm),
                 * we were able to make this work.
                 * he took over the regex and patched it all up, I did the replace string
                 */
                'match'=>'/((?:^|\b|\(|\s|,))(?![a-z_]+)([+\-]?\d+(?:\.\d+)?(?:[eE]-?\d+)?)((?=$|\b|\s|\(|\)|,|;))/',
                'replace'=>'$1$2$3'
            ),
            array(
                'class'=>'name',
                'match'=>'/(`[^`]+`)/'
            ),
            array(
                'class'=>'var',
                'match'=>'/(@@?[a-z_][a-z_\d]*)/'
            ),
            array(
                'class'=>'keyword',
                //the keyword replace must have an aditional check (`(?!\()` after the name), due to the function replace()
                'match'=>'/\b(accessible|add|all|alter|analyze|and|as|asc|asensitive|before|between|bigint|binary|blob|both|by|call|cascade|case|change|char|character|check|collate|column|condition|constraint|continue|convert|create|cross|current_date|current_time|current_timestamp|current_user|cursor|database|databases|day_hour|day_microsecond|day_minute|day_second|dec|decimal|declare|default|delayed|delete|desc|describe|deterministic|distinct|distinctrow|div|double|drop|dual|each|else|elseif|enclosed|escaped|exists|exit|explain|false|fetch|float|float4|float8|for|force|foreign|from|fulltext|generated|get|grant|group|having|high_priority|hour_microsecond|hour_minute|hour_second|if|ignore|in|index|infile|inner|inout|insensitive|insert|int|int1|int2|int3|int4|int8|integer|interval|into|io_after_gtids|io_before_gtids|is|iterate|join|key|keys|kill|leading|leave|left|like|limit|linear|lines|load|localtime|localtimestamp|lock|long|longblob|longtext|loop|low_priority|master_bind|master_ssl_verify_server_cert|match|maxvalue|mediumblob|mediumint|mediumtext|middleint|minute_microsecond|minute_second|mod|modifies|natural|nonblocking|not|no_write_to_binlog|null|numeric|on|optimize|optimizer_costs|option|optionally|or|order|out|outer|outfile|parse_gcol_expr|partition|precision|primary|procedure|purge|range|read|reads|read_write|real|references|regexp|release|rename|repeat|replace(?!\()|require|resignal|restrict|return|revoke|right|rlike|schema|schemas|second_microsecond|select|sensitive|separator|set|show|signal|smallint|spatial|specific|sql|sqlexception|sqlstate|sqlwarning|sql_big_result|sql_calc_found_rows|sql_small_result|ssl|starting|stored|straight_join|table|terminated|then|tinyblob|tinyint|tinytext|to|trailing|trigger|true|undo|union|unique|unlock|unsigned|update|usage|use|using|utc_date|utc_time|utc_timestamp|values|varbinary|varchar|varcharacter|varying|virtual|when|where|while|with|write|xor|year_month|zerofill)\b/i'
            ),
            array(
                'class'=>'func',
                'match'=>'/\b([a-z_][a-z_\d]*)\b(?=\()/i'
            ),
            array(
                'class'=>'name',
                'match'=>'/\b([a-z\_][a-z_\d]*)\b/i'
            )
        )
    );

Isto tudo é chamado no ficheiro index.php:

Testing highlight of a string:

<?php

    include('highlight.php');

    highlight::add_lang('sql','lang/sql.php');

    echo highlight::highlight_string('sql','select 1,"2";');

?>

Que deveria fazer echo do seguinte html:
select 1,"2";

Portanto, a estrutura final de ficheiros é a que se segue:
/
|--- index.php
|--- highlight.php
|--- /lang/
     |--- sql.php
     |--- ...

Já tentei imensas experiências e todas falharam.
Uma delas foi o seguinte código:
<?

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('code', 'select 1,"2","test"; #test');

$element->setAttribute('class','highlight');

$dom->appendChild($element);

while($element->childNodes->length){
    $element->removeChild($element->firstChild);
}

$fragment = $dom->createDocumentFragment();

$fragment->appendXML('select 1,"2","test"; ');

$element->appendChild($fragment);

echo '
',htmlentities($dom->saveXML());

Que funciona! E é bastante semelhante!
O código é gerado correctamente, mas nunca é actualizado o HTML da tag code.
O que é que estou a fazer de errado no código?


text:
Q: How can I superimpose an image on the frame of the camera (in real time)? I am developing an object recognition program with opencv and android, the program basically makes the moment the real time camera recognizes the object displays an image with information of the object in augmented reality form on the frame of the camera.
The problem is that it shows an error in the addition of the images how can I successfully do the addition?
The images are not of the same size.
public Mat onCameraFrame(Mat aInputFrame) {
// Crear una imagen en escala de grises
Imgproc.cvtColor(aInputFrame, grayscaleImage, Imgproc.COLOR_RGBA2RGB);

Mat imagen = Highgui.imread(ruta, Highgui.CV_LOAD_IMAGE_UNCHANGED);
Rect roi = new Rect(150, 200, 40, 60);
MatOfRect faces = new MatOfRect();

// Utilice el clasificador para detectar rostros
if (cascadeClassifier != null) {
    cascadeClassifier.detectMultiScale(grayscaleImage, faces, 1.1, 2, 2,
            new Size(absoluteFaceSize, absoluteFaceSize), new Size());
}

Mat copia = aInputFrame.clone();
Mat imgroi = imagen.submat(roi);
Mat salidaroi = copia.submat(roi);

Core.addWeighted(imgroi, 0.5, imagen, 0.2, 1,  salidaroi);

return salidaroi;

}
Error

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x
  + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in cv::Mat::Mat(const cv::Mat&, const Rect&),
  file
  /hdd2/buildbot/slaves/slave_ardbeg1/50-SDK/opencv/modules/core/src/matrix.cpp,
  line 323


text:
Q: How to set values of a masked Pandas Series from a different mask I have a series. I would like to extract some elements from that series using a mask and put them back to same or different locations in the same series using a different mask. Something like this:
s = pd.Series(randn(5))
s
0    0.466829
1   -1.821200
2    0.025857
3    0.238267
4    2.192390
dtype: float64
s[pd.Series([False,True,False,True,False])] = s[pd.Series([True,False,True,False,False])]
s
0    0.466829
1         NaN
2    0.025857
3         NaN
4    2.192390
dtype: float64

As you can see that example doesn't work. Note that in my use case, both masks are guaranteed to have the same number of True and False elements.

A: When setting values on a Pandas series, the index is used to align values. So for you example, even though the number of values is the same, the indexes are different, hence the null values. If you want to override this behavior, you can use values to access the underlying array of the Series (ignoring the index). Also you don't need to cast your indexers explicitly with pd.Series, this will happen implicitly if you past a list:
s[[False,True,False,True,False]] = s[[True,False,True,False,False]].values

s
Out[300]:
0    0.013654
1    0.013654
2    0.691198
3    0.691198
4    0.344096
dtype: float64


text:
Q: "Data source name not found and no default driver specified" error I'm getting an error like ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified when publish the website. If I'm running the website from VisualStudio it's working fine, no issue. I had put the connection string in web.config file. The connection string is like
<appSettings>
<add key="ConnectionStr" value="DRIVER={MySQL ODBC 5.1 Driver};SERVER=10.7.26.75;PORT=3306;DATABASE=XXXXXX;UID=XXXXX;PASSWORD=root123"/>
</appSettings>
Please guide me to resolve this issue.

A: Are you publishing to a different computer/server? If so, it could be possible that the MySql ODBC Driver is not installed on the machine you are publishing to.
MySQL ODBC Driver:
http://dev.mysql.com/downloads/connector/odbc/
EDIT
Another thing to check. See this article, and search for the text "Master genius John". He describes a similar error due to there being 32bit and 64bit versions of the driver. If you are running a 64bit OS, it's possible you've configured the DSN for one version and not the other.

A: Had this same issue, the problem was I only had the 64 bit driver for my console application in C#, once I installed the 32 bit driver the program ran with no issues.
very weird.


text:
Q: Continuity correction in proportion test Can you please clarify to me when to use continuity correction in proportion test please? I'm using this formula in R and I want to know the difference in the option correct= TRUE or FALSE. Also, I noticed the p value with correction goes up, so I'm just concerned if I'm using this option (TRUE or FALSE) correctly? how this might impacts my analysis. Any help is really appreciated!
prop.test(x=c(84,105.5),n=c(99,146),correct = TRUE)

Thank you

A: There are many opinions on how to best test for 2 x 2 contingency tables like this. Here the prop.test implements a chi-squared test. The issue is that in some cases data from a 2 x 2 contingency table isn't well approximated by the chi-squared distribution under the null. This can lead to p-values that are too small. Yates continuity correction adjusted for this but can lead to p-values that are too large.
There are other tests that you could use (Fisher's exact test being one) but another option in R is to simulate the distribution under the null and utilize this empirical distribution to calculate the p-value.
mat <- matrix(data = c(84, (99 - 84), 105.5, (146 - 105.5)), ncol = 2)

chisq.test(x = mat, correct = FALSE)

chisq.test(x = mat, correct = TRUE)

chisq.test(x = mat, simulate.p.value = TRUE)

Without the continuity correction, the p-value is 0.021. With the continuity correction, it's 0.031. Simulating the distribution produces a p-value of ~ 0.026. (One issue with this approach is that in R this simulation samples from a hypergeometric distribution which may not approximate your sampling situation.)
For other good threads on this see: Yates continuity correction for 2 x 2 contingency tables and Given the power of computers these days, is there ever a reason to do a chi-squared test rather than Fisher's exact test?

A: In order to consider what you asked, without additional material, consider the $2\times 2$ table TAB as follows:
TAB = rbind(c(80,90), c(20,15))
TAB
     [,1] [,2]
[1,]   80   90
[2,]   20   15

A chi-squared test of independence with the Yates
correction is as follows:
chisq.test(TAB)

        Pearson's Chi-squared test
        with Yates' continuity correction

data:  TAB
X-squared = 0.81215, df = 1, p-value = 0.3675

In R, prop.test compares proportions $80/100$ and
$90/105.$  A two-sided test is equivalent to the
chi-squared test above--if the 'continuity correction'
is used. Notice that the chi-squared statistic and the P-value are exactly the same. [The procedure prop.test gives more
detail.]
prop.test(c(80,90), c(100,105), cor=T)

        2-sample test for equality of proportions
        with continuity correction

data:  c(80, 90) out of c(100, 105)
X-squared = 0.81215, df = 1, p-value = 0.3675
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.16998808  0.05570236
sample estimates:
   prop 1    prop 2
0.8000000 0.8571429

For sufficiently large counts, Yates' correction is not
needed. (And in my opinion too conservative.) If parameter
cor=F is used to disable the correction, the chi-squared
test is as follows:
chisq.test(TAB, cor=F)

        Pearson's Chi-squared test

data:  TAB
X-squared = 1.1813, df = 1, p-value = 0.2771

Similarly, if cor=F is used, prop.test gives
the same test statistic and P-value as just above.
prop.test(c(80,90), c(100,105), cor=F)

        2-sample test for equality of proportions
        without continuity correction

data:  c(80, 90) out of c(100, 105)
X-squared = 1.1813, df = 1, p-value = 0.2771
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.16022617  0.04594046
sample estimates:
   prop 1    prop 2
0.8000000 0.8571429

Note: Simulated test statistics in case of expected counts
below 5, and the use of Fisher's exact test are interesting
topics, but have no direct connection with use or non-use of
the Yates correction.