text:
Q: How to pass QLabel to openCV cv2.imread I am trying to import a image using pyqt4 I am displaying it using Qlabel.
Now I want to do some pre-processing on this image , i.e GrayScale, Noise removal, and segmentation.
and display the change when I click on the action button in toolbar.
Here is the code I have made its dosen't work
from PyQt4 import QtCore, QtGui
from main_window import Ui_MainWindow
import cv2

class module_one(QtGui.QMainWindow, Ui_MainWindow):
    "Module One i.e Pre-processing of the Project Handwriting analysis"
    def __init__(self,parent=None):
        "Initilization of Class module_one"
        super(module_one,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.createActions()
    #Open Function
    def open(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, "Open Image", QtCore.QDir.currentPath(), "Image Files (*.jpg *.jpeg)")
        if filename:
            image = QtGui.QPixmap(filename)
            self.ui.label.setPixmap(image)
            if image.isNull():
                QtGui.QMessageVox.information(self,"Image Viewer","Cannot load %s."%filename)
                return

    #Function that will convert the image into grayscale
    def gray_scale(self):
        image = cv2.imread(self.ui.label) **#Gives Error here**
        gray_scale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        self.ui.label.setPixmap(gray_scale)

    #Function that will connect all buttons to its function
    def createActions(self):
        self.ui.actionOpen.triggered.connect(self.open)
        self.ui.actionExit.triggered.connect(QtGui.qApp.quit)
        self.ui.actionGray_Scale_Conversion.triggered.connect(self.gray_scale)

Which gives the following error
image = cv2.imread(self.ui.label)
TypeError: expected string or Unicode object, QLabel found

I know I am passing Qlabel and its expecting string or unicode object.
But, I don't know how to resolve this issue.
Please can anyone tell me what to do or If you have better solution please put forward.
P.S: I am using PyQt4 Designer and OpenCV version 2.4.8

A: AFAIK, cv2.imread() expects a filename hence it throws the TypeError: expected string or Unicode object, QLabel found.
So in your case it makes more sense to just pass filename than a QLabel (self.ui.label).


text:
Q: Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android' I try to create my own Xamarin Android Library Binding.
The build process is okay.
But when I run some method on the library, it throws an exception

Java.Lang.IllegalStateException: 'Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android''

I've tried to add EmbeddedReferenceJar to kotlinx-coroutines-android and kotlinx-coroutines-core but still same error.

A: Probably related to this issue in Xamarin.Android.
Was fixed in v 10.1, see the release notes.
So just try to update the Visual Studio (possibly to the latest Preview version)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Monte Carlo gamma function This question was asked before but I'd like to ask something more precise given the answer that was given.
[ Estimate gamma function using monte carlo ]
What is the criterion for a random point to be considered inside the function gamma?
Usually the Monte Carlo method multiplies the area of a square enclosing the function by the  number of points generated ending up inside the function, divided by the total number of points generated.
Here, I'm confused as to what is the area of the square enclosing gamma and what is the number of points generated ending up inside the function. I'm guessing (1/N) is the division by the total number of points generated. To me, it seems like this is just an estimate of the gamma function itself using a sum, but not actually a Monte Carlo method, so I might be missing something.
Anyone could help? Thank you !

A: This is a very good question.
For one-dimensional integrals, there are two ways we could approach it.
Method 1: This is the approach in the other link you listed.

*

*Pick $n$ randomly distributed points $x_1, x_2, \ldots, x_n$ in the interval $a \le x \le b$.

*Determine the average value of the function $\displaystyle f_{avg} = \dfrac{1}{n} \sum_{i = 1}^n f(x_i)$.

*Compute the approximation to the integral $\displaystyle \int_a^b f(x)~dx = (b-a)f _{avg}$.

*An estimate of the error is Error $\approx (b-a) \sqrt{\dfrac{f_{avg}^2 - (f_{avg})^2}{n}}$, where $f_{avg}^2 = \dfrac{1}{n} \sum_{i = 1}^n f^2(x_i)$.

Notice that in this approach, we know the function values apply because we are using the function itself as part of the calculation. Just like other numerical integration techniques, you can interpret $(1/n)f(x_n)$ as the area of a rectangle of height $f(x_n)$ and base $1/n$, so you are adding up the areas of those rectangles. Typically, the more rectangles (larger the $n$), the better the approximation.
Method 2: The way you are asking.

*

*First, we must determine the rectangular $R$ box containing the area $A$ where $R = \{ (x, y): a \le x \le b ~\mbox{and}~ 0 \le y \le d$ where $\displaystyle d = \max_{a \le x \le b} f(x)$.

*Second, randomly pick points $n$ point, $(x_n, y_n) \in R$, where the $x_n$ and $y_n$ are chosen from an independent uniformly distributed random variables over $x_n \in [a, b]$ and $y_n \in [0, d]$ , respectively.

*Third, calculate the ratio $\rho$ as $\rho = \dfrac {m}{n}$, where $m$ is number of points that lie in $A$.

*The area is computed using the approximation area $A = \rho (b-a) d$.

*An estimate for the accuracy of the above computation is Error $\approx (b-a) d \sqrt{\dfrac{\rho - \rho^2}{n}}$.

It is worth noting that Method 2 makes it easier to move to higher dimensional integrals, but is probably overkill for $1D$.
Lets apply these methods and compare to the exact problem you mentioned for the Gamma Function in the other problem:
$$\displaystyle \Gamma(\beta) = \int_0^\infty x^{\beta - 1} e^{-x} dx$$
I will use $\beta = \pi$.
Approach 1: A naive approach is that since we have this integral going to infinity, we can look at a plot and determine a suitable range to do the Monte Carlo simulation.
$$\displaystyle \Gamma(\pi) = \int_0^\infty x^{\pi - 1} e^{-x} dx$$
If we plot this function over $0 \le x \le 10$, we get a reasonable range given how fast the exponential approaches zero:
$~~~~~~~~~~~~~$
Using Method 1, with $n = 1000$, we get:
$$I = 2.28421$$
Using Method 2, with $n = 1000$, we get:
$$I = 2.29143$$
Calculating the exact value, we have:
$$\Gamma[\pi] = 2.288037795340033$$
Both approximations are not bad for only $1000$ samples and more samples will improve the result given the Central Limit Theorem. Note running multiple trials does show that there is some variation in the result, but in all cases it is not bad.
Lastly, using a sophisticated Adaptive-Quasi-Monte-Carlo Method, the samples and plot look like:
$~~~~~~~~~~~~~$
This approach yields a result of:
$$\Gamma[\pi] = 2.28804242000413$$
Update
Approach 2: In this approach we will make a change in variables so as to map an infinite range of integration into a finite one.
A good example that works for functions that decrease towards infinity faster than $\frac{1}{x^2}$ is to use:
$$\displaystyle \int_a^b f(x)~dx = \int_{\frac{1}{a}}^{\frac{1}{b}} \dfrac{1}{t^2}f\left(\dfrac{1}{t}\right)~dt$$
With this altered approach, we can now do integrals when one of the limits is infinite
and the other limit is of the same sign. If you need to integrate say something that has $a = 0$, what you do is break the integral into two parts and use Monte Carlo on each one.
If we have infinite limits for both limits, we could split the integral into three or more parts. So, for this problem, we have to split it into two pieces as:
$$\displaystyle \Gamma(\pi) = \int_0^\infty x^{\pi - 1} e^{-x} dx = \int_0^1 x^{\pi - 1} e^{-x} dx + \int_0^1 \dfrac{1}{t^2} \left(\dfrac 1t\right)^{\pi - 1} e^{-\frac 1t} ~dt$$
Using the Monte Carlo for the first part, we get $I_1 = 0.14972956088031433$ and for the second part, we get $I_2 = 2.1272262548687735$, which yields:
$$ \displaystyle \Gamma(\pi) = \int_0^\infty x^{\pi - 1} e^{-x} dx = 2.276955815749088$$
Compare that to our previous and the exact result.
Approach 3: In this approach we will make a change in variables so as to map an infinite range of integration into a finite one. This time, we will transform variables using $u = \frac{1}{1+x}$, yielding:
$$\int_0^1 \left( \frac{1-u}{u}\right)^{\beta-1}e^{-\frac{1-u}{u}}\frac{1}{u^2}du$$
Using Method I with $n=1000$ yields:
$$I = 2.2895585648008825$$


text:
Q: How to do XMLHttpRequest (AJAX) with AngularJS I'm trying to use AngularJS within an POST request, but I cannot use $scope within the event.
Thats my code (for demonstration purpose I just add status within the Angular construct):
myApp.controller('myController', function myController($scope) {
    $scope.myVal = [{status:"before (working)"}];

    doRequest(p1, p2, myCallback.bind(null, $scope));

    function myCallback($scope, a) {
        $scope.myVal = [{ status: a }];
    }

    function doRequest(p1, p2, callback) {
        $scope.myVal = [{ status: "prepare request (working)" }];

        var xhr = new XMLHttpRequest();
        var url = "http://...";
        xhr.open("POST", url, true);
        //....
        xhr.send(myQuery);

        $scope.myVal = [{ status: "after post send (working)" }];
        callback("after post via callback (working)");

        //callback working till this point

        xhr.onreadystatechange = function () {

            if (xhr.readyState === 4 && xhr.status === 200) {
                callback("in event (NOT working)");
                //This is NOT working anymore (even this point is reached)!
            }
        };
    }

as added via comments in the code, the callback is working till the EventHandler assignment.
What I'm looking for is: How to use the callback (or more precise how to make $scope available/transfered in the event handler function)?

A: You don't need to pass $scope into the callback, cause $scope is defined within the controller scope.
You may encounter into a problem when using "native" Ajax as you did, cause this operation is outside of Angular and angular doesn't know about, you need to make it familiar with Angular with $scope.$apply.
If you need to make a shortcut, Angular did it for you with the $http service.
You can replace the entire XMLHttpRequest with injecting $http and calling .post method:
myApp.controller('myController', function myController($scope, $http) {
    $scope.myVal = [{status:"before (working)"}];

    doRequest(p1, p2);

    function doRequest(p1, p2) {
        $scope.myVal = [{ status: "prepare request (working)" }];
        $http.post(url, myQuery).then(() => {
           $scope.myVal = [{ status: 'Finished' }]; // $scope is available here
        });
    }
}


text:
Q: Using a dictionary to store default values I am working on a machine learning program, which has a lot of meta parameters. The intended usage of the program is to research the learning process itself, and therefore I expect I am going to train the model many different times, changing a subset of meta parameters each time, and leave the rest at their default values.
I figured the best way to implement this would be with a default parameter dictionary, for which any value can be overridden by the user.
DEFAULT_PARAMETERS={
    "parameter_1": 1,
    "parameter_2": 2,
    #...
}

def main(**kwargs):
    parameters = {}
    for key in DEFAULT_PARAMETERS:
        if key in kwargs:
            parameters[key] = kwargs[key]
        else:
            parameters[key] = DEFAULT_PARAMETERS[key]

However, I have never seen people use this method, is there a reason why not? Also, is there a list comprehension sort of syntax that would let me implement the above loop in one line?

A: For python 3.5+
merged = { **DEFAULT_PARAMETERS, **kwargs }

This will do the trick. The ** syntax expands the dicts.
Be careful! Order matters!
Related PEP

A:
However, I have never seen people use this method

Have you seen enough of other perople's code ? Possibly not (hint: this is a very common pattern, however it's actually implemented)

is there a reason why not?

Nope, that's just the obvious thing to do here.

Also, is there a list comprehension sort of syntax that would let me implement the above loop in one line?

For python 3.5+ you could try Vittorio Camisa's solution, but this one works in Python 3.x and latest Python 2.7.x releases:
parameters = {k: kwargs.get(k, v) for k, v in DEFAULT_PARAMETERS.items()}


text:
Q: Is there a portable method of preventing all IR radiation from being emitted? Me and some friends were recently disuccing "How cool it would be to be invisible", from a military viewpoint, I said that Camouflage, when done correctly, works surprisingly well, so invisibility was unnecessary. They countered with the argument that an infrared camera could see you easily. Apart from several warm coats, are there any non-restictive ways of preventing IR radiation being emitted from your person?

A: The usual way to achieve minimal radiative losses (and thus a low thermal signature) is using MLI - multilayer insulation. The use of multiple layers of reflectors creates a "thermal series" - each layer gets a temperature that is closer to the radiative temperature of the environment, and it allows you to achieve a low thermal emission. This is very important in cryogenic systems where a small amount of radiative heat transfer can be devastating (it's really hard to pump even one watt of energy from near absolute zero to room temperature).
A nice description can be found here. A very simple (single layer) example is the radiative emergency blanket - typically a thin sheet of metallized plastic that helps reduce heat losses in cases of exposure. These are sometimes known as "space blankets".
Note that the ultimate goal of such insulation is that the outermost layer is at the same temperature as the environment. This means that the rate at which it gets heated (by whatever is inside) must be relatively low compared to the rate at which it loses heat (by radiation, or by convection). This opens up another avenue - make the "blanket" bigger.
For the simple case of a small source of heat with a thermal output of $W$, you can see that the temperature of a black body shell of radius R will depend on the size of the shell. Heat that needs to be dissipated is constant, but as the area increases, the temperature needed for thermal dissipation decreases. If you assume radiative losses only, the expression becomes
$$W = \sigma T^4 4 \pi R^2\\
T = \sqrt[4]{\frac{W}{4 \sigma \pi R^2}}$$
More importantly, if you assume that there will be convective heat losses, then the increased area again plays a role - but now $T$ will scale with $1/R^2$ and therefore go down substantially more quickly.
Note that multilayer insulation doesn't just have to be reflector-void-reflector; it could equally be reflector-insulator-reflector, and for the purposes of camouflage you might want the outermost layer to be similar to the background (rather than a reflector which would presumably stand out in daylight or under spot illumination). A video showing the effect of some approaches to insulation / thermal invisibility is given here - with a tip of the hat to Dirk Bruere who made me aware of it.

A: Of course there is a limitation. If you prevent all heat to escape from your body, your body will heat up until it reaches complete thermal equilibrium with its closed environment. That's called heat death in physics because it quite literally means that you will die.


text:
Q: How to display the therotical transmission range of the vehicle, when it become a cluster head? I know that in the ned file, the following line can display a circle representing the transmission range of the vehicle.
@display("p=1025,1025;is=s;r=300");

How can I disable/enable this code from the cc file? Or is there another way to do it from the source code?

A: In C++ code of your module use the following commands:

*

*to show a range:
getDisplayString().setTagArg("r", 0, 300);

*to disable showing a range:
getDisplayString().removeTag("r");

References:

*

*OMNeT++ Simulation Manual - Changing Display Strings at Runtime

*OMNeT++ Simulation Manual - Appendix G: Display String Tags


text:
Q: Hide "Logged on", "# programs running" on Windows 7 Fast User Switching I want to do the exact same thing that this question did in Windows XP:

Hide "Logged on", "# programs running" on WinXP Fast User Switching

However, I want to do it in Windows 7. I attempted to do it the same way they did it, but the filepaths were different.


text:
Q: UITableView on top of MapView in Swift iOS-App I'm relatively new to Swift, so any help is appreciated!
I'm searching for a way to use a pull up UITableView on top of a MapView, just like it is in the Apple Maps App. Instead of the search bar I would like to have a title, but that is a next step.
I couldn't find any guide on how to do anything like this on the internet, so even if you just have a guess leading in the right direction, I would be thankful!
Right now I have a map view inside a NavigationController inside a TabBarController.
Unfortunately I can't post pictures, as this is my first question, but it should look like this http://media.idownloadblog.com/wp-content/uploads/2016/07/Apple-MAps-PArkopedia-silver-iPhone-screenshot-001.png

A: just put a TableView on the MapView in your storyboard, add your constraints for how big/where you want to be and set the background to be clear color.
Nothing special to it/different than setting up a normal TableView.


text:
Q: Order in which code is executed with UIView.animate I have an issue with my code which exemplified by a simplified version below. I expect for "2" to be printed before "1". However, that is not the case.
Does this have something to do with the fact that the code doesn't actually run from top to bottom?
if moveConclusion.patternDetected == true {
    for i in 0...8 {
        if pressedArray[i] {
            self.panlButtons[i].backgroundColor = UIColor.clear

            UIView.animate(withDuration: 0.1, animations:{
                self.panlButtons[i].backgroundColor = self.correctColour
                //self.panlButtons[i].transform = CGAffineTransform(rotationAngle: CGFloat.pi / -12)
            }, completion: { finished in
                UIView.animate(withDuration: 0.1, animations:{
                    self.panlButtons[i].backgroundColor = UIColor.clear
                    // self.panlButtons[i].transform = CGAffineTransform(rotationAngle: CGFloat.pi / 12)
                    print("2")
                })
            })
        }
    }
    print("1")
}

Output:

1
  2
  2
  2
  ...

A: Calling UIView.animate orders the animation; it does not perform it. The animation engine will perform it — later. You are handing to the animation engine two blocks to be executed later, meaning after all your code comes to an end (to be technical, it's when the next screen refresh frame comes along and the current CATransaction is committed):

*

*The animations block will run after all your code has finished and it's time for the animation to start.

*The completion block will run after the animation ends (that's what "completion" means).

A: This is because print("2") executes approximately 0.1-0.2 seconds after this code starts, but print("1") happens after the for loop executes.
The animations do not execute synchronously with the for loop. The print("2") will happen during the second animation, but by that time, the for loop has completed and print("1") has executed.

A: UIView.animate runs on the main thread and is asynchronous. So as soon as that code is called it dispatches it onto the NEXT runloop, (which is after the this function terminates, which means after the entire for loop).
In other words, the UIView.animate call essentially just queues it for the next run loop. And the print("1") statement still occurs on the current run loop.
Then the animation block is run, and once the animation block finishes, the completion block runs. So the print for the 2 comes WAAAAAY later in terms of CPU processing, and is definitely the expected behavior.


text:
Q: While не работает с несколькими условиями Питон kk = 1, но вайл не прекращается, если добавлено 2 условие. Правильно ли я записал?
        while (kk != 1) or (i != 10):
            try:
                time.sleep(1)
                InfoIP[0] = driver.find_element(By.XPATH, '//*[@id="d_clip_button"]/span').text
                InfoIP2[0] = driver.find_element(By.XPATH, '//*[@id="d_clip_button"]/span').text
            except Exception:
                i += 1
            else:
                kk = 1


text:
Q: What does OIO mean in java? Forgive me I just began to learn Java network programming. I just read Netty in Action which mentions a OIO.

NIO is used in this example because it's currently the most widely used transport, thanks to its scalability and thoroughgoing asynchrony. But a different transport implementation could be used as well. If you wished to use the OIO transport in your server, you'd specify OioServerSocketChannel and OioEventLoopGroup.

I knew the Java IO and NIO already before. But what is the OIO?
I tried to search it in the google but got nothing. Could anyone please help explain what it is?

A: OIO stands for Old IO or Blocking IO. In this model each socket or client connection results in spawning a new dedicated thread to handle the request. So, Number or threads == Number of clients/sockets active.
With NIO or New IO, it is possible to have fewer threads serve more number of clients. Here, Number or threads < Number of clients/sockets active.


text:
Q: How to configure httpc profiles with rebar3? How can I set configuration options for httpc's profiles when using rebar3?
Here is the only example being via erl -config inets.config that looks like this:
[{inets,
[{services,[{httpc,[{profile, server1}]},
            {httpc, [{profile, server2}]}]}]
}].

I tried adopting it to my rebar3 project structure.
Code
Project was created with rebar3, with standard OTP layout:
rebar3 new release myapp

Here is my myapp/config/sys.config:
[
  { myapp, []},
  {inets, [{services, [{httpc, [{profile, myapp}]}]}]}
].

rebar.config:
{erl_opts, [debug_info]}.
{deps, []}.

{relx, [{release, { myapp, "0.1.0" },
         [myapp,
          sasl]},

        {sys_config, "./config/sys.config"},
        {vm_args, "./config/vm.args"},

        {dev_mode, true},
        {include_erts, false},

        {extended_start_script, true}]
}.

{profiles, [{prod, [{relx, [{dev_mode, false},
                            {include_erts, true}]}]
            }]
}.

Here is my myapp.app.src file for completeness:
{application, myapp,
 [{description, "An OTP application"},
  {vsn, "0.1.0"},
  {registered, []},
  {mod, { myapp_app, []}},
  {applications,
   [kernel,
    stdlib
   ]},
  {env,[]},
  {modules, []},

  {maintainers, []},
  {licenses, []},
  {links, []}
 ]}.

Requests
Here is a request I'm trying to make from rebar`s shell:
$ ./rebar3 shell
1> ===> Booted myapp
1> ===> Booted sasl
...
1> httpc:request( "http://reddit.com", myapp).
** exception exit: {noproc,
                    {gen_server,call,
                     [httpc_myapp,
                      {request,
                       {request,undefined,<0.88.0>,0,http,
                        {"reddit.com",80},
                        "/",[],get,
                        {http_request_h,undefined,"keep-alive",undefined,
                         undefined,undefined,undefined,undefined,undefined,
                         undefined,...},
                        {[],[]},
                        {http_options,"HTTP/1.1",infinity,true,
                         {essl,[]},
                         undefined,false,infinity,...},
                        "http://reddit.com",[],none,[],1478280329839,
                        undefined,undefined,false}},
                      infinity]}}
     in function  gen_server:call/3 (gen_server.erl, line 212)
     in call from httpc:handle_request/9 (httpc.erl, line 574)

Here is the request without a profile, to check that inets actually works:
2> httpc:request( "http://reddit.com").

=PROGRESS REPORT==== 4-Nov-2016::13:25:51 ===
          supervisor: {local,inet_gethost_native_sup}
             started: [{pid,<0.107.0>},{mfa,{inet_gethost_native,init,[[]]}}]

=PROGRESS REPORT==== 4-Nov-2016::13:25:51 ===
          supervisor: {local,kernel_safe_sup}
             started: [{pid,<0.106.0>},
                       {id,inet_gethost_native_sup},
                       {mfargs,{inet_gethost_native,start_link,[]}},
                       {restart_type,temporary},
                       {shutdown,1000},
                       {child_type,worker}]
{ok,{{"HTTP/1.1",200,"OK"},...

A: rebar3 itself use inets http clients so when It starts your application in shell, inets is already started and configured.  One workaround would be stop inets before your application starts, as It's suggested by rebar3 developer (copied below).  Another one would be boot your release in console mode:
./_build/default/rel/myapp/bin/myapp console

Beside that there is another problem with your project.  You have not told you want inets being started for you.  You should have this line in myapp.src:
{applications, [kernel, stdlib, inets]}

Or you can list inets in rebar.config release section, to tell relx this app should be included in release and started on boot.
{relx, [{release, { myapp, "0.1.0" }, [inets, myapp, sasl]} ]}

Stop Inets from Loading on rebar3 shell startup
Here is the copy of the full answer by Fred Hebert from the rebar3 mailing list:

We do need inets for package fetching and will likely not turn it off
  automatically for all use cases as this could compromise general usage
  of the rebar3 agent in case where the user application does not use
  inets, but still asks to fetch packages in a subsequent run. The
  workaround I would suggest would be to use a hook script for it. Hook
  scripts run before we boot user applications and are regular escripts:
#!/usr/bin/env escript
main(_) -> application:stop(inets).

You can then hook the script in with:
{shell, [{script_file, "path/to/file"}]}

in rebar3.config, or with
rebar3 shell --script_file test/check_env.escript

A: I can't find anything in the documentation to suggest that rebar.config can contain the application configuration you want.
Instead, application configuration is often kept in a configuration directory in your application, and like the example you gave says, you must use the -config flag when launching erl to point to the configuration file.
If you use rebar3 for making release and start your service by script made with relx (from _build/default/rel/<release_name>/bin/<release_name> by default) the application configuration file is passed to erl for you.  If config file exist in your application directory, by default in config/sys.config, It will be regarded as application configuration, otherwise an empty configuration will be made.  You can customize Its path by relax' release option sys_config.
For our software, we typically had a single config/sys.config file. The structure is the same as the config sample you have provided. Note that the configuration file can contain settings for many different services. For example, mixing inets with one of ours:
[{inets, [
     {services,[{httpc,[{profile, server1}]},
     {httpc, [{profile, server2}]}]}
 ]},
 {my_app, [
     {my_setting, "my value"}
 ]}
].

We launch with erl -config config/sys.config.
This way if we need to set service configuration we can simply update our configuration file, which also houses the configuration specific to this application.
As far as I'm aware, this is the correct method to use. I have not been able to find documentation supporting any other way of doing this.


text:
Q: Rails: ActiveRecord::PendingMigrationError I need some help getting my Cloud 9/Rails environment working again for an online course I'm working on through Upskill. I ran into a problem with one section and ended up rolling back to a previous commit. However, since I did that, I've run into some database errors I haven't been able to resolve.
Here is what I get when I try to access my app:

ActiveRecord::PendingMigrationError
  Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development

I've tried the suggested method to resolve it, but it hasn't worked, nor have a dozen other suggestions I've found in other threads with a similar message.
Below is what I see when I run rails db:migrate:status. So I believe maybe it has something to do with the third item there.
Status   Migration ID    Migration Name
up     20170331144924  Create contacts
up     20170406172755  Devise create users
down    20170410151911  Add devise to users
I am really lost but just hoping to get back to where I was so I can continue with the lessons. Thank you.

A: What worked for me was:
rake db:test:purge
rake db:test:prepare

A: Have you tried running a specific migration which is down like this? Ref
rake db:migrate:up VERSION=20170410151911


text:
Q: Difference between web sockets and WCT netTCP (.NET remoting?) I have a PHP chatroom that currently uses long polling with JQuery. Someone recommended that I upgrade to using PHP Websockets in order to get my PHP Chatroom to communicate with a project I've been working on for a tutorial in familiarizing myself with dual channel with callbacks in WCF with netTCPBinding. As soon as I looked up chat app-building tutorials, sure enough I started seeing more socket-based programming (which I have not done much of).
Can someone please clarify the difference to me between WCF's netTcpBinding (or a modern version of .NET remoting as I have heard a PluralSight author call it) and using websockets or just sockets in general? And any advice in getting me to connect either a Java chat client or my PHP chatroom connected to my server in my tutorial WCF chat client-server project?


text:
Q: How can I keep the following asynchronous pattern DRY in JavaScript? The basic pattern is if X do something asynchronously else do something synchronously.  For example
if (varNotSet) {
    setVarAsynchronously(function(callback) {
        // process callback then...
        render(page, {'var': myVar});
    });
}
else
    render(page, {'var': myVar});

What's bothering me is the following
render(page, {var: myVar});

since the same code is repeated.  Is there some way that I can encapsulate that logic in a single place?

A: Sure, use another function.
function resolve() {
    render(page, {'var': myVar});
}

if (varNotSet) {
    setVarAsynchronously(result) {
        // process result then...
        resolve();
    }
}
else resolve();

A: If you are using jQuery, I highly recommend its build-in $.Deferred function which is available sincs version 1.5
It is made precisely to help with issues like the one you wrote.
Using jQuery, you would do this the following way:
var def = new $.Deferred;
var promise = def.promise();
if (varNotSet) {
    setVarAsynchronously(function(callback) {
        def.resolve();
    });
}
else
    def.resolve();

promise.done(function () {
    render(page, {'var': myVar});
});

If the deferred object's promise was already resolved, its callback is run immediately, otherwise it runs when it is resolved. Later you can attach more callbacks to the promise with .done(), and all of them will be called immediately if the deferred object was resolved.
(You don't have to make a promise object from the deferred object for making callbacks, it is just an optional thing that allows you to separate setting the deferred's status from being able to add callback listeners. Otherwise you can do everything on the deferred object.

A: The completely generic way of doing this could be a helper function like this:
// helper function
function runWhenVal(val, asynchFn, fn) {
    if (!val) {
        asynchFn(function(callback) {
            fn();
        });
    } else {
        fn();
    }
}

// using the helper function
runWhenVal(x, setVarAsychronously, function() {
    render(page, {'var': myVar});
});


text:
Q: Commutativity of permutations Two permutations $\tau_1$ and $\tau_2$ commute if and only if they are disjoint or there exists a permutation $\sigma$ and $k_1,k_2\in\mathbb{Z}$ such that $\tau_1=\sigma^{k_1}$ and $\tau_2=\sigma^{k_2}$
The $\Leftarrow$ implication is obvious but ¿is it true the biconditional? ¿Can you prove it or show a counterexample?

A: In $S_4$, let $p,q$ be given by
\begin{align*}
p&=(1\;2)\\[4pt]
q&=(1\;2)(3\;4)\\[4pt]
\end{align*}
It easily verified that $pq=qp$.

It's clear that $p,q$ are not disjoint.

Noting that $p,q$ both have order $2$, it follows that $p,q$ can't belong to the same cyclic subgroup of $S_4$, since a cyclic group can't have two distinct elements of order $2$.

So that's one counterexample.

Here's an entire class of counterexamples . . .

Let $G$ be any finite, abelian, non-cyclic group.

Let $a,b\in G$ be any two elements such that the subgroup of $G$ generated by $a,b$ is not cyclic.

To see that such a pair $a,b$ always exists, we can let $a$ be an element of $G$ of maximum order, and let $b$ be any element of $G$ not in the cyclic subgroup generated by $a$.

Now let $n=|G|$, and let $p,q\in S_n$ be the permutations in a left regular representation of $G$ corresponding to $a,b$, respectively.

Since $G$ is abelian, we have $ab=ba$, hence $pq=qp$.

Since neither of $a,b$ is the identity in $G$, it follows that $p,q$ are fixed-point free, hence $p,q$ are not disjoint.

Finally, if $p,q$ were elements of the same cyclic subgroup of $S_n$, then since any subgroup of a cyclic group is cyclic, the subgroup of $S_n$ generated by $p,q$ would be cyclic, contradiction, since the subgroup of $G$ generated by $a,b$ is not cyclic.


text:
Q: create a select and populating it using a php function, after pressing a button I have been trying a lot of things, but I dont get the solution.
I have a form which has this structure:
<form>
<input type="text" name="nombre">
<input type="submit" name="first submit">
<input type="text" name="address">
</form>

when I submit on "first submit"... I want to put on that form, a select, which will be populated with the results of a php function (passing the "name" as function variable)
the php function, receives the name written and returns an array, which needs to be looped, to get every element  as an option of the select
the form at the end need to look as:
<form mode="post" action="somephp.php" >
<input type="hidden" name="nombre" value=(name inserted before)>
<input type="hidden" name="nombre" value=(address inserted before)>
<select>
    <option value="i">$function_return[i]</option>
    <option value="i">$function_return[i]</option>
    <option value="i">$function_return[i]</option>
</select>
<input type="submit" name="second submit">
<form>

I have waste a lot of time... but im getting crazy.... could anyone save my life?
thanks
pd: adding the code i have tried:
<script>
function datos() {
var min = 0,
    max = <?php echo count(obtener("manuel")) ?>,
    select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = <?php echo obtener("manuel")[i][element] ?>;
    select.appendChild(opt);
}
}
</script>

</head>
<body>
<input type="button" value="Submit" onclick="datos()"/>;
</body>
</html>
<?php
function obtener($link) {
$buscar= (too large, simply it receives things, its only a practice exercise, i give to every name things like "color" "clothes" etc)
return $buscar;
}
?>


text:
Q: Регулярное выражение выбирает вместо перечисленных букв, все подряд Написал регулярное выражение для php  if( preg_match("/[Кк]ра[юй]/",$name));
Я хотел сделать так, что бы оно пропускало строки "Край", "Краю", "край" и "краю", но в результате оно почему-то пропускает все слова начинающиеся на кра или Кра, у который 4-ая буква любая. Т.е. пропускает и краб. Подскажите пожалуйста, почему последнее условие [юй], работает не так, как нужно, пропуская слова не только с ю и й, но и с другими буквами?

A: Судя по всему, вы работаете с utf8. Для корректной работы с юникодом для регулярных выражений в PHP необходимо указывать модификатор u (не U, а u)
melkij@melkij:~$ php -r 'var_dump(preg_match("/[Кк]ра[юй]/","краб"));'
int(1)
melkij@melkij:~$ php -r 'var_dump(preg_match("/[Кк]ра[юй]/u","краб"));'
int(0)
melkij@melkij:~$ php -r 'var_dump(preg_match("/[Кк]ра[юй]/u","край"));'
int(1)

Без этого модификатора символьная маска рассматривает 2-байтовые коды кириллицы как два разных символа и поэтому нормально работать не будет.

A: Верный regex, непонятно почему не работает, попробуйте так:
"#[к]ра[юй]#i"
Также дополните примерные содержания переменной $name

A: Вот если мне надо всего 4-ре варианта я бы написал скорее всего такую конструкцию
if( strpos($message,'Край') !== false
    || strpos($message,'край') !== false
    || strpos($message,'краю') !== false
    || strpos($message,'Краю') !== false
  ) {
     echo 'true';
}


text:
Q: Perform task after model's DOM is displayed in view I have a code snippet in my content which is a model fetched from http. I am using syntax highlighter to prettify the code. So I need to call a javascript function as soon as the DOM is updated for that particular model.
Here is a sample code to make it clear. I am using alert to demonstrate it. In my project I would use a third party plugin which will find matching dom elements and remodel them.
Here,
I want the alert to occur after the list is displayed
jsfiddle :
http://jsfiddle.net/7xZde/2/
My controller has something like this.
$scope.items = Model.notes();
alert('test');

alert comes even before the items list is shown, I want it after the list is displayed.
Any hint to help me achieve this.

A: We need to use $timeout ,
$scope.items = Model.notes();
$timeout(function () {
    alert('test');
})

Yeah it was silly , $timeout seemed to be a misnomer to me. I am 2 days old to angularjs . Sorry for wasting your time.

A: Lucky for you, I wanted to do the exact same thing. Mutation observers are the path forward, but if you need backwards compatibility with older browsers, you'll need a bit more code than this.
Working plunker for Firefox, Chrome, and Safari.
Javascript:
var app = angular.module('plunker', [])

.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
})

.directive('watchChanges', function ($parse, $timeout) {
    return function (scope, element, attrs) {
        var setter = $parse(attrs.watchChanges).assign;

        // create an observer instance
        var observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                $timeout(function () {
                    var text = angular.element('

').text(element.html()).text();
                    setter(scope, text);
                });
            });
        });

        // configuration of the observer:
        var config = {
            attributes: true,
            childList: true,
            characterData: true,
            subtree: true
        };

        // pass in the target node, as well as the observer options
        observer.observe(element[0], config);
    };
});

HTML:

Hello {{ name }}

      Name
      <input type="text" ng-model="name" />

{{text}}


text:
Q: How to display FullHD images? I am writing a simple application displaying 1080p images full screen. My problem is when I start application the resolution changes to 1280x720 (values returned by getDisplayMetrics) and I loose important for me details of images. Is there a way to set resolution to 1920x1080 or to prevent scaling to 720p?
I am using a Measy U1A smart tv dongle connected via HDMI to a 23" LG monitor. Android version is 4.0.4 and in display settings 1920x1080 60Hz is set. The pictures are 1920x1080 bmp files stored in "drawable-xhdpi" folder and I display them as background images using setBackgroundResource.

A: try putting the image in a folder named
drawable-nodpi


text:
Q: Per URI based ACL for IIS? I have ASPX website running on Windows 2008 R2, I want to limit the access for several interfaces, but not all of them.
e.g  I have an interface /admin for website www.contoso.com, but I only want people from 192.168.X.X to access this specific location. For the rest it's open to public.
But I checked the IIS configuration, looks like I can only set global IP acls with IPv4 Accress and Domain Restrictions, is there any other solutions?

A: You have the right feature, it's just not terribly clear how to use it to do what what you need.  You can indeed use the IP Address and Domain Restrictions feature to restrict access to a single folder, there just isn't any UI that make it obvious that's what you're doing.
First, you highlight the folder that you want to restrict access to (admin, in this case) in the IIS Manager, and then any rules you add using the IP Address and Domain Restrictions feature will apply only to that folder.
So, once you've highlighted the folder, set the feature default to deny all, add an entry to allow your subnet, and you'll be set.


text:
Q: Mule ESB and OAuth I want to use OAuth 1.1 with a Mule RESTful flow
I have been reading the following site:
http://www.mulesoft.org/documentation/display/current/Using+a+Connector+to+Access+an+OAuth+API
This document states the following:
There are currently two versions of OAuth that are generally n
use: OAuth1 and OAuth2. This document explains the process for
working with OAuth2. OAuth1 implementation details vary from
connector to connector, so please review the connector's
specific documentation if you need to consume OAuth1.

So I found this site:
http://www.mulesoft.org/documentation-3.2/display/32X/Authorizing+your+Connector+with+OAuth+1.0a
Which describes how to support OAuth 1 with Mule ESB
My basic understanding is that OAuth 1 is simpler and more popular (especially amoung mobile device use)
... and the OAuth 2 is more complex and less often used
I noticed taht OAuth 2 is supplied by the SalesForce connector
My questionw:
Which protocol is more widely used in general, and
which one is more used within the Mule community
Which is harder to perform within Mule
(I need the answers to these questions before I can gain approval for a direction towards one protocol or another)

A: Not sure about OAuth 1 but I guess OAuth 2 is easier to implement and is much popular specially implementing Rest Apis.
Here are few examples of implementation of OAuth 2 https://developer.mulesoft.com/docs/display/current/Mule+STS+OAuth+2.0a+Example+Application
https://dzone.com/articles/oauth-20-mule

A: In Mule, we have some policies to apply on the APIs through API manager in which there are three types of OAuth 2.0 security policies that you can configure it.
This is the screenshot of applying and configuring the API policies on API managerenter image description here
Regarding OAuth 1.0, I haven't seen any OAuth 1.0 policies present in the API manager at MuleSoft. But in general it totally depends upon the scenarios which OAuth protocols are suitable as per your requirements.


text:
Q: Adding Jar Plugins Dynamically, but issuing NoClassDefFoundError I am recently making a PluginClassLoader to load java plugins to my programs dynamically. So that the plugins can interacts with my program.
However, things won't go nicely though. So I looked up with bukkit's implementation of loading plugins. [Bukkit's source code] I followed with it, Java still throws me a NoClassDefFoundError.
Here's my implementation:
All the plugins that to be added are extended to com.mob41.sakura.plugin.Plugin. This abstract class contains onCallPlugin(), onEndPlugin(), etc. functions for the main program to interact to them. [Abstract class source code]
All the plugins will be placed in a /plugins folder on the working directory (System.getProperty("user.dir") + "\\plugins"). My program will find the folder (/plugins) on the working directory. If it doesn't exist, it creates a new folder. If exists, it will find all the jar files. And create a PluginClassLoader [Source Code] to add the plugins.
I expected the plugins will be added to the my program and the classloader will create their instances. Through this testing code:
public static void main(String[] args) {
    System.out.println("Loading...");
    try {
        PluginManager.getPluginManager().loadAllPlugins();
    } catch (Exception e){
        e.printStackTrace();
        return;
    }
    System.out.println("Loaded.");
    JSONObject json = new JSONObject();
    json.put("ext", false);
    System.out.println((JSONObject) PluginManager.getPluginManager().runPluginLifeCycle("Sakura-Plugin-HKOWeather", json));
    }

If the plugin invalid/causes error when loading it, this exception will be thrown.
I don't know why my program cannot find the plugin that extended itself...
com.mob41.sakura.plugin.exception.InvalidPluginException: java.lang.NoClassDefFoundError: com/mob41/sakura/plugin/Plugin
    at com.mob41.sakura.plugin.PluginManager.loadPlugin(PluginManager.java:180)
    at com.mob41.sakura.plugin.PluginManager.loadAllPlugins(PluginManager.java:145)
    at com.mob41.sakura.Main.main(Main.java:12)
Caused by: java.lang.NoClassDefFoundError: com/mob41/sakura/plugin/Plugin
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.mob41.sakura.plugin.PluginClassLoader.<init>(PluginClassLoader.java:25)
    at com.mob41.sakura.plugin.PluginManager.loadPlugin(PluginManager.java:176)
    ... 2 more
Caused by: java.lang.ClassNotFoundException: com.mob41.sakura.plugin.Plugin
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 17 more

A: Through hours of debugging, I finally found the answer.
I was specifying a wrong ClassLoader to my implementation of PluginClassLoader.


text:
Q: Upgraded to Jquery Validation Library CDN version 1.19.5 from 1.19.3 stops triggering server side validation in C# MVC Project With the old jquery-validate 1.19.3 CDN version, my date validation(both client and server side) was working correctly, but as soon as I migrated to 1.19.5 CDN version(https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js), Only client side validations are triggering and no server side validations are triggering. For date picker if there is no any client side validation then for invalid date entered (e.g. 01/01/20001), its throwing Validation as

*

*Please enter a valid date (ISO).

and not hitting the server side validation method.
Note - The server side validations was correctly working with version 1.19.3
Fronted code
@Html.TextBoxFor(model => model.MovingDate, "{0:yyyy-MM-dd}", htmlAttributes: new { type = "date", maxlength = "20", @class = "form-control", value = Model.MovingDate, @required = "required", title = "Test validation" })
Expecting some workaround to fix this issue


text:
Q: kafka streams serilaization error: java.lang.String cannot be cast to [Byte], issue in using json data I am new to kafka streams and i face an issue when i try to do aggregations on json data.below is my streams code, i have copied the code and the sample input below and the error , i am using kafka version : 2.12 . I have tried few days on various implementations and now stuck at this error. error and couldn't proceed. can someone please help?
public static void main(String[] args) throws InterruptedException {
 // TODO Auto-generated method stub

 Properties props=new Properties();
 props.put(StreamsConfig.APPLICATION_ID_CONFIG, "bank_stream_001");
 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
 props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE);

 final Serializer<JsonNode> jsonSerialize=new JsonSerializer();
 final Deserializer<JsonNode> jsonDeserialize= new JsonDeserializer();
 final Serde<JsonNode> jsonSerd= Serdes.serdeFrom(jsonSerialize, jsonDeserialize);

 String inputtopic = "bank_topic1";
 String outputtopic = "bankout_topic1";
 StreamsBuilder builder =new StreamsBuilder();

 //stream for reading
 KStream<String,JsonNode> stream1=builder.stream(inputtopic, Consumed.with(Serdes.String(), jsonSerd));

 //create balance node for caluclations
 ObjectNode initial_balance= JsonNodeFactory.instance.objectNode();
 initial_balance.put("count",0);
 initial_balance.put("balance", 0);
 initial_balance.put("time", Instant.ofEpochMilli(0L).toString());
 stream1.peek((k,v) -> System.out.println(k+" : "+v));
 KTable<String, JsonNode> bank_bal= stream1.groupByKey()
             .aggregate(
             () -> initial_balance,
             (key,value,cur_balance) -> newbalance(value,cur_balance)

         );

 bank_bal.toStream().peek((k,v) -> System.out.println(k+" : "+v));
 bank_bal.toStream().to(outputtopic, Produced.with(Serdes.String(), jsonSerd));

 KafkaStreams streams = new KafkaStreams(builder.build(),props);
 streams.cleanUp();

 streams.start();
   System.out.println(stream1.toString());
 Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}

private static JsonNode newbalance(JsonNode transaction,JsonNode balance) {
 ObjectNode newbal = JsonNodeFactory.instance.objectNode();
 newbal.put("count", balance.get("count").asInt()+1);
 newbal.put("balance", balance.get("balance").asInt()+transaction.get("amount").asInt());

 Long balanceEpoch= Instant.parse(balance.get("time").asText()).toEpochMilli();
 Long transEpoch =Instant.parse(transaction.get("time").asText()).toEpochMilli();
 Instant newbalanceinstant = Instant.ofEpochMilli(Math.max(balanceEpoch, transEpoch));
 newbal.put("time", newbalanceinstant.toString());
 return newbal;
 }

my data in topic : bank_topic1 is
aruna   {"name":"aruna","amount":58,"time":"2021-02-26T15:12:43.811Z"}
varun   {"name":"varun","amount":3,"time":"2021-02-26T15:12:45.081Z"}
kali    {"name":"kali","amount":16,"time":"2021-02-26T15:12:46.082Z"}
aruna   {"name":"aruna","amount":80,"time":"2021-02-26T15:13:32.806Z"}
varun   {"name":"varun","amount":33,"time":"2021-02-26T15:13:34.015Z"}
kali    {"name":"kali","amount":30,"time":"2021-02-26T15:13:35.016Z"}

i am getting error due to serde.
java.lang.ClassCastException: java.lang.String cannot be cast to [B at
org.apache.kafka.common.serialization.ByteArraySerializer.serialize(ByteArraySerializer.java:21)

can you please help?

A: I believe you need to use the overloaded version of KGroupedStream.aggregate that takes a Materialized config object.  With the Materialized config you can provide the correct Serdes to use with the statestore.
So you can try to update your aggregate call to this:
.aggregate(
           () -> initial_balance,
           (key,value,cur_balance) -> newbalance(value,cur_balance),
           Materialized.with(Serdes.String(), jsonSerd)
   );

Let me know how it goes.
HTH,
Bill


text:
Q: The JavaScript runtime exited unexpectedly when parsing CSV from an URL I am trying to import a data file from a web link and then parse it so that I can use the information. I think the problem is the big amount of data. Is there any way to avoid this error?

*

*Variables year and user are only used to filter data from the dataset depending on the URL

function importCSV() {
  var year = "2022";
  var user = "mail@mail.es";
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BBDD");
  var csvUrl = "http://erp.gruposupra.es/csv/download/?token=***************************" + year + "&user=" + user;
  Logger.log(csvUrl);
  var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
  var csvData = Utilities.parseCsv(csvContent, ";");
  Logger.log(csvData);
}


text:
Q: HLSL: problematic pixelshader code (alpha at zero when sampling)? I have this strange problem with the sampler in the pixel shaders. When I sample from a sampler into an empty float4 variable I always get black/transparent color back. So if I use this I get a black screen:
float4 PixelShaderFunction(float2 TextureCoordinate : TEXCOORD0) : COLOR0
    {
        float2 uv = TextureCoordinate;
        float4 pixelColor = tex2D(implicitInputSampler, uv);

        //contrast
        pixelColor.rgb = ((pixelColor.rgb - 0.5f) * max(Contrast, 0)) + 0.5f;

        //brightness
        pixelColor.rgb = pixelColor.rgb + (Brightness - 1);

        // return final pixel color
        return pixelColor;
    }

I I use this instead it works ok:
float4 PixelShaderFunction(float2 TextureCoordinate : TEXCOORD0) : COLOR0
    {
        float2 uv = TextureCoordinate;
        float4 pixelColor = {0,0,0,1};
        pixelColor += tex2D(implicitInputSampler, uv);

        //contrast
        pixelColor.rgb = ((pixelColor.rgb - 0.5f) * max(Contrast, 0)) + 0.5f;

        //brightness
        pixelColor.rgb = pixelColor.rgb + (Brightness - 1);

        // return final pixel color
        return pixelColor;
    }

This happens only on my dev environment at home on a AMD 4850 GPU. When I try it on some nVidias or AMD5850 it works in any case...
What is the reason for this?
Did I miss some device initialization?
Cheers!

A: It seems that the A in the pixel shader source texture indeed is 0...
The texture is declared as A8R8G8B8 and device.StretchRectangle is used to fill the texture.
This method works differently depending on hardware :/

A: I would be interested to know if the texture is 32 bit.  Mainly because I have come up against issues of AMD vs Nvidia.  In fact, what would be a non functional shader in one case was fully functional in another (AMD worked, NVIDIA didnt) just because I had an offset in my vertex buffer declaration off by 1 byte...but I digress, my question that each driver might be taking liberties on the interpretation of the alpha component if it is undeclared or not a true 32 bit texture.  Does the same thing occur if you use a different texture?   Is your alpha channel set to opaque (1.0f)?
Interested seeing I have had the old AMD/NVIDIA Driver behaviour differences before.  What works in one can actually be a error in the other driver.


text:
Q: Meteor AutoForm set optional field to be required I've the following (simplified) SimpleSchema:
EventSchema = new SimpleSchema({
    eventType: {
        type: String
    },
    kicker: {
        type: String
    },
    kicker2: {
        type: String,
        optional: true
    }
});

With this I'm using AutoForm to generate a insert form. Here is a simplified version of it:
{{#autoForm schema="EventSchema" type="method" meteormethod="addEvent"}}
    {{> afFieldInput name="eventType" options=getSubstitutionEventTypes type="select-radio-inline"}}

    {{> afFieldInput name="kicker" type="select" options=this}}

    {{> afFieldInput name="kicker2" type="select" options=this}}
{{/autoForm}}

As I'm using this Schema in an other autoForm where I don't have to input "kicker2", I've set this field to be optional. But in the form mentioned above, this field is required too. So how can I override the optional setting for a field in a specific form?
I've already tried the following, but it didn't work (required isn't rendered in the HTML):
{{> afFieldInput name="kicker2" type="select" options=this required="required"}}

Thanks in advance!

A: You have some tricks to have an optional value depending on situations, a nice one would be to set the optional value on the return of a function, giving something like this:
EventSchema = new SimpleSchema({
    eventType: {
        type: String
    },
    kicker: {
        type: String
    },
    kicker2: {
        type: String,
        optional: function() {
            return (! this.isInsert)
        }
    }
});

So it is optional on update but not on insert (you can use whatever means to customize it).
Another way to have different validation rules between forms is simply by creating a specific schema for a given form and then having autoForm(schema=yourSpecificSchema ... instead of autoForm(collection="Meteor.users". Do not forget to register an helper so your schema is accessible from your form. You can refer on the official documentation for more details: https://github.com/aldeed/meteor-autoform#non-collection-forms


text:
Q: HttpURLConnection! Connection.getInputStream is java.io.FileNotFoundException I created a method "UPLPAD2" to upload file to server. Splitting my file to packets(10MB). It's OK (100%). But when i call getInputStream, i get FileNotFoundException. I think, in loop, i make new HttpURLConnection to set  "setRequestProperty". This is a problem.
Here's my code:
@SuppressLint("NewApi")
public int upload2(URL url, String filePath,
        OnProgressUpdate progressCallBack, AtomicInteger cancelHandle)
        throws IOException {
    HttpURLConnection connection = null;
    InputStream fileStream = null;
    OutputStream out = null;
    InputStream in = null;
    HttpResponse response = new HttpResponse();
    Log.e("Upload_Url_Util", url.getFile());
    Log.e("Upload_FilePath_Util", filePath);
    long total = 0;
    try {
        // Write the request.
        // Read from filePath and upload to server (url)
        byte[] buf = new byte[1024];
        fileStream = new FileInputStream(filePath);
        long lenghtOfFile = (new java.io.File(filePath)).length();
        Log.e("LENGHT_Of_File", lenghtOfFile + "");

        int totalPacket = 5 * 1024 * 1024; // 10 MB
        int totalChunk = (int) ((lenghtOfFile + (totalPacket - 1)) / totalPacket);
        String headerValue = "";
        String contentLenght = "";

        for (int i = 0; i < totalChunk; i++) {
            long from = i * totalPacket;
            long to = 0;
            if ((from + totalPacket) > lenghtOfFile) {
                to = lenghtOfFile;
            } else {
                to = (totalPacket * (i + 1));
            }
            to = to - 1;
            headerValue = "bytes " + from + "-" + to + "/" + lenghtOfFile;
            contentLenght = "Content-Length:" + (to - from + 1);
            Log.e("Conten_LENGHT", contentLenght);
            connection = client.open(url);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Range", headerValue);
            connection.setRequestProperty("Content-Length",
                    Long.toString(to - from + 1));
            out = connection.getOutputStream();
            Log.e("Lenght_Of_File", lenghtOfFile + "");
            Log.e("Total_Packet", totalPacket + "");
            Log.e("Total_Chunk", totalChunk + "");
            Log.e("Header_Valure", headerValue);

            int read = 1;

            while (read > 0 && cancelHandle.intValue() == 0
                    && total < totalPacket * (i + 1)) {
                read = fileStream.read(buf);
                if (read > 0) {
                    out.write(buf, 0, read);
                    total += read;
                    progressCallBack
                            .onProgressUpdate((int) ((total * 100) / lenghtOfFile));
                }
            }
            Log.e("TOTAL_", total + "------" + totalPacket * (i + 1));
            Log.e("I_", i + "");
            Log.e("LENGHT_Of_File", lenghtOfFile + "");
            if (i < totalChunk - 1) {
                connection.disconnect();
            }
            out.close();
        }
        // Read the response.
        response.setHttpCode(connection.getResponseCode());
        in = connection.getInputStream(); // I GET ERROR HERE.
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException("Unexpected HTTP response: "
                    + connection.getResponseCode() + " "
                    + connection.getResponseMessage());
        }
        byte[] body = readFully(in);
        response.setBody(body);
        response.setHeaderFields(connection.getHeaderFields());
        if (cancelHandle.intValue() != 0) {
            return 1;
        }
        JSONObject jo = new JSONObject(response.getBodyAsString());
        Log.e("Upload_Body_res_", response.getBodyAsString());
        if (jo.has("error")) {
            if (jo.has("code")) {
                int errCode = jo.getInt("code");
                Log.e("Upload_Had_errcode", errCode + "");
                return errCode;
            } else {
                return 504;
            }
        }
        Log.e("RESPONE_BODY_UPLOAD", response.getBodyAsString() + "");
        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Http_UpLoad_Response_Exception", e.toString());
        response.setHttpCode(connection.getResponseCode());
        Log.e("ErrorCode_Upload_Util_Return", response.getHttpCode() + "");
        if (connection.getResponseCode() == 200) {
            return 1;
        } else if (connection.getResponseCode() == 0) {
            return 1;
        } else {
            return response.getHttpCode();
        }
        // Log.e("ErrorCode_Upload_Util_Return", response.getHttpCode()+"");
    } finally {
        if (fileStream != null)
            fileStream.close();
        if (out != null)
            out.close();
        if (in != null)
            in.close();
    }
}

And Logcat
06-12 09:39:29.558: W/System.err(30740): java.io.FileNotFoundException: http://download-f77c.fshare.vn/upload/NRHAwh+bUCxjUtcD4cn9xqkADpdL32AT9pZm7zaboHLwJHLxOPxUX9CQxOeBRgelkjeNM5XcK11M1V-x
06-12 09:39:29.558: W/System.err(30740):    at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:187)
06-12 09:39:29.563: W/System.err(30740):    at com.fsharemobile.client.HttpUtil.upload2(HttpUtil.java:383)
06-12 09:39:29.563: W/System.err(30740):    at com.fsharemobile.fragments.ExplorerFragment$7$1.run(ExplorerFragment.java:992)
06-12 09:39:29.568: W/System.err(30740):    at java.lang.Thread.run(Thread.java:856)
06-12 09:39:29.568: E/Http_UpLoad_Response_Exception(30740): java.io.FileNotFoundException: http://download-f77c.fshare.vn/upload/NRHAwh+bUCxjUtcD4cn9xqkADpdL32AT9pZm7zaboHLwJHLxOPxUX9CQxOeBRgelkjeNM5XcK11M1V-x

A: FileNotFoundException is HttpURLConnection.getInputStream()'s way of giving you an HTTP 404 status. So the URL you are POST-ing to doesn't exist. If the response code you get isn't 200 you shouldn't call getInputStream() at all, you should call getErrorStream().
But you don't need all this code. Java will set the content-length for you, and your copy loop only needs to look like this:
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

where count is an int and buffer is a byte[] of any size greater than zero, typically 8192. You don't have to worry about making it the same size as the file, or chunks, or any of that. Just set chunked transfer mode, and Java will figure it out.

A: make sure the URL you open the connection with, actually exists. It's probably cause some typo in the URL or similar.


text:
Q: spliting the html files using perl I am new to Perl but I have tried to write a program to split a single HTML file into multiple HTML files.
#!/usr/bin/env perl

use strict;
#use warnings;

my @file_names;

## Read the list of file names
open( my $fh, "$ARGV[0]" );
while ( <$fh> ) {
    chomp;    #remove new line character from the end of the line
    push @file_names, $_;
}

my $counter = 0;
my ( $file_name, $fn );

## Read the input file
open( $fh, "$ARGV[1]" );
while ( <$fh> ) {

    ## If this is an opening class, open the next output file,
    ## and set $counter to 1.

    if ( / class="bch_ha"/ ) {
        $counter   = 1;
        $file_name = shift(@file_names);
        open( $fn, ">", "$file_name" );

        #print "\n";
    }

    ## If this is a closing class, print the line and set $counter back to 0

    if ( /\n
", "$file_name" );

        #print "\n";
    }

    if ( /\n
", "$file_name" );

        #print "\n";
    }

    if ( /\n
", "$file_name" );

        #print "\n";
    }

    if ( /\n
", "$file_name" );

        #print "\n";
    }

    if ( /\n
", "$file_name" );

        #print "\n";
    }

    if ( /\n<\/body>\n<\/html>/ ) {
        $counter = 0;
        print $fn $_;
        close($fn);
    }

    ## Print into the corresponding file handle if $counter is 1

    print $fn $_ if $counter == 1
}

I need to add some more options. The code should ask for manual input for the delimiters and the split files should go to folder name chapterxx. Please help me on this
Yeah Please find the below HTML sample.
<!DOCTYPE html>

<meta charset="UTF-8" />

<p sourcepage="27" `class="bch_ha"`>

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%    Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

I just need to split the html based on the class class="bch_ha" to next class="bch_ha" and write the content in new html named reader_0.html. the file name will be incremental like reader_1.html.

A: Maybe this example will give you an idea on how to be able to complete your program.
In this example the focus is on how to split files based on the delimiter.
Note: Only the html body is saved.
#!/usr/bin/env perl
# test.pl

use strict;
use warnings;

my $file = './htmlInput.html'; # input file
my $delim = 'class="bch_ha"'; # delimiter
my $dir = 'chapter' . time; # folder with unix timestamp

# mkdir returns 1 if success
if ( mkdir($dir, 0755) ) {
    print "INFO: Created folder $dir to collect files.\n";
} else {
    die "Can't make folder $dir\n";
}

# reader_x.html, x = [0..]
my $reader = 'reader_0.html';

my $fh2;
my $cnt = 0;
my $delim_first_time = 1;
open(my $fh, "<", $file) or die "Can't open and read $file: $!"; # read file
while (my $li = <$fh>) {
    last if ( $li =~ /<\/body>/ ); # quit the while loop

    if ( $delim_first_time && $li =~ /$delim/ ) {
        open($fh2, ">", "./$dir/$reader") or die "Can't write to $reader : $!"; # write
        $delim_first_time = 0;
    } elsif ( $li =~ /$delim/ ) {
        close($fh2);
        $cnt++;
        $reader =~ s/[0-9]+/$cnt/; # reader_0.html -> reader_1.html
        open($fh2, ">", "./$dir/$reader") or die "Can't write to $reader : $!"; # write
    }
    print $fh2 $li if !$delim_first_time;
}
close($fh);
close($fh2);

# output:
# [~]$ ./test.pl
# INFO: Created folder chapter1465642603 to collect files.
# [~]$ ls chapter1465642603
# reader_0.html  reader_1.html
# [~]$ cat chapter1465642603/reader_0.html
# <p sourcepage="27" `class="bch_ha"`>

#
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

#
Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%    Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX%    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

# [~]$
# [~]$ cat chapter1465642603/reader_1.html
#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%

# [~]$


text:
Q: Alpha shape (concave hull) algorithm in C# I'm in need of concave algorithm to outline shape from set of points, is there implementation in AForge.NET that I could use, I have read somewhere that AForge.NET has implementation of that algorithm but I can't find it in documentation.
Any help would be greatly appreciated,
Best regards,
Daniel

A: I was also looking for a simple .NET implementation creating an alpha shape but couldn't find one. So I did my own. The crucial insights were provided by ETH Zurich's Kaspar Fischer in this document.
The idea is simply eating up the surrounding space of a finite point set with a circular spoon of radius alpha without actually hitting the points. Here's an image from Kaspar's paper:

Now, every circle that contains exactly two points on its boundary but none inside is said to be alpha-exposed (AEC), and it's these AEC that give you the eventual alpha shape--just replace the two points defining an AEC by an edge.
Note: If your alpha shape looks too much like a convex hull, make alpha smaller. If, on the other hand, your alpha shape is fragmented or has too many holes in it, make alpha larger.
Here's the minimalist code (it runs in O(n³), where n ist the number of points):
public class Edge
{
    public PointF A { get; set; }
    public PointF B { get; set; }
}

public class AlphaShape
{
    public List<Edge> BorderEdges { get; private set; }

    public AlphaShape(List<PointF> points, float alpha)
    {
        // 0. error checking, init
        if (points == null || points.Count < 2) { throw new ArgumentException("AlphaShape needs at least 2 points"); }
        BorderEdges = new List<Edge>();
        var alpha_2 = alpha * alpha;

        // 1. run through all pairs of points
        for (int i = 0; i < points.Count - 1; i++)
        {
            for (int j = i + 1; j < points.Count; j++)
            {
                if (points[i] == points[j]) { throw new ArgumentException("AlphaShape needs pairwise distinct points"); } // alternatively, continue
                var dist = Dist(points[i], points[j]);
                if (dist > 2 * alpha) { continue; } // circle fits between points ==> p_i, p_j can't be alpha-exposed

                float x1 = points[i].X, x2 = points[j].X, y1 = points[i].Y, y2 = points[j].Y; // for clarity & brevity

                var mid = new PointF((x1 + x2) / 2, (y1 + y2) / 2);

                // find two circles that contain p_i and p_j; note that center1 == center2 if dist == 2*alpha
                var center1 = new PointF(
                    mid.X + (float)Math.Sqrt(alpha_2 - (dist / 2) * (dist / 2)) * (y1 - y2) / dist,
                    mid.Y + (float)Math.Sqrt(alpha_2 - (dist / 2) * (dist / 2)) * (x2 - x1) / dist
                    );

                var center2 = new PointF(
                    mid.X - (float)Math.Sqrt(alpha_2 - (dist / 2) * (dist / 2)) * (y1 - y2) / dist,
                    mid.Y - (float)Math.Sqrt(alpha_2 - (dist / 2) * (dist / 2)) * (x2 - x1) / dist
                    );

                // check if one of the circles is alpha-exposed, i.e. no other point lies in it
                bool c1_empty = true, c2_empty = true;
                for (int k = 0; k < points.Count && (c1_empty || c2_empty); k++)
                {
                    if (points[k] == points[i] || points[k] == points[j]) { continue; }

                    if ((center1.X - points[k].X) * (center1.X - points[k].X) + (center1.Y - points[k].Y) * (center1.Y - points[k].Y) < alpha_2)
                    {
                        c1_empty = false;
                    }

                    if ((center2.X - points[k].X) * (center2.X - points[k].X) + (center2.Y - points[k].Y) * (center2.Y - points[k].Y) < alpha_2)
                    {
                        c2_empty = false;
                    }
                }

                if (c1_empty || c2_empty)
                {
                    // yup!
                    BorderEdges.Add(new Edge() { A = points[i], B = points[j] });
                }
            }
        }
    }

    // Euclidian distance between A and B
    public static float Dist(PointF A, PointF B)
    {
        return (float)Math.Sqrt((A.X - B.X) * (A.X - B.X) + (A.Y - B.Y) * (A.Y - B.Y));
    }
}

And, as a proof of concept, here's the output of the code used in an actual app:

A: i know that AForge DONT have the Concave Hull.
You need to use EmguCV if you want compute it.


text:
Q: Console application with read only pure HTML UI Story
I would like to make an application with two parts:
1. Console
Normal, bash-like CLI, implemented by me. That would be the way of communicating with the user, processing information, etc.
2. HTML
I would like to print HTML somewhere on the screen. It would be updated by the console.
Question
What should be the approach here? I'm not sure if a Windows Forms or WPF application is good here. IMO, that's too heavy. Ideally, a console application + some additional process would be used. But I've never heard of anything like that. Could you give me names of some frameworks / technologies where this would be possible?
Or maybe the other way - create this application but emulate console within it. I'm not sure if this is feasible...


text:
Q: Program type already present: com.mapbox.android.core.location.GoogleLocationEngine I'm trying to use Mapbox together with google play services location.
Everything worked fine until I added implementation 'com.google.android.gms:play-services-location:16.0.0' to be able to request location updates when app in background.
Gradle builds fine but when compiling the project I get the following error:
....
Caused by: com.android.tools.r8.utils.AbortException: Error: Program type already present: com.mapbox.android.core.location.GoogleLocationEngine$1$2
at com.android.tools.r8.utils.Reporter.failIfPendingErrors(Reporter.java:116)
at com.android.tools.r8.utils.Reporter.fatalError(Reporter.java:74)
at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:59)
... 57 more

I had a similar problem before and I was able to exclude the library causing the issue. However, with Mapbox I can't figure out how to resolve this conflict.
What I tried:
implementation ('com.mapbox.mapboxsdk:mapbox-android-sdk:6.8.0'){
    exclude group: "com.google.android.gms", module: "play-services-location"
} // Probably will have no effect as this module doesn't seem to be a dependency of Mapbox

OR
implementation ('com.google.android.gms:play-services-location:16.0.0'){
    force = true
}

Any help would be appreciated.
EDIT: Trying the version 7.0.0 beta2 of Mapbox seems to solve the issue, but I would like to avoid using a beta version in prod, so if there is any way I can make the current version of Mapbox with google play services location it will be great

A: Add android location services :
implementation 'com.google.android.gms:play-services-location:16.0.0'

At the end of build.gradle(app level) after dependencies close section add this line :
apply plugin: 'com.google.gms.google-services'

Like this :
    dependencies {
       ...
       implementation 'com.google.android.gms:play-services-location:16.0.0'
    }
    apply plugin: 'com.google.gms.google-services'


text:
Q: LinkageError whilst trying to invoke CXF/SOAP webservice I have a project (say myproject) in which I have hosted a CXF RESTful service and CXF WS/SOAP service, and running on JBoss (6.0.0.FINAL). The RESTful interface is used by all of our internal systems, and the SOAP interface is used by the third party systems (as a callback interface)
Following URLs are working fine.

*

*REST URL: http://localhost:8080/myproject/internal/someOperation   (content-type: application/json and POST body)

*SOAP WSDL: http://localhost:8080/myproject/cbsoap?wsdl
Now my problem is that actual SOAP calls are not successful. I use SOAPUI to try the SOAP calls but just to able to query the WSDL. I am getting the following error:-

javax.servlet.ServletException: Servlet execution threw an exception
    org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:67)

root cause

java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.apache.cxf.jaxb.attachment.JAXBAttachmentUnmarshaller.getAttachmentAsDataHandler(Ljava/lang/String;)Ljavax/activation/DataHandler;" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, org/apache/cxf/jaxb/attachment/JAXBAttachmentUnmarshaller, and its superclass loader (instance of ), have different Class objects for the type r used in the signature
    org.apache.cxf.jaxb.JAXBDataBase.getAttachmentUnmarshaller(JAXBDataBase.java:78)
    org.apache.cxf.jaxb.io.DataReaderImpl.createUnmarshaller(DataReaderImpl.java:123)
    org.apache.cxf.jaxb.io.DataReaderImpl.read(DataReaderImpl.java:156)
    org.apache.cxf.interceptor.DocLiteralInInterceptor.handleMessage(DocLiteralInInterceptor.java:109)
    org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
    org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
    org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:207)
    org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:209)
    org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:191)
    org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:114)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:185)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:108)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
    org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:164)
    org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:67)

A: LinkageError is JBoss is generally caused by your app packaging its own copies of certain libraries that JBoss considers restricted. These are usually things in the java.* and javax.* packages.
Looking at your stack trace, I'd guess that the culprit is javax.activation.DataHandler. Check your app's bundled JAR files, make sure there's nothing like that in them. If there is, then remove it.
It may not be javax.activation.DataHandler, but may be something it in turn depends on.

A: I finally solved the problem but it is really weird.

*

*I added cxf-rt-frontend-jaxws and cxf-bundle-rs as dependencies and mark some exclusions -> jetty-server, gernomino-servlet.

*I had the beans.xml under WEB-INF folder but had to place it under src/main/resources. The beans.xml is expected to be under the classpath, instead of WEB-INF.

Thanks for your responses.


text:
Q: How to direct a domain to subdomain (Next.js + ZEIT) I have a web platform where each user has a profile, eg. domain.com/user/morgan.
I'm using Next.js, and by detecting either req.headers.host or window.location.host on the index page, I can serve up that same profile page on morgan.domain.com.
Now I want to allow users to choose their own domain name, and have it point to their profile page. I've managed to point mycustomdomain.com to domain.com, but I can't work out how to point it to morgan.domain.com.
Or perhaps it is connecting properly to morgan.domain.com but my Next.js code (which detects literally from the URL what the subdomain is) cannot work out that it's a subdomain.
In any case, is it possible with ZEIT and Next.js, to have mycustomdomain.com point to morgan.domain.com and have the page realise that this is a subdomain, and it should serve the user profile page and not the domain.com homepage?


text:
Q: Finding the smallest number of steps between two points? I have a grid, The Grid have two "Material" -

*

*Floor

*Wall

For example :

In this grid we have objects that have size and location (The location of an object is the top left point).
On each object we can do some action like -

*

*Move Up

*Move Down

*Move Left

*Move Right

*Turn The Object (Relative to the top left point)

I need to make a function that returns me the Minimum amount of actions I need to do on a object to move it from one point to another point (I need only the amount of action).
I solved this problem using dijkstra's algorithm, but without the turn action.
So can anyone help me to build this function.
Example of the problem -

*

*The starting point -

*The end point

And I need to return the minimum amount of actions I need to do on a object.

A: Consider the problem as finding the shortest path in a 3D grid, with a depth of 2 (each of the possible states: horizontal and vertical). You have to code the constraints that disallows one from moving from one depth to another, e.g., cannot go vertical if it doesn't fit that way.
Now you can just use regular BFS to find the shortest path in a grid (i.e., an unweighted graph).

A: For your problem, I think BFS still works.
Using BFS to solve traditional Maze problem, starting from the beginning point, you have to:
1. Enqueue every point that is accessible (not a piece of wall, and not visited) and connected to the current point.
2. Dequeue current point and mark it as VISITED.

From above, you can see that BFS won't let any point to be visited twice, thus loop is avoided.
Your Problem
As for your problem, BFS still works, but we will slightly change the definition of "accessible":
First, I will introduce what the "maze" matrix looks like.
Here is what the numbers mean in the following images.
(Assume that the size of the object is 1*2, and when moving, the top-left corner of the object stays at each point).
00: The point can't be accessed, neither the object is horizontal nor vertical.
10: The point can be accessed if the object is horizontal
01: The point can be accessed if the object is vertical
11: The point can be accessed if the object is either horizontal or vertical

And your graph can be converted into a matrix like below:

Fill in those inaccessible points with 00, and you'll get

This is more like a Maze problem, but a little bit different.
Finally, let's see how to "access" those points:
The definitions of connected is similar to the traditional Maze problem. Here are some examples:
---------
| 01| 10|
|---|---|
| 10|   |
---------    (Not Connected from top-left to either top-right or bottom-left)

---------
| 11| 10|
|---|---|
| 01|   |
---------    (Connected from top-left to both top-right and bottom-left)

---------
| 10| 10|
|---|---|
| 01|   |
---------    (Connected from top-left to top-right, but not connected to bottom-left)

So the rest may be simple. Follow the traditional BFS method, and create a 2-dimension array to store the length of the shortest path at each point. Dequeue to get the current point, add connected neighbors of current point to the queue, and mark this point as VISITED, then everything will be the same as BFS.
After you've got the shortest path, re-run your program, maintain a state of whether the object is vertical or horizontal at current point, and simulate your move on the image. Add turns only when necessary, and you will get the result with turns added.

A: If I understand what you're asking, writing this out would take too long, but the easiest way of doing it I can think of is finding the path first, check for collision along that path, rotate, and add the actions accordingly.

*

*Use basic pathing algorithm to find the path to the end.

*Store path nodes in some sort of traversable array (should be 4 total if the pathing algorithm is good/simple).

*Attempt to follow path notes (i to array count)

*Check for collision on each movement.

*(do while) If movable object intersects with the wall, rotate 90 degrees and try again.

*(next) If success, save to move action list (move x/y, rotate z)

*Return action count

With a more complicated grid, this would obviously get more complicated, but you only have to do 90 degree turns. It should be possible in ~9 actions.

A: Use the Breadth-first search strategy, assigning weights to edges depending on must turn the object or not.


text:
Q: flutter moved all dependencies of pubspec.lock to pubspec.yaml to report an error In order to control the version of all indirect dependencies, I moved all dependencies of pubspec.lock to pubspec.yaml. I compared the differences between pubspec.yaml and pubspec.lock, and finally pubspec.yaml looks like this:
name: xxxx
description: A new flutter plugin project.
version: 0.0.1
homepage:

environment:
  sdk: ">=2.12.0 <3.0.0"
  flutter: ">=1.20.0"

dependencies:
  flutter:
    sdk: flutter

  # flutter packages=========
  async: 2.6.1
  boolean_selector: 2.1.0
  characters: 1.1.0
  charcode: 1.2.0
  clock: 1.1.0
  collection: 1.15.0
  fake_async: 1.2.0
  ffi: 1.1.2
  matcher: 0.12.10
  meta: 1.3.0
  path: 1.8.0
  sky_engine: 0.0.99
  source_span: 1.8.1
  stack_trace: 1.10.0
  stream_channel: 2.1.0
  string_scanner: 1.1.0
  term_glyph: 1.2.0
  test_api: 0.3.0
  typed_data: 1.3.0
  vector_math: 2.1.0

dev_dependencies:
  flutter_test:
    sdk: flutter

Then I get an error:

pub get failed (1; Because xxx depends on sky_engine >=0.0.2 which
requires SDK version <2.0.0, version solving failed.)

The error is obvious, sky_engine requires SDK version <2.0.0. But sky_engine is a dependency of flutter sdk, everything worked before I moved to pubspec.yaml.
My questions:

*

*Why does sky_engine work in pubspec.lock without version problems? If I don't lower the flutter sdk version, how can I solve the current problem?

*If I want to control all indirect dependent versions, is there a better way?

A:
Why does sky_engine work in pubspec.lock without version problems?

I'm not certain, but my guess is that the reference in Flutter is pulled from the Flutter SDK, but the way you've added it to your pubspec is trying to pull this very old package from pub.

If I don't lower the flutter sdk version, how can I solve the current problem?

You could just remove sky_engine from the list. It will be implicity versioned through your Flutter SDK. However:

If I want to control all indirect dependent versions, is there a better way?

Yes, you would be better committing your pubspec.lock file (and only listing your specific dependencies in pubspec.yaml). This is suggested practice for your applications:
https://dart.dev/guides/libraries/private-files#pubspeclock

For application packages, we recommend that you commit the pubspec.lock file. Saving pubspec.lock ensures that everyone working on the app uses the exact same versions.

However, if you're creating a package/reusable library, doing this may create unnecesary version constraints for projects using the package and therefore this might not be a good idea. You don't say why you're trying to do this though.

A: I re-checked the pubspec.lock file, and I found that the SDK depends on the way, and I wrote it wrong.
This is pubspec.lock:
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
  async:
    dependency: "direct main"
    description:
      name: async
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "2.6.1"
  boolean_selector:
    dependency: "direct main"
    description:
      name: boolean_selector
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "2.1.0"
  characters:
    dependency: "direct main"
    description:
      name: characters
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.1.0"
  charcode:
    dependency: "direct main"
    description:
      name: charcode
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.2.0"
  clock:
    dependency: "direct main"
    description:
      name: clock
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.1.0"
  collection:
    dependency: "direct main"
    description:
      name: collection
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.15.0"
  fake_async:
    dependency: "direct main"
    description:
      name: fake_async
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.2.0"
  ffi:
    dependency: "direct main"
    description:
      name: ffi
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.1.2"
  flutter:
    dependency: "direct main"
    description: flutter
    source: sdk
    version: "0.0.0"
  flutter_test:
    dependency: "direct dev"
    description: flutter
    source: sdk
    version: "0.0.0"
  matcher:
    dependency: "direct main"
    description:
      name: matcher
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "0.12.10"
  meta:
    dependency: "direct main"
    description:
      name: meta
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.3.0"
  path:
    dependency: "direct main"
    description:
      name: path
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.8.0"
  sky_engine:
    dependency: "direct main"
    description: flutter
    source: sdk
    version: "0.0.99"
  source_span:
    dependency: "direct main"
    description:
      name: source_span
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.8.1"
  stack_trace:
    dependency: "direct main"
    description:
      name: stack_trace
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.10.0"
  stream_channel:
    dependency: "direct main"
    description:
      name: stream_channel
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "2.1.0"
  string_scanner:
    dependency: "direct main"
    description:
      name: string_scanner
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.1.0"
  term_glyph:
    dependency: "direct main"
    description:
      name: term_glyph
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.2.0"
  test_api:
    dependency: "direct main"
    description:
      name: test_api
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "0.3.0"
  typed_data:
    dependency: "direct main"
    description:
      name: typed_data
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "1.3.0"
  vector_math:
    dependency: "direct main"
    description:
      name: vector_math
      url: "https://pub.flutter-io.cn"
    source: hosted
    version: "2.1.0"
sdks:
  dart: ">=2.12.0 <3.0.0"
  flutter: ">=1.20.0"

I found that the sources of sky_engine, flutter, and flutter_test are all sdk, and then I referred to the use of flutter and flutter_test in pubspec.yaml, so I got the following writing, it works.
sky_engine:
    sdk: flutter

Coupled with @Danny Tuppeny's suggestion, I now have two ways to control indirect dependencies:

*

*Add all indirect dependencies to pubspec.yaml

*The application of pubspec.lock commit to a remote repository


text:
Q: Spring boot + apache tiles I'm trying to create that bean:
@Bean
public TilesConfigurer tilesConfigurer() {
    TilesConfigurer configurer = new TilesConfigurer();
    configurer.setDefinitions("/tiles/tiles-definition.xml");
    return configurer;
}

I'm getting this problem:

Error creating bean with name 'tilesConfigurer'. Invocation of init
  method failed; nested exception is java.lang.IllegalArgumentException:
  No URL for ServletContext resource [/tiles/tiles-definition.xml]

tiles-definition.xml is in src/main/resources/static/tiles/ folder, but Spring cannot find it. What is the default root of webcontent?
When I used Spring MVC, it was webapp/WEB-INF, but I read that in Spring Boot it is resources/static, so I thought it is the root of every static web resource. Can you help me make that work?

A: Path of resource seem to be wrong.
@Bean
public TilesConfigurer tilesConfigurer() {
    TilesConfigurer configurer = new TilesConfigurer();
    configurer.setDefinitions("static/tiles/tiles-definition.xml");
    return configurer;
}

A: I've resolved this issue today. Just packaging with WAR instead of JAR. Hope this help!


text:
Q: How to make a background picture transparent? I used the wallpaper package to add a background picture to a document site. My code:
\documentclass{scrartcl}
\usepackage{wallpaper}
\begin{document}
  \ThisTileWallPaper{\paperwidth}{\paperheight}{hands}
  \Huge Text!
\end{document}

I wish to make it transparent so the result looks like this. I mean the transparent package with the command {\transparent{0.4}}. How can I do it? Here's the picture:

A: Use eso-pic to insert the picture in the BackGround of the page you're working on. This way you have full control over the way the image is processed, including setting the appropriate transparency level:

\documentclass{article}

\usepackage{eso-pic,graphicx,transparent}

\begin{document}

\AddToShipoutPictureBG*{%
  \AtPageLowerLeft{%
    \transparent{0.4}\includegraphics[width=\paperwidth,height=\paperheight]{hands}%
  }%
}

\Huge Text!

\end{document}

A: One can also use TikZ.  Be sure to run it twice.
\documentclass{scrartcl}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}[remember picture, overlay]
  \node[opacity=0.6,inner sep=0pt] at (current page.center)
   {\includegraphics[width=\paperwidth,height=\paperheight]{example-image}};
  \end{tikzpicture}
  \Huge Text!
\end{document}


text:
Q: How to combine Expression objects without invoking? I have a delegate as follows:
public delegate TestResult TestCase(byte[] source);

...where the return TestResult is as follows:
public class TestResult {

    public bool Pass { get; }
    public int Index { get; }

    public TestResult(bool result, int index) {
        Pass = result;
        Index = index;
    }
}

An example TestCase delegate looks like:
public static TestResult In(byte[] tkn, ITestSet testSet) {
    return testSet.Contains(tkn);
}

ITestSet is not much more than an encapsulated HashSet<byte[]>.
In one use case I have 2 test sets: (1) A - z, (2) 0 - 9. I want to test if an input byte[] is in either test set.
I am using Expression<TestCase> but having trouble figuring out how to implement the Or test case. I have a TestCaseBuilder with the following methods:
public class TestCaseBuilder {
    private Expression<TestCase> tcExpr;

    public TestCaseBuilder With(TestCaseBuilder tcBuilder) {
        tcExpr = tcBuilder.tcExpr;
        return this;
    }

    public TestCaseBuilder Or(TestCaseBuilder tcBuilder) {
        tcExpr = tcExpr.Or(tcBuilder.tcExpr);
        return this;
    }
}

...and my extension method:
public static Expression<TestCase> Or (this Expression<TestCase> tcLeft, Expression<TestCase> tcRight) {
    var lExpr = (LambdaExpression)tcLeft;
    var rExpr = (LambdaExpression)tcRight;
    var param = lExpr.Parameters;

    return Expression.Lambda<TestCase>(/* what to do here ? */, param);
}

Expression.OrElse is mechanically what I would think is appropriate but cannot use that since I am returning a TestResult, not a bool.
Here is how the TestCaseBuilder is used:
testcaseBuilder.As("Foo")
    .With(isLetterTestCase)
    .Or(isDigitTestCase);

I have performed the Or using just the TestCase delegates:
public static TestCase Or(this TestCase tc1, TestCase tc2) {
    return tkn => {
        var res = tc1(tkn);
        if (res.Pass) {
            return res;
        }

        return tc2(tkn);
    };
}

How can I combine the 2 Expression<TestCase> in a custom Or method without invoking the first test case?

A: Is this what you wanted
        public static Expression<Func<byte[], TestResult, TestCase, TestResult>> helperExp = (inp, res, next) => res.Pass ? next(inp) : res;

        public static Expression<TestCase> Or(Expression<TestCase> exp1, Expression<TestCase> exp2)
        {
            var param = exp1.Parameters;

            Expression<TestCase> or = Expression.Lambda<TestCase>(
               Expression.Invoke(helperExp,
                param[0], Expression.Invoke(exp1, param), exp2),param);

            return or;
        }

With a block expression no invoke
public static Expression<TestCase> Or(Expression<TestCase> exp1, Expression<TestCase> exp2)
        {
            var param = exp1.Parameters;

            ParameterExpression local = Expression.Parameter(typeof(TestResult), "local");

            BlockExpression block = Expression.Block(
                new[] { local },
                Expression.Assign(local, exp1.Body),
                Expression.Condition(Expression.Property(local, nameof(TestResult.Pass)), exp2.Body, local));

            return Expression.Lambda<TestCase>(block, param);
        }

Test
            Expression<TestCase> exp1 = (tc) => new TestResult(true);
            Expression<TestCase> exp2 = (tc) => new TestResult(false);

            var first = Or(exp1, exp1);

            var second = Or(first, exp2);

            var func = second.Compile();

            var result = func(new byte[] { });

There might be a better way to do a conditional monad without expressions using https://github.com/louthy/csharp-monad
I thing .net core uses the monad principle for middleware.