text:
Q: How to limit the scope of a logical call context I  have placed some data on the call context (CallContext.SetData(key,data)) where data is of a type that implements ILogicalThreadAffinative.  The reason that it implements ILogicalThreadAffinative is that it must be shared across multiple threads in the current application.
However, the application also makes remote calls to another service, and this is where the problem comes in.  My ILogicalThreadAffinative implementation is not serializeable and should not be.  Even if I were to mark it serializable, the remote application does not have access to the assembly in which the type is declared so it would not be able to deserialize it.
So how do I share call context data within my application (AppDomain) but not with every external application it happens to need to talk to?

A: Ultimately I solved this by implementing a custom IMessageSink which I inserted before the formatter sink on the client side of the remoting call.  The sink strips out the call context data before it goes across the wire.  Below is the relevant method.
private static void SanitizeCallContext(IMessage msg)
    {
        var callContext = msg.Properties["__CallContext"] as LogicalCallContext;

        if (callContext == null) return;

        var sanitizedContext = (LogicalCallContext) callContext.Clone();
        var prop = typeof (LogicalCallContext).GetProperty("Datastore",
                                                           BindingFlags.Instance | BindingFlags.NonPublic);
        var dataStore = (Hashtable) prop.GetValue(sanitizedContext, null);
        foreach (var key in dataStore.Keys.Cast<string>().ToArray())
            sanitizedContext.FreeNamedDataSlot(key);

        msg.Properties["__CallContext"] = sanitizedContext;
    }

I don't especially like this solution.  It seems more than a little hackish, but it is the best solution I have been able to come up with.

A: My understanding, which might be wrong, is that putting data in the CallContext is sufficient to cause it to be flowed across multiple threads.  Implementing ILogicalThreadAffinative (or putting the data into the CallContext via LogicalSetData) is only required if you want it to flow "automatically" across AppDomains.  So it seems that if you put your data in the CallContext but don't implement ILogicalThreadAffinative it should do what you want (flow within your application but NOT across Appdomains)?
Here are some links that I found regarding CallContext and ILogicalThreadAffinative (or LogicalSetData):
http://social.msdn.microsoft.com/forums/en-US/netfxremoting/thread/aec8dda5-102e-44eb-9a41-0a5d8b8b96e9
Another link that apparently references the information from the above link:
http://dotnetmustard.blogspot.com/2008/08/identifying-differences-between.html
(See Nicko Cadell's reply in this link for an explanation of how log4net uses CallContext):
http://www.l4ndash.com/Log4NetMailArchive%2Ftabid%2F70%2Fforumid%2F1%2Fpostid%2F15288%2Fview%2Ftopic%2FDefault.aspx
Good luck!


text:
Q: Выделение памяти для массива с использованием больших чисел Пытаюсь разобраться, как выделять память для массивов с использованием больших чисел. Я понимаю, что нельзя выделить память, если у типа данных нет size_t. Вот, например, использую библиотеку boost(если есть другие, которые лучше подойдут, посоветуйте пожалуйста)
#include <boost/multiprecision/cpp_int.hpp>

using namespace boost::multiprecision;

int128_t v = 68718952447;
int128_t *r;

    r = new int128_t[sqrt(v)];

В последней строчке ошибка, я понимаю, это из-за того, что int128_t нет size_t. Вот как выкрутиться можно? Думаю тут наверное, когда выделяешь память под значения, надо конвектировать в тип, где есть size_t, но как это сделать не знаю. Подскажите, пожалуйста, как сделать правильно.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I access object field by variable in template? I have a nested loop:
{{$columns := .columns}}
{{range $dx := .dataList}}
    {{range $c := $columns}}
        {{index $dx $c}}
    {{end}}
{{end}}

dataList is the orm model array. With ID, Title fields , then columns is the []string variable contains all orm model field names like ID, Title.
type AdFile struct {
    ID      uint `gorm:"primary_key"`
    Title   string
}

I've tried with {{(index .listData 0).Title}} and it works.
But if i want to access $dx.Title, $dx.ID .... with Title, ID as variables, but it doesn't work. I've tried $dx[$c].
Can achieve the same thing with Python easily
for i in list_data
    tr
        for p in columns
            td=i[p]

A: To access field values of a struct given by their names, you need help from the reflect package. It can be done like this:
v := AdFile{ID:1, Title: "T1"} // A struct value
name := "ID"                   // field name

fieldValue := reflect.ValueOf(v).FieldByName(name).Interface()

Since this is Go code, you can't embed this in templates. But you may register custom functions with the Template.Funcs() method which may be called from templates.
So let's do this: wrap this functionality into a function, and register it by the name "Field" so we can call it from our template.
func main() {
    t := template.Must(template.New("").Funcs(template.FuncMap{
        "Field": func(v interface{}, name string) interface{} {
            return reflect.ValueOf(v).FieldByName(name).Interface()
        },
    }).Parse(templ))

    m := map[string]interface{}{
        "columns": []string{"ID", "Title"},
        "dataList": []AdFile{
            {ID: 1, Title: "Title1"},
            {ID: 2, Title: "Title2"},
        },
    }

    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }

}

const templ = `{{$columns := .columns}}
{{range $dx := .dataList}}
    {{range $c := $columns}}
        {{- Field $dx $c }}
    {{end}}
{{end}}`

Output of the above app (try it on the Go Playground):
1
Title1

2
Title2

Note: error check is omitted in the registered "Field" function. You may improve it to return nil if the given field name is invalid, or return an error which is handled by the template engine (in which case template execution would be aborted with the error you return).


text:
Q: Rust module import visibility in library crate It seems like I haven't fully understood Rust's module system yet. I have the following file structure:
module_issue
|_Cargo.toml
|_src
  |_main.rs
  |_lib.rs
  |_bindings
    |_mod.rs

This code compiles and runs without issues:
// file: bindings/mod.rs

pub fn say_hello() {
    println!("Hello from the bindings module!");
}

// file: lib.rs

mod bindings;

pub fn try_bindings() {
    bindings::say_hello();
}

// file: main.rs

use module_issue;

fn main() {
    module_issue::try_bindings();
}

However, if I make a sub-module in lib.rs and try to use bindings::say_hello() from there, I get a compiler error. Here's what lib.rs now looks like:
// file: lib.rs

mod bindings;

pub fn try_bindings() {
    bindings::say_hello();
}

mod debugging {
    pub fn try_bindings_debug() {
        bindings::say_hello(); // <- can't find 'bindings' - shouldn't it be in scope?
    }
}

and this is the error I get:
error[E0433]: failed to resolve: use of undeclared type or module `bindings`
  --> src\lib.rs:10:9
   |
10 |         bindings::say_hello();
   |         ^^^^^^^^ use of undeclared type or module `bindings`

error: aborting due to previous error

In lib.rs, I also tried replacing mod bindings; with use crate::bindings;, but that resulted in a different error:
error[E0432]: unresolved import `crate::bindings`
 --> src\lib.rs:2:5
  |
2 | use crate::bindings;
  |     ^^^^^^^^^^^^^^^ no `bindings` in the root

error[E0433]: failed to resolve: use of undeclared type or module `bindings`
  --> src\lib.rs:10:9
   |
10 |         bindings::say_hello();
   |         ^^^^^^^^ use of undeclared type or module `bindings`

error: aborting due to 2 previous errors

My understanding of the module system was as follows: If I bring a module A into the scope of module B, then the public members of A will be accessible in B and all the sub-modules of B. In this case, I bring the bindings module into the scope of the library root. The debugging module is a sub-module of that root, so it should have access to bindings as well. Can you tell me where I went wrong? My priority isn't really to solve the problem, but to understand why this doesn't work.
I'm working on Windows 10, with the following toolchain:
cargo 1.39.0 (1c6ec66d5 2019-09-30)
rustc 1.39.0 (4560ea788 2019-11-04)

A:
If I bring a module A into the scope of module B, then the public members of A will be accessible in B and all the sub-modules of B.

This assertion is incorrect. The scope of each module contains only things defined or used in the module itself, not in its parents.
You can, however, pull items from the parent explicitly:
mod debugging {
    use super::bindings; // referring to library root
    pub fn try_bindings_debug() {
        bindings::say_hello();
    }
}

Playground


text:
Q: Why do x amp rated consumer electronics often come with >> x A rated BS1363 fused plugs? I often find that consumer electronics from reputable brands come with fused plugs that are rated significantly higher than the actual product.
I would have thought that the ideal fuse would be \$x+\epsilon\$ where \$x\$ is the product's expected maximum draw. Obviously, that's not practical, but frequently I find the fuses are larger than they 'have to be', that there's a standard size between what they shipped and \$x\$.
Is it just being cheap, using whatever's available (even if it's actually more expensive than the better choice, I suppose it may be 'cheaper' by availability)?
Surely the greater difference between the fuse and \$x\$ the less point there is in having it at all. Or is it more complex than I realise, should I prefer whatever was shipped over one closer in rating even if I happen to have it?

A: The purpose of the fuse is not to protect the product, it's to protect the wiring — to keep it from getting hot enough to start a fire. The fuse is rated according to the gauge of the wire. The only connection with the actual power consumption of the product is that the wire gauge must be selected to support the expected power draw.
The same thing is true for the circuit breakers in your house. They exist in order to keep the branch circuit wires from overheating in the walls.
In most jurisdictions, the minimum permitted wire size is established by regulations. For example, in the USA, the minimum gauge for house wiring is AWG14, and the minimum gauge for product line cords is AWG18.

A: In addition to the answer by Dave Tweed, while BS1362 fuses can be bought in a wide variety of ratings, there are only two "standard" values that people are expected to keep to hand.  These are 3A and 13A.  3A is for small flexes on things such as table lamps.  13A is for everything else.  So long as the fuse blows before the flex melts, that is considered acceptable.
In reality a lot of IT equipment is supplied with cables only rated at 6A, so these are often fitted with 5A fuses.


text:
Q: Why cant I use c++ syntax on Node.JS terminal? I always wondered why I can't use C++ syntax on the Node.js terminal.
For example, V8 is a JavaScript engine that implements ECMAScript. Node.js itself is a C++ program that tells the V8 engine to use it's function. So these function are written C++ code hence this application should be able to take in C++ native syntax. Meaning if I were to type C++ code in the Node.js terminal, then the Node.js terminal should be able to pass those syntax to the C++ modules in the Node.js core and output successfully. But instead it gives a :
SyntaxError: Unexpected identifier
at Object.exports.createScript (vm.js:24:10)
at REPLServer.defaultEval (repl.js:236:25)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.<anonymous> (repl.js:441:10)
at emitOne (events.js:101:20)
at REPLServer.emit (events.js:188:7)
at REPLServer.Interface._onLine (readline.js:224:10)
at REPLServer.Interface._line (readline.js:566:8)
at REPLServer.Interface._ttyWrite (readline.js:843:14)

I am just looking for a clear explanation how the two languages are abstracted although Node.js is written on top of C++.

A: Just because a program is written in C++, doesn't mean it can interpret C++ code. Would you expect this program to understand C++ code when you run it?
#include <iostream>

int main()
{
    std::string line;
    while (std::getline(std::cin, line)) {
        std::cout << line << '\n';
    }
}

A: Node and V8 are written in C++ but their job is to interpret Javascript code. They won't run any C++ code, the same way a C++ compiler won't compile any Javascript code.


text:
Q: Cisco ASA 5505 does not initiate site to site VPN? I am using Cisco ASA 5505 to establish a site to site VPN tunnel.
The problem is that, my ASA 5505 does not seem to initiate the negotiation but once the device on the other starts the negotiation the tunnel establishes successfully!
Is there any such configuration that enables the initiation of phase 1 negotiation?
Any clues what am I missing?
Thanks,

A: I would run through these steps:

*

*Before the L2L P2 is up, go ahead and ping an interesting traffic host. If everything is set up correctly, this will initiate the tunnel. Apologies if you already knew that but some do not.

*On the ASA, ensure that you have set up a crypto map entry for the interesting traffic. What could be happening, and this is just a guess, but perhaps you do not have the correct crypto map in place and instead when the peer initiates you are establishing using the dynamic crypto map.

*Using ASDM you can check out your connection profile and check your setting under Crypto Map and make sure that it is on "Bidirectional" rather than "answer only"

*Finally, make sure that is not your peer that is the issue.

A: You can debug using ASDM and Packet tracer from Tools menu.
Do you have a NAT exempt rule for the other end IP(s)?


text:
Q: How to use Laravel Blade in JS (PHP) I am developing a blog project in Laravel 5.6. I am using the Laravel built-in function called str_slug() to convert titles into slugs and JavaScript to auto generate the slugs using JavaScript's keyup function. Here's my code:
var postTitle = $('#post-title');
var postSlug = $('#post-slug');
postTitle.keyup(function() {
    postSlug.val({{ str_slug(postTitle.val()) }});
});

However, it's throwing an error of unknown constant. Can anyone tell me how to what I want? I am new to Laravel.

A: Here's a simple function to create a slug in JS:
function slugify(text)
{
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}

Source Gist

A: You can use the html markup to get this done. In the html mark up create a hidden input and put in the value of str_str() operation on the post-title and in your js set the post-slug input value to that on keyup.
<input type="text" id="post-title" value="{{$title}}">
<input type="hidden" id="hidden-post-title" value="{{str_slug($title)}}">

var postTitle = $('#post-title');
var postSlug = $('#post-slug');
postTitle.keyup(function() {
    postSlug.val($('#hidden-post-title').val());
});


text:
Q: how to fix unwanted double copy of uploaded file? My code is running fine and adding the files correctly but it is adding one additional copy of uploaded file. What is wrong?
My controller is like this:
public function add_audio(){

            $config['upload_path'] = './musics/';
            $config['allowed_types'] = 'mp3';
            $config['max_size'] = '999999999999999999999';

            $this->load->library('upload',$config);
            $this->upload->do_upload();

    if ( ! $this->upload->do_upload())
        {
            $data['error'] = $this->upload->display_errors();
            print_r($data['error']);
            //line of codes that displays if there are errors
        }
    else
    {
        $data['audio'] = $_FILES['userfile']['name'];

        $this->load->model('main');
        $query = $this->main->insert('audio',$data);

        if($query == TRUE){
            $this->load->view('admin/success');
        }
    }

A:
... but it is adding one additional copy of uploaded file. What is wrong?

That's because you're calling do_upload() twice...
public function add_audio()
{
    ....

    $this->upload->do_upload(); // <- FIRST upload (remove this one)

    if ( ! $this->upload->do_upload() ) // <- SECOND upload
    {
        ....

Since you may need the conditional logic that handles upload failures, delete the first instance of do_upload().


text:
Q: Multiple-Try Metropolis question I read Multiple-Try Metropolis from Wikipedia and I do not understand some points.

Suppose the current state is $\mathbf{x}$. The MTM algorithm is as
  follows:

*

*Draw ''k'' independent trial proposals
  $\mathbf{y}_1,\ldots,\mathbf{y}_k$ from $Q(\mathbf{x},.)$. Compute
  the weights
  $w(\mathbf{y}_j,\mathbf{x})=\pi(\mathbf{y}_j)Q(\mathbf{y}_j,\mathbf{x})\lambda(\mathbf{y}_j,\mathbf{x})$
  where $\lambda$ is non-negative and symmetric, but otherwise arbitrarily chosen.

*Select $\mathbf{y}$ from the $\mathbf{y}_i$ with probability
  proportional to the weights.

*Now produce a reference set by drawing
  $\mathbf{x}_1,\ldots,\mathbf{x}_{k-1}$ from the distribution
  $Q(\mathbf{y},.)$. Set $\mathbf{x}_k=\mathbf{x}$ (the current
  point).

*Accept $\mathbf{y}$ with probability :$$r=\text{min} \left(1,
     \frac{ w(\mathbf{y}_1,\mathbf{x} )+ \ldots+
     w(\mathbf{y}_k,\mathbf{x}) }{ w(\mathbf{x}_1,\mathbf{y})+ \ldots+
     w(\mathbf{x}_k,\mathbf{y}) } \right)$$

*

*why is probability proportional?

*Why do we sample a reference set at the step 3?

A: [Warning: I used the same notations $Q(y,x)$ $-$and $w(y,x)$$-$ as in the question but it is counter-intuitive as we usually denote this proposal kernel $Q(y|x)$ or $Q(x,y)$.]
Multiple-Try Metropolis is a regular Metropolis move when including the other proposals $y_2,\ldots,y_k$ as auxiliary variables (assuming $y=y_1$ and when picking $Q(y_2,x)\cdots Q(y_k,x)$ as the target for those auxiliaries. Indeed, if one considers the Metropolis-Hastings ratio for the proposed move from the vector $(x,x_2,\ldots,x_k)$ to the vector $(y_1,y_2,\ldots,y_k)$, one gets
$$\begin{align*}\overbrace{\dfrac{\pi(y_1)Q(y_2|x)\cdots Q(y_k|x)}{\pi(x_1)Q(x_2|y_1)\cdots Q(x_k,y_1)}}^{\text{ratio of targets}} &\times
\overbrace{\dfrac{Q(x,y_1)Q(x_2,y_1)\cdots Q(x_k,y_1)}{Q(y_2,x)\cdots Q(y_k|x)}}^{\text{ratio of proposals}}\\
&\times \underbrace{\dfrac{\frac{w(x,y_1)}{w(x,y_1)+w(x_2,y_1)+\ldots+w(x_k,y_1)}}{\frac{w(y_1,x)}{w(y_1,x)+w(y_2,x)+\ldots+w(y_k,x)}}}_{\text{ratio of selection probabilities}}\\
\end{align*}
$$
Things then simplify to
$$\dfrac{w(y_1,x)+w(y_2,x)+\ldots+w(y_k,x)}{w(x,y_1)+w(x_2,y_1)+\ldots+w(x_k,y_1)}$$ when using $$w({y}_j,{x})=\pi({y}_j)Q({y}_j,{x})\lambda({y}_j,{x})$$ since
$$\dfrac{w(x,y_1)}{w(y_1,x)}=\dfrac{\pi(x)Q(x,y_1)\lambda(x,y_1)}{\pi(y_1)Q(y_1,x))\lambda(y_1,x)}$$
[An even more detailed validation is to establish that the move satisfies detailed balance, that is, that $$\pi(\mathbf{y})\mathfrak{h}(\mathbf{y},\mathbf{x})=\pi(\mathbf{x})\mathfrak{h}(\mathbf{x},\mathbf{y}),$$ where $\mathfrak{h}$ is the multiple-try kernel.]
A different validation is to use a pseudo-marginal approach since
$$\dfrac{w(y_1,x)}{w(y_1,x)+w(y_2,x)+\ldots+w(y_k,x)}\,Q(y_1,x)$$ is an unbiased estimator of the marginal distribution of $Y_1$ given $X=x$, when integrating out the auxiliary $y_j$'s.


text:
Q: Stripe Tokenisation Timeout with Apple Pay I'm following the tutorial here to integrate Apple Pay in a native swift app. I've completed all the steps and am currently attempting to test on a physical device.
Unfortunately the payment fails after a long wait, looking at the network traffic it looks like https://api/stripe.com/v1/tokens is timing out, Please find my code for creating an Apple Pay context below (empty strings are sensitive info that I don't want to share but are usually populated);
private func makePayment() {
    let merchantIdentifier = ""
    let paymentRequest = Stripe.StripeAPI.paymentRequest(withMerchantIdentifier: merchantIdentifier, country: "GB", currency: "GBP")

    paymentRequest.paymentSummaryItems = [
        PKPaymentSummaryItem(label: "Payment", amount: amount),
        PKPaymentSummaryItem(label: "Service Charge", amount: 0.05),
        PKPaymentSummaryItem(label: "", amount: NSDecimalNumber(value: amount.doubleValue + 0.05))
    ]

    guard let context = STPApplePayContext(paymentRequest: paymentRequest, delegate: self) else { return }
    context.presentApplePay(completion: nil)
}

I have recreated the merchant ID and certificate etc. and made sure the merchant identifier matches the one on stripe.


text:
Q: Error while installing pygame 1.9.2 for Python 3.4 (OS X) I was wondering why does the installation of Pygame 1.9.2 for Python 3.4 fail to work (Procedure at http://pygame.org/wiki/macintosh).
When I try to run the pip command to install pygame (last step), the following error shows up:
# pip3 install hg+http://bitbucket.org/pygame/pygame
# doing the installation stuff successfully for the first part
clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Ddarwin -D_THREAD_SAFE -DENABLE_NEWBUF=1 -I/usr/X11R6/include -I/usr/local/include/SDL -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c src/cdrom.c -o build/temp.macosx-10.11-x86_64-3.5/src/cdrom.o
    clang -bundle -undefined dynamic_lookup build/temp.macosx-10.11-x86_64-3.5/src/cdrom.o -L/usr/local/lib -L/usr/local/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/sqlite/lib -lSDLmain -lSDL -o build/lib.macosx-10.11-x86_64-3.5/pygame/cdrom.cpython-35m-darwin.so -Wl,-framework,Cocoa
    building 'pygame.color' extension
    clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Ddarwin -D_THREAD_SAFE -DENABLE_NEWBUF=1 -I/usr/X11R6/include -I/usr/local/include/SDL -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c src/color.c -o build/temp.macosx-10.11-x86_64-3.5/src/color.o
    src/color.c:316:5: error: use of undeclared identifier 'Py_TPFLAGS_CHECKTYPES'
        COLOR_TPFLAGS,
        ^
    src/color.c:276:23: note: expanded from macro 'COLOR_TPFLAGS'
    #define COLOR_TPFLAGS COLOR_TPFLAGS_COMMON
                          ^
    src/color.c:272:49: note: expanded from macro 'COLOR_TPFLAGS_COMMON'
        (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES)
                                                    ^
    1 error generated.
    error: command 'clang' failed with exit status 1

    ----------------------------------------
Command "/usr/local/opt/python3/bin/python3.5 -c "import setuptools, tokenize;__file__='/var/folders/yj/c9jf0d390yn3lnqrpz8489fr0000gn/T/pip-s2tg3zc8-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/yj/c9jf0d390yn3lnqrpz8489fr0000gn/T/pip-we1hfsvl-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /var/folders/yj/c9jf0d390yn3lnqrpz8489fr0000gn/T/pip-s2tg3zc8-build

Any help is appreciated!

A: I had the same error just now. I pointed to the commit before the last revision to get it working for now.
pip install hg+http://bitbucket.org/pygame/pygame/@96203be


text:
Q: Relay indicator light I feel a bit silly asking this..
I have a relay, which has a switch that turns it on/off.
Next to the switch I have an indicator light which needs to turn on when the switch is turned on.
I tried putting the LED in parallel (seen below) and in line, but no luck.

What am I missing here?
(by the way, the 22k resistor is a good value for this LED at this voltage)

A:

simulate this circuit – Schematic created using CircuitLab
Youll want to double check your resistor value
You may also want to add a back emf protection diode, as seen here:

simulate this circuit

A: I'd suggest the following circuit:

simulate this circuit – Schematic created using CircuitLab
R1 will allow approximately 20 mA through the LED.
D2 protects the LED from the transient when the relay is turned off. D2 could go directly across the relay coil but it does not have to.


text:
Q: How to lock/synchronize access to a variable in Go during concurrent goroutines? In his answer to this question:  Golang for Windows erratic behavior?
user @distributed recommended to lock/synchronize access to a shared variable on concurrent goroutines.
How can I do that?
More on the issue:
I get this code (the returned function with a closure on views) running on several goroutines at the same time:
func makeHomeHandler() func(c *http.Conn, r *http.Request) {
    views := 1
    return func(c *http.Conn, r *http.Request) {
        fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)
        views++
    }
}

It looks like the IO function takes it's time, and as a result I get this kind of output:
Counting monkeys, 5 so far.
Counting monkeys, 5 so far.
Counting monkeys, 5 so far.
Counting monkeys, 8 so far.
Counting monkeys, 8 so far.
Counting monkeys, 8 so far.
Counting monkeys, 11 so far.

It increments fine, but when it gets printed I can see that the operation printing+incrementing is not atomic at all.
If I change it to:
func makeHomeHandler() func(c *http.Conn, r *http.Request) {
    views := 0
    return func(c *http.Conn, r *http.Request) {
        views++
        // I can only hope that other goroutine does not increment the counter
        // at this point, i.e., right after the previous line and before the
        // next one are executed!
        views_now := views
        fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views_now)
    }
}

It seems to work fine, but I'm not completely sure if it will not fail eventually...

A: If a synchronized counter is all you want, then using sync.Mutex is the canonical solution. The sync/atomic package should only be used for low level stuff or when you've measured a serious performance problem.
type Counter struct {
    mu  sync.Mutex
    x   int64
}

func (c *Counter) Add(x int64) {
    c.mu.Lock()
    c.x += x
    c.mu.Unlock()
}

func (c *Counter) Value() (x int64) {
    c.mu.Lock()
    x = c.x
    c.mu.Unlock()
    return
}

func makeHomeHandler() func(c http.ResponseWriter, r *http.Request) {
    var views Counter
    return func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Counting %s, %d so far.", r.URL.Path[1:], views.Value())
        views.Add(1)
    }
}

For your particular problem, I'd suggest defining a new type that satisfies the http.Handler interface, rather than returning a closure. That looks simpler too:
type homeHandler struct {
    mu  sync.Mutex
    views   int64
}

func (h *homeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    h.mu.Lock()
    defer h.mu.Unlock()
    fmt.Fprintf(w, "Counting %s, %d so far.", r.URL.Path[1:], h.views)
    h.views++
}

func init() {
    http.Handle("/", new(homeHandler))
}

A: The sync package has some synchronization primitives. Depending on the problem you could use a RWMutex or a plain Mutex.
If you want a more specific answer please give some more information  on what it's for.
Edit: After reading the linked question you're probably looking for sync/atomic, though a Mutex is fine too.
Edit2: I saw you updated your post with an example. Here's the code using sync/atomic.
func makeHomeHandler() func(w http.ResponseWriter, r *http.Request) {
    var views *uint64 = new(uint64)
    atomic.StoreUint64(views, 0) // I don't think this is strictly necessary
    return func(w http.ResponseWriter, r *http.Request) {
        // Atomically add one to views and get the new value
        // Perhaps you want to subtract one here
        views_now := atomic.AddUint64(views, 1)
        fmt.Fprintf(w, "Counting %s, %d so far.", r.URL.Path[1:], views_now)
    }
}

(Note: I have not tested the above so there might be typos/brainfarts) I tested it now.


text:
Q: Querying a database in joomla article I am unable to query the database inside an article in joomla 2.5. I tried copying some codes from sites and creating an article with the codes as the content but its just showing the raw code. I have searched google but there is no comprehensive tutorial on this, starting from the beginning. So my question is how can i use JFactory or how and where can i query a database with joomla in an article ?. I just want to query the database and use joomla to display the results.

A: You can't add code to a Joomla article by default. You need to use a plugin. For this I would highly recommend Sourcerer.
Once installed, you can add code to your articles like so:
{source}
<?php
    $user = JFactory::getUser;
    echo 'Hello' . $user->username;
?>
{/source}

There will be a button below the article content area which will bring up a popup window allowing you to add your code.
Hope this helps


text:
Q: One-Jar FileNotFoundException I have une Java application, and I use in it the openCv(opencv_java259.jar).
It work correcly in Eclipse.
For pack the application in a executable .jar file, I use One-Jar (Command Line Approch) but it don't work correctly and I have this errors:
C:\Users\User\Desktop\Tool> jar -cvfm ../one-jar.jar boot-manifest.mf .java.io.FileNotFoundException: boot-manifest.mf
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:97)
    at sun.tools.jar.Main.run(Main.java:171)
    at sun.tools.jar.Main.main(Main.java:1177)

I have done these steps :

*

*I have create from Eclipse an runnable .jar file : right clik on the project-->Export--->Runnable Jar File

*I Create a working directory "Tool" contains directories main and lib

*Copy my main application jar file (create on step 1) into root/main (named MyApplication.jar) and library dependencies into root/lib (the opencv_java259.jar)

*I have Unjar the one-jar-boot-0.97.jar file into the root directory

*Edit the boot-manifest.mf :

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: One-Jar 0.97 Ant taskdef
One-Jar-Main-Class: main.MyApplication
Main-Class: com.simontuffs.onejar.Boot

But I have the errors when i execute the command line:

C:\Users\User\Desktop\Tool> jar -cvfm ../one-jar.jar boot-manifest.mf .

Have you suggestions? Thanks for all.


text:
Q: Behaviour space simultaneous simulations error I'm using behaviour space to run 100 simulations.
The problem is when I try to run more than 1 simulation at a time, some of the variables don't seem to be cleared properly.
Here is an example output:

Each simulation (the first column is the run number) has a variable (in the last column) reset to 0. It then adds a number between 0 and 5 until it eventually maxes out at 25. Since it only runs 2 ticks, the max result should be 10...
However as can be seen, the next simulation occasionally starts out with the max value for the variable. Is this a glitch or has someone seen something like it before? (perhaps the parallel processing isn't properly working?)
Problem/Solution
I had a setup function that initialized certain variables, THEN used clear-all, and then created turtles using the variables at the beginning. By looking at the results, it looks like rather than the new turtles being initialized... they somehow retained values from the previous simulation (with the score property already maxed). The problem was fixed by repositioning clear-all at the top. Note that this only caused problems when running multiple simulations

A: Interface globals (e.g., sliders) do not have a default value (unfortunately!) so clear-all does not affect them.  This means you can run into problems if your BehaviorSpace experiments (i) do not specify values for all interface globals and (ii) describe simulations that alter the values of some interface globals.  In this case, one foreground run can affect the next foreground run, even though you call clear-all in your setup.
If you instructed BehaviorSpace to call your setup, which includes a call to clear-all, this is the only way I see for your problem to arise.  If it is something else, I hope you will post a description.

A: It seems possible that you are running into https://github.com/NetLogo/NetLogo/issues/105.
Are you calling clear-all at the start of your setup procedure?


text:
Q: Después de enviar formulario hace validación (error) Tengo un formulario HTML en Apps Script con validación class="needs-validation", todo funciona correctamente.
El form tiene un botón reset, que funciona correctamente
<button id="B_Borrar_Form" type="reset"  class="btn btn-secondary" style="float: right;">Borrar Datos</button>
El form tiene un botón que se llama desde JavaScript y ejecuta un función para guardar datos (Funciona)
<button id="G_C" type="submit" class="btn btn-primary" >Guardar Nuevo Colectivo</button>

Al final llama una función para resetear el formulario
function limpiarFormulario(miform) {
        document.getElementById(miform).reset();
      }

El problema es que después de limpiar el formulario, este queda como si se hubiera validado

document.getElementById("G_C").addEventListener("click", Enviar_Colectivos)

      function Enviar_Colectivos(){
        N_Colectivo=document.getElementById("N_Colectivo").value;
        C_Colectivo=document.getElementById("C_Colectivo").value;
        T_Colectivo=document.getElementById("T_Colectivo").value;
        M_Colectivo=document.getElementById("M_Colectivo").value;
        N_Objetivos=document.getElementById("N_Objetivos").value;
        O1_Colectivo=document.getElementById("O1_Colectivo").value;
        O2_Colectivo=document.getElementById("O2_Colectivo").value;
        O3_Colectivo=document.getElementById("O3_Colectivo").value;
        O4_Colectivo=document.getElementById("O4_Colectivo").value;
        google.script.run.Grabar_Colectivo(N_Colectivo,C_Colectivo,T_Colectivo,M_Colectivo,N_Objetivos,O1_Colectivo,O3_Colectivo,O3_Colectivo,O4_Colectivo);

        limpiarFormulario("Colectivo");
        alert ("El Colectivo ha sido guardado correctamente");
      }

      function limpiarFormulario(miform) {
        document.getElementById(miform).reset();
      }
 <form id="Colectivo" class="needs-validation" novalidate>

                        <input type="text" class="form-control" id="N_Colectivo" required/>
                         Escribe el Nombre del Colectivo

                            Correcto

                            Es necesario Ingresar el nombre del colectivo

                        <input type="text" class="form-control" id="T_Colectivo" required/>
                        Teléfono de contacto

                            Correcto

                            Es necesario diligenciar el numero telefonico

                        <input type="text" class="form-control" id="C_Colectivo" required/>
                        Persona de contacto

                            Correcto

                            Es necesario diligenciar el nombre de la persona

                        <input type="email" class="form-control" id="M_Colectivo" required/>
                        Correo Electrónico

                            Correcto

                            Es necesario diligenciar un correo electrónico válido

                        <select
                        id="N_Objetivos"
                        class="form-select"
                        required
                        onchange="mostrar_cajas()"
                        >
                        <option selected></option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        </select>
                        Elige el número de objetivos

                            Correcto

                            Es necesario elegir el numero de objetivos

                        <textarea
                        class="form-control"
                        id="O1_Colectivo"
                        style="height: 100px"
                        required
                        ></textarea>
                        Objetivo # 1

                            Correcto

                            Es necesario diligenciar el objetivo

                        <textarea class="form-control" id="O3_Colectivo" style="height: 100px" required></textarea>
                        Objetivo # 3

                            Correcto

                            Es necesario diligenciar el objetivo

                        <textarea
                        class="form-control"
                        id="O2_Colectivo"
                        style="height: 100px"
                        required
                        ></textarea>
                        Objetivo # 2

                            Correcto

                            Es necesario diligenciar el objetivo

                        <textarea
                        class="form-control"
                        id="O4_Colectivo"
                        style="height: 100px"
                        required
                        ></textarea>
                        Objetivo # 4

                            Correcto

                            Es necesario diligenciar el objetivo

                <button id="B_Borrar_Form" type="reset"  class="btn btn-secondary" style="float: right;">Borrar Datos</button>

                  <button id="G_C" type="submit" class="btn btn-primary" >Guardar Nuevo Colectivo</button>

      </form>

var rutaWeb = ScriptApp.getService().getUrl();
const Libro = SpreadsheetApp.openById("10cJ4HedtvXgLP_gOoeTh4AsAQNwrBaTprAmft9Iy6Vc")
const Hoja_Colectivo = Libro.getSheetByName("Colectivos")

function doGet(e) {
  var page = e.parameter.p || "App";
  return HtmlService.createTemplateFromFile(page).evaluate();
  }

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
};

//Guardar Colectivos
function Grabar_Colectivo(N_Colectivo,C_Colectivo,T_Colectivo,M_Colectivo,N_Objetivos,O1_Colectivo,O3_Colectivo,O3_Colectivo,O4_Colectivo) {
  //const Libro = SpreadsheetApp.openById("10cJ4HedtvXgLP_gOoeTh4AsAQNwrBaTprAmft9Iy6Vc")
  //const Hoja_Colectivo = Libro.getSheetByName("Colectivos")

  var Fila_Id = Hoja_Colectivo.getLastRow()
  var Celda_N_O = "A"+Fila_Id
  var New_Id = Hoja_Colectivo.getRange(Celda_N_O).getValue()

  //verificar si la Celda_N_O es un numero o es texto
  if (isNaN(New_Id)){
    var New_Id = 1
  } else {
    var New_Id = Hoja_Colectivo.getRange(Celda_N_O).getValue()+1
  }

  Hoja_Colectivo.appendRow([New_Id,N_Colectivo,C_Colectivo,T_Colectivo,M_Colectivo,N_Objetivos,O1_Colectivo,O3_Colectivo,O3_Colectivo,O4_Colectivo])

}

A: Si estás usando Bootstrap 5, retira la clase was-validated del elemento form. Una forma de hacerlo es la siguiente:
document.querySelector('form').classList.remove('was-validated');

Lo anterior usualmente se coloca en un callback del evento submit del elemento form que corresponda luego de haber verificado que el elemento form sea válido.
Nota: El código del Stack Snippet está incompleto y tiene varios problemas:

*

*Se está asignando un event listener tipo click al elemento button tipo submit. Usualmente lo que se hace es usar un event listener tipo submit al elemento form.

*El callback de del evento anterior incluye un google.script.run y después de este la confirmación de que se envió correctamente, lo cual es incorrecto porque google.script.run es asíncrono y en caso de falla se le habría mostrado al usuario una confirmación de envío correcto siendo que ha ocurrido un error. Debería utilizarse los métodos withSuccessHandler y withFailureHandler de google.script.run para controlar lo que se hace en caso de éxito y/o falla de llamada a la función del lado del servidor.

*Aparentemente se está usando Bootstrap, este requiere de la asignación de la clase .was-validated al elemento form pero el código no incluye esto.

*No se incluye el código para agregar la hoja de estilos de Bootstrap.

La documentación de Bootstrap cuenta con varios ejemplos sobre cómo realizar la validación de formularios.


text:
Q: Elasticsearch matching names with initial I am using elasticsearch search template mustache language
Searching 'Joe Gray' returns anybody named 'Joe Gray' or searching "J Gray" returns "Joe Gray".
But searching 'Joe Gray' does not return any names with 'J Gray'
how can I achieve this with using analyzer in my mustache query.

A: Not quite sure what your index mapping looks like. I have two examples here:
1 Name is contained in one field:
    PUT t2/doc/1
    {
      "name":"Joe Gray"
    }

    PUT t2/doc/2
    {
      "name":"J Gray"
    }

    POST t2/_search
    {
      "query": {
        "match": {
          "name": "j gray"
        }
      }
    }

##Result

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0.51623213,
    "hits": [
      {
        "_index": "t2",
        "_type": "doc",
        "_id": "2",
        "_score": 0.51623213,
        "_source": {
          "name": "J Gray"
        }
      },
      {
        "_index": "t2",
        "_type": "doc",
        "_id": "1",
        "_score": 0.25811607,
        "_source": {
          "name": "Joe Gray"
        }
      }
    ]
  }
}

2 If you have your name as two separate fields(from what i noticed in the comments) - you can use a bool query with should clause:
PUT t3/doc/1
{
  "firstname":"Joe",
  "lastname":"Gray"
}

PUT t3/doc/2
{
  "firstname":"J",
  "lastname":"Gray"
}

POST t3/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "firstname": "J"
          }
        },
        {
          "match": {
            "lastname": "Gray"
          }
        }
      ]
    }
  }
}

## Result

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0.5753642,
    "hits": [
      {
        "_index": "t3",
        "_type": "doc",
        "_id": "2",
        "_score": 0.5753642,
        "_source": {
          "firstname": "J",
          "lastname": "Gray"
        }
      },
      {
        "_index": "t3",
        "_type": "doc",
        "_id": "1",
        "_score": 0.2876821,
        "_source": {
          "firstname": "Joe",
          "lastname": "Gray"
        }
      }
    ]
  }
}


text:
Q: R: arrange vector into matrix by a factor I have an R data table where one of the columns is effectively a factor, say, day of the week. How can I arrange a different column of the table into a matrix, and that matrix's columns correspond to each day of the week?
For example, the original table is
Mon  21   A
Tue  50   C
Thur 12   D
Wed  11   K
...
Mon  9    B
Wed  100  S
Tue  99   Z
Thur 32   J

where it is guaranteed each day of the week (in this sample only Mon - Thur) appear the same number of times. Now I want to arrange the 2nd column to a matrix of (with the column title in parenthesis, not part of the matrix)
(Mon Tue Wed Thur)

21  50  11  12
...
9   99  100 32

What is the best way to do that? Thx!

A: Try using a auxiliar array to save the current one then you get the first column and display into a line on the new array. Do it do the second column and display into a line, and go on....


text:
Q: Calling app.locals outside of app.js Normally, by declaring app.locals variables, like below, I can then use the variable in jade templates.
// app.js
var express = require('express');
var app = express();

app.locals.varName = 'blah blah'

I'm looking to move app.local.varName to an external file (ie: vars.js) and then import them back in app.js for use. I'm familiar with the export module/require system, but I don't know how to make the variables become "active" for use. This is what I've got so far:
// vars.js
module.exports = {
   all : {
      var express = require('express');
      var app = express();

      app.locals.varName = 'blah blah'
   }
}

and then import back into app.js:
// app.js
var variables = require('./vars');
var variables2 = variables.all()

variables2

However, my jade templates still don't recognize the varName variable.

A: Your all in exports does not appear to be valid. But that should be easily fixed. The problem here could be because the locals get added into a separate app created from all() and not the one which you use in app.js. Try modifying your code like so (passing your in use app):
app.js
var express = require('express');
var app = express();

var variables = require('./vars');
variables.all(app)
console.log(app.locals);

vars.js
module.exports = {
   all : function(app){
      app.locals.varName = 'blah blah'
   }
}

Output
{ [Function: locals]
  settings:
   { 'x-powered-by': true,
     etag: true,
     env: 'development',
     'subdomain offset': 2,
     view: [Function: View],
     views: '/home/hadoop/views',
     'jsonp callback name': 'callback',
     'json spaces': 2 },
  varName: 'blah blah' }

A: After playing around with it, I figured out what I was looking for:
// vars.js
module.exports = {
   all : function() {
      var siteName = 'blah blah'
      return siteName;
   }
};

// app.js
var express = require('express');
var app = express();

app.locals.whateverName = require('./vars').all();

And then, in jade templates you can simply call =whateverName to get the blah blah output.

A: Try this...
var app = express();
var variables = require('./vars')(app);

and
module.exports =function(app) {
    app.locals.varName = 'blah blah'
}


text:
Q: Error Trying to create App following guide on android studio 4.1 with Kotlin following the guide: "Build your first app" using Kotlin:
https://developer.android.com/training/basics/firstapp/starting-activity#BuildIntent
Android Studio 4.1
until "Build a simple user interface" all works fine.
then after finishing "start another activity" appears the error "Unresolved reference: editText"

*

*that error appears first time at "Build an intent"

error message:
e: C:\Users\Rodrigo\AndroidStudioProjects\MyFirstApp\app\src\main\java\com\example\myfirstapp\MainActivity.kt: (17, 52): Unresolved reference: editText

Task :app:mergeExtDexDebug

FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
code:
src\main\AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myfirstapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyFirstApp"
        android:fullBackupContent="@xml/backup_descriptor">
        <activity android:name=".DisplayMessageActivity"
            android:parentActivityName=".MainActivity">
            <!-- The meta-data tag is required if you support API level 15 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

src\main\java\com\example\myfirstapp\DisplayMessageActivity.kt
package com.example.myfirstapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.AlarmClock.EXTRA_MESSAGE
import android.widget.TextView

class DisplayMessageActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display_message)
    }

    val message = intent.getStringExtra(EXTRA_MESSAGE)

    val textView = findViewById<TextView>(R.id.textView).apply {
        text = message
    }
}

src\main\java\com\example\myfirstapp\MainActivity.kt error is here
package com.example.myfirstapp

import androidx.appcompat.app.AppCompatActivity
import android.content.Intent
import android.os.Bundle
import android.provider.AlarmClock.EXTRA_MESSAGE
import android.view.View
import android.widget.EditText

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun sendMessage(view: View) {
        val editText = findViewById<EditText>(R.id.editText)
        val message = editText.text.toString()
        val intent = Intent(this, DisplayMessageActivity::class.java).apply {
            putExtra(EXTRA_MESSAGE, message)
        }
        startActivity(intent)
    }
}

src\main\res\layout\activity_display_message.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DisplayMessageActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

src\main\res\layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/edit_message"
        android:textAlignment="center"
        android:textSize="14sp"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:insetTop="0dp"
        android:insetBottom="0dp"
        android:onClick="sendMessage"
        android:text="@string/button_send"
        app:layout_constraintBaseline_toBaselineOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

src\main\res\values\strings.xml
<resources>
    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
</resources>

A: I encountered the same problem with the MyFirstApp following the Android Development guide at "https://developer.android.com/training/basics/firstapp/building-ui".
The problem does in fact lie in id of the Plain Text field in the example on that page as depicted in Layout view in Figure 5.
The id listed in that figure is "editTextTextPersonName".
Once you change the id to "editText" and re-run the program it works fine in Kotlin.

A: You don't have EditText at activity_main.xml.
You have written
val editText = findViewById<EditText>(R.id.editText)

But in your layout you don't have 'EditText' with that id. So that is causing problems


text:
Q: Publish to MQTT in django Serializer save() method I have a really simple API that uses django with restframework that act as an endpoint for iot devices.
iot Devices --HTTP POST--> REST API (django)
Data is validated and saved.
No need for any render or GET/PATCH/DELETE at all.
The only thing is that I'm not saving to database but I'd like to push to MQTT channel (other process that listen for messages will save/postprocess)
As I am not a django expert at all, My idea was to override the Serializer save() method that it actually does not save but publish.
MODEL
class Meas(models.Model):
    SENSOR_TYPES = [
        ('temperature','temperature'),
        ('humidity','humidity')
        ]
    sensorType = models.CharField(max_length=100, default='UNKNOWN', choices = SENSOR_TYPES )
    sensorId = models.CharField(max_length=100)
    homeId = models.CharField(max_length=100)
    roomId = models.CharField(max_length=150)
    hubId = models.CharField(max_length=100)
    value = models.CharField(max_length=100)
    last_seen = models.DateTimeField()
    elapsed = models.IntegerField()

    objects = MeasManager()

SERIALIZER

class MeasMQTTSerializer(serializers.ModelSerializer):

    client = RMQPublisher(ch_name=rmq_chname,routing_key=rmq_routingkey,host=rmq_host,user=rmq_user,password=rmq_pass,port=rmq_port)
    class Meta:
        model = Meas
        fields = '__all__'
    def save(self):

        logging.debug("Saving measurement")

        measurement = self.validated_data['sensorType']
        mytags = {
            'sensorId' : self.validated_data['sensorId'],
            'roomId' : self.validated_data['roomId'],
            'hubId' : self.validated_data['hubId'],
            'homeId' : self.validated_data['homeId'],
            'elapsed' : self.validated_data['elapsed'],
            'last_seen' : self.validated_data['last_seen']
        }
        for a, x in mytags.items():
            mytags[a]=str(x)
        value = float(self.validated_data['value'])

        rmq_msg = mytags
        rmq_msg['value']=value
        rmq_msg['measurement'] = measurement
        MeasMQTTSerializer.client.pushObject(rmq_msg)
        logging.debug("Pushed to RMQ")

and RMQPublisher use just simple push to mqtt:
class RMQPublisher(object):

    def __init__(self,ch_name,routing_key,host,user,password,port):
        self.routing_key = routing_key
        self.ch_name     = ch_name
        self.rmq_host    = host
        self.rmq_user    = user
        self.rmq_pass    = password
        self.rmq_port    = port
        pass

    def pushObject(self,object):
        self.connect()
        self.sendMessage(object)
        self.disconnect()

    def connect(self):
        credentials = pika.PlainCredentials(self.rmq_user, self.rmq_pass)
        parameters = pika.ConnectionParameters(self.rmq_host,self.rmq_port,'/',credentials)
        self.connection = pika.BlockingConnection(parameters)
        self.channel = self.connection.channel()
        self.channel.exchange_declare(exchange=self.ch_name, exchange_type='direct')

    def sendMessage(self,pushObj):
        message = {}
        message["content"]  = pushObj

        self.channel.basic_publish(exchange=self.ch_name,
                            routing_key=self.routing_key,
                            body=json.dumps(message))

    def disconnect(self):
        self.connection.close()

Approach seems to be half-working as some of the measurements as some
of the measurements are pushed but for some I'm getting an errors that I cannot really find a rootcause.
My guess it that with higher number of messages there is something going wrong with Serializer life-cycle that I might not understand propely
safeh-api      |     body=json.dumps(message))
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/blocking_connection.py", line 2248, in basic_publish
safeh-api      |     self._flush_output()
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/blocking_connection.py", line 1336, in _flush_output
safeh-api      |     self._connection._flush_output(lambda: self.is_closed, *waiters)
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/blocking_connection.py", line 513, in _flush_output
safeh-api      |     self._impl.ioloop.poll()
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/select_connection.py", line 576, in poll
safeh-api      |     self._poller.poll()
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/select_connection.py", line 1200, in poll
safeh-api      |     self._dispatch_fd_events(fd_event_map)
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/select_connection.py", line 904, in _dispatch_fd_events
safeh-api      |     handler(fileno, events)
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/utils/selector_ioloop_adapter.py", line 391, in _on_reader_writer_fd_events
safeh-api      |     callbacks.writer()
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/diagnostic_utils.py", line 53, in log_exception_func_wrap
safeh-api      |     return func(*args, **kwargs)
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/utils/io_services_utils.py", line 1108, in _on_socket_writable
safeh-api      |     self._initiate_abort(error)
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/diagnostic_utils.py", line 53, in log_exception_func_wrap
safeh-api      |     return func(*args, **kwargs)
safeh-api      |   File "/usr/local/lib/python3.6/site-packages/pika/adapters/utils/io_services_utils.py", line 911, in _initiate_abort
safeh-api      |     'non-_STATE_COMPLETED', self._state)
safeh-api      | AssertionError: ('_AsyncTransportBase._initate_abort() expected non-_STATE_COMPLETED', 4)

Any tips for better design or fixing existing one will be appreciated!
Thank you!

A: I know it sounds like a paranoid solution but I ended up rewriting this simple API into 3 files flask-restplus application.
Same module for MQTT works as a charm, so probably it has something to do with my misunderstanding of django objects life-cycle.


text:
Q: LINQ to Entities does not recognize the method 'Boolean Contains I have written this statement:
if (!db.Customers.Contains<Customer>(customer,customerCompairor))
                {
                    db.Customers.Add(customer);
                }

Don't see a reason why getting following error:

LINQ to Entities does not recognize the method
   'Boolean Contains[Customer](System.Linq.IQueryable1[DBInteractor.Customer], DBInteractor.Customer, System.Collections.Generic.IEqualityComparer1[DBInteractor.Customer])' method, and this method cannot be translated into a store expression.

I have created a reference :
  IEqualityComparer<Customer> customerCompairor = new PMKeyCompairor();

and PMKeyCompairor is implementing IEqualityComparer<Customer>
class PMKeyCompairor:IEqualityComparer<Customer>
    {
            ........................
            .............................
     }

Customers has an extension method Contains (returns a bool) as it's DbSet .
So where am I going wrong?

A: Linq to Entities queries are translated to SQL, but there is no way to translate the logic of your custom comparer to SQL, so the comparison has to be done in memory. You could do something like that:
if (!db.Customers.AsEnumerable().Contains<Customer>(customer,customerCompairor))

But it would load each customer in memory before comparing it to the customer variable, which is probably not a very good idea...
If you can, try to express the comparison logic as an inline Linq expression, e.g.:
if (!db.Customers.Any(c => c.Id == customer.Id && c.Name == customer.Name))


text:
Q: Does this prototype match the schematic? I'm following this project which shows how to make an OpenTherm Adapter for an Arduino. It includes this schematic:

Along with this simplistic PCB diagram:

I am now in the process of making my own version of this circuit on a prototype PCB board. This is my first time making anything more complex than a simple header wire circuit using an Arduino and has therefore posed a bit of a challenge. However, with the help of Fritzing, I have been able to prototype a board design:

I understand this is a messy design and has lots of room for optimisation, but my question is whether or not the design I have made matches the schematic in the first image above. I would really appreciate it if someone could look over my schematic and let me know.
Thank you in advance for you help.
P.S. Here is a link to where you can download the schematic file (.fzz)
EDIT
The circuit will be connected with a combination of excess solder and wires. Please bear this in mind where it may look like some tracks overlap. Feel free to download the file for clarification.

A: Lessons to be learnt:

*

*to make it neat, like the logic diagram is neat

*to make neat placement of parts.

*to connect the dots.

*to correct your own mistakes.

*to learn that not all DIY kits are best way to do things.

*any of these parts will the same or better job.

*if the schematic doesn't follow global conventions of left to right (even in Asia) , worry about the experience of the designer.

That circuit  provides a DC current shunt to an AC rectified source and series load from a 24Vac furnace transformer.  All it has to drive is a logic driver to activate the furnace, the same way a reed relay might work.
My suggestion is use an opto-isolated triac for small signal currents.  There's many other solutions.
It is better to learn good layout methods to make look like the schematic on a PCB with focus on tight signal loops and heavy power and ground paths with decoupling caps.
It's much quicker to learn how to research how something works than to figure out your mistakes why it doesn't work ( if you designed and built it yourself) yet you won't forget when you experience the pain of the process of learning by trial and error.
Look for an old EE Design magazine 1 page articles that describes in detail how reader design suggestions work.  (available at archive.org)  Start from the 1960's and move up.
Look on the web at  Breadboards and note how many details you can spot that makes it satisfy or not, all the above lessons.
e.g. https://www.instructables.com/id/How-to-use-a-breadboard/
Bottom Line: Research your technology to find how it's done and try to understand why things are done a certain way,rather than guess.
As posted in comments below my answer I guess the application. Of your circuit wrong, but if you follow the link, you will see there I followed by own advice above and analyzed the application is either for PWM or Manchester BiPhase insensitive to polarity which when used on untwisted pairs will be greatly affected by noise interference. The half duplex nature and method of single wire encoding for each direction was explained .  Good luck.

A: Here's a bit of rerouting of the schematic. Should be able to place the parts on your board just like that. No jumper wires required. Remember that you are using through hole parts, not surface mount. The parts can act as jumpers themselves.

You can fill in the rest. It's not much.
You are using optocouplers for isolation. Ideally, you should have a big hole/slit with no copper under them. Make sure not to route or have any tracks under the optocouplers. If you are unsure, read up on isolation and creepage. You should not have nearby wires/tracks passing from one side of the optocoupler to the other. Keep the area near the optocouplers physically clean (no oil or dirt, or stuff that can attract moisture).


text:
Q: Uso de switch case para escolha de uma função Gostaria de usar o switch case para escolher qual função irá prosseguir com o programa.
O programa tem 3 funções: uma função soma, outra multiplica e a ultima é responsável por escolher qual função o usuário irá escolher. Segue o trecho do programa:
float escolhaFuncao (int escolha){

 switch (escolha) {
 case 1:
    float SomaDigitos (float soma_A, float soma_B);
    break;
 case 2:
     float Multiplicacao (float num1, float num2);
     break;
 default:
    printf("numero nao permitido");
    break;
 }

return (escolha);
}

Não sei se esse método é o mais eficiente, na verdade to aprendendo a trabalhar com funções, o programa está fluindo corretamente, fazendo a soma e a multiplicação, só gostaria de saber qual método eu usaria para o usuário escolher se quer usar a função soma ou a função multiplicação.
Caso necessite que eu poste o código completo, me avisem que edito a postagem, não postei logo pois minha duvida é somente nessa função.

A: esta correto essa forma de usar o switch case, porem não sei dizer se esse programa funcionaria, pois soma_A,soma_B, num1 e num2 não estão sendo recebidos de nenhnum lugar(se forem variaveis globais funciona, mas é bom evitar variavel global). é necessario salvar esse resultado para poder dar o return, seria algo do tipo
float escolhaFuncao (int escolha,float a, float b){
    float resultado;
    switch (escolha) {
    case 1:
        resultado = SomaDigitos (a, b);// não tem necessidade por o tipo da variavel ao chamar a função
        break;
    case 2:
        resultado = Multiplicacao (a, b);
        break;
    default:
        printf("numero nao permitido");
        break;
    return resultado;
    }

main(){
    ...
    resposta = escolhaFuncao(escolha, a, b)
    ...
    }


text:
Q: Clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions Here is the query
WITH PopVSVac (continent, location, date, population, new_vaccinations, RollingPeopleVaccinated) AS
(
    SELECT
        DEATHS.continent, DEATHS.location, DEATHS.date,
        DEATHS.population, VAC.new_vaccinations,
        SUM(CAST(VAC.new_vaccinations AS INT)) OVER (PARTITION BY DEATHS.location
                                                     ORDER BY DEATHS.location, DEATHS.date) AS RollingPeopleVaccinated
    FROM
        PortfolioProject1..CovidDeaths AS DEATHS
    JOIN
        PortfolioProject1..CovidVaccinations AS VAC ON DEATHS.location = VAC.location
                                                    AND DEATHS.date = VAC.date
    WHERE
        DEATHS.continent IS NOT NULL
    ORDER BY
        2, 3
)

If I use offset 0 rows after by "order by 2, 3" I will get an error

incorrect syntax near ')'-

I also tried adding "TOP 1000*" next o select but then the PopVSVAC will have an error 'PopVsVac has more column than specified column list.
Please help


text:
Q: Possible number combinations within a range of sums I have a range of sums between $50$ and $100$
I need to determine how many possible combinations of $5$ unique selections between $1$ and $69$ will add up to a number this range.
So, for instance, let's say one possible combination would be:
$1+17+20+25+30 = 93$
or
$1+2+3+4+45 = 55$
How would I determine the $5$ unique selections to generate a sum within an acceptable range of between $50$ and $100$?
I know I've learned some of this before, but I can't find the right nomenclature for my searches so I can relearn it.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
$$
\left\{\begin{array}{rll}
\ds{\left. 1\right)} &
\mbox{Choose any}\ \ds{5}\ \mbox{numbers}\ \in\ \mathbb{N}_{\ 1\ \leq\ ?\ \leq\ 69}\
\mbox{such that their sum is}\ \ds{s}: &
\ds{\sum_{n_{1} = 1}^{69}\ldots\sum_{n_{5} = 1}^{69}
\bracks{\sum_{i = 1}^{5}n_{i} = s}}
\\ &\ds{\bracks{\cdots}}\ \mbox{is the}\ Iverson\ Bracket:\ \ds{\bracks{P} = 1}\
\mbox{whenever}\ \ds{P}\ \mbox{is}\ true
\\
&\mbox{and}\ \ds{0}\ otherwise.&
\\[5mm]
\ds{\left. 2\right)} & \mbox{Sum the above expression over all the values of}
\\
&\ds{s = 50,51,\ldots,99,100.}&
\end{array}\right.
$$

Then, the answer is given by

\begin{align}
&\bbox[10px,#ffd]{\ds{\sum_{s = 50}^{100}\braces{%
\sum_{n_{1} = 1}^{69}\ldots\sum_{n_{5} = 1}^{69}
\bracks{\sum_{i = 1}^{5}n_{i} = s}}}} =
\sum_{s = 50}^{100}\braces{\sum_{n_{1} = 1}^{69}\ldots
\sum_{n_{5} = 1}^{69}\bracks{z^{s}}z^{\sum_{i = 1}^{5}n_{i}}}
\\[5mm] = &\
\sum_{s = 50}^{100}\bracks{z^{s}}\pars{\sum_{n = 1}^{69}z^{n}}^{5} =
\sum_{s = 50}^{100}\bracks{z^{s}}\pars{z\,{z^{69} - 1 \over z - 1}}^{5} =
\sum_{s = 45}^{95}\bracks{z^{s}}{\pars{1 - z^{69}}^{5} \over \pars{1 - z}^{5}}
\\[5mm] = &\
\sum_{s = 45}^{95}\bracks{z^{s}}{1 - 5z^{69} \over \pars{1 - z}^{5}} =
\sum_{s = 45}^{95}\bracks{z^{s}}\pars{1 - z}^{-5} -
5\sum_{s = 45}^{95}\bracks{z^{s}}z^{69}\pars{1 - z}^{-5}
\\[5mm] = &\
\sum_{s = 45}^{95}\bracks{z^{s}}\sum_{k = 0}^{\infty}{-5 \choose k}\pars{-z}^{k} -
5\sum_{s = 45}^{95}\bracks{z^{s}}z^{69}
\sum_{k = 0}^{\infty}{-5 \choose k}\pars{-z}^{k}
\\[5mm] = &\
\sum_{s = 45}^{95}{-5 \choose s}\pars{-1}^{s} -
5\sum_{s = 45}^{95}\bracks{s \geq 69}{-5 \choose s - 69}\pars{-1}^{s - 69} =
\sum_{s = 45}^{95}{s + 4 \choose 4} -
5\sum_{s = 69}^{95}{s - 65 \choose 4}
\\[5mm] & =
\sum_{s = 0}^{50}{s + 49 \choose 4} - 5\sum_{s = 0}^{26}{s + 4 \choose 4}
\end{align}

The binomial arguments are polynomials, in $\ds{s}$, of grade four.

Then,
$$
\bbx{\bbox[10px,#ffd]{\ds{\sum_{s = 50}^{100}\braces{%
\sum_{n_{1} = 1}^{69}\ldots\sum_{n_{5} = 1}^{69}
\bracks{\sum_{i = 1}^{5}n_{i} = s}}}} = 72\ 531\ 081}
$$

A: By unique selection, I assume you mean the 5 numbers selected are distinct.
Furthermore, I will assume the order of selection doesn't matter. i.e. selections like $1+17+20+25+30 = 93$ and $30+17+20+25+1 = 93$ will be treated as same selection.
By brute force (i.e the most time consuming version of looping through everything), the number of combinations is $467711$.
Following is another way to derive the number mathematically (through we still need an CAS to complete some of the steps).

For any formal power series $\sum_{(i,j) \in \mathbb{N}^2} f_{ij} t^i x^j$
in $t$ and $x$. We will use the notation $[t^i x^j] (\cdots)$ to refer to the coefficient $f_{ij}$ in front of $t^i x^j$.
Let $A$ be any finite subset of positive integers. For any $m, n\in \mathbb{Z}_{+}$, the number of subsets of $A$ with $m$ elements whose element sum to $n$ is given by the formula
$$\mathcal{N} \stackrel{def}{=} \# \left\{ B \subset A : \# B = m \land \sum_{k\in B} k = n \right\}
= [t^m x^n ] \prod_{k\in A}( 1 + t x^k )$$
For the problem at hand, $m = 5$ and $A = \{ 1, \ldots, 69 \}$. We have
$$\mathcal{N} = \sum_{n=50}^{100} [t^5 x^n] \prod_{k=1}^{69} (1 + tx^k)
= [t^5 x^{100} ] \sum_{\ell=0}^{50} x^\ell \prod_{k=1}^{69} (1 + tx^k)
= [t^5 x^{100} ] \left(\frac{1-x^{51}}{1-x}\right)\prod_{k=1}^{69} (1 + tx^k)
$$
Expand the product into a polynomial in $t$.
$$\prod_{k=1}^{69}(1+tx^k) = 1 + \sum_{\ell=1}^{69} e_\ell(x) t^\ell
\quad\text{ where }\quad
e_\ell(x) = \sum_{1\le k_1 \le \ldots \le k_\ell \le 69} x^{k_1 + \cdots + k_\ell}$$
The coefficient $e_\ell(x)$ is the $\ell^{th}$ elementary symmetric polynomial associated with the set $A' = \{ x^1, \ldots, x^{69} \}$. In terms of $e_\ell(x)$, we have
$$\mathcal{N} = [x^{100}]\left(\frac{1-x^{51}}{1-x}\right)e_5(x)$$
Let $p_\ell(x)$ be the power sum symmetric polynomial associated with $A'$.
$$p_\ell(x) = \sum_{z \in A'} z^\ell = \sum_{k=1}^{69} x^{k\ell} = q_\ell(x)(1 - x^{69\ell}) \quad\text{ where }\quad q_\ell(x) = \frac{x^\ell}{1-x^\ell}$$
They are related to $e_\ell(x)$ through the
Newton–Girard formulae. In particular, we have
$$e_5(x) = \frac{1}{5!}
\left|\begin{matrix}
p_1(x) & 1 & 0 & 0 & 0\\
p_2(x) & p_1(x) & 2 & 0 & 0\\
p_3(x) & p_2(x) & p_1(x) & 3 & 0\\
p_4(x) & p_3(x) & p_2(x) & p_1(x) & 4\\
p_5(x) & p_4(x) & p_3(x) & p_2(x) & p_1(x)
\end{matrix}\right|$$
Substitute $p_\ell(x) = q_\ell(x)(1-x^{69\ell})$ into this and throw away terms which don't contribute to $[x^{100}]$, we obtain ($q_\ell(x)$ abbreviated as $q_\ell$):
$$e_5(x) =
\frac{1}{5!}
\underbrace{\left|\begin{matrix}
q_1 & 1 & 0 & 0 & 0\\
q_2 & q_1 & 2 & 0 & 0\\
q_3 & q_2 & q_1 & 3 & 0\\
q_4 & q_3 & q_2 & q_1 & 4\\
q_5 & q_4 & q_3 & q_2 & q_1
\end{matrix}\right|}_{ \Delta_5}
- \frac{x^{69}q_1}{4!}
\underbrace{\left|\begin{matrix}
q_1 & 1 & 0 & 0\\
q_2 & q_1 & 2 & 0\\
q_3 & q_2 & q_1 & 3\\
q_4 & q_3 & q_2 & q_1\\
\end{matrix}\right|}_{\Delta_4}
+ o(x^{100})\\
{\Large\Downarrow}\\
\mathcal{N}
= [x^{100}]\left( \frac{1-x^{51}}{5!(1-x)} \Delta_5 - \frac{x^{70}}{4!(1-x)^2}\Delta_4 \right)$$
With help on a CAS, this simplifies to
$$\mathcal{N} = [x^{100}] \frac{P(x)}{Q(x)}\quad\text{ where }\quad
\begin{cases}
P(x) &= x^{15}(1 - x^{51} - x^{65} - x^{66} - x^{67} - x^{68} - x^{69})\\
Q(x) &= (1-x)^2(1-x^2)(1-x^3)(1-x^4)(1-x^5)\\
&=  1- 2x + x^3 + x^5 - 2x^8 + x^{11} + x^{13} - 2x^{15} + x^{16}
\end{cases}
$$
Expand $\frac{1}{Q(x)}$ as a power series in $x$, $\displaystyle\;\frac{1}{Q(x)} = s_0 + s_1 x + s_2 x^2 + \cdots$. The coefficients $s_k$ can be computed using following recurrence relation:
$$
\begin{cases}
n < 0, & s_n = 0,\\
n = 0, & s_n = 1,\\
n > 0, & s_n - 2s_{n-1} + s_{n-3} + s_{n-5} - 2s_{n-8} + s_{n-11} + s_{n-13} - 2s_{n-15} + s_{n-16} = 0
\end{cases}
$$
The end result is
$$\begin{align}\frac{1}{Q(x)}
 = &\;\; 1+2x+4x^2 +7x^3 + \cdots \\
   & + 509x^{16}+628x^{17}+769x^{18}+933x^{19}+1125x^{20} + \cdots\\
   & + 8837x^{34} + \cdots\\
   & + 480512x^{85} + \cdots
\end{align}$$
In terms of $s_k$, we find
$$\begin{align}
\mathcal{N} &= [x^{100}]  \frac{x^{15}(1 - x^{51} - x^{65} - x^{66} - x^{67} - x^{68} - x^{69})}{Q(x)}\\
&= \left([x^{85}] - [x^{34}] - [x^{20}] - [x^{19}] - [x^{18}] - [x^{17}] - [x^{16}]\right)\frac{1}{Q(x)}\\
&= s_{85} - s_{34} - s_{20} - s_{19} - s_{18} - s_{17} - s_{16}\\
&= 480512 - 8837 - 1125 - 933 - 769 - 628 - 509\\
&= 467711
\end{align}
$$
Reproducing what we have obtained by brute force.


text:
Q: Solving system of two fractional differential equations using Matlab I would appreciate help with this task:
Solve the following system of fractional differential equations:
$$
\begin{cases}A_{1} \cdot D^{2}_{t}y(t)+A_{2} \cdot D^{1}_{t}y(t)+A_{3} \cdot y(t) = 1 \\ B_{1} \cdot D^{2}_{t}y(t)+B_{2} \cdot D^{1}_{t}y(t)+B_{3} \cdot y(t) + B_{4} \cdot D^{v}_{t}y(t) = B_{5} + B_{6} \cdot \frac{t^{-v}}{\Gamma(-v+1)}
 \end{cases}
$$
where
$
A_{1},A_{2},A_{3},B_{1},B_{2},B_{3},B_{4},B_{5},B_{6}
$
are known real numbers
and
$
v
$
is known real positive number
$
(v>0)
$
(actually, only the second equation is fractional)
We also know that $y(0)=0$
I want to write a program in Matlab which will find the $y(t)$ , given $A_{1},A_{2},A_{3},B_{1},B_{2},B_{3},B_{4},B_{5},B_{6}$ and $v$
It is okay to use external scripts.
Update: Thank you for your comments. I have edited the formatting according to them.
Yes, a numerical solution would be good enough.
Yes, I have found scripts for Matlab to solve fractional differential equations:
https://www.mathworks.com/matlabcentral/fileexchange/66603-solving-multiterm-fractional-differential-equations-fde
https://www.mathworks.com/matlabcentral/fileexchange/32918-predictor-corrector-pece-method-for-fractional-differential-equations
However, they need the set of initial conditions, which are not given in this task.
$D^{\alpha}_{x}$ is a fractional differintegral. For $\alpha > 0$ it is a fractional derivative: http://mathworld.wolfram.com/FractionalDerivative.html
Update 2: I've replaced $-v$ with $v$ and corrected $\gamma$ to $\Gamma$
Update 3: Now the task is easier. We know that $y(0)=0$


text:
Q: Is there any way to get edit branch protection rules in a mirrored repo in local? I'm trying to migrate a repo which has branch protection rules from Github Enterprise Server to Github Enterprise Cloud.
After cloning and pushing the mirror repo using git clone --mirror and git push --mirror commands.
After this clone and push, I'm trying to rename branches in my local (from master to main).
I already have branch protection rules pushed as part of push --mirror. and If I rename the branch locally from master to main, it's throwing error because the master branch itself gets deleted entirely.
I'm looking if there is a way to edit the the protection rules locally in the mirror repo even before pushing it to Github Cloud.
I did look at the contents of the mirror repo. But can't seem to find where the branch protection rules exists in mirror repo if any.
How do I resolve this?

A: I would suggest :

*

*go to the github GUI of your mirror repo, and remove the protection rule on master,

*push your renamed branch (either through a full git push --mirror, or git push origin <local main>:main; git push origin --delete master)

*on the github GUI set a protection rule on main

[edit]
with additional information in your comment, you indicate that you need to do this several times for a whole list of repositories, and that you are using the gh cli tool.

*

*you can use github API for protected branches to script a way to remove the rule on master and add it on main

*you may use gh api to do so
Reading the doc for the API, I don't see a way to update the rule field -- the field you can set in Github's GUI.
You could write a script that:

*

*gets the current protection settings for master

*creates a new rule with similar settings for main

*deletes the rule for master


text:
Q: How to make setStudentName method? I'm supposed to kinda create a student account in java (I'm very new to Java so please don't flame me). Everything is working fine except for when I need to set a Name/degree program (so string I believe). By the way, I'm using BlueJ.
I have tried using the void instead of string but I get the same problem. I also did this before the method starts:
private String studentName;
public String setStudentName (String setStudentName) {
    return studentName = setStudentName;
}

I just want to set the Student Name so I can work with it, but if I try running it, I get the following error: "Error: cannot find symbol - variable Robin" Robin is the Name I tried to enter.

A: Your class and methods should look something like this:
public final class Student {
    private String studentName;

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
   }
}

Then, you can use your class like so:
public static void main(String[] args) {
    Student student = new Student();
    student.setStudentName("Robin");
    System.out.println(student.getStudentName());
}

Take a look into the official Java Tutorials on how to write classes.

A: Just want to sum up all responses above, you have to write this.studentName = studentName instead of studentName = studentName, because in your context you have both method class field and method parameter studentName, so if you write inside your method studentName you work with method parameter. this is link to 'class instance itself' and this.studentNamecalls exactly class field.
One more solution is to rename studentName method param to e.g. newStudentName so it wouldn't be in conflict with class field and afterwords studentName = newStudentName will work as you expects.


text:
Q: Installing Magento - Error in File I'm completely new to Magento and I'm having trouble installing it on my local server using WAMP. Here is the error I'm getting:
Error in file: "C:\wamp\www\magentoempty\app\code\core\Mage\ImportExport\sql\importexport_setup\install-1.6.0.0.php" - SQLSTATE[HY000]: General error: 7 Error on rename of '.\magentoempty\#sql-598_ccd.frm' to '.\magentoempty\catalog_product_link_attribute_int.frm' (Errcode: 13 - Permission denied)

Trace:
#0 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(644): Mage::exception('Mage_Core', 'Error in file: ...')
#1 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(421): Mage_Core_Model_Resource_Setup->_modifyResourceDb('install', '', '1.6.0.2')
#2 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(327): Mage_Core_Model_Resource_Setup->_installResourceDb('1.6.0.2')
#3 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(235): Mage_Core_Model_Resource_Setup->applyUpdates()
#4 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\App.php(428): Mage_Core_Model_Resource_Setup::applyAllUpdates()
#5 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\App.php(354): Mage_Core_Model_App->_initModules()
#6 C:\wamp\www\magentoempty\app\Mage.php(684): Mage_Core_Model_App->run(Array)
#7 C:\wamp\www\magentoempty\index.php(83): Mage::run('', 'store')
#8 {main}

I got this error after I clicked Continue on the Configuration step. I checked the database and 326 empty tables were added.
Then when I refresh the page, I get a new error:
Error in file: "C:\wamp\www\magentoempty\app\code\core\Mage\ImportExport\sql\importexport_setup\install-1.6.0.0.php" - SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'importexport_importdata' already exists, query was: CREATE TABLE `importexport_importdata` (
  `id` int UNSIGNED NOT NULL auto_increment COMMENT 'Id' ,
  `entity` varchar(50) NOT NULL COMMENT 'Entity' ,
  `behavior` varchar(10) NOT NULL default 'append' COMMENT 'Behavior' ,
  `data` text NULL default '' COMMENT 'Data' ,
  PRIMARY KEY (`id`)
) COMMENT='Import Data Table' ENGINE=INNODB charset=utf8 COLLATE=utf8_general_ci

Trace:
#0 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(644): Mage::exception('Mage_Core', 'Error in file: ...')
#1 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(421): Mage_Core_Model_Resource_Setup->_modifyResourceDb('install', '', '1.6.0.2')
#2 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(327): Mage_Core_Model_Resource_Setup->_installResourceDb('1.6.0.2')
#3 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\Resource\Setup.php(235): Mage_Core_Model_Resource_Setup->applyUpdates()
#4 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\App.php(428): Mage_Core_Model_Resource_Setup::applyAllUpdates()
#5 C:\wamp\www\magentoempty\app\code\core\Mage\Core\Model\App.php(354): Mage_Core_Model_App->_initModules()
#6 C:\wamp\www\magentoempty\app\Mage.php(684): Mage_Core_Model_App->run(Array)
#7 C:\wamp\www\magentoempty\index.php(83): Mage::run('', 'store')
#8 {main}

Help!


text:
Q: Multiple entity framework 6 contexts in oracle throw ORA-00955 I am using Entity Framework 6.1.3 connecting to an oracle database.
I am trying to use multiple contexts with the same schemaName for oracle. But when I create the contexts it appears they share the __MigrationHistory table and when the second context attempts to create itself it throws "ORA-00955: name is already used by an existing object".  To be clear the two contexts I attempted to split by domain design and do not share any entities between the two.
This is the code I'm attempting to run, and it works fine when I run it against SQL Server.  But Oracle throws the ORA-00955 error.
try
{
    using (var hContext = new HContextORCL(connectionString, "SchemaName"))
    using (var aContext = new AContextORCL(connectionString, "SchemaName"))
    {
        hContext.Database.Initialize(true);
        aContext.Database.Initialize(true);
    }
}

I've tried using CreateIfNotExists() instead of the Initialize but receive the same error.  I have tried setting both contexts Database.SetInitializer<context>(null); because I don't need the migrations at this point.  But that doesn't seem to work either.
Ideally I would like to keep the __MigrationHistory table and have both my contexts initialized in Oracle.  But that's not necessary.  I can sense myself going off the rails trying to figure out all these work-arounds which when I look at them seem overly complicated for something that works in SQL Server.
I am at a loss how to intialize two contexts with the same schema name in an oracle database.

A: Alright, for better or worse this is the work around I'm going with.  My issue appears to be the MigrationHistory table is shared between the two contexts.
Entity Framework 6 allows you to manipulate the migration table using the System.Data.Entity.Migrations.History namespace (Migrations.History Namespace).
So I open the migrations table, copy all the history rows out, delete the migration table, perform my second context initialization and copy the history rows back into the migration database (created during the second context initialization).
try
{
    var dbConnection = new OracleConnection(connectionString);
    using (var migrationContext = new Migrations.History.HistoryContext(dbConnection, "SchemaName"))
    using (var hContext = new HContextORCL(connectionString, "SchemaName"))
    using (var aContext = new AContextORCL(connectionString, "SchemaName"))
    {
        hContext.Database.Initialize(true);

        List<HistoryRow> currentHistory = migrationContext.History.ToList();
        migrationContext.Database.Delete();

        aContext.Database.Initialize(true);

        currentHistory.ForEach(rowItem => migrationContext.History.Add(rowItem));
        migrationContext.SaveChanges();
    }
}


text:
Q: Log4Net LevelEvaluator Ignored when bufferSize greater than 1 for SmtpAppender I have configured log4net with a RollingLogFileAppender and a SmtpAppender, with the intention of logging the DEBUG level to the RollingLogFileAppender and FATAL only to the SmtpAppender:
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
  <to value="test@test.com" />
  <from value="test@test.com" />
  <subject value="Fatal Error" />
  <smtpHost value="smtp.test.com" />
  <SMTPPort value="366"/>
  <Username value="test@test.com"/>
  <Password value="password"/>
  <bufferSize value="1" />
  <lossy value="true" />
  <evaluator type="log4net.Core.LevelEvaluator">
    <threshold value="FATAL"/>
  </evaluator>
  <layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline"                             />
  </layout>
</appender>

<root>
  <level value="DEBUG" />
  <appender-ref ref="RollingLogFileAppender" />
  <appender-ref ref="SmtpAppender" />
</root>

This works perfectly until I increase the bufferSize. When I do this, all levels are sent via email and the log4net.Core.LevelEvaluator seems to be ignored. I have also tried using LevelRangeFilter and LevelMatchFilter but with these configured I seem to get no emails at all.

A: The evaluator is not ignored, but it does not do what you expect: Your settings instruct the appender to put all log messages on a buffer and send an email only when a message with level FATAL is logged. If the buffer is full then the oldest messages are discarded (that is the lossy setting; without it you would also get an email as soon as the buffer is full).
If you want to filter the messages then you need to use a filter. For instance like this:
<filter type="log4net.Filter.LevelMatchFilter">
   <acceptOnMatch value="true" />
   <levelToMatch  value="FATAL" />
</filter>
<filter type="log4net.Filter.DenyAllFilter" />

I am not sure though if I would consider my mail appender like this since I would want to get notified immediately if my application has a problem that it needs to log it with level FATAL.


text:
Q: Boolean flows sync I have few StateFlow fields in the ViewModel class. It's add/edit form screen where each StateFlow is validation property for each editable field on the screen.
I would like to write some class FormValidation with StateFlow property for validation state of whole form. Value of this field based on the values of validation state of all fields and emit true when all field is valid and false when any field is invalid.
Something like this:
class FormValidation(initValue: Boolean, vararg fieldIsValid: StateFlow<Boolean>) {

    private val _isValid = MutableStateFlow(initValue)
    val isValid: StateFlow<Boolean> = _isValid

    init {
        // todo: how to combine, subscribe and sync values of all fieldIsValid flows?
    }

}

I know how to do it with LiveData<Boolean> and MediatorLiveData but i can't understand how to make it with flows.

Solution based on the answer of @tenfour04
class BooleanFlowMediator(scope: CoroutineScope, initValue: Boolean, vararg flows: Flow<Boolean>) {
    val sync: StateFlow<Boolean> = combine(*flows) { values ->
        values.all { it }
    }.stateIn(scope, SharingStarted.Eagerly, initValue)
}

Demo code with StateFlow and ViewModel
class SyncViewModel : ViewModel() {

    companion object {
        private const val DEFAULT_VALUE: Boolean = false
    }

    private val values: List<List<Boolean>> = listOf(
        listOf(false, false, false),
        listOf(true, false, false),
        listOf(false, true, true),
        listOf(true, true, true)
    )

    private var index: Int = 0

    private val _flow1 = MutableStateFlow(DEFAULT_VALUE)
    val flow1: StateFlow<Boolean> = _flow1

    private val _flow2 = MutableStateFlow(DEFAULT_VALUE)
    val flow2: StateFlow<Boolean> = _flow2

    private val _flow3 = MutableStateFlow(DEFAULT_VALUE)
    val flow3: StateFlow<Boolean> = _flow3

    val mediator = BooleanFlowMediator(viewModelScope, DEFAULT_VALUE,
        flow1, flow2, flow3)

    fun generateValues() {
        val idx = (index + 1).mod(values.size).also { index = it }
        val row = values[idx]
        _flow1.value = row[0]
        _flow2.value = row[1]
        _flow3.value = row[2]
    }

}

A: I think you can do this using combine. It returns a new Flow that emits each time any of the source Flows emits, using the latest values of each in a lambda to determine its emitted value.
There are also overloads of combine for up to five input Flows of different types, and one for an arbitrary number of Flows of the same type, which is what we want here.
Since Flow operators return basic cold Flows, but if you want to have a StateFlow so you can determine the initial value, you need to use stateIn to convert it back to a StateFlow with an initial value. And for that you'll need a CoroutineScope for it to run the flow in. I'll leave it to you to determine the best scope to use. Maybe it should be passed in from an owning class (like passing viewModelScope to it if the class instance is "owned" by the ViewModel). If you're not using a passed in scope, you will have to manually cancel the scope when this class instance is done with, or else the flow will leak.
I didn't test this code, but I think this should do it.
class FormValidation(initValue: Boolean, vararg fieldIsValid: StateFlow<Boolean>) {

    private val scope = MainScope()

    val isValid: StateFlow<Boolean> =
        combine(*fieldIsValid) { values -> values.all { it } }
            .stateIn(scope, SharingStarted.Eagerly, initValue)

}

However, if you don't need to synchronously inspect the most recent value of the Flow (StateFlow.value), then you don't need a StateFlow at all, and you can just expose a cold Flow. The instant the cold Flow is collected, it will start collecting its source StateFlows, so it will immediately emit its first value based on the current values of all the sources.
class FormValidation(initValue: Boolean, vararg fieldIsValid: StateFlow<Boolean>) {

    val isValid: Flow<Boolean> = when {
        fieldIsValid.isEmpty() -> flowOf(initValue) // ensure at least one value emitted
        else -> combine(*fieldIsValid) { values -> values.all { it } }
            .distinctUntilChanged()
    }

}


text:
Q: Protecting resources such as images in a servlet Let's say that you have an image I that you only want users who have logged into your website to be able to see. What is the best way to protect I from non-logged in users. One possible way is to have a page where you pass the image name via get or post parameters, and it would return the image by reading the image from disk and writing back in the response based on if the user was logged in the session. Is/Are there better ways to achieve security of resources more efficiently?

A: use your session. when the user is logged in, you load the image to your page.

A: There are couple easy ways you could to this with servlet filters or just plain servlet that servers your resource.
Personally I would check if the principal have been set is so then you know the user is authenitcated
    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        return null;
    }

If there is no principal you know the user is not authenticated, you could return 403 status, blank image or whatever you like.

A: If you want to protect the urls of the image files, set some rules about their access in your code. I think a better alternative is using some security framework. There are some security platforms like Spring Security provide very comprehensive access rules based on user authentication status, url-role combination, and acl, etc..


text:
Q: WCF Webservice does not fill komplex Type send by Soap Lite I try to send a complex Datatype from Perl to .NET WCF.
Simple Types work fine.
WCF Interface:
[ServiceContract]

public interface IWebservice
{
    [WebInvoke(RequestFormat = WebMessageFormat.Xml,
        ResponseFormat = WebMessageFormat.Xml,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
    [OperationContract]
    void PutColledtedData(ServerInfoCollection Serverdata);
}

Class For DataType
[DataContract (Name="ServerInfoCollection")]
public class ServerInfoCollection
{

    [DataMember]
    public string OperatingSystem { get; set; }
    [DataMember]
    public string OS_Version { get; set; }
    [DataMember]
    public string OS_Architecture { get; set; }
    [DataMember]
    public string OS_ServicePack { get; set; }

    private long pysicalMem = 0;
    [DataMember]
    public long PysicalMemory
    {
        get { return pysicalMem; }
        set { pysicalMem = value; }
    }
    [DataMember]
    public List<FileSystem> Filesystems { get; set; }
    [DataMember]
    public string Manufacturer { get; set; }
    [DataMember]
    public List<Interface> Interfaces { get; set; }
    [DataMember]
    public string Model { get; set; }
    public ServerInfoCollection()
    {
        Filesystems = new List<FileSystem>();
        Interfaces = new List<Interface>();
    }
    [DataMember]
    public string Hostname { get; set; }
    [DataMember]
    public string Alias { get; set; }
    [DataMember]
    public string WindowsDomain { get; set; }
    [DataMember]
    public string WindowsDomainRole { get; set; }
    [DataMember]
    public DateTime InstallDate { get; set; }
    [DataMember]
    public int LogicalProcessors { get; set; }
    [DataMember]
    public int PhysicalProcessors { get; set; }
    [DataMember]
    public IPAddress MonitoringIP { get; set; }
}

Soap Envenlove Send to Server
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
<PutColledtedData xmlns="http://tempuri.org/">
  <Serverdata>
    <OperatingSystem />

    <OS_Version>13.1 (Bottle)</OS_Version>

    <OS_Architecture>x86_64</OS_Architecture>

    <OS_ServicePack>13.1</OS_ServicePack>

    <PysicalMemory>6272438272</PysicalMemory>

    <Manufacturer>VMWare</Manufacturer>

    <Model />

    <Hostname>myServerName</Hostname>

    <Alias>myServerName</Alias>

    <WindowsDomain />

    <WindowsDomainRole />

    <InstallDate>Thu Nov 27 12:21:33 2014</InstallDate>

    <LogicalProcessors>4</LogicalProcessors>

    <PhysicalProcessors>4</PhysicalProcessors>
  </Serverdata>
</PutColledtedData>
</soap:Body>
</soap:Envelope>

Perl Code:
use strict;
use SOAP::Lite trace =>  'debug', maptype => {};
use Sys::Hostname;

my $serverinfos={
OperatingSystem=>'',
OS_Version=>'',
OS_Architecture=>'',
OS_ServicePack=>'',
PysicalMemory=>'',
Manufacturer=>'',
Model=>'',
Hostname=>'',
Alias=>'',
WindowsDomain=>'',
WindowsDomainRole=>'',
InstallDate=>'',
LogicalProcessors=>'',
PhysicalProcessors=>'',
Interfaces=>'',
Filesystems=>'',

};
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;
$SOAP::Constants::DO_NOT_USE_CHARSET = 1;

my $uri="http://tempuri.org/";
my $url ='https://myserver.her.de:1986/Webservice/Webservice.svc';
my $xmlns = 'http://schemas.datacontract.org/2004/07/com.aii.observer';

my $soap = SOAP::Lite
  -> uri($uri)
  -> on_action(sub { sprintf '%sIObserverWebservice/%s', @_ })
  -> proxy($url, ssl_opts => [ SSL_verify_mode => 0 ] )
  ->autotype(0)
  ->readable('false');

 # some stuff to initialize the serverinfos Hash truncated

  my $param=SOAP::Data->name( "Serverdata"=>\SOAP::Data->value(
SOAP::Data->name(OperatingSystem=>''),
SOAP::Data->name(OS_Version=>$serverinfos->{OS_Version}),
SOAP::Data->name(OS_Architecture=>$serverinfos->{OS_Architecture}),
SOAP::Data->name(OS_ServicePack=>$serverinfos->{OS_ServicePack}),
SOAP::Data->name(PysicalMemory=>$serverinfos->{PysicalMemory}),
SOAP::Data->name(Manufacturer=>$serverinfos->{Manufacturer}),
SOAP::Data->name(Model=>''),
SOAP::Data->name(Hostname=>$serverinfos->{Hostname}),
SOAP::Data->name("Alias")->value($serverinfos->{Alias}),
SOAP::Data->name(WindowsDomain=>''),
SOAP::Data->name(WindowsDomainRole=>''),
SOAP::Data->name(InstallDate=>$serverinfos->{InstallDate}),
SOAP::Data->name(LogicalProcessors=>$serverinfos->{LogicalProcessors}),
SOAP::Data->name(PhysicalProcessors=>$serverinfos->{PhysicalProcessors})

)
);
my $res=$soap->call('PutColledtedData',$param);

in Webservice I get the Obekct for ServerInfoCollection but all Properties are null.
Where is my missunderstanding??
EDIT:
Added Perl Code,
Added Webinvoke to ServiceInterface

A: Your perl code serverinfos values are empty. If filled, the server answer is ok.