text:
Q: set of layouts for activity with multiple buttons and views I want to create an activity composed by many buttons and edittexts.
I have a first row with 5 buttons (equispaced and of the same dimension),
a second row with two buttons (1/4 and 3/4 are the relative dimensions)
and a third row (the largest one) which is divided into two columns:
on the left I just add programmatically some editexts, on the right
I have three big buttons. Which set of layouts should I use to create such an activity?

A: This looks like a linearlayout, since with these you can get your first two rows fairly easily.
Something like this.
<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="wrap_content"
            android:layout_weight=".2"
            android:layout_height="wrap_content"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_weight=".2"
            android:layout_height="wrap_content"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_weight=".2"
            android:layout_height="wrap_content"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_weight=".2"
            android:layout_height="wrap_content"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_weight=".2"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
        android:layout_width="wrap_content"
        android:layout_weight=".25"
        android:layout_height="wrap_content"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_weight=".75"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_height="wrap_content">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_height="wrap_content">
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
      </LinearLayout>

</LinearLayout>


text:
Q: ini_set disabled functions I'm working in a hosting company and I'm pretty new. One of the company's policies is disabling ini_set php function for security reasons. There are lots of clients that have shared hosting asking us to enable this function. My task is to find out how can we enable this function without putting others at risk. We use Redhat Enterprise 5 and Cpanel.
I would be grateful if anyone has an answer to this.
Thanks a lot.

A: I've found that it's generally unnecessary.  As cPanel specific advice, fire up easyapache and recompile it with suPHP support.  From there, your customer can create php.ini files inside their public_html directories that will be applied as a local PHP config.  It's not quite as convenient as ini_set(), but it will suffice.

A: Best solution - use separate instance of PHP for each user what need ini_set() with different UIDs.
Yes, it needs more memory.

A: You can (currently) set different php.ini configuration for different PHP versions installed on the same machine (VPS):
PHP5.6 with ini_set() allowed on its php.ini, meanwhile PHP7.0 with ini_set() NOT allowed on its php.ini.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's a good way to bind from a shared utility window and the frontmost document window? I have an application which allows for multiple NSDocuments to be open.  In this application is a single utility window that contains some functionality that I want to apply to the frontmost document.
I am trying to use bindings here, so the trick is how to cleanly bind the user interface of the utility window to the frontmost document.  The goal is that then switching the frontmost document window will update the view in the utility window; controls that are bound to properties of the frontmost document's model would be updated appropriately when state changes in the document's model, etc.
For sending actions from such a window, it's easy to just use first responder; the document object can intercept actions via the responder chain.  But I want more than this, and of course you can't bind to the first responder.
A few ideas that I have:

*

*put an object controller in my nib for the shared window.  When a document window changes frontmost status, change the content of that binding. A disadvantage of this is that if I were to have another kind of utility window, I'd have to remember to hook up the bindings from the document window to that utility window too!

*Make an accessor in the application delegate that gets the frontmost document window by traversing the window list.  My utility window would just bind through the application delegate's method.  A disadvantage here is that it's not KVO compliant

*Have a getter and setter in the application delegate to determine (and perhaps set to be KVO-compliant? would that make sense?) the frontmost document. Perhaps use window notifications set an ivar to the appropriate value when a window loses main status. Update: I'm using this for now, and it actually seems pretty clean.  I set the value from the windowDidBecomeMain notification of my doc window and clear it (if it's the current value) in windowWillClose.  Unless there is any major objection, this is probably the approach I'll use.

*One idea was to bind to mainWindow.windowController.document ... this comes close, except that when my shared window becomes main, then this binding goes away. So really I need to find the frontmost document window's controller (and of the right class).

None of these seem quite right. Is there a better way to do this that I'm missing?

A: I've always bound through Shared Application, mainWindow.document, which works fine.  if you have windows w/o documents, you may want to add a mainYourKindOfWindow key that is implemented by watching mainWindow and updating the value based on some filter criteria.

A: Leopard's TextEdit does this for its inspector.  Check it out in file:///Developer/Examples/AppKit/TextEdit.

A:

*

*put an object controller in my nib for the shared window. When a document window changes frontmost status, change the content of that binding.

That makes the most sense to me. You'd change the content to the document instance ([NSDocumentController currentDocument]).

A disadvantage of this is that if I were to have another kind of utility window, I'd have to remember to hook up the bindings from the document window to that utility window too!

Huh? I don't understand this.

A:
Leopard's TextEdit does this for its inspector. Check it out in >file:///Developer/Examples/AppKit/TextEdit.

In TextEdit, inspector values are bound via an intermediate object controller. The controller content object is bound to the shared application mainWindow.
You may bind the content to mainWindow.firstResponder and uncheck "Raises for not applicable keys".

A: Use the key window, not the main window. KVO might not be supported for NSApplication's keyWindow property, but you can still use NSNotifications if it doesn't work. The reason for this is that NSDocumentController's currentDocument uses the keyWindow, so it better represents the built in functionality. Also, panels can be set to avoid becoming key window.


text:
Q: What does it mean that "a declaration shadows a parameter"? I am trying to make a function that returns double the integer number that I will pass to it.  I am getting the following error message with my code:

declaration of 'int x' shadows a parameter int x; "

Here is my code:
#include <iostream>
int doublenumber();
using namespace std;
int doublenumber(int x)// <-- this is the function which returns double the value .
{
    int x;
    return 2 * x;
    cout << endl;
}
int main()
{
    int a;
    cout << "Enter the number that you want to double it : " << endl;
    cin >> a;
    doublenumber(a);

    return 0;
}

A: You have x as a parameter and then try to declare it also as a local variable, which is what the complaint about "shadowing" refers to.

A: #include <iostream>
using namespace std;
int doublenumber(int x)
{
return 2*x;
}
int main()
{
int a;
cout << "Enter the number that you want to double it : " << endl;
cin>>a;
int d = doublenumber(a);

cout << "Double : " << d << endl;

return 0;
}

There are some problem with your code. Your declaration and definition of function dies not match. So remove declaration as no necessity of it.
You are declaring local x variable inside function which will shadow your function arguments.

A: I did it because your advice was so helpful, and this is the final result :
#include <iostream>
using namespace std;

int doublenumber(int x)
{
    return 2*x;
}

int main()
{
    int a;
    cout << "Enter the number that you want to double it : " << endl;
    cin>>a;
    int n= doublenumber(a);
    cout << "the double value is : " << n << endl;
    return 0;
}


text:
Q: Передать контекст в функцию jQuery Я реально искал и на СО, и в Интернете, хоть заголовок вопроса везде один и тот же, но такой похожей ситуации, как у меня, я не встретил.
Хотя странно, ведь вопрос насущный должен быть для всех jQuery-вцев.
Есть такая структура:
var articles = $('article');

articles.click(function() {
    console.log(this);             // Выведется тот артикл, который кликнут
    articles.each(function() {
        console.log(this);         // Нужно вывести этот же артикл, который был кликнут
    });
});

Вместо вывода в консоль будет логика, само собой.
Но нужно понять, как ссылаться внутри функции в методе .each на тот артикл, который был кликнут, и при этом обойтись без переменных... Потому что тот this, который предоставляет метод .each, мне особо-то не нужен.
Такая ситуация у меня возникает не только тут, полезно было бы узнать, можно ли вообще передавать в эти функции свои аргументы.


text:
Q: How to disable the correct button in a for loop I have a 1-8 rows (with their own button) and I want to correctly disable each button when the user. Right now, it is just disabling the last button when any button is clicked. Any idea what I am doing wrong? How can I correctly disable the button when it is a for loop?
class ResolveSourceContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
        modalOpen: false,
        updated: [],
        key: 0,
    };
}

disableRow = (key) => {
    let {updated} = this.state
    updated.push(key)
    this.setState({updated})
}

render() {

    const { size, modalOpen} = this.state;
    let {key} = this.state
    const { element} = this.props;

    return (

            <Modal size={size} open={modalOpen} onClose={this.closeModal}>
                <Modal.Content style={{textAlign: 'center'}}>

                        <Modal.Header>
                            {`${element.lid}`}
                        </Modal.Header>

Type

Update

                        {Object.keys(element.auditdiff).map(function(dataType){
                            if (dataType !== "Lid" && dataType !== "Datacenter" && dataType !=="Id")
                            return (
                                Object.keys(element.auditdiff[dataType]).map(function(data){
                                    {key++}
                                    return (

{data + " " + dataType}

                                            <Button content='Update Row' color='green' disabled = {updated.indexOf(key) >-1} //not correctly disabling the button
                                                onClick = {() =>  {this.disableRow(key)} }
                                                />

                                        );
                                    })
                            )})
                        }

                </Modal.Content>
            </Modal>

    )
}
}

A: First, you need to use concat to setState, instead of push. concat will return a new array, but push is just adding new item to your original array
Second, you are directly modifying key state by {key++}. You actually don't need key state, you can use the index in map function.

class ResolveSourceContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
        modalOpen: false,
        updated: [],
        key: 0,
    };
}

disableRow = (key) => {
    let {updated} = this.state
    this.setState({updated: updated.concat([key])})
}

render() {

    const { size, modalOpen} = this.state;
    let {key} = this.state
    const { element} = this.props;

    return (

            <Modal size={size} open={modalOpen} onClose={this.closeModal}>
                <Modal.Content style={{textAlign: 'center'}}>

                        <Modal.Header>
                            {`${element.lid}`}
                        </Modal.Header>

Type

Update

                        {Object.keys(element.auditdiff).map(function(dataType){
                            if (dataType !== "Lid" && dataType !== "Datacenter" && dataType !=="Id")
                            return (
                                Object.keys(element.auditdiff[dataType]).map(function(data, index){
                                    return (

{data + " " + dataType}

                                            <Button content='Update Row' color='green' disabled = {updated.indexOf(index) >-1} //not correctly disabling the button
                                                onClick = {() =>  {this.disableRow(index)} }
                                                />

                                        );
                                    })
                            )})
                        }

                </Modal.Content>
            </Modal>

    )
}
}

A: Problem #1: You are mutating state object!
Issue: Pushing new value into existing array and storing back in state
disableRow = (key) => {
  let {updated} = this.state
  updated.push(key) // <--- mutating current array reference
  this.setState({updated})
}

Solution: Copy previous array and new value into a new array
disableRow = (key) => {
  this.setState(prevState => ({
    updated: [...prevState.updated, key],
  }));
}

Problem #2: You aren't using consistent keys to identify rows, they update each render cycle.
Solution: Use keys for each data element unique within the dataset, like id's, names, etc.. keys for the same elements should persist through re-renders.


text:
Q: Cannot extract .tar.gz file? I installed the .tar.gz file for BRL-CAD.
File name is BRL-CAD_7.26.0.2_Linux_x86_64.tar.gz at location /home/user/Downloads.
I opened Terminal and typed in
$ tar -zxvf BRL-CAD_7.26.0.2_Linux_x86_64.tar.gz
tar (child): BRL-CAD_7.26.0.2_Linux_x86_64.tar.gz: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now

What exactly should I type into Terminal so I can extract the .tar.gz file?

A: Try this:
Open a terminal,Press Ctrl+Alt+T
Run it:
cd /home/user/Downloads
tar -zxvf BRL-CAD_7.26.0.2_Linux_x86_64.tar.gz


text:
Q: Sheafification of singular cochains Let $S^k$ be the presheaf on a space $X$ that assigns to every open set $U$ the abelian group $S^k(U)$ of singular k- cochains on $U$. This is clearly not a sheaf. Consider the sheafification $F^k$ of each $S^k$. These sheaves form an exact resolution of the constant sheaf of integers.
We can take global sections on this sheaf resolution to obtain a cochain complex $F^*(X)$. Does the cohomology of this cochain complex coincides with ordinary singular cohomology?

A: You haven't said this explicitly, but your claim is that the sheaf cohomology of the constant sheaf $\Bbb Z_X$ is isomorphic to the singular cohomology of $X$:
$$H^\ast(X, \Bbb Z_X) \cong H^\ast_{\text{sing}}(X; \Bbb Z).$$
This is true for $X$ locally contractible. One checks that the complexes $S^\ast(X)$ and $\Gamma(X, S^\ast(X))$ are quasi-isomorphic. More generally, the assertion holds for any abelian group $G$:
$$H^\ast(X, G_X) \cong H^\ast_{\text{sing}}(X; G)$$
when $X$ is locally contractible.
I don't have any references on hand, but I would expect that you could find the proof in most books that introduce the concept of sheaf cohomology.


text:
Q: Assign value to int in one method, next method value is changed to -89xxxxxxxxx class test
{
    public:
        int a;
        void init(int _a);
        void read(void);
}

I have this simple program. From another class I init the test object with some value of "_a".
void init(int _a){
    a = _a;
}

Init:
testObject.init(3);

But when I enter "read()", the value of a = -858993460.
I understand that something is wrong ( :)   ). That it might be a pointer that is not used anymore. But. When I write "a = _a", shouldn't the VALUE of a be a copy of value of _a?
void read(void){
    printf("a-value %d \n" , a);
}

How do I copy the value of _a to a, so that a doesnt change when _a change?

A: My psychic debugging sense tells me that either a is not actually getting set, or you're not actually setting the a that you think you're setting.
Maybe you're not really calling init before you call read, or maybe you're calling them on different instances of test
Normally when you get a jumbled number like that, it's a telltale sign of a "garbage" number that has not been initialized.


text:
Q: Transfer file from one cloud storage to another I'm wondering if it's possible to transfer files from one cloud storage to another "on the fly"? Specifically I want to build an app that will transfer my photos from Skydrive to Box.net without saving files temporarily to my databases, but saving files directly to Box.net storage?
Thanks,
Lojza

A: I'm not aware of any cloud provider that provides an API for transferring data to a competing cloud provider, but I'm not familiar with skydrive or box.net.  Cloud providers have no incentive to help you move your data to the competition.  You will almost certainly have to read the data to your local machine then write it to Box.net

A: You can do it with https://app.mover.io/ and http://otixo.com/
These are just for this purpose..


text:
Q: Reduce Queries in Rails 5 I need to retrieve a list of collections ie @medications, @treatments, @therapies etc. with a count of each collections related records.
This works but creates the initial query and then a new query for each related record count.  Is there a way I can minimize the number of queries?
@medications = Medication.includes(:records).select(:id, :name).where(office_id: current_user.selected_office)

@medications.each do |medication|
  medication.record_count = medication.records.count
end

if @medications query has 10 results I have total of 11 queries. I need 10 collections with related record counts so I would end up with 110 queries per request.
All models have same attributes of name, office_id , etc
I am wondering how I can restructure database to better use or restructure query.  Incidentally I am using Postgres db v 9.6

A: What about with joins and count?:
Medication.left_outer_joins(:records)
          .select('medications.name, medications.id, COUNT(records.id) AS records_count')
          .group(:id)
          .where(office_id: current_user.selected_office)

If you're planning to count on each record per medication, then you can use joins, and count passing the records and assigning an alias.
As each model has the name and id columns, you need to be more precise on defining them, and group in this case (correct me if I'm wrong), is mandatory, otherwise you'd get a PG::GroupingError.


text:
Q: Error shows when I use pygments with redcarpet on rails, how would I fix this? I have installed both gems, redcarpet and pygments.rb, and created a method and class in my application helper and called the method on @content on my show.html.erb, yet I get an error message.
code is on imgur
http://imgur.com/a/HAKAc
the error message shows when I replace Redcarpet::Render::HTML with HTMLwithPygments in the markdown method
if there are any more bits of the application you need to see please ask
error message as requested:
MentosError in Posts#show
Showing C:/Sites/mainsite/app/views/posts/show.html.erb where line #23 raised:
Failed to get header.
app/helpers/application_helper.rb:4:in `block_code'
app/helpers/application_helper.rb:18:in `render'
app/helpers/application_helper.rb:18:in `markdown'
app/views/posts/show.html.erb:23:in `_app_views_posts_show_html_erb__448466666_71119812'

Request
Parameters:
{"id"=>"sixth-post"}

application helper below:
module ApplicationHelper
  class HTMLwithPygments < Redcarpet::Render::HTM
    def block_code(code, language)
      Pygments.highlight(code, lexer: language)
    end
  end
  def markdown(content)
    renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)
    options = {
      autolink: true,
      no_intra_emphasis: true,
      disable_indented_code_blocks: true,
      fenced_code_blocks: true,
      lax_html_blocks: true,
      strikethrough: true,
      superscript: true
    }
    Redcarpet::Markdown.new(renderer, options).render(content).html_safe
  end
end


text:
Q: Exception safety in a self-contained application In a self-contained application (as opposed to a library) I am led to believe that in terms of exception safety the aim should be "provide the basic guarantee throughout".
Does that sound reasonable? Should we only worry about providing the strong and nothrow guarantees where they contribute to that aim?

A: Your aim is to provide the strongest exception safety you can and only lower it if you have to or if not lowering it would be expensive.
The best exception safety you can provide is nothrow, but this is obviously hard to avoid at all times. There are some places where your code should throw, otherwise you're just avoiding exceptions in general.
Next, you should strive for the strong guarantee, but this can be expensive to implement. It often requires making excessive temporary copies to ensure that no observable state is affected during the operation of your function.
At a minimum, you should provide the basic guarantee. This usually isn't expensive to ensure, as you're just making sure nothing leaks. The smart pointer types can help you with that. That doesn't mean the basic guarantee is bad, but if you can do better you should.
Perhaps the aim would be better written as "provide at least the basic guarantee throughout but strive for the best guarantee you can get".

A: I think that this question is best answered by the one writing the application. I have code that calls exit() to signal failure, which violates quite a few guidelines, but I think I can justify that decision in that particular case (a one-shot application, like a compiler). Actually, it doesn't even clean up resources but leaves that to the OS. On the other hand, if the standalone application was a long-living server app, the basic guarantee isn't even enough. Further, for library code, you generally don't have the necessary knowledge to determine where it is used, so you have to be careful.
In summary, I'd say you should try to provide strong/nothrow guarantees as a guideline, but you can make a (hopefully well-informed) decision to lower those requirements in a particular case.


text:
Q: What does this LM393N circuit do? I'm attempting to connect to Loconet(spec) to a PIC32, and I've found a circuit to connect to an Arduino, but I'm not sure what exactly it does:

(source page)
Specifically, I don't know what the LM393N voltage comparator at the top middle of the schematic does.  I think that what is going on is that the LM393N is clamping the voltage to a certain level, between 0 and 5V or so in order for a microcontroller to read it as either a 0 or 1.  I'm assuming that because of the following statements in the spec, as well as the given that VCC=5v:
Page 3:
a) High = 1 = "MARK" : LOCONET+/- voltage above +4.0 Volts with respect to ground conductors.
b) Low =0 = "SPACE" : LOCONET+/- voltage below +4.0 Volts with respect to grounds.
c) The data should be received with 1.0 volt of HYSTERESIS centered on +4.0 volts.
d) Maximum LOCONET+/- high voltage is +24V and nominal is +12V

I've seen another circuit that is similar, but uses an opto-isolator after the voltage comparator to actually interface with the microcontroller, which I'm assuming will then drop the voltage down to CMOS levels if it isn't already.
BONUS QUESTION: The LM393N in the center doesn't appear to be connected to anything, what's up with that?

A: The inverting input(pin 6) to the comparator is a voltage reference of 3V. This is what you are comparing the non-inverting input(pin 5) to. When the non-inverting input is greater than the inverting input, the output(pin 7) will be high.
Notice that there is a feedback resistor from the non-inverting input to the output. This is for hysteresis. It will keep the voltage at the non-inverting pin slightly higher when the output is high, and keep the voltage slightly lower when the output is low. This will prevent the output from toggling when both inputs are at very similar voltage levels.
This is basically what a schmitt trigger does.
It gives you a nice digital output for your microcontroller.
Bonus: There are two comparators on the LM393N. One is simply not used.

A: The comparator provides a 5V copy of the data on the LocoNet connection.  Here's how -
An LM393 can handle up to 36V on one of its inputs REGARDLESS of the voltage being used to run it (so long as the other input remains below the voltage used to run it), in this application it is being run on 5V (VCC to pin 8) with one input held at 3V while the other input varies between approx 16V and 0V.  The 'output' is a connection to the collector of an internal NPN transistor that has its emitter connected internally to 0V through pin 4.
The 47K and 150K provide ~200K, a tiny loading on the LocoNet (16V / 200,000 = 80 mico Amps).
The 47K will also protect the comparator from any inrush currents.
The 27K and 39K provide a reference voltage to trigger the comparator (5V * 39K / 68K = 2.9V).
The 240K 'feedback' resistor prevents the comparator from oscillating if the LocoNet signals do not have sharp transistions, effectively 'cleaning up' the copied signal.
The 1K at the 'output' provides 5V at 5mA on the 'LN_RX' connection which is switched to 0V when the comparator trips.
There are 2 comparators in the LM393 package, the second one should be shut down by tying both its inputs to 0V if it is not used.
'LN_TX' uses a transistor to switch the LocoNet to 0V when required.  As LocoNet typically uses just 12 to 15mA the output transistor in the unused comparator may be used instead, share the reference voltage by connecting pin 2 to pin 6, connect the 'LN_TX' to pin 3 and connect the LocoNet directly to pin 1.


text:
Q: How to start and stop a Sinatra application using Thin on Windows? class App < Sinatra::Base
  def hello
    "world"
  end
end

From documentation I found that I can start the application like this:
App.run

Although this does not return the control.
How do I start the application in the background and how can I then stop it.
My environment is: Windows, Ruby 1.9.2

A: Use a config.ru file like Dmitry Maksimov suggested:
#config.ru
require './your_app_file'

run YourApp

And then start with rackup -D which means deamonize and therefore it runs in the background.
I wouldn't recommend this for development though. Better have a look at Shotgun

A: Create in the top directory of your application rackup file - config.ru - with the following content:
# config.ru
$: << File.expand_path(File.dirname(__FILE__))

require 'your app'
run Sinatra::Application

Then just run your app with the thin start


text:
Q: Oracle PL/SQL User input error "Bind variable not declared" accept x char prompt 'Please enter something: '
declare
  a varchar2(50);
begin
  a := '&x';
  Select MIN(lowest_elevation) as lowest , Max(highest_elevation)as highest FROM countries where country_name = :a;
end;

i am taking input from a user then passing it into a where clause. and i cant seem to find any solutions online. I don't know what i am doing wrong. Thank you in advance.

A: a is a PL/SQL local variable, not a SQL bind variable, so it should not have the colon when you refer to it:
where country_name = a;

For it to be a bind variable it would need to be defined by the client/application/IDE; in SQL Developer, for instance:
accept x char prompt 'Please enter something: '
variable a varchar2(50);

begin
  :a := '&x';
  Select MIN(lowest_elevation) as lowest , Max(highest_elevation)as highest
  FROM countries
  where country_name = :a;
end;

Note that now there is no declare section, as you are no longer declaring a as a PL/SQL variable - it's a client variable. To assign the substitution variable &x to it it then needs the colon, :a := '&x';, because it's a bind variable there too.
I'm not saying that's what you should do; just showing the difference.
You can also skip the a variable completely, of course:
accept x char prompt 'Please enter something: '

begin
  Select MIN(lowest_elevation) as lowest , Max(highest_elevation)as highest
  FROM countries
  where country_name = '&x';
end;

Incidentally, you have to select into something, so your code still won't work as it's currently written.


text:
Q: Django: Combining two for loops Is there a way to combine the two for loops into one?
I was looking for a solution like this. But it didn't work that way:
ticket_stats_by_event = {
    x['pk']: {'sold_tickets': x['sold_tickets'], 'available_tickets: y['avaiable_tickets']}
    for x, y in sold_tickets_by_event, available_tickets_by_event
}

The result will be:
<EventQuerySet [{'pk': 6, 'organizer': 1, 'available_tickets': 20, 'sold_tickets': 2}, {'pk': 1, 'organizer': 1, 'available_tickets': 1765746, 'sold_tickets': 2116}, {'pk': 5, 'organizer': 1, 'available_tickets': 10, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'available_tickets': 60, 'sold_tickets': 4}]>

Here the full function:
def ticket_stats_by_event(self, organizer):
    sold_tickets_by_event = [
        x for x in self.sold_tickets if x['organizer'] == organizer.pk
    ]

    # <EventQuerySet [{'pk': 6, 'organizer': 1, 'sold_tickets': 1}, {'pk': 1, 'organizer': 1, 'sold_tickets': 529}, {'pk': 5, 'organizer': 1, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'sold_tickets': 2}]>

    available_tickets_by_event = [
        x for x in self.available_tickets if x['organizer'] == organizer.pk
    ]

    # <EventQuerySet [{'pk': 1, 'organizer': 1, 'available_tickets': 1721}, {'pk': 4, 'organizer': 1, 'available_tickets': 30}, {'pk': 5, 'organizer': 1, 'available_tickets': 10}, {'pk': 6, 'organizer': 1, 'available_tickets': 20}]>

    ticket_stats_by_event = {
        x['pk']: {'sold_tickets': x['sold_tickets']}
        for x in sold_tickets_by_event
    }

    for item in available_tickets_by_event:
        pk = item.pop('pk')
        ticket_stats_by_event[pk].update(item)

    return ticket_stats_by_event

A: You can write your function like this using only a loop instead of four:
def ticket_stats_by_event(self, organizer):

    ticket_stats_by_event = {}

    for st, at in zip(self.sold_tickets, self.available_tickets):

        # if organizer is not same in any then skip
        if organizer.pk != st['organizer'] or organizer.pk != at['organizer']:
            continue

        st_pk = st['pk']
        st_value = {'sold_tickets': st['sold_tickets'], 'organizer': st['organizer']}
        at_pk = at['pk']
        at_value = {'available_tickets': at['available_tickets'], 'organizer': at['organizer']}

        # add values from sold_tickets_by_event
        if st_pk in ticket_stats_by_event:
            ticket_stats_by_event[st_pk].update(st_value)
        else:
            ticket_stats_by_event[st_pk] = st_value
        # add values from available_tickets_by_event
        if at_pk in ticket_stats_by_event:
            ticket_stats_by_event[at_pk].update(at_value)
        else:
            ticket_stats_by_event[at_pk] = at_value

    return ticket_stats_by_event

Also, you can break this into three loops where in first and second you fetch sold and available tickets for a particular organization. I haven't used one liner functions to make it more readable.


text:
Q: String type alternative in C I currently have a function defined in a header that looks like this
void foo::GetValue(std::string& str);

This function basically assigns a value to str. I need to come up with an alternative to str (basically, nothing that employs the standard library).
The implementation of the above function is like this in the .cpp file:
void foo::GetValue(std::string& str)
{
    std::string s = bar.someMethod();
    str = s;
}

I want to know what is the best/easiest option for replacing the header?
One approach I had was to replace std::string in the header file with char* so I would have this in the header:
void foo::GetValue(char* str);

And in the implementation I would have this:
void foo::GetValue(char* str)
{
    std::string resp = bar.someMethod();
    char* c = new char[resp.size() + 1];
    std::copy(resp.begin(), resp.end(), c);
    c[resp.size()] = '\0';
}

The problem with the above approach is that a lot of files are calling this function and they will need to modify their code. Also, they will need to free the above memory. Two concerns I have with this is that other callers to this function will need to do the following two things

*

*Replace std::string being passed to the function with char*.

*Free the char* when done using it.
These two items seem very costly to me to trust other callers to do.
Any suggestions on what I can do to solve this problem? Perhaps change the signature to something else? I would prefer if the caller still passes a string, however string.c_str() is a constant char pointer.

A: For a given C++ function like this:
std::string foo::GetValue(std::string& str)
{
  return bar.someMethod(str);
}

Then your equivalent C code looks like this:
void foo_GetValue(char* str, char* res, size_t size)
{
  std::string str_arg = str;
  std::string result = bar.someMethod(str_arg);
  strncpy(res, result.c_str(), size - 1);
  res[size-1] = 0; // Ensure is NUL terminated
}

When calling from C:
void example() {
  const BUFFER_LEN = 1024;
  char buffer[BUFFER_LEN];

  foo_GetValue("example", buffer, BUFFER_LEN);
}


text:
Q: Working with Reverse Proxies and Multisite Installation We have a wordpress multi site, the main site has a URL similar to mainsite.com
Each of the sub sites have a URL such as subdomain1.mainsite.com, subdomain2.mainsite.com etc  Each of the sub sites we would like to potentially hide behind a separate reverse proxy eg revprox1.com/rp1subsite shows subdomain1.mainsite.com, revprox2.com/rp2subsite shows subdomain2.mainsite.com etc
Doing the reverse proxy on IIS7 works using the code below and the site is  displayed on the relevant reverse proxy URL, however all the hyper links on the page refer to the original URL and not the reverse proxy due to wordpress using absolute paths.  We installed a plugin to force wordpress to enforce relative paths for all the links, at this point all the links worked, the reverse proxy folder was appended to the beginning of the link, however the CSS was broken as it was looking for the CSS at the root of the reverse proxy and was not appending the reverse proxy folder eg it was looking for  the CSS at revprox1.com/css.css rather than revprox1.com/rp1subsite/css.css
I was wondering if anyone has ever tried to set Wordpress up like this before and what I should be looking at to combat this problem, as if the CSS was looking in the correct place it would work for us.  We cant really be changing the database as we want to be able to allow our site administrators to setup new sites with minimal involvement from IT.
    <rule name="Reverse Proxy to Site 1" stopProcessing="true">
        <match url="^rp1subsite/(.*)" />
        <action type="Rewrite" url="http://subdomain1.mainsite.com/{R:1}" />
    </rule>
    <rule name="Reverse Proxy to Site 2" stopProcessing="true">
        <match url="^rp2subsite/(.*)" />
        <action type="Rewrite" url="http://subdomain2.mailsite.com/{R:1}" />
    </rule>
</rules>
<outboundRules>
    <rule name="Add application prefix" preCondition="IsHTML">
        <match filterByTags="A" pattern="^/(.*)" />
        <conditions>
            <add input="{URL}" pattern="^/(rp1subsite|rp2subsite)/.*" />
        </conditions>
        <action type="Rewrite" value="/{C:1}/{R:1}" />
    </rule>
    <preConditions>
        <preCondition name="IsHTML">
            <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
        </preCondition>
    </preConditions>
</outboundRules>

A: If you want wordpress to behave nice when asked to serve content from example.com you need to configure it to know that. This is done automatically at the install process for the domain on which wordpress is installed on but can also be controlled from wp-config.php by setting values to the WP_HOME and WP_SITEURL constants.
What you need to do is set the contants differently when a request comes from your proxy. You should have in your wp-config.php something like
if (request is comming from the proxy) {
  define('WP_HOME', 'http://www.revproxy.com');
  define('WP_SITEURL', 'http://www.revproxy.com');
}

This will solve problem with all the URLs which are generated by the wordpress APIs, but you will still need the code to convert links in the content to be "relative" or replace the domain based on the value of WP_HOME


text:
Q: R object in function not found I have a problem with a function after I commented it out and again in. It worked before, but now I cannot find what's causing the problem.
Data to reproduce:
xmat <- matrix(rexp(200, rate=.1), ncol=20)
ymat <- matrix(rexp(10, rate=.1), ncol=1)

package used:
if ( !("ensr" %in% rownames(installed.packages())) || (packageVersion("ensr") < "0.1.0.9001" ) ) {
  remotes::install_github('dewittpe/ensr')
}

Code:
set.seed(2020)

nboot = 1000

bootstraps <- replicate(nboot, {ws <- sample(1:nrow(xmat), replace = TRUE);
  ensr(xmat[ws, ], ymat[ws, ], standardized = FALSE, family="gaussian", nlambda=100, nfolds=10,
alpha=c(0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0)
)},
simplify = FALSE)

I get the error that the object "ws" cannot be found. If I create it outside the function it is no problem, but I need it inside, to have it in every bootstrap.
Does anyone have an idea what's going wrong?


text:
Q: Fantasy book series about a young girl and a talking dog solving mysteries This one was known to me years ago, but I don't recall much so I'll do my best in detailing what i remember:

*

*Most of the cover used in the series had a dark blue color in the background, with some other containing more color/being colorful.

*The "talking" dog usually had weird clothes or apparel on him (pretty sure it was a male dog). I vaguely recall the dog having a monocle/or glasses in one of the book series

*I don't exactly recall any of the story used in the book from the said series, but I do recall it had all the usual/recurrent ingredient/stereotypes from certain TV trope (which I'll detail on more below)

*One enemy in the series was being called "shadow" or coming from the shadows...Not sure of their exact name but it was a recurring theme in one of the story at some point

*The cover of most of the book in the series have the girl and dog being drawn in the middle with varying expressions

*The dog could sometimes see or hear things the girl couldn't (eg: hear voices, see strange figures etc)

*The dog sometimes was seen wearing human-like clothing that was fitting to him

*In one of the book, I vaguely recall the dog wearing a kilt (red/with red pattern on it)

*The girl sometimes had a magnifying glass in one of her hand

*The girl isn't tall at all (mentioning the covers depicting her since I don't know the detail of her exact height) and the dog is mostly on all fours, even though he seems to show human emotions/tendencies...

Details on the "stereotypes":

*

*There was one book in the series where you could clearly see the dog becoming "evil" or at least, foreshadowing that (based on the cover where the shadow/figure of the dog was drawn, and the summary of the said book described the girl noticing the dog "acting" strange)

*A Talking dog

*A group of individuals solving mysteries

That's all I can remember. I don't recall how many book there is in the series, but I know there more than 4 at least...
I'm unsure if the dog was clearly talking to the girl or "talking" as in, communicating to her in other way than speak, or if the girl just understood him and interpreted what he meant (but it was described so well, it looked like he was talking, so It's hard to say given it was a long time I read this).


text:
Q: Can't get SOQL statement to work for related object I have an object Tourist_Details__c which has 2 child objects Contacts and Incidents__c.
I already have a list of Incidents__c called results and now I need to get a list of all Tourist_Details__c where the related incident is in results. This is so I can perform some functions on the related Contact.
Here is my code:
public void anonymise() {
    List<Incident__c> results =
        [SELECT id, Incident_name__c, Date_of_incident__c, Name, Garda_Name__c
         FROM Incident__c WHERE Date_of_Incident__c <= :firstDate.Date_Of_Incident__c AND
        Date_of_Incident__c >= :lastDate.Date_Of_Incident__c];

    for (Incident__c inc : results) {
        inc.Incident_name__c = inc.Name;
        inc.Garda_Name__c = '';
    }
    update results;

    List<Tourist_Details__c> touristDetails =
        [SELECT Id, (SELECT Id FROM IncidentContacts__r)
         FROM Tourist_Details__c
         WHERE Incident__c in :results];
}

    for (RELATED_CONTACT : touristDetails) {
    //do something
    }
    update touristDetails;

My problem is that I am getting the following error:
SELECT Id, (SELECT Id FROM IncidentContacts__r)
                       ^
ERROR at Row:1:Column:28
Didn't understand relationship 'IncidentContacts__r' in FROM part of query
call. If you are attempting to use a custom relationship, be sure to append
the '__r' after the custom relationship name. Please reference your WSDL or
the describe call for the appropriate names.

For my inner select statement in touristDetails I have tried using the object name, API name and also the given Child Relationship Name (shown in code) on the Contact field in Tourist_Details__c but I always seems to get the same error.

A:
For my inner select statement in touristDetails I have tried using the object name, API name and also the given Child Relationship Name (shown in code) on the Contact field in Tourist_Details__c but I always seems to get the same error.

You were on the right track: the Child Relationship Name is always the correct choice when performing a parent-to-child subquery in SOQL. However, the presence of the error indicates that IncidentContacts__r just isn't the child relationship name, which is shown on the lookup field from the child to the parent.
Based on your comment, you've discovered that your data is arranged a little differently, so that should resolve the issue.


text:
Q: Does Dreamweaver CS 5.5 Hang for anybody else for very long periods of time? Every day, I load up Dreamweaver and it takes anywhere from 5-10 minutes to get going (sometimes if at all). I have tried the following steps:

*

*Uninstalled and reinstalled the software

*repaired windows registry using Free Windows Registry Repair

*uninstalled, run registry repair, reinstalled, run repair

*modified registry for Dreamweaver cs 5.5 and added the ResolveRemoteURLtoIPAddress to False

Nothing seems to be working. Has anybody else had this issue? I can't seem to find much information online about it and if I do, it is Mac related.
Note: I have other Adobe products installed as well (Reader X and Fireworks CS 5) if this helps with any troubleshooting.
Update
I also just tried the following:
 - Remove all Adobe products
 - restarted machine
 - run registry cleaner
 - restarted machine
 - ran Adobe Creative Suite Cleaner
 - restarted machine
 - run registry cleaner
 - restart machine
still no luck and I'm waiting 6+ minutes for this program to load.
Update 2
Just wiped CS 5.5 and installed CS6 trial to test - I am running into the same issues. No idea what is going wrong here now.
I have this on a i7 8gb machine as well so system resources are plenty.

A: If you have a bucket load of fonts I believe Dreamweaver attempts to load them all in, it might also be trying to load in the last project, if so this could take a while depending on the size of the project.


text:
Q: How do you select custom colours to fill regions of a Voronoi diagram using scipy.spatial's Voronoi package? I have a code that reads in a csv file containing places, their latitude and longitude, and whether I've been there (marked by 'Y' or 'N'). I want to present this in a Voronoi diagram, but crucially I want to colour the regions according to the following criteria:

*

*If I've not been there ('N') mark region as white

*If I have been there ('Y') mark region as a random colour that is unique to any other colours on the map

I have two issues with my code: I can't seem to match the regions produced by Voronoi(coords) to my original list of places (so I can't readily correspond the region to the colour I want to fill that region, because the order in which the regions are defined and filled is not the order in which they appear in the dataframes), and secondly, how to ensure each random colour is "unique", i.e. not the same random colour appearing in each region.
The second issue I am fairly certain I can find a solution for, it's the first issue that I am struggling with. Any help would be much appreciated. Here is my code:
import pandas as pd
from scipy.spatial import Voronoi, voronoi_plot_2d
import numpy as np

# read places, with lat and lon
places = pd.read_csv("places.csv")

# convert subset to numpy array
coords = places[['Longitude','Latitude']].values

# add 4 distant dummy points
coords = np.append(coords, [[999,999], [-999,999], [999,-999], [-999,-999]], axis = 0)
colours = np.append(places[['Been']].values, [['N'], ['N'], ['N'], ['N']], axis = 0).flatten()
colours = np.insert(colours, 0, ['N','N'])

# assign a random colour to the array if visited, leave white if not
colours[colours == 'N'] = 'w'
import random
r = lambda: random.randint(0,255)
colours[colours == 'Y'] = '#%02X%02X%02X' % (r(),r(),r())
print(places['Place'])
print(colours)
print(coords)
# compute voronoi tesselation
vor = Voronoi(coords)

# plot voronoi diagram
import matplotlib.pyplot as plt
fig = voronoi_plot_2d(vor, show_vertices = False)

j = -1
# colourise the regions
for region in vor.regions:
    j = j+1
    print(region)
    if not -1 in region:
        polygon = [vor.vertices[i] for i in region]
        plt.fill(*zip(*polygon), colours[j])

# fix the range of axes, plot locations
plt.plot(coords[:,0], coords[:,1], 'ko')
plt.xlim([places['Longitude'].min() - 0.6, places['Longitude'].max() + 0.6]), plt.ylim([places['Latitude'].min() - 0.6, places['Latitude'].max() + 0.6])

# annotate each point with the place name
[plt.annotate(places['Place'][i], (coords[i,0], coords[i,1]), xytext=(coords[i,0]-0.2, coords[i,1]+0.2)) for i in range(len(places))]
plt.show()

I've produced this in Jupyter Notebooks. My csv file looks like this:
Place,Latitude,Longitude,Been
Bern,46.948,7.4474,N
Juras,47.0086,6.7856,N
Lake Como,46.016,9.2572,N
Lyon,45.764,4.8357,N
Marseille,43.2965,5.3698,N
Milan,45.4642,9.19,N
Monaco,43.7384,7.4246,N
Mont Blanc,45.8326,6.8652,N
Mont Saleve,46.0942,6.1403,Y
Munich,48.1351,11.582,N
Turin,45.0703,7.6869,N
Zurich,47.3769,8.5417,N

I've left in print statements, if that helps, and some commented lines of code from my tests. I currently colour the region marked by Lyon, which demonstrates the issue I have of not knowing how to use region in vor.regions to retrieve the coordinates it corresponds to. Thanks in advance.

A: You need to use the point_region attribute of the resulting Voronoi result to determine which input point corresponds to which Voronoi region. Here is the updated code which colors the regions indicated.
I updated the code to give a different random color for each colored Voronoi region. Here is the code:
import pandas as pd
from scipy.spatial import Voronoi, voronoi_plot_2d
import numpy as np

# read places, with lat and lon
places = pd.read_csv("places.csv")

# convert subset to numpy array
coords = places[['Longitude','Latitude']].values

# add 4 distant dummy points
coords = np.append(coords, [[999,999], [-999,999], [999,-999], [-999,-999]], axis = 0)
colourFlag = np.append(places[['Been']].values, [['N'], ['N'], ['N'], ['N']], axis = 0).flatten()

# assign a random colour to the array if visited, leave white if not
import random
r = lambda: random.randint(0,255)
colours = list(map(lambda flag: '#%02X%02X%02X' % (r(),r(),r()) if (flag == 'Y') else 'w', colourFlag))

# compute voronoi tesselation
vor = Voronoi(coords)

# plot voronoi diagram
import matplotlib.pyplot as plt
fig = voronoi_plot_2d(vor, show_vertices = False)

for j in range(len(coords)):
    region = vor.regions[vor.point_region[j]]
    if not -1 in region:
        polygon = [vor.vertices[i] for i in region]
        plt.fill(*zip(*polygon), colours[j])

# fix the range of axes, plot locations
plt.plot(coords[:,0], coords[:,1], 'ko')
plt.xlim([places['Longitude'].min() - 0.6, places['Longitude'].max() + 0.6]), plt.ylim([places['Latitude'].min() - 0.6, places['Latitude'].max() + 0.6])

# annotate each point with the place name
[plt.annotate(places['Place'][i], (coords[i,0], coords[i,1]), xytext=(coords[i,0]-0.2, coords[i,1]+0.2)) for i in range(len(places))]
plt.show()

Here is a plot I produced adding colors to some of the lines in your original file:


text:
Q: How to avoid rc.local been executed? I created a rc.local in /etc/ on Ubuntu 18.04
The content is
sleep 180
reboot

I thought I can stop this during the 180 seconds, but the fact is it just hang there waiting 180 seconds then reboot.
This means I can't never normal login, it will just repeat reboot.
I tried to boot by another disk and try to mount the problematic Ubuntu.
I found it can't be mount.
I tried to mount the problematic Ubuntu, mount /dev/sdb1, it response error. It can't be mount
Any way to recover this?

A: I finally got a way to fix this.
By pressing RIGHT 'shift', (the left shift doesn't work) the grub menu will show up.
Then I can select enter emergency mode, after that, OS boot into the shell, I can edit /etc/rc.local


text:
Q: Graphing polar equation $r\sin \theta = 1$?
How would you graph $r \sin \theta = 1$?

I know that $r\sin \theta$ is equal to $y$, but the place where I'm told to graph this function on is a polar graph. How should I go about this?

A: While Milo is correct about this particular graph, let me pretend it isn't that easy so as to give you an idea how to proceed with this in general:
$(x, y) = (r\cos \theta, r\sin \theta)$, and the equation you want to graph is $r \sin \theta = 1$ which solves to $r = 1/\sin \theta$. so:
$$(x, y) = \left(\frac{\cos \theta}{\sin \theta}, \frac{\sin \theta}{\sin \theta}\right) = (\tan \theta, 1)$$
Now, choose various values of $\theta$, and plot the corresponding points $(x, y)$, and there is your graph. (Okay, I'm old-school. This is how you plot it by hand.)

A: Note that equation can be rewritten as $\ r  = \dfrac{1}{\sin \theta}$.
Therefore you can explicitly compute the value of $r$ for each value of $\,\theta$, except for $\theta = \pi n$, in which case you can compute a limit.
For example,  for $\theta=\pi/2$ you get $r = 1$,  for $\theta=\pi/3$ $r = 2/\sqrt{3}$, for  $\theta=3\pi/4$  $r = \sqrt{2}$, etc.


text:
Q: flutter program work okay on chrome, but cannot work correctly on web server I'm pretty new to flutter, and wrote the following flutter program to get the client IP address and location. I'm calling "http://ip-api.com/json" for IP address and location information. The program works okay by using device "chrome" and "web server", I can print client's location on the page.
.
When I deployed to github webpage or firebase hosting , and the program  shows "loading circle" for ever. It seems that the program cannot get the ip address after it was deployed to the github web server (or other web server).
I found the program throw "XMLHTTPRequest Error" once i deployed it to Github html page or firebase hosting.  It works fine on the local web server or chrome.  any suggestion on that?  Thanks a lot.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class IP_info{
  final String IP;
  final String city;
  final String ZIP;
  final String st_code;
  final String state_name;
  final String country_code;
  final String country_name;

  IP_info({this.IP, this.city, this.st_code,this.ZIP,
     this.state_name,this.country_code,this.country_name});

  factory IP_info.fromJson(Map<String, dynamic> json){
    return IP_info(
      IP:json['query'],
      ZIP:json['zip'],
      city:json['city'],
      country_code:json['countryCode'],
      st_code:json['region'],
      country_name:json['country_name'],
      state_name:json['regionName'],
    );
  }

}
void main() {
  runApp(MaterialApp(
      title: 'Covid 19 cases near you',
      home: MyApp()
  ),
  );
}

class MyApp extends StatefulWidget{
  @override
  State<StatefulWidget> createState()  => MyAppState();
}

class MyAppState extends State<MyApp> {

  bool _isLoading = false;
  IP_info ip_info;

  @override
  void initState() {
     _isLoading=true;
    _getPublicIP();
  }

_getPublicIP() async {
    try {

      const url = 'http://ip-api.com/json';

      final response = await http.get(url);
      if (response.statusCode == 200) {
        ip_info = IP_info.fromJson(json.decode(response.body));
        print(ip_info.toString());

        setState(() {
          _isLoading = false;
        });
        }
      else {
        // The request failed with a non-200 code
        print(response.statusCode);
        print(response.body);
      }

    } catch (e) {
      print(e);
    }
  }

 @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(title: Text('Testing IP address'),    ),
        body: Container(
          padding: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          child: _isLoading? Center(
              child: Column(children: [
                CircularProgressIndicator(),
                SizedBox(height: 10,),
                Text("Loading your location infomation ...", style: TextStyle(color: Colors.blueAccent),),
              ]
              )
          )
              : new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center ,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget> [
              Text('You are in ${ip_info.city} ${ip_info.state_name} ',
                style: TextStyle(
                  fontWeight: FontWeight.bold,),
              ),

            ],
          ),
        )
    );
  }

A: This is probably because of the service worker file generated only for the release build. The { credentials: 'include' } part of service work file breaks all requests without Access-Control-Allow-Origin or with that of value * which is all public APIs.
There is an issue on that, and it is said to be fixed in master which has not been released yet. So some workarounds you can do currently is to remove the credentials part manually after every build or to unregister the service worker.
Here's how you can remove that part if you still want to use service worker. There should be a flutter_service_worker.js file inside the build/web folder. You will find that credentials part as the second argument of the fetch function. You can remove that argument. But the bad thing about this is you have to remove that part manually every time after building, which is not programmatic or effective.
The best way for this problem is to completely unregister the service worker. You can do that by, removing this script part from the web/index.html file.
<script>
      if ("serviceWorker" in navigator) {
        window.addEventListener("load", function() {
          navigator.serviceWorker.register("/flutter_service_worker.js");
        });
      }
</script>

A: I switched to geolocation-db.com/json (instead of using 'ip-api.com/json) to get the location information of the client's node, and it works! I think it is related to the server side. I think it may be related to the web request has to be https instead of http.


text:
Q: making an asynchronous UDP client using boost::asio I tried to make an asynchronous UDP client using boost::asio
I get some code on internet, and I managed to send message.
But my client didn't received the message from the server ( and it works when i don't use boost ).
Here's my code
 class udp_async_client
 {
 public:

   udp_async_client (boost::asio::io_service& io_service, std::string& host, std:: string port, char **av , int ac)
: reply ()
, _io_service (io_service)
, _sock (io_service, udp:: endpoint (udp:: v4 (), 0)) {

udp:: resolver resolver (_io_service);
udp:: resolver:: query query (udp:: v4 (), host, port);
udp:: resolver:: iterator endpoint_iterator = resolver.resolve (query);
sender_endpoint = *endpoint_iterator;

_io_service.run ();

//test request string
using namespace std;

std::string request = av[3];
for (int i = 4 ; i < ac ; ++i)
  {
    request += ";";
    request += av[i];
  }

std:: cout <<"Request is:" <<request <<std:: endl;

_sock.async_send_to (boost:: asio:: buffer (request.c_str(), request.length())
                     , sender_endpoint
                     , boost:: bind (&udp_async_client::handle_send_to_server
                                     , this, boost:: asio:: placeholders:: error
                                     , endpoint_iterator));

  }

 ~udp_async_client () {
_io_service.stop ();
  }

  void handle_receive_from (const boost::system::error_code& error,
                        size_t bytes_recvd) {}

  void handle_receive_from (const boost::system::error_code& error,
                        size_t bytes_recvd) {}

  void handle_send_to_server (const boost::system::error_code& e,
                          udp:: resolver:: iterator endpoint_iterator) {
std:: cout <<"Handle send to" <<std:: endl;
char reply [max_length] = {};
_sock.async_receive_from (
                          boost:: asio:: buffer (reply, max_length), sender_endpoint,
                          boost:: bind (&udp_async_client::handle_receive_from, this,
                                        boost:: asio:: placeholders:: error,
                                        boost::asio::placeholders::bytes_transferred));

std:: cout <<"Reply is:" <<reply <<std:: endl;
  }

private:
char reply [max_length];
boost::asio::io_service& _io_service;
udp:: socket _sock;
boost:: asio:: ip:: udp:: endpoint sender_endpoint;

};

and my main :
int main (int ac, char** av) {

  if (ac < 5) {
   std:: cerr <<"Usage: nonblocking_udp_echo_client <host> <port> <name> <name to reach> \n";
 return 1;
 }

  boost:: asio:: io_service io_service;
  std:: string host (av[1]);
  std:: string port (av[2]);

  while (true)
    {
     udp_async_client cli (io_service, host, port, av , ac);
     boost:: this_thread:: sleep (boost:: posix_time:: millisec (500));
   }
 return 0;
  }

I don't know what i did wrong ...

A: _io_service.run() is a blocking call. Your code is actually not passing that line until the stop is called on io_service.


text:
Q: Parse xml file with python I have this simple xml file:
<BSB>
    <APPLSUMMARY>
        <MAIN W="S1" X="{ND}"/>
        <COUNTS Z="0" AB="0" BB="0" CB="0" DB="0" EB="0" FB="0" GB="{ND}"/>
        <SCOTDEBT OQB="{ND}"/>
        <NOTICES HB="0" IB="3"/>
        <SUB_BLOCKS C="3" D="3" E="1" F="0"/>
        <ALIAS_NO UPB="0" VPB="{ND}" WPB="0"/>
        <ASSOC_NO DD="0" ED="0" AC="0"/>
        <ALERTSUMM PB="0" QB="0" RB="{ND}" SB="{ND}" TB="{ND}" UB="{ND}"/>
        <HHOSUMM BC="{ND}" RGB="{ND}"/>
        <TPD INB="{ND}" JNB="{ND}" KNB="{ND}" LNB="{ND}"/>
        <OCCUPANCY AD="1"/>
        <DECEASED LQB="1" FCC="{ND}" GCC="{ND}" HCC="{ND}" ICC="{ND}"/>
        <IMPAIRED MQB="0"/>
        <ACTIVITY JCC="{ND}" KCC="{ND}" LCC="{ND}"/>
        <ADVERSE MCC="{ND}" HHC="{ND}"/>
    </APPLSUMMARY>
</BSB>

I want to create in python a csv file that contains only the DECEASED contents in columns like this:

So, I am trying to get the values of the DECEASED bit and align them in columns.
I have tried this:
import xml.etree.ElementTree as ET
import io
parsed = objectify.parse(open(path)) // path is where the xml file is saved
root = parsed.getroot()
data = []

for elt in root.BSB.DECEASED:

    el_data = {}
    for child in elt.getchildren():
        el_data[child.tag] = child.text
        data.append(el_data)
    perf =pd.DataFrame(data).drop_duplicates(subset=None, keep='first', inplace=False)

    print(perf)
    perf.to_csv('DECESEAD.csv')

I get an empty dataset:
Empty DataFrame
Columns: []
Index: []
Can anyone help me get the values inside the DECEASED tag, please?

A: The code below collects the data you are looking for
import xml.etree.ElementTree as ET
from typing import Dict

xml = '''<BSB>
    <APPLSUMMARY>
        <MAIN W="S1" X="{ND}"/>
        <COUNTS Z="0" AB="0" BB="0" CB="0" DB="0" EB="0" FB="0" GB="{ND}"/>
        <SCOTDEBT OQB="{ND}"/>
        <NOTICES HB="0" IB="3"/>
        <SUB_BLOCKS C="3" D="3" E="1" F="0"/>
        <ALIAS_NO UPB="0" VPB="{ND}" WPB="0"/>
        <ASSOC_NO DD="0" ED="0" AC="0"/>
        <ALERTSUMM PB="0" QB="0" RB="{ND}" SB="{ND}" TB="{ND}" UB="{ND}"/>
        <HHOSUMM BC="{ND}" RGB="{ND}"/>
        <TPD INB="{ND}" JNB="{ND}" KNB="{ND}" LNB="{ND}"/>
        <OCCUPANCY AD="1"/>
        <DECEASED LQB="1" FCC="{ND}" GCC="{ND}" HCC="{ND}" ICC="{ND}"/>
        <IMPAIRED MQB="0"/>
        <ACTIVITY JCC="{ND}" KCC="{ND}" LCC="{ND}"/>
        <ADVERSE MCC="{ND}" HHC="{ND}"/>
    </APPLSUMMARY>
</BSB>'''

def _clean_dict(attributes: Dict) -> Dict:
    result = {}
    for k, v in attributes.items():
        if v[0] == '{':
            val = v[1:-1]
        else:
            val = v
        result[k] = val
    return result

data = []
root = ET.fromstring(xml)
for d in root.findall('.//DECEASED'):
    data.append(_clean_dict(d.attrib))
print(data)

output (list of dicts)
[{'LQB': '1', 'FCC': 'ND', 'GCC': 'ND', 'HCC': 'ND', 'ICC': 'ND'}]


text: Q: iis web site launch service on startup once only I have a number of IIS 7.5 web sites hosted on various servers. I want to run a web service just once each time each site is started (not when the app pool is recycled) i.e. when the site comes up for the first time (is created) and then not to run again until the site is stopped and restarted. I had trouble Googling this because the terms cover so many things. Its the IIS equivalent of running autoexec.bat on a windows computer starting on a network (where computer maps to each hosted site). I.e. once IIS its self is up, then when each individual site starts some sort of event that can launch a further service. ASP.NET Application Life Cycle Overview for IIS 7.0 does not seem to answer this...


text:
Q: PHP Magic methods not working I am trying to create a registry class with magic __set and __get my class looks like
  class Registry {
      private $vars = array();

      public function __set($key, $value)
      {
          $this->vars[$key] = $value;
          dump($key, $value);
      }

      public function __get($index)
      {
          $this->vars[$index];
      }
  }

but if i try to save some variable in registry class in gets only the $key the $value
is alway NULL.
here is the sample code how I am try to call this class
$registry   = new registry;
$registry->router = $router;
$registry->title = "Welcome ";

A: *

*You forgot to return value in the __get method

*What does the dump function do?

A: Your __get function doesn't return a value, that's why it's always null. It should be:
return $this->vars[$index];


text:
Q: Trouble with web browsers Randomly one day I turn on my computer into Ubuntu and all of a sudden firefox (my browser of choice) keeps opening on its own, and if I let it will open 100+ instances of firefox so I had to uninstall it.
So then I try google chrome and it starts doing the same exact thing. So I uninstall that and try chromium and whadya know, same thing. Then I try opera and strangely enough, it works just fine.
But to my dismay I find opera to be a slow alternative, not very good and often unresponsive. So I really want to use firefox its my favourite browser. and this clearly seems to be a problem with the OS not the specific software. This problem makes my installation of Ubuntu virtually useless so if anyone has had this same problem or knows any sugestions it will be much appreciated thanks.

A: Try these once hope it would help you

*

*First completely remove firefox with it's configuration file using following commands:
sudo apt-get autoremove firefox
sudo apt-get --purge remove firefox

*Then remove the the ~/.mozilla directory by using this command:
rm -r ~/.mozilla

It will remove the configuration file/history of firefox for the current user

*Then re-install firefox using this:
sudo apt-get -f install firefox

If it doesn't help then repeat the same procedure beginning from step 1, just replace the command in step 2 with this one:
sudo find / | grep -i firefox | sudo xargs rm -rf

Reply if something goes wrong..
Alternated Way
Run this command in terminal:
exo-preferred-applications

Then under Web Browser chose some other browser as you told Opera is working fine, select that. Restart your system and check if it happens again..


text:
Q: Escape Base64 String in URL? For some reason I need to put a Base64 encoded string in the URL, i.e.
<script>
    var URL = "localhost:8080/MyApp/order?z=AAAAAAAEJs4"
</script>

The URL is generated by Java, problem here is I can only use java to make the Base 64 encoded string to be URL friendly, but not javascript friendly, so fire bug give me the following error:
SyntaxError: unterminated string literal

Apparently there are charactors in the Base64 string requires escaping. However I cannot use escape() or URLencoding() method as the request will directly deliver to the controller and manipulated by java code, so there is no "next page" in this situation.
So how to make this work then?

A: If your're trying to convert that z url attribute into an understandable string/variable, you have to use a library to convert that. Below is a link to a base64 library for Javascript that you must load in.
http://www.webtoolkit.info/javascript-base64.html
You maybe also need a library to access the z attribute in your url. I would recommend this:
https://github.com/allmarkedup/purl

A: Just in case it helps, here is a short JS code requiring no dependency:
String.prototype.base64EncodeUrl = function () {
    var str = this;
    str = window.btoa(unescape(encodeURIComponent( str )));
    return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
};

String.prototype.base64DecodeUrl = function () {
    var str = this, str_pad = (str + '===');
    str = str_pad.slice(0, str.length + (str.length % 4));
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    return decodeURIComponent(escape(window.atob( str )));
};


text:
Q: table design or div design, confusion have the following screen design for my demo application.
Should this design be done using a <DIV> or a <TABLE>?
Note: when you click on the data row it expands (accordion like) and shows description row where you can see some description about the row as a single column which spans across the width of the table.
The menu works when user clicks on an image given in that column.
I know that a table is used only to represent tabular data.
I have the menu in last column as well as an accordion like hidden row for each data row showing the description when user clicks on the data row.
So, I am not sure whether it can be considered as part of a tabular data.
This is related to fulfilling the following web-guideline:
http://www.w3.org/TR/2014/NOTE-WCAG20-TECHS-20140311/complete-diff.html#H51
The data is going to be text apart from the menu. Each menu link performs different functionality. The accordion row is also text mostly.
Please advise here.
Thanks.


text:
Q: Why are the number of magnetic field lines finite in a particular area? One can draw/imagine as many unique (curved/straight) lines as he/she wants in some specified finite area (assuming that each line is unique if it doesn't overlap with another line). Then how can the number of field lines in a particular area be a fixed quantity? This statement is contradicted by the fact that a particle will experience a magnetic force for each and every point in space. This would not be possible if at some specific points there are no magnetic field lines. The surface integral approach is clearer as some limits are taken into account and also there is no such thing as 'number of lines', but I find it very confusing when people say that the strength of the magnetic field is proportional to number of field lines/area. Why is this terminology still used? Is it because we assume that no magnetic field lines exist at places where the forces are very weak?
EDIT: Then why are there gaps between the iron filing lines? Is it because of my previous statement

because we assume that no magnetic field lines exist at places where the forces are very weak

And hence the iron filings align themselves to stronger field lines. Is this a reason why this terminology is still used?

A:
I find it very confusing when people say that the strength of the magnetic field is proportional to no. of field lines/area. Why is this terminology still used?

The terminology is still used because it is correct and it gives a graphical way to understand magnetic fields that is particularly intuitive to understand and apply.
For an example, consider the set of all lines in the plane passing through the origin and through the vertical line segment $x=1$ and $y=[0,1]$. There are an uncountably infinite number of points in that segment and a unique line for every such point. There are no gaps or missing points.
Now consider the set of all lines passing through the origin and the vertical line segment $x=2$ and $y=[0,1]$. Note that there is also an uncountably infinite number of points in this second segment and a unique line for every such point in the second segment. There are again no gaps or missing points.
Now, consider the relationship between these two sets of lines. All of the lines that go through the second segment also go through the first, but the reverse is not true. Half of the lines that go through the first segment do not go through the second. Therefore, indeed the number of lines through the second is less than the number of lines through the first. Half of an infinite number of lines is still an infinite number of lines, so the cardinality of the set is unchanged (infinity is weird).
No gaps have opened up, but the number of lines through the second segment is, in a physically valid sense, half the number of lines through the first segment. Sometimes the ratio of two infinite quantities is finite. Of course, we cannot draw every such line, but we can draw a representative set of a few and convey the concept of the whole field of lines. Doing so allows us to correctly and intuitively reason about the behavior of the field in a way that is difficult using the integrals directly.
This is the sense in which the strength of the magnetic field is proportional to the number of field lines/area. There are an infinite number of lines through each area, but some of the lines going through one area do not go through another. The proportion of lines that miss the other area is the proportion that the field strength decreases.

A: The number of magnetic field lines you draw are just a means to describe the strength of a magnetic field, so it is a convention to draw more lines.
If the field is stronger, but even if you draw only a few lines, the magnetic field between the lines still is there.
These lines do not really exist. They just show in what direction the force is. You could draw as many lines as you wish, but then you would not see anything any more.

A: This is a very under-discussed topic in introductory physics classes. The instructor would just tell you this for a fact with no further discussion on the topic which is the source of a lot of confusion. Well, as answered already, it is a matter of convention. You "agree" to draw a certain number of field lines and then compare, "fixing" the number of field lines to what you agreed. This concept is better understood when talking about electric fields. Know that electric field due to a charge $q$ is $$E= \frac{1}{4\pi\epsilon_0}\frac{(q)}{r^2}$$
Field density is something you'd appreciate being called what we're dealing with.
Let field density be defined as
$$D= \frac{n}{A}$$
$n$ is number of field lines passing through any surface we choose and $A$ is area of that surface. For simplicity, sphere is the most symmetrical surface, so we choose it to be a sphere. Note that it is purely conventional. $r$ be the radius of sphere. We choose a sphere around a charge, certain number of field lines cross it, we choose a larger sphere, same number of field lines cross it, but now less "densely" namely, less number of field lines per unit area.
The convention is that we choose $\frac{1}{\epsilon_0}$ lines for a unit charge. A charge $q$ would "give out" $\frac{q}{\epsilon_0}$. This convention makes life simple as in, the Electric field at any point is now the lines density itself.
Similarly, for magnetic field, since we choose to draw a certain number of field lines, say 7 field lines for every one "bar magnet", then we can cleverly compare things without getting mathematically complex.

A:
why there are gaps between the the iron filling lines?

Iron filings are ferromagnetic. They don't just show the field, they change it.

...hence the iron filings align themselves to stronger field lines.

The filings self-organize into distinct lines because their presence concentrates the field. Magnetic field lines prefer to go through a ferromagnetic body rather than through empty space. The field actually is stronger inside the iron particles than in the gaps between them.
If you drop a new filing into the gap between two of the visible "lines," it will feel attraction toward either of the surrounding lines. It will only stay put, and become the seed for a new line, if the magnetic force that it feels is too weak to overcome the static friction between the particle and the paper (or whatever) underneath.

A: The number of field lines is not a meaningful physical quantity, but only a useful tool to visualize the magnetic of electric fields. It is not a meaningful quantity because it is not measurable, for the reason that, as you said,
"One can draw/imagine as many unique (curved/straight)lines as he/she wants in some specified finite area (assuming that each line is unique if it doesn't overlap with another line)."
In other words, the number of lines is $N=a B$ where $B$ is the field and $a$ is a proportionality constant. However, the constant a is arbitrary, and you can basically decide how many lines to draw in order to make your plot/figure looking better. The number of lines is just a useful way to visualize the field, they are not a physically well defined quantity.
Another reason why they are not physically well defined is because the number of lines is a discrete objects, but fields are continuous. Consider a uniform field with field lines parallel to each other. The field is constant at any point in space, but there are the white regions between field lines where there are, by definitions, no lines. These points also have a finite field, but zero number of lines. So, places where the no. of lines is zero have no special meaning, they do not have a field weaker that other places.
Also, consider that, practically, there is no place in the universe where the magnetic field is zero. In order to have no magnetic field you need 1) that the charge distribution is completely static in your reference frame (no currents), or that you are infinitely far away from any moving charge, and away from any source of propagating electromagnetic waves.
The terminology is only used to visualize the fields. Usually, advanced text books do not even mention the concept of number of field lines.


text:
Q: Can I share business objects between UWP client and a WCF server? Can I do a classic n-tier app with a UWP client and a WCF server, where a business objects are in a shared library (so I don't have to generate proxy classes as in Silverlight)?

A: Yes, the general idea of portable class library would let the library be used in server and mobile apps. Caveats include need to be careful about dependencies, there is a fair amount of flux between "versions" of PCL-ness versus netStandard versions, and certain target platforms (like Xamarin) have their own specific narrowing to portability, but again, the basic answer is yes.


text:
Q: How to reset widget layout inside a view layout during device rotation? Well, i am developing new features inside a product which means lots of limitations i just can't break.
There is one activity which monitor the rotation event but use one unified layout for both portrait and landscape. Now i need to add some animations for several widgets inside the view.
For example, animation A to expand a toolbar, while B to collapse it.
But when i do A in landscape mode, and then rotate to portrait mode, the widgets still keep the position after animation A instead of the original layout configured in the xml file.
So what i want is to reset the layout partially. How can i achieve it???
Thanks!

A: Finally, i found a solution. Well may be not the best, it still solve my problem.
Insert a parent layout inside the activity view, let's say  and put nothing inside it.
During the run time, add the child view according to the screen orientation dynamically as following:
Put the codes inside the onConfigurationChanged().
LinearLayout ll = (LinearLayout)findViewById(R.id.linearlayoutId);
View viewPor/viewLand = getLayoutInfalter().Infalte(R.layout.Por/Land, null);
ll.addView(viewPor/viewLand);

You may need a object associated with the specific view for manipulating the widgets inside the view for the animations.


text:
Q: How to show google ads one time in android app? I want my android app to show google ad only one time. I mean in my app it shows the ad everytime that users open the main activity. But i want it to show the ad only at the first time.

A: You could make use of SharedPreferences.
Store a boolean for example, don't show the ad if it's true and set it to true after the first start.


text:
Q: mvc view Show preview when sharing (Facebook,whatsapp,Twitter) i know that might be stupid Question and even get negative votes
 but i really need to know the answer
in some websites when share the url it shows a preview for the website
check the image

now i have a MVC View works fine on browser and also om mobile (responsive)
but when sharing it only share the url text
do i need to add some thing to my view to do the same preview when sharing over social media
my URL : http://xxx.xxx.xx.xxx/SiteName/newspreview/ShowOneNews/4333
the x is static IP For the server Not yet have Domain Name
Thank you

A: WhatsApp would render a preview for your website but you can improve that. Check out this answer: https://stackoverflow.com/a/43154489/592651


text:
Q: Configure static IP-adress to connect to device in subnet I have a Dragino-Yun v2.4-shield, which is a device that can be connected with an Arduino to give it networking-capabilities. It has An Ethernet-Port and Wifi. I don't have a wifi-antenna at the moment so i tried connecting to it via the Ethernet-Port.
According to the manual, the address 172.31.255.254 is assigned to the Ethernet-Port in a /4 subnet (DNS-mask: 255.255.255.252). I started with a blank Arch-Linux-ISO on a ThinkPad and got it so far, as to pinging the device was succesfull. According to the manual it should also be possible to connect via ssh, but that didn't work.
I then rebooted and wanted to ran the commands cleanly, but didn't have any success on the second try. Here are the commands i ran, following this Archwiki-page (enp0s25 is the ethernet-link of my ThinkPad):
$ systemctl stop dhcpcd
$ ip link set enp0s25 up  # It is up by default though
$ ip addr add 172.31.255.253/4 dev enp0s25
$ ip route add default via 172.31.255.252
$ ping 172.31.255.254 -c3
PING 172.31.255.254 (172.31.255.254) 56(84) bytes of data.
FROM 172.31.255.253 icmp_seq=1 Destination Host Unreachable
FROM 172.31.255.253 icmp_seq=2 Destination Host Unreachable
FROM 172.31.255.253 icmp_seq=3 Destination Host Unreachable
--- 172.31.255.254 ping statistics ---
3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 4054ms
pipe 3

I will add, that i have very little networking-experience. Where am i wrong? Is there something i've missed?

A: First, ip addr does not automatically know the netmask. It is impossible to determine that from just the address itself, so you must specify the /prefixlen along with it. If you forget to do that, then the address will be added as /32 (single-host) and you will not be able to reach the rest of your subnet.
Second, your netmask is not a /4, it's a /30. The slash notation is used to indicate bit length of the netmask, not the literal subnet size. So the correct command would be:
ip addr add 172.31.255.253/30 dev enp0s25

(You can calculate /length as 32−log2(size) and size as 2(32-length), or just count the bits.)
Also, it'a "netmask" or "subnet mask" and not "DNS-mask", as it has nothing to do with DNS.

I see you're also specifying a rather unusal address as the gateway. With your netmask, .252 is the "zeroth" address of the subnet, and is usually considered reserved in IPv4. (Are you perhaps confusing 'gateway' and 'network address'?)
However, communications within the same subnet do not need a gateway in the first place – that's what a subnet is – so you can just skip that ip route add line entirely for now.

Finally, "Destination Host Unreachable" often means a different kind of error: it means the OS does know that the address is within a local subnet, but isn't receiving any responses from trying to look up its MAC address using ARP. (That step is mandatory before sending anything to a same-subnet device.)
Try to make manual ARP queries (similar to what the OS does) – if they succeed, then something is still wrong with your IP configuration:
arping -I enp0s25 172.31.255.254


text:
Q: Project will not start in debug mode I'm using VS2008, and I have a project that will not start when I press F5 or when I click the little green triangle in the toolbar.  The screen flickers once, like the project is going to run, and then it doesn't.  The build message claims the build was successful, but the project won't start.
In the Configuration Manager, my 'Active solution configuration:' is set to Debug, and in the 'Project contexts' list, the 'Configuration' column for my Project is set to Debug.  I've even switched them back and forth between Debug and Release and then back to Debug, all with no effect.  The project that I'm trying to run is set as the 'Startup Project' in my solution.
If I go to my \bin\Debug folder and double-click the .exe, (which shows the proper time-stamp on the file) my app runs just fine.
Any ideas why I can't get the silly thing to run in debug mode?
EDIT:
It's a winforms application.
My version of Visual Studio is 9.0.30729.1 SP
.NET Framework: Version 3.5 SP1
EDIT:
This may be related to TortoiseSVN.  I keep my source code for this project in SVN.  When I do a different/new checkout in TortoiseSVN, sometimes the new checkout will then allow the project to run.  I don't understand the seemingly intermittent nature of this problem.
EDIT:
Not sure if this information is relevant to the problem, but when I do a new checkout and have a folder structure that is less deep (not as many nested folders) than the original checkout, I seem to have a better chance of the project running without problems.
EDIT:  The problem had nothing to do with TortoiseSVN, see my answer below.

A: IT ran some type of Windows update on my machine and that has apparently fixed the issue.  It had something to do with a System.Runtime.InteropServices.COMException and an error in a 'Hosting' .dll.  I'm not sure why a corrupt Hosting dll had an impact on a winforms application, but it has fixed the issue.

A: I had a similar issue in the past.  The project would not run in debug mode.
It was also caused by a corrupted dll, but not the 'Hosting' one.  It's been a long time, so I don't recall the exact dll, but it had something to do with Messaging.

A: Gotta start with the basics... Have you eliminated the possibility of a run-time crash before the main form is shown?

A: There are actually some questions that are similar to yours. The most common workaround is to uncheck the "Enable the Visual Studio hosting process" in project properties.
I sometime has to switch between debugging under x64 bit to Any CPU; re-loading the project, and delete any *.suo files in the project folder.

A: Don't have a precise answer, but do have a solution that worked for me.
Close the project / solution all down.
Via Explorer, go to the bin\debug directory. Rename each of the files present within the directory. In my case i simply prefixed each entry with an "xxx". I did this so that I could backtrack once again, if required, as I didn't have the confidence simply to delete the entries.
By re-opening the project/solution, and attempting to debug again, seems to force the regeneration of those files once again.
For me the program resumed re-working.
I have no idea what the specific cause of the problem is, but the complete rebuild of the files, does appear to work, rather than just a "Build" which must partially retain what was there before.


text:
Q: Kafka Streams creates avro topic without schema I developed a java application which reads data from an avro topic, using Schema Registry, then makes simple transformations and prints the result in the console. By default I used GenericAvroSerde class for keys and values. Everything worked fine except that I had to define additionally configuration for each serde like
    final Map<String, String> serdeConfig = Collections.singletonMap("schema.registry.url", kafkaStreamsConfig.getProperty("schema.registry.url"));
    final Serde<GenericRecord> keyGenericAvroSerde = new GenericAvroSerde();
    final Serde<GenericRecord> valueGenericAvroSerde = new GenericAvroSerde();
    keyGenericAvroSerde.configure(serdeConfig, true);
    valueGenericAvroSerde.configure(serdeConfig, false);

Without that I always get an error like:
Exception in thread "NTB27821-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Failed to deserialize value for record. topic=CH-PGP-LP2_S20-002_agg, partition=0, offset=4482940
at org.apache.kafka.streams.processor.internals.SourceNodeRecordDeserializer.deserialize(SourceNodeRecordDeserializer.java:46)
at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:84)
at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:117)
at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:474)
at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:642)
at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:548)
at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:519)
Caused by: org.apache.kafka.common.errors.SerializationException: Error deserializing Avro message for id 69
Caused by: java.lang.NullPointerException
    at io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer.deserialize(AbstractKafkaAvroDeserializer.java:122)
    at io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer.deserialize(AbstractKafkaAvroDeserializer.java:93)
    at io.confluent.kafka.serializers.KafkaAvroDeserializer.deserialize(KafkaAvroDeserializer.java:55)
    at io.confluent.kafka.streams.serdes.avro.GenericAvroDeserializer.deserialize(GenericAvroDeserializer.java:63)
    at io.confluent.kafka.streams.serdes.avro.GenericAvroDeserializer.deserialize(GenericAvroDeserializer.java:39)
    at org.apache.kafka.common.serialization.ExtendedDeserializer$Wrapper.deserialize(ExtendedDeserializer.java:65)
    at org.apache.kafka.common.serialization.ExtendedDeserializer$Wrapper.deserialize(ExtendedDeserializer.java:55)
    at org.apache.kafka.streams.processor.internals.SourceNode.deserializeValue(SourceNode.java:56)
    at org.apache.kafka.streams.processor.internals.SourceNodeRecordDeserializer.deserialize(SourceNodeRecordDeserializer.java:44)
    at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:84)
    at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:117)
    at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:474)
    at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:642)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:548)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:519)

Well, it was unsual, but fine, after that (when I added configuration call as I posted above) - it worked and my application was able to to all the operations and print out the result.
But!
When I tried to use call through() - just to post data to the new topic - I faced the problem I am asking about: TOPIC WAS CREATED WITHOUT A SCHEMA.
How it can be???
Interesting fact is that the data is being written, but it is:
a) in binary format, so simple consumer cannot read it
b) it has not a schema - so avro consumer can't read it either:
    Processed a total of 1 messages
[2017-10-05 11:25:53,241] ERROR Unknown error when running consumer:  (kafka.tools.ConsoleConsumer$:105)
org.apache.kafka.common.errors.SerializationException: Error retrieving Avro schema for id 0
Caused by: io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException: Schema not found; error code: 40403
        at io.confluent.kafka.schemaregistry.client.rest.RestService.sendHttpRequest(RestService.java:182)
        at io.confluent.kafka.schemaregistry.client.rest.RestService.httpRequest(RestService.java:203)
        at io.confluent.kafka.schemaregistry.client.rest.RestService.getId(RestService.java:379)
        at io.confluent.kafka.schemaregistry.client.rest.RestService.getId(RestService.java:372)
        at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.getSchemaByIdFromRegistry(CachedSchemaRegistryClient.java:65)
        at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.getBySubjectAndId(CachedSchemaRegistryClient.java:131)
        at io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer.deserialize(AbstractKafkaAvroDeserializer.java:122)
        at io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer.deserialize(AbstractKafkaAvroDeserializer.java:93)
        at io.confluent.kafka.formatter.AvroMessageFormatter.writeTo(AvroMessageFormatter.java:122)
        at io.confluent.kafka.formatter.AvroMessageFormatter.writeTo(AvroMessageFormatter.java:114)
        at kafka.tools.ConsoleConsumer$.process(ConsoleConsumer.scala:140)
        at kafka.tools.ConsoleConsumer$.run(ConsoleConsumer.scala:78)
        at kafka.tools.ConsoleConsumer$.main(ConsoleConsumer.scala:53)
        at kafka.tools.ConsoleConsumer.main(ConsoleConsumer.scala)
[2017-10-05 11:25:53,241] ERROR Unknown error when running consumer:  (kafka.tools.ConsoleConsumer$:105)
org.apache.kafka.common.errors.SerializationException: Error retrieving Avro schema for id 0
Caused by: io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException: Schema not found; error code: 40403
        at io.confluent.kafka.schemaregistry.client.rest.RestService.sendHttpRequest(RestService.java:182)
        at io.confluent.kafka.schemaregistry.client.rest.RestService.httpRequest(RestService.java:203)
        at io.confluent.kafka.schemaregistry.client.rest.RestService.getId(RestService.java:379)
        at io.confluent.kafka.schemaregistry.client.rest.RestService.getId(RestService.java:372)
        at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.getSchemaByIdFromRegistry(CachedSchemaRegistryClient.java:65)
        at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.getBySubjectAndId(CachedSchemaRegistryClient.java:131)
        at io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer.deserialize(AbstractKafkaAvroDeserializer.java:122)
        at io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer.deserialize(AbstractKafkaAvroDeserializer.java:93)
        at io.confluent.kafka.formatter.AvroMessageFormatter.writeTo(AvroMessageFormatter.java:122)
        at io.confluent.kafka.formatter.AvroMessageFormatter.writeTo(AvroMessageFormatter.java:114)
        at kafka.tools.ConsoleConsumer$.process(ConsoleConsumer.scala:140)
        at kafka.tools.ConsoleConsumer$.run(ConsoleConsumer.scala:78)
        at kafka.tools.ConsoleConsumer$.main(ConsoleConsumer.scala:53)
        at kafka.tools.ConsoleConsumer.main(ConsoleConsumer.scala)

Of course I checked out the schema registry for the subject:
curl -X GET http://localhost:8081/subjects/agg_value_9-value/versions
{"error_code":40401,"message":"Subject not found."}

But the same call to another topic written by Java App - producer of the initial data shows that schema exist:
curl -X GET http://localhost:8081/subjects/CH-PGP-LP2_S20-002_agg-value/versions
[1]

Both applications use identical "schema.registry.url" configuration
Just to summarize - topic is created, data is written, can be read with simple consumer, but it is binary and the schema doesn't exist.
Also I tried to create a schema with a Landoop, somehow to match the data, but no success - and by the way it is not a proper way to use kafka streams - everything should be done on the fly.
Help, please!

A: When through is called, the default serde defined via StreamsConfig is used unless users specifically overrides it. Which default serde did you use? To be correct you should be using the AbstractKafkaAvroSerializer which will automatically register the schema for that through topic.


text:
Q: Why doesn't 'haml --check' find this glaring syntax error I was looking for rake tasks that would help me track down syntax errors, and I came across haml --check as a possible solution for double checking haml files. Unfortunately, when I passed it this broken example, haml says the syntax is OK.
Have I misunderstood the purpose of haml --check or is this feature not fully implemented?
I suppose I should mention I'm using Haml/Sass 3.0.25 (Classy Cassidy), rails 3.0.3, ruby 1.9.2p0, and Mac 10.6.6.

$ haml --check /tmp/edit.html.haml
Syntax OK

#/tmp/edit.html.haml
- content_for :head do
  = include_javascripts :aspects

#aspect_edit_pane
  #facebox_header
    %h4
      = @aspect
      .description
        = t('contacts', :count =>@aspect_contacts.count)}

The last character (curly brace) should trigger a syntax error, it certainly does when the template is executed as part of a request:

ActionView::Template::Error (compile error
    /usr/local/app/diaspora/app/views/aspects/edit.html.haml:13:
    syntax error, unexpected '}', expecting ')'

A: Maybe because -c, --check Just check syntax, don't evaluate.
Guess: it checks just the haml syntax and doesn't evaluate inline ruby.
--edit
This probably needs some more testing but I got it working on simple haml files :)
haml --debug newsletter.html.haml 2> /dev/null | sed '$d' | ruby -c

In theory:
Haml prints out the precompiled Ruby source (and error messages in the end), we try to get just the ruby part and check the syntax.


text:
Q: How to set JS variable value into an Odoo qweb template variable value I need to set a JS variable value into a Odoo template variable value.
For example, the select_val value:
<script>
$(document).ready(function() {
 var button = $('#select_coas_report_sign');
 button.change(function() {
  select_val = $(this).val();
 });
});
</script>

I need to be setted into the next variable value:
<t t-set="my_var" t-value="select_val" />

Also, I need to set this variable into a function call in the template, but is giving me Server Error.
<t t-set="callUrl"
t-value="sale_order.get_portal_url(suffix='/accept_order/' + {{ my_var }})" />

Any idea? Thanks for reading!

A: You are mixing multiple types of rendering odoo templates into something that can not work.
Your javascript <script> tag is executed after the server renders the template so it can only set variables on the server side if you re render the orginal page. Usually that's done by creating a <form> and passing data via <input> to a controller. The controller then renders the template with the variable values from the inputs.
The error you are seeing TypeError: unhashable type: 'set' is because:

*

*when doing <t t-set="callUrl" t-value="sale_order.get_portal_url(suffix='/accept_order/' + {{ my_var }})" /> the string inside t-value is run as a python expression

*the python expression {{ my_var }} gives you the error TypeError: unhashable type: 'set'
To fix the error you could change setting the callUrl to:
<t t-set="callUrl" t-value="sale_order.get_portal_url(suffix='/accept_order/' +  my_var )" />
Hint: the {{var}} is only used inside t-attf-$name
To prevent the error following from my_var being potentially None (TypeError: must be str, not NoneType) you could use python string formating:
<t t-set="callUrl" t-value="sale_order.get_portal_url(suffix='/accept_order/%s' % (my_var or '') )" />
As an alternative to posting a form, you can render templates in javascript if you do not need server side variables.