text:
Q: Backbone.js and Require.js I want to create Backbone.js app with Require.js.
But I have an error in console:  Uncaught Error: Module name "underscore" has not been loaded yet for context: _. Use require([])
require.config({
        baseUrl: 'js/',
        paths : {
            'jquery' : 'jquery',
            'underscore' : 'underscore',
            'backbone' : 'backbone',
            shim: {
                'underscore': {
                    exports: '_'
                },
                'backbone': {
                    deps: ['underscore', 'jquery'],
                    exports: 'Backbone'
                }

            }
        }
    });

    define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){

        var Model = Backbone.model.extend({});
        var model = new Model;
    });

    require(['app','jquery', 'backbone', 'underscore']);

How I can resolve this problem?

A: The shim is mentioned inside the paths object. I am not sure if that is the problem, but wanted to mention that here.

A: You still need to list underscore as a part of paths so you can refer to it in the shims.  Also, not sure what your directory structure looks like, but I'm writing this with the assumption that library code is in the /js/libs directory).  Finally, note you won't need to require any of the dependencies of app -- the joy of RequireJS is that it'll figure out what to load.
So...
require.config({
    baseUrl: 'js/',
    paths : {
        'jquery' : 'lib/jquery',
        'underscore' : 'lib/underscore',
        'backbone' : 'lib/backbone',
    },
    shim: {
        'underscore': {
            exports: '_'
        },
       'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        }

    }
});

define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){
    var Model = Backbone.Model.extend({});
    var model = new Model({
        foo: 'bar'
    });

    var app = {
        model: model
    };

    // ...

    return app;
});

require(['app'], function(App) {
    App.model.get('foo'); // <<=== returns 'bar'
});

A: You need Underscore.js as listed in your require statement.


text:
Q: Tuple as Key for ets table? I want to store tuples regarding information on other network participants in an ETS table.
I would like to use a tuple of {ip_address(), port_number()} (return of inet:peername(Socket) as the key of the entries. Aka I want to use the combination of address / port as an identifier for the other nodes / entries in the ETS table.
Is this possible with ets? Or do I have to use an other type as a key?

A: ETS stands for "Erlang Term Storage" and it can store any Erlang term, including tuples and tuples of tuples. The description section of the ets man page details how terms are compared and matched for particular table types, and the documentation for ets:lookup/2 discusses this as well. For some table types, Erlang term order is important.
There is no confusion regarding which part of a stored tuple is the key; the ets:new/2 function, used to create a table, includes the {keypos, Pos} option to indicate the key element. If {keypos, Pos} is not provided, the first element is the key.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a good Java client for Complete Version 4 Signing Process? I am working with AWS and need a good Java client that help with the Signing Process for Signature Version 4.  Anyone know of one?  Thanks.

A: Looks like we may go with okhttp-aws-signer.  Thanks for your help.


text:
Q: Как сделать запрос с группировкой в связных моделей через промежуточную таблицу? Есть две модели - User и Project и связная модель которая их объединяет ProjectUser
Выборка всех проектов где есть пользователь организована в модели User:
 public function getProjects()
    {
        return $this->hasMany(Project::class, ['id' => 'fk_project_id'])
            ->viaTable(ProjectsUsers::tableName(), ['fk_user_id' => 'id'])
            ->orderBy('title');
    }

Выборка всех пользователей в проекте организована:
 public function getUsers()
    {
        return $this->hasMany(User::class, ['id' => 'fk_user_id'])
            ->viaTable(ProjectsUsers::tableName(), ['fk_project_id' => 'id'])
    }

Есть особенность, в таблице Projects, есть поля fk_owner_id, fk_owner_id2, fk_owner_id3, куда назначаются владельцы (Users) по id
Мне нужно получить выборку всех проектов где пользователь является одним из владельцем или участником. На sql я делаю так(пример с id User = 20):
        select projects.* FROM projects
        left join projectsusers on projectsusers.fk_user_id = 20
        where projects.fk_owner_id like 20
        or projects.fk_owner_id2 like 20
        or projects.fk_owner_id3 like 20
        group by projects.title

Как мне организовать правильно запрос внутри модели User ?

Пробовал вот так:
public function getAllProjects(){
        $projects = Project::find()
        ->leftJoin('projectsusers','projectsusers.fk_user_id ='.$this->id)
        ->orWhere(['fk_owner_id' => $this->id])
        ->orWhere(['fk_owner_id2' => $this->id])
        ->orWhere(['fk_owner_id3' => $this->id])
        ->groupBy('projects.title')
        ->orderBy('projects.title')
        ->all();
        return $projects;
    }

, но это не дает результата.

A: Решено так:
$query = Project::find()
            ->with('fkOwner')
            ->with('fkOwner2')
            ->with('fkOwner3')
            ->join(
            'join',
            ProjectsUsers::tableName(),
            ProjectsUsers::tableName().'.fk_project_id = '.Projects::tableName().'.id')
            ->where(ProjectsUsers::tableName().'.fk_user_id = '.$this->id)
            ->orWhere(['or',
                ['fk_owner_id' => $this->id],
                ['fk_owner_id2' => $this->id],
                ['fk_owner_id3' => $this->id]
            ])
            ->orderBy(Project::tableName().'.title')
            ->all();


text:
Q: Why can't I just offer a bounty for a question right off the bat? Sometimes at work I have an immediate need to get an answer for a question. I have 3,000 points at my disposal so I'd like to just put a bounty on the question as soon as I post it to give it the highest possible chance of being seen. Why do I have to wait?

A: Why not allow a +100 bounty with no contributions on behalf of SO (not 50:50).  Sometimes if you ask a difficult or complicated question you just plain want to reward whoever gives you the answer (plus encourage people to invest the time).  At the moment complex or difficult questions just drop off a lot of the time as there is less motivation to answer them.

A: In Podcasts #26 and #34, Joel and Jeff talked about this. They didn't want a bounty to interfere with the 'normal' method of asking/answering questions. If you're allowed to offer it right away, then it has the potential to create an economy where people only focus on questions with bounties.
It's important to note that it's very rare (over 90% of questions are answered) for your question not to be answered. As far as getting it answered quickly, well that depends on what time you ask your question (All times UTC).

A: I'm for cutting the necessary waiting period for a bounty in half. 48 hours is too long.

A: Because you then get even more questions like https://superuser.com/questions/12442/where-i-can-get-free-cd-dvd-of-any-linux-distribution
I mean really? was the 100 rep bounty even necessary?

*

*First, there's enough Linux love around there that it will get answered in short order.

*Second, is teh Google failing you that bad?

Its because there aren't enough people to intelligently use the feature that it shouldn't get implemented as you suggest. I'm probably one of the few who think that while the bounty thing was a good idea on paper, human nature just kinda makes it not work right. (still on the first cup of coffee - for a more detailed and coherent answer see my answer to one of the initial bounty questions - or it might have been the blog post.)
That said, I've not seen many questions that don't get answers in the first 6-12 hours. The few that don't tend to be esoteric, or very technology specific, and in any case wouldn't significantly benefit from the bounty - except to attract people trying to post something to at least score the default position.

A: I don't ask many questions (3 in 7 months); I mostly answer them.  That said, the reasons George (posting for the SO team) outlines are IMHO garbage.
Regarding people focusing only on bounties.  All you have to do is look at the current list of bounty questions to know that's bollocks.  There are a lot of bounty questions, there are also a lot of non-bounty questions.  People answer both now, why would they change?  Answer: they wouldn't.
Also, the graph shown doesn't really matter. So what if most questions are answered during those time periods.  So what if most questions are answered within an hour or two of posting?
At the time of this writing I have over 40k of rep.  Once I passed the 10k mark, there apparently is zero Rep related reason to keep answering questions.  I do so simply because I like to help others; which I was doing anyway.
I'd love to put this into use.
How about having the MINIMUM bounty start at something like 1000 rep points.  Every hour that goes by drop it by 20 points until 48 hours is up.  This would certainly limit the number of people even willing to consider making an immediate bounty; unless it was critical to them.

One additional thing: George mentioned that 90% of questions get answered.  Which is great; however I believe that 90% of questions out there are fairly simple ones.  It's the hard ones that don't get answered.  The hard questions generally involve a little more research plus domain knowledge.  That should be worth something.
For example, if I have a question about an issue that is a high priority to me which may involve a responder writing code to solve then I would like to be able to reward them quickly on it.   I know I've certainly had problems that if a solution was available within an hour then it would have been worth 2000+ rep points to me.  In short, I'd rather trade rep points to get difficult problems solved faster than expending real cash on my own research time.

A: Perhaps something could be worked here so that the you could offer an initial bounty, but they would be featured differently, it wouldn't affect their front page rating and the site wouldn't match the bounty points, something like that. I agree you've earned the points and it would be nice if you could "put that to work", but I also understand what I think (from memory here) was Joel's point that you wouldn't want the site to become people camping for questions with bounty points, so I don't think it should be overly encourage. Maybe even the person could incur a penalty. I think the key if the feature was added would be to disinsentivise it to the point that it would be used sparingly.

A: There is another issue here... IIRC, some of the voting options are disabled for posts with bounty - which has potential for abuse (although I believe ♦ moderators can still kill it if needed).
OK, in reality even under the current process somebody could radically edit their original post just before adding bounty, but it would be an obvious abuse, making it much easier for us to justify hitting delete.
However; I can easily imagine "what is your favourite pet's name for programming?" with a +50 bounty to prevent regular voting.

A: I'm in favor of being able to offer a bounty from the start. I think this will yield more quality answers.

A:
I have 3,000 points at my disposal so I'd like to just put a bounty on
  the question as soon as I post it to give it the highest possible
  chance of being seen. Why do I have to wait?

Why should you get to give your question "the highest possible chance of being seen" right away? Does your 3K reputation make you more important than users with lower rep? You shouldn't think of the rep you've accumulated as currency that you can use to buy a better position for your questions.
The right way to draw attention to your question is to spend some time writing a question that's clear, concise, and well-researched. High quality questions get voted up, which raises their visibility, improves your chance of getting solid answers, and increases your reputation all at the same time.
Bounties are fine for giving an extra incentive for people to spend time to help you find an answer to a difficult or obscure question, but only after time has shown that extra incentive is required.

A: I'm going to pull something that RLH said earlier in a comment out into an answer, because I think it deserves notice.  Let immediate bounties happen, but put some sort of an overhead on it - enough so that the bounty transaction itself is a net rep consumer.  (Say, twice as many points for the bounty as it's worth, minimum bounty of 100).  If you wait the two days, you can go under standard bounty rules.  This has the following effects.

*

*Immediate bounties are inherently costly.  They're going to take at least 200 points to throw out there.  The effectiveness is much higher if you wait.  Also, even being able to afford one in the first place indicates that you've been around for a little while, and have hopefully picked up a bit on how to write a good question.  Possibly set a higher initial rep threshold (500, say?  1000?) to be more certain of that.  Even if we don't open up standard close procedures, I'd think that a 1000+ point user blowing 200 points inefficiently for an immediate answer to a bad question would be rare enough we could afford a bit of mod time for it.

*It won't break the rep economy, since swapping immediate bounties inherently takes rep out of the system.  Anyone who wants to do it and keep doing it is going to have to generate a fair bit more rep than they're handing out.

*It will allow a case where a moderately high-rep user who needs an answer to a high-complexity problem immediately can pay for one.  It gives a certain class of experts a serious motivation to build rep - because they might want or need an immediate answer (or two, or three) some day.  Personally, I fit into that group.  I'd wince a bit at throwing 200 to 400 points at a problem, but there are times where I cannot afford to wait the two days.
...and in response to those who say "well, just hire a consultant" or suggest that we go to pay sites, it's not that simple.  First, I honestly don't trust the resources at pay sites as much as I do the resources here.  I know SO and use it frequently.  I don't know the other sites.  Second, I do not have money to spend elsewhere.  I can build rep here, and then spend it just fine, but as soon a actual cash comes into the equation, the situation becomes far more complicated.  Third, if it's a problem that's confusing and finicky enough that I can't figure it out after a bunch of poking at it, asking my coworkers, and a thorough web search or two, I feel like it would be better to have the answer out there - make life easier for the next coder who tries that web search.

A: There is a problem with this SO. If a question isn't answered in the first few hours, then it goes way behind in list of question ie making it almost unseeable through regular visits.
It also very unlikely that someone who knows the answer would search such a question.
I think SO can easily determine that 90% of the questions get answered in the first ~2hr or whatever it is, therefore having a bounty available after that period is over is a good idea. However with a 3 hour window, people would just say, let's wait just for 3 hrs and hopefully then the person would place a bounty so I think 24hrs would suffice. (12hrs is kinda ineffective because the person may be in a different timezone and it's also too early)


text:
Q: Complex SQL issues with mulitple lookup I have a complex sql need to solve, the idea is to determine the ADMIN_ID for a particular CUSTOMER_ID. The rule to determine the ADMIN_ID is as below:

*

*To determine the ADMIN_ID for a particular account, the system should query the
account from bottom up to the parent, and the first account with TXT01 is not null
it the parent.

*The ADMIN_ID is only applicable to CUSTOMER Group E.

*In case Top account have an absence of a TXT01, it should give a warning message

*Only CUSTOMER_ID = PAYING_ACCOUNT_ID need to analyze
Account Table
CUSTOMER_ID       PAYING_ACCOUNT_ID         PARENT_ACCOUNT_ID
3271516           3271516                   719216
1819276           1819276                   810546
719216            719216                    719216
810546            810546                    810547
810547            810547                    810547
999999            111111                    111111
111111            111111                    111111
123456            123456                    231
231               231                       231

Customer Table
CUSTOMER_ID         TXT01
719216              TOM
810546              NULL
810547              JIM
3271516             NULL
1819276             NULL
999999              NULL
111111              BEN
123456              NULL
231                 NULL

Customer Group
CUSTOMER_ID         GROUP
719216              E
810546              E
810547              E
3271516             E
1819276             E
999999              E
111111              E
123456              E
231                 E
888                 A

Output
CUSTOMER_ID       PAYING_ACCOUNT_ID        PARENT_ACCOUNT_ID        ADMIN_ID
3271516           3271516                    719216                  TOM
1819276           1819276                    810546                  JIM
719216            719216                     719216                  TOM
810546            810546                     810547                  JIM
810547            810547                     810547                  JIM
111111            111111                     111111                  BEN
123456            123456                     231                     Warning!!
231               231                        532                     Warning!!

DDL
CREATE TABLE ACCOUNT (CUSTOMER_ID NUMBER(20) NOT NULL,
PAYING_ACCOUNT_ID NUMBER(20),
PARENT_ACCOUNT_ID NUMBER(20));

CREATE TABLE CUSTOMER (CUSTOMER_ID NUMBER(20) NOT NULL,
TXT01 VARCHAR2(20));

CREATE TABLE CUSTOMER_GROUP (CUSTOMER_ID NUMBER(20) NOT NULL,
GROUP VARCHAR2(20));

INSERT INTO ACCOUNT VALUES (3271516,3271516,719216);
INSERT INTO ACCOUNT VALUES (1819276,1819276,810546);
INSERT INTO ACCOUNT VALUES (719216,719216,719216);
INSERT INTO ACCOUNT VALUES (810546,810546,810547);
INSERT INTO ACCOUNT VALUES (810547,810547,810547);
INSERT INTO ACCOUNT VALUES (999999,111111,111111);
INSERT INTO ACCOUNT VALUES (111111,111111,111111);
INSERT INTO ACCOUNT VALUES (123456,123456,231);
INSERT INTO ACCOUNT VALUES (231,231,231);
INSERT INTO CUSTOMER VALUES (719216,'TOM');
INSERT INTO CUSTOMER VALUES (810546,NULL);
INSERT INTO CUSTOMER VALUES (810547,'JIM');
INSERT INTO CUSTOMER VALUES (3271516,NULL);
INSERT INTO CUSTOMER VALUES (1819276,NULL);
INSERT INTO CUSTOMER VALUES (999999,NULL);
INSERT INTO CUSTOMER VALUES (111111,'BEN');
INSERT INTO CUSTOMER VALUES (123456,NULL);
INSERT INTO CUSTOMER VALUES (231,NULL);
INSERT INTO CUSTOMER_GROUP VALUES (719216,'E');
INSERT INTO CUSTOMER_GROUP VALUES (810546,E);
INSERT INTO CUSTOMER_GROUP VALUES (810547,'E');
INSERT INTO CUSTOMER_GROUP VALUES (3271516,'E');
INSERT INTO CUSTOMER_GROUP VALUES (1819276,'E');
INSERT INTO CUSTOMER_GROUP VALUES (999999,'E');
INSERT INTO CUSTOMER_GROUP VALUES (111111,'E');
INSERT INTO CUSTOMER_GROUP VALUES (123456,'E');
INSERT INTO CUSTOMER_GROUP VALUES (231,'E');
INSERT INTO CUSTOMER_GROUP VALUES (888,'A');

This is my code..still doing but stuck in some point. Appreciate guru here can gv me a hand
WITH myData AS (
SELECT CUSTOMER_ID, TXT01 FROM CUSTOMER WHERE CUSTOMER_ID IN
(SELECT CUSTOMER_ID from CUSTOMER_GROUP WHERE GROUP = 'E')
)
SELECT v.*
FROM
(SELECT m.* ,
CASE WHEN TXT01 IS NOT NULL THEN TXT01
ELSE ( *STUCK HERE*
END ADMIN_ID
FROM myData m) v

A: SELECT
C.CUSTOMER_ID, nvl(a.TXT01, 'warning!')
FROM CUSTOMER c
   JOIN CUSTOMER_GROUP cg ON (cg.customer_id = c.customer_id and cg.group = 'E')
   JOIN ACCOUNT a ON (a.customer_id = c.customer_id)
WHERE c.CUSTOMER_ID = a.PAYING_ACCOUNT_ID

A: Try this
with acc_hierarchy as
 (select level lev, ac.*, connect_by_root(ac.paying_account_id) account_id
    from account ac
  connect by prior ac.parent_account_id = ac.paying_account_id
         and prior ac.paying_account_id <> prior ac.parent_account_id),
acc_customers as
 (select ah.account_id, min(c.txt01) keep(dense_rank first order by ah.lev) admin_id
    from acc_hierarchy ah
    left join (select cus.customer_id, cus.txt01
                from customer cus
                join customer_group cg
                  on cg.customer_id = cus.customer_id
                 and cg."GROUP" = 'E') c
      on c.customer_id = ah.customer_id
   where c.txt01 is not null
   group by ah.account_id)
select a.customer_id, a.paying_account_id, a.parent_account_id, NVL(ac.admin_id, 'Warning!!') admin_id
  from account a
  left join acc_customers ac
    on ac.account_id = a.paying_account_id
 where a.customer_id = a.paying_account_id
;

Here are my results:
SQL> with acc_hierarchy as
  2   (select level lev, ac.*, connect_by_root(ac.paying_account_id) account_id
  3      from account ac
  4    connect by prior ac.parent_account_id = ac.paying_account_id
  5           and prior ac.paying_account_id <> prior ac.parent_account_id),
  6  acc_customers as
  7   (select ah.account_id, min(c.txt01) keep(dense_rank first order by ah.lev) admin_id
  8      from acc_hierarchy ah
  9      left join (select cus.customer_id, cus.txt01
 10                  from customer cus
 11                  join customer_group cg
 12                    on cg.customer_id = cus.customer_id
 13                   and cg."GROUP" = 'E') c
 14        on c.customer_id = ah.customer_id
 15     where c.txt01 is not null
 16     group by ah.account_id)
 17  select a.customer_id, a.paying_account_id, a.parent_account_id, NVL(ac.admin_id, 'Warning!!') admin_id
 18    from account a
 19    left join acc_customers ac
 20      on ac.account_id = a.paying_account_id
 21   where a.customer_id = a.paying_account_id;

CUSTOMER_ID PAYING_ACCOUNT_ID PARENT_ACCOUNT_ID ADMIN_ID
----------- ----------------- ----------------- --------------------
    3271516           3271516            719216 TOM
    1819276           1819276            810546 JIM
     719216            719216            719216 TOM
     810546            810546            810547 JIM
     810547            810547            810547 JIM
     111111            111111            111111 BEN
     123456            123456               231 Warning!!
        231               231               231 Warning!!

8 rows selected.


text:
Q: ansible jinja template hostvars can not get ansible_host I am trying to iterate over hostvars in an ansible playbook and it appears to be working just fine to several hostvars, except the one I need: ansible_host
If I try:
{% for host in groups['all'] %}
  server {{ host }} {{ hostvars[host] }}
{% endfor %}

It outputs this for each server:
server server2 {'ansible_verbosity': 0,, '...  'ansible_check_mode': False, 'ansible_run_tags': [u'all'], 'ansible_skip_tags': [], u'ansible_host': u'10.192.11.17', 'ansible_version': {'major': 2, 'full': '2.9.11', 'string': '2.9.11', 'minor': 9, 'revision': 11}}
Which holds all vars.
Now If I try
{% for host in groups['all'] %}
  server {{ host }} {{ hostvars[host]['verbosity'] }}
{% endfor %}

it will get me the ansible_verbosity just fine. But I can not find a way to get the ansible_host
{% for host in groups['all'] %}
  server {{ host }} {{ hostvars[host]['ansible_host'] }}
{% endfor %}

I think the problem maybe related to the fact ansible_host is a unicode var ( u'ansible_host' ). I say that because the other 2 unicode vars fails with the same problem while all the others work just fine.
Any idea how to get that var?

A: Q: "hostvars can not get ansible_host"
A: ansible_host is not included in hostvars if it is not explicitly declared. ansible_host is a Connection variable. It is used, for example, as a parameter of the ssh connection plugin (see ansible-doc -t connection ssh). It is needed if inventory_hostname does not resolve. Very probably, any of your hosts don't have an ansible_host explicitly set. This is causing the problem. If ansible_host is not explicitly declared its value is set to inventory_hostname.
For example
shell > grep test_11 hosts
test_11

- hosts: test_11
  tasks:
    - debug:
        var: hostvars[inventory_hostname]['ansible_host']
    - debug:
        var: ansible_host

gives
TASK [debug] *************************************************************
ok: [test_11] =>
  hostvars[inventory_hostname]['ansible_host']: VARIABLE IS NOT DEFINED!

TASK [debug] *************************************************************
ok: [test_11] =>
  ansible_host: test_11

If you declare ansible_host, for example, in the inventory
shell > grep test_11 hosts
test_11 ansible_host=10.1.0.61

the same playbook gives
TASK [debug] *************************************************************
ok: [test_11] =>
  hostvars[inventory_hostname]['ansible_host']: 10.1.0.61

TASK [debug] *************************************************************
ok: [test_11] =>
  ansible_host: 10.1.0.61

*

*See Inventory aliases

*Quoting Connection variables

ansible_host: The ip/name of the target host to use instead of inventory_hostname.

*

*See also What's the difference between inventory_hostname and ansible_hostname

A quick solution to the problem might be defaulting to inventory_hostname, assuming ansible_host is not needed, i.e. inventory_hostname resolves. For example
{% for host in groups['all'] %}
  server {{ host }} {{ hostvars[host]['ansible_host']|default(host) }}
{% endfor %}


text:
Q: Substracting number from list not raising TypeError If I do
a = [1, 2, 7]
a - a[-1]

I get TypeError: unsupported operand type(s) for -: 'list' and 'int'
However, I have a list b made of np.float64, and the following code works:
type(b)
# list
b - b[-1]
# array([ 281.04209146,    6.57013103,    0.        ])

I think this is because the numbers in b are np.float64, and b is somewhat cast to np.array, then broadcasting happens.
But I still found this behavior surprising: since all elements in a list do not need to have the same type, what if b[0] had been a string ? The operands in  b - b[-1] would still have been list and np.float64, so why is b - b[-1] not raising a TypeError?
EDIT: Someone answered saying that list and np.array are different; well, I know. But there b is not a np.array. It is behaving like one, but its type is list, like I've stated in the code snippet.
Here's a minimal working example for b:
b
# [1598.717274996219, 1324.245314569733, 1317.6751835362861]
type(b[0])
# numpy.float64

A: In an expression like A-B, the interpreter can either implement it as A.__sub__(B) or B.__rsub__(A).
Lists implement mul and add but not sub
In [29]: [1,2,3]*3
Out[29]: [1, 2, 3, 1, 2, 3, 1, 2, 3]
In [30]: [1,2,3]+[1]
Out[30]: [1, 2, 3, 1]
In [31]: [1,2,3]-3
TypeError: unsupported operand type(s) for -: 'list' and 'int'

np.ndarray implements a __rsub__
In [32]: [1,2,3]-np.array([1,2,3])
Out[32]: array([0, 0, 0])
# np.array([1,2,3]).__rsub__([1,2,3])

And that method tries to turn the LHS into an array, so this expression is the same as:
In [33]: np.asarray([1,2,3]) - np.array([1,2,3])
Out[33]: array([0, 0, 0])

If the list contains strings, this fails:
In [35]: ['a',2,3]-np.array([1,2,3])
TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U11') dtype('<U11') dtype('<U11')

because that list becomes an array of strings:
In [36]: np.asarray(['a',2,3])
Out[36]:
array(['a', '2', '3'],
      dtype='<U1')

and array subtraction with string dtype is not implemented.
All that I wrote with the array RHS applies if it is np.float64.  np.float64(10) behaves (in most contexts) the same as np.array(10.0).
So all these subtractions with b are the same:
 b = [np.float64(10), np.float64(1)]
 b - b[-1]
 b - np.float64(1)
 b - np.array(1.0)
 np.array(b) - np.array(1.0)

In sum, if the RHS is some sort of array, it turns the LHS list into an array as well.  From there it's a question of whether the 2 arrays are compatible (in shape and dtype).

A: You don't get the same TypeError when you make b[0] a string though.
b=[np.float_(a_) for a_ in a]

b
Out[4]: [1.0, 2.0, 7.0]

b-b[-1]
Out[5]: array([-6., -5.,  0.])

b[0]='a'

b
Out[7]: ['a', 2.0, 7.0]

b-b[-1]
Traceback (most recent call last):

  File "<#>", line 1, in <module>
    b-b[-1]

TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

You get a TypeError for mismatching types in subtract.  In the original, when you get a np.float64 for b[-1], it casts the whole expression to numpy arrays.  So if b[-1] is a string:
b[2]='a'

b-b[-1]
Traceback (most recent call last):

  File "<#>", line 1, in <module>
    b-b[-1]

TypeError: unsupported operand type(s) for -: 'list' and 'str'

you're back to the original TypeError.


text:
Q: MVC ScriptManager XHTML Transitional Doctype validation error The server side team are using the following MVC ScriptManager in my current project
:
http://mvcscriptmanager.codeplex.com/
It is causing a small validation error whereby the generated, concatenated script does not output the type="text/JavaScript" attribute.
It's no big deal but i was wondering how i can make this ScriptManager output valid XHTML in this instance.

A: the server side developers fixed this issue by updating the ScriptManager itself.


text:
Q: Find non convergent Cauchy sequence Let $B$ be the set of all bounded real sequences. Prove that $(B,\rho)$, where  $\rho(x,y):=\sup_{n}\dfrac{|x_n-y_n|}{n}$ is a non complete metric space.
I could show that this is a metric space and I also know that with the metric $d(x,y):=\sup_{n}|x_n-y_n|$ this space is complete. How do I prove that it is not complete with $\rho$?

A: The intuition you should have here is that the metric $\rho$ reduces the information you have about the tails of the sequences you're looking at so we should try to make something bad happen there.
For $k \leq n$, let $x_k^{(n)} = k^{1/2}$ and otherwise let $x_k^{(n)} = 0$. So then, for fixed $n$, $x^{(n)} \in B$. It is straightforward to show that $(x^{(n)})_{n \geq 1}$ is a Cauchy sequence for $\rho$ (in fact, this is why I chose something like $k^{1/2}$).  I claim that $x^{(n)}$ does not converge in $(B, \rho)$ as $n \to \infty$.
To see this, first notice that if $\rho(x^{(n)}, x) \to 0$ then in particular, for each fixed $k$, $x_k^{(n)} \to x_k$. As a result, if $x^{(n)} \to x$ in $(B, \rho)$ then we must have $x = (1, 2^{1/2}, 3^{1/2}, 4^{1/2}, \dots)$. But this is not a bounded sequence and hence doesn't lie in $B$, giving us a contradiction.


text:
Q: How do I give a group 'service httpd graceful' permission in sudoers without passwd prompt? I'm currently trying to lock down my users a bit. I've created some users:

*

*www.foo

*www.bar
and a group:

*

*apacheadmins
Both www.foo, and www.bar are members of the apacheadmins group. They do not currently have sudo access, but I would like to grant them sudo access for:

*

*service httpd configcheck

*service httpd restart

*service httpd graceful
I've added the following lines, using visudo at the very bottom of the sudoers file:
### Setting permissions for www.* users
Cmnd_Alias APACHECMDS = /sbin/service httpd configcheck, /sbin/service httpd graceful, /sbin/service httpd restart
%apacheusers ALL = NOPASSWD: APACHECMDS

I would like these users to be able to use these commands without password prompt, but they have key only access, and don't currently have passwords assigned to them.
Whenever I save my changes, open a new bash session as www.foo or www.bar, I am still greeted with a password prompt.
I've played with it a bit, and I can get it to work if I specify the full path, ie:
sudo service httpd graceful does not work.
sudo /sbin/service httpd graceful does work.
Can I get this to work without specifying the full path?
EDIT: I'm using:
[foo@bar~]$ uname -a
Linux bar 2.6.18-164.el5 #1 SMP Thu Sep 3 03:28:30 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
[foo@bar~]$ cat /etc/redhat-release
CentOS release 5.4 (Final)

A: The problem is that the users' $PATH variable doesn't include /sbin, and so sudo isn't actually finding the command.
$ sudo service acpid status
[sudo] password for mgorven:
$ sudo /sbin/service acpid status
acpid (pid 3185) is running...
$ echo $PATH
/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
$ export PATH=$PATH:/sbin:/usr/sbin
$ sudo service acpid status
acpid (pid 3185) is running...

Add /sbin to the users' $PATH to solve this.


text:
Q: Android ImageView Overlay textview in given area I am trying to build a custom View such that it has image and certain area of the image where I need to have a text. For example draw map of a country and overlay certain region like "East", "West" and have text overlay on the given region.
The reason I want it to be custom view is so that Image can be scaled in different size screens and image is placed in appropriate place.
Similar to Image Map:
I found multiple ways,
Android: how to make a clickable map image with each country producing a different action?
http://catchthecows.com/?p=113
Any other simpler solution?

A: Place the map and the textview inside a RelativeLayout and the textview will appear to be overlayed on the map. You can then adjust the position of the textview programmatically.


text:
Q: i hava two spinner in my application how to reload the selected spinner items repeate selected spinner items like first i selcted A and B it  displays AB second time selct BA i want to display AB and BA one below another
sp_spinner_a=(Spinner)findViewById(R.id.sp_spinner_a);
        sp_spinner_b=(Spinner)findViewById(R.id.sp_spinner_b);

        lay2=(LinearLayout)findViewById(R.id.lay2);
        lay5=(LinearLayout)findViewById(R.id.lay5);
        sp_spinner_a.setOnItemSelectedListener(this);
        sp_spinner_b.setOnItemSelectedListener(this);
          // Spinner Drop down elements
        String[] AgeArr = {"SELECT", "A", "B"};
         String[] iiemsArr = {"SELECT", "a", "b"};

          ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, AgeArr);

          // Drop down layout style - list view with radio button
          dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

          // attaching data adapter to spinner
          sp_spinner_a.setAdapter(dataAdapter);

          ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, iiemsArr);

          // Drop down layout style - list view with radio button
          dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

          // attaching data adapter to spinner
          sp_spinner_b.setAdapter(dataAdapter1);

    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub
    String isChecking=(String) sp_spinner_a.getSelectedItem();
    String isCheckingb=(String) sp_spinner_b.getSelectedItem();

    if(isChecking.equals("SELECT")){
        lay2.setVisibility(View.GONE);
        lay5.setVisibility(View.GONE);

    }else{
        lay2.setVisibility(View.VISIBLE);
    }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


text:
Q: Simulating RemoteOnly custom errors using Application_Error ASP.NET I handle my errors using Application_Error in global.asax.
How to check if the request is from the local client to display more information about the error or just show the yellow error page. Something like "remoteOnly" that ASP does when handling errors using web.config.

A: After I posted the question, I went back to my application and played around a little bit then I found this. Now I'm using it.
    void Application_Error(object sender, EventArgs e)
    {

        if(!HttpContext.Current.Request.IsLocal)
            HttpContext.Current.Server.ClearError();

        // process error handling
    }


text:
Q: Not sure how to plot this, a scatter plot with categories I have the following dataset
SIZE ALG1 ALG2 ALG3
  A   2    3    5
  A   3    2    1
  A   1    2    2
  B   10  10    11
  B   12  12   12

I'd like a plot having as a horizontal axis the SIZE column and as Y values the series ALG1 ALG2 ALG3.
E.g.

How can I get it wit Excel (actually OOCALC) or R?
In general I get the SIZE values repeated on the x-axis, which appears then much longer.
TIA

A: In R you could do it as follows:
df <- data.frame(
   size = c(rep('A', 3), rep('B', 2)),
   alg1 = c(2,3,1,10,12),
   alg2 = c(3,2,2,10,12),
   alg3 = c(5,1,2,11,12)
   )

plot(alg1 ~ jitter(as.numeric(size)), data = df,
  xlim = c(0.5, 2.5), ylim = c(0, 14), col = 'red',
  axes = FALSE, xlab = 'Size', ylab = 'Alg')
points(alg2 ~ jitter(as.numeric(size)), data = df, col = 'blue')
points(alg3 ~ jitter(as.numeric(size)), data = df, col = 'black')
axis(side = 2)
axis(side = 1, at = c(1, 2), labels = c('A', 'B'))
legend(x = 2, y = 4, legend = c('alg1', 'alg2', 'alg3'),
  col = c('red', 'blue', 'black'), lty = 1)

A: Suppose your data frame is called df1.
You have to convert it in a long format using reshape2::melt
melt(df1) -> dfmelt

library(ggplot2)

ggplot(data=dfmelt, aes(x=SIZE, y=value)) + geom_jitter(aes(color=variable))

or, more simply and quickly:
qplot(data=dfmelt, x=SIZE, y=value, geom="jitter", color=variable)

If you just want the points without "jittering" them:
qplot(data=dfmelt, x=SIZE, y=value, geom="point", color=variable)


text:
Q: How to use the ToolButton clicked signal (in a HeaderBar)? While creating a simple ToolButton, one can use the clicked.connect interface as in the Toolbar example from the Vala guide. The interface of adding a button to a HeaderBar is similar to what is shown in that example. However, the way of handling the clicked connection seems to be different (or there is something that I am missing).
The following example is of a small text editor, where a open dialog button is packed into the HeaderBar. The clicked.connection syntax, however returns an error.
Here is the code:
[indent=4]
uses
    Gtk

init
    Gtk.init (ref args)

    var app = new Application ()
    app.show_all ()
    Gtk.main ()

// This class holds all the elements from the GUI
class Application : Gtk.Window

    _view:Gtk.TextView

    construct ()

        // Prepare Gtk.Window:
        this.window_position = Gtk.WindowPosition.CENTER
        this.destroy.connect (Gtk.main_quit)
        this.set_default_size (400, 400)

        // Headerbar definition
        headerbar:Gtk.HeaderBar = new Gtk.HeaderBar()
        headerbar.show_close_button = true
        headerbar.set_title("My text editor")

        // Headerbar buttons
        open_button:Gtk.ToolButton = new ToolButton.from_stock(Stock.OPEN)
        open_button.clicked.connect (openfile)

        // Add everything to the toolbar
        headerbar.pack_start (open_button)
        show_all ()
        this.set_titlebar(headerbar)

        // Box:
        box:Gtk.Box = new Gtk.Box (Gtk.Orientation.VERTICAL, 1)
        this.add (box)

        // A ScrolledWindow:
        scrolled:Gtk.ScrolledWindow = new Gtk.ScrolledWindow (null, null)
        box.pack_start (scrolled, true, true, 0)

        // The TextView:
        _view = new Gtk.TextView ()
        _view.set_wrap_mode (Gtk.WrapMode.WORD)
        _view.buffer.text = "Lorem Ipsum"
        scrolled.add (_view)

The open_button.clicked.connect returns at compilation:
text_editor-exercise_7_1.gs:134.32-134.39: error: Argument 1: Cannot convert from `Application.openfile' to `Gtk.ToolButton.clicked'
        open_button.clicked.connect (openfile)

Does the way of handling that signal changes when one uses the HeaderBar widget?
The code is working as long as the line is commented (you may want to add a stub for the openfile function).
Thanks
UPDATE
This question deserves an update, because the error was actually not in the body I attached above.
The error was at the definition of the function. I wrote:
    def openfile (self:Button)

When I should've instead:
    def openfile (self:ToolButton)

Or simply:
    def openfile ()

A: You didn't include the click handler in your code, using this example stub it works just fine:
def openfile ()
    warning ("Button clicked")

So I guess that the type signature of your click handler is wrong and that's why the compiler is complaining here.


text:
Q: Exclude the header files coverage while doing the unitests for .cpp files using lcov I have generated the html code coverage for unittest. The problem is that it generates the code coverage for everything that is defined in the include preprocessor.
The codecoverage for the unittest is inside the unitTest link of the code coverage report. I only need the unitTest
I also remove everything else and keep the gcda and gcno files of the test file before generating the code coverage but it still doesnot help. The code that does this is :
find obj/ ! -name '*_unittests*' -type f -delete

The code coverage report is show below :

I tried to add LCOV_EXCL_START and LCOV_EXCL_STOP at the beginning and end of include preprocessors as follows but it still doesnot help.
LCOV_EXCL_START
#include <inttypes.h>
#include "../src/generators/buffersss.h"
#include "gtest/gtest.h"
#include <getopt.h>
LCOV_EXCL_STOP
Test code goes here.....

What am i doing wrong here?

A: The following code solved the issue
lcov --remove coverage.info '/usr/include/*' 'src/*' -o filtered_coverage.info

A: For CMake users I strongly suggest using:
https://github.com/bilke/cmake-modules/blob/master/CodeCoverage.cmake
e.g. macro setup_target_for_coverage_lcov and its EXCLUDE parameter.


text:
Q: Adding custom commands to the publish process in a .net core web api app I'm publishing a .net core web API app in a macOS and Ubuntu environments. Other than the .net packages which are published smoothly in both cases I'm also trying to publish a custom dynamic library. The library is defined as Copy Always and it is indeed copied to the output folder as needed. But before copying it I would like to recompile it by running a custom make command using a pre-existing Makefile. The Makefile is generic and works in both environments, creating a 'shared library' in Ubuntu and a 'dylib' file in macOS.
I edited the pre-build custom commands in visual studio and I'm able to recompile the library with every build but I can't replicate this behavior to the dotnet publish command. Is there any way to add custom commands to the dotnet publish process?


text:
Q: Intersection of open sets?
(a) Show that the intersection of finitely many open sets is open
(b) Give an example showing that the intersection of infinitely many open sets
may fail to be open.

(a)

*

*An open set is defined as having all its points' $\epsilon$-neighborhood contained inside.

*Assuming The intersection of finitely many open set $O_1,O_2,...,O_k$ is non-null, we have at least a point $x$ such that $x \in \bigcap_{k=1}^{n} O_k$.

*By definition, this point $x$ has $\epsilon$-neighborhood contained in each set $O_1,O_2,...,O_k$ .

*However, the magnitude of each $\epsilon$-neighborhood of $x$ contained in each set is specific to each set.

*Among all the  $\epsilon$-neighborhood magnitude of $x$ contained specifically in each open-set {$\epsilon$_1,$\epsilon$_2,...,$\epsilon$_n},

*Only the $\epsilon$ with the minimal magnitude will be contained by all the set and therefore by the intersection.

(b) I do not see here how the intersection of infinitely many open could fail to be open.
Regarding (a) Is the reasoning correct or sufficient? If this is correct, what would be a more efficient approach?
Any input for (a) or (b) is much appreciated.

A: Consider the sets $(-1/n,1/n)$. Their intersection is $\{0\}$.

A: Your reasoning for $(a)$ is correct, but lets look at it more closesly:
For each $i$ with $1\le i \le n$ we can find $\varepsilon_i$ such that $B_{\varepsilon_i}(x)\subset O_i$. Now, since the $\varepsilon_i$ are finitely many, then we can pick $\delta>0$ such that $\delta <\varepsilon_i$ for all $i$. Therefore, $B_\delta(x)\subset B_{\varepsilon_i}(x)\subset O_i$ for every $i$ and hence $B_\delta(x)\subset \bigcap_{i=1}^n O_i$.
The key is that the infimum among the $\varepsilon_i$ is $>0$ because we are considering finitely many positive numbers. Note that this fails for infinite sets of numbers, for example
$$\inf\{ 1/n: n\in\mathbb{Z}^+\}=0$$
With this in mind, it is not difficult to show that
$$\bigcap_{n=1}^\infty (-1/n,1/n)=\{0\}$$
which is not open, and answers (b).


text:
Q: Create spark dataframe from arbitrary length csv column I'm trying to create a new dataframe from a single csv formatted column in my dataframe. I don't know the schema ahead of time so am trying to use the spark.createDataFrame method without the schema parameter (similar to method 1 in this example)
I'm trying code such as the following, but getting exceptions thrown:
var csvrdd = df.select(df("Body").cast("string")).rdd.map{x:Row => x.getAs[String](0)}.map(x => x.split(",").toSeq)
var dfWithoutSchema = spark.createDataFrame(csvrdd)

Error:
error: overloaded method value createDataFrame with alternatives:
  [A <: Product](data: Seq[A])(implicit evidence$3: reflect.runtime.universe.TypeTag[A])org.apache.spark.sql.DataFrame <and>
  [A <: Product](rdd: org.apache.spark.rdd.RDD[A])(implicit evidence$2: reflect.runtime.universe.TypeTag[A])org.apache.spark.sql.DataFrame
 cannot be applied to (org.apache.spark.rdd.RDD[Seq[String]])
       var dfWithoutSchema = spark.createDataFrame(csvrdd)

A: First, the cause for the failure can be seen clearly in the signature of createDataFrame:
def createDataFrame[A <: Product : TypeTag](rdd: RDD[A]): DataFrame

The type A is bounded to be a subclass of scala.Product. Your RDD contains Array[String] which is not such a subclass. If you really want to, you can artificially  wrap the array in a Tuple1 (which extends Product) and get this to work:
val csvrdd: RDD[Tuple1[Array[String]]] = df
  .select(df("Body").cast("string"))
  .rdd
  .map{ x:Row => x.getAs[String](0)}
  .map(x => Tuple1(x.split(","))) // wrapping with a Tuple1, which extends scala.Product

val dfWithoutSchema = spark.createDataFrame(csvrdd) // now this overload works

dfWithoutSchema.printSchema()
// root
// |-- _1: array (nullable = true)
// |    |-- element: string (containsNull = true)

However - this doesn't seem too useful. This will create a DataFrame with a single column of type ArrayType. This can be achieved with the much simpler split function from org.apache.spark.sql.functions:
val withArray = df.select(split(df("Body").cast("string"), ",") as "arr")

withArray.printSchema()
// root
//  |-- arr: array (nullable = true)
//  |    |-- element: string (containsNull = true)

Alternatively, if what you wish to obtain is a DataFrame with separate columns for each of the "CSV columns", you'd have to "decide" on a common schema for all records (not all records are known to have the same amount of "CSV parts"). You can do that by adding another scan of the DataFrame and calculating the maximum number of required columns, then let Spark "fill in the blanks" with nulls where the actual value contained less parts:
// first - split String into array of Strings
val withArray = df.select(split(df("Body").cast("string"), ",") as "arr")

// optional - calculate the *maximum* number of columns;
// If you know it to begin with (e.g. "CSV cannot exceed X columns") -
// you can skip this and use that known value
val maxLength: Int = withArray.select(size($"arr") as "size")
  .groupBy().max("size")
  .first().getAs[Int](0)

// Create the individual columns, with nulls where the arrays were shorted than maxLength
val columns = (0 until maxLength).map(i => $"arr".getItem(i) as s"col$i")

// select these columns
val result = withArray.select(columns: _*)

result.printSchema() // in my example, maxLength = 4
// root
//  |-- col0: string (nullable = true)
//  |-- col1: string (nullable = true)
//  |-- col2: string (nullable = true)
//  |-- col3: string (nullable = true)


text:
Q: Getting properties in under test Service class by @Value returns null I have a Spring Boot version 2.7.0 project with different profiles for dev and test with two different properties files: application-dev.properties and application-test.properties. (I have NO default application.properties file.)
In under test service class I have a property that I want to load its value from application-test.properties file. The service class:
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    @Value("${files.root-directory}")
    private String fileDirectory;

    @Override
    @Transactional(readOnly = false)
    public File createFile(CreateFileCommand command) {
        var filePath = FileUtil.getPath(fileDirectory); // <- fileDirectory is null in tests
        // ....
    }
}

When I run the application in dev profile, everything is OK. But in tests, fileDirectory is always null.
Test class:
@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(MockitoExtension.class)
public class FileServiceTest {
    // ...
}

ApplicationTest class:
@SpringBootTest
@ActiveProfiles("test")
@TestPropertySource("classpath:application-test.properties")
@EnableConfigurationProperties
class ApiApplicationTests {

    @Test
    void contextLoads() {
    }
}

application-dev.properties file:
files.root-directory=${user.home}\\api\\files

application-dev.properties file:
files.root-directory=/home/api/var/api/files

EDIT Screenshot of file structure

A: Put your properties file under src/test/resources  for your (JUnit,Integration, Contract etc) test files. That should work!
Property files under src/main/resources are accessible to source files present under src/main/ only!


text:
Q: How to calculate two-way mixed ICC? I want to calculate ICC for two-way mixed model, single rater, and either for consistency and absolute agreement. I found two packages for calculating ICC (intra-class correlation coefficient), that is, "irr" and "psych". However, from their argument description, I cannot sure that whether they are suitable for the use. I'll describe my concerns as following.

If they are indeed not suitable, hope you can recommend package or
provide some work example or steps for this use case.

"irr" package: icc
The "irr" package, it provides detailed argument for user to customize their situation, includes model, type and units, which is all parameters we need for selecting correct ICC form [ref]. However, I'm not sure whether this is a suitable package for the mixed model, that is, when judges are fixed and NOT randomly selected, since it only describe the use of "random effect" in the document

model:a character string specifying if a '"oneway"' model (default) with row effects random, or a '"twoway"' model with column and row effects random should be applied.

"psych" package: ICC
This is rather a simpler function, what we only need to do is input our data and it'll shows kinds of report under different ICC parameters. However, though this time it clearly tell that "ICC3" is for "fixed set of k judges" (i.e. two-way mixed model) and report both results for single and mean of k raters, I'm not sure whether the result comes from "consistency" or "absolute agreement".

A: From the "psych" package documentation, under the ICC section, I found this:

As M&W say "The importance of the random-fixed effects distinction is in its effect on the interpretation, but not calculation, of an ICC. Namely, when levels of the column factor are randomly sampled, one can generalize beyond one's data, but not when they are fixed. In either case, however,the value of the ICC is the same," (p 37)

So, you can use the results from the "irr" package to report absolute agreement in a two way mixed model(as the "psych" package returns consistency for the two way mixed model). You would only need to mention that the raters were not randomly sampled but were fixed.
I used both packages to check ICC on some of my data and present the results below. You will find that the icc value and 95% CI are similar for a two way model with absolute agreement based on a single rater in both packages (randomised effects for "irr" and ICC3 for "psych")
"irr" results

Subjects = 119; Raters = 2; ICC(A,1) = 0.942

F-Test, H0: r0 = 0 ; H1: r0 > 0
F(118,87.8) = 35.2 , p = 5.55e-46

95%-Confidence Interval for ICC Population Values:
0.914 < ICC < 0.96

"psych" results

Single fixed raters (ICC3): ICC value (0.94); 95% CI (0.92- 0.96)


text:
Q: Reading lists from a low level in app.config file I want to read a list of values from the app.config xml file. Here is an example app.config file :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>
  <appSettings>
    <add key="test" value="testoutput" />
  </appSettings>
  <references>
    <firstLevel>
      <ref name="first1"></ref>
      <ref name="first2"></ref>
      <ref name="first3"></ref>
    </firstLevel>
    <secondLevel>
      <ref name="second"></ref>
    </secondLevel>
    <thirdLevel>
      <ref name="third"></ref>
    </thirdLevel>
  </references>
</configuration>

I can get the app settings part. I would like to get the 'ref' tags and put them in a list. For example, configuration/references/firstlevel. I would like to loop through all of its children and put each name into a list.
So the list would be ["first1", "first2", "first3"]

A: All required documentation how to create custom configuration sections is listed
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx


text:
Q: Using Angular values in a pie chart I have length values derived from a table using ng-repeat.  I would like to use these values in a pie chart but can't figure out how to do so.  Here are my values:

    PM Alert Green

        {{pmalert.pmAlert}}

    PM Alert

        {{pmalert.pmAlert}}

PM Alert Filtered: {{pmalertcount.length}}

PM Alert Filtered: {{pmalertcountgreen.length -1}}

Here is the pie chart I would like to use:
angular.module('plunker', ['angularCharts']);

function PiechartCtrl($scope) {
  $scope.config = {
title: 'Site Phases:',
tooltips: true,
labels: true,
mouseover: function() {},
mouseout: function() {},
click: function() {},
legend: {
  display: false,
  //could be 'left, right'
  position: 'right'
}
  };

  $scope.data = {
series: ['Sales', 'Income', 'Expense', 'Laptops', 'Keyboards'],
data: [{
  x: "",
  y: [100],
  tooltip: "Pre-Submittal"
}, {
  x: "Zoning",
  y: [500],
  tooltip: "In Zoning"
}, {
  x: "Building",
  y: [200],
  tooltip: "In Building"
}, {
  x: "Construction",
  y: [54],
  tooltip: "In Construction"
}]
};
}

Here is the HTML part:

or please let me know if there is a better way of doing this.  Thank you.


text:
Q: `auto` specifier type deduction for references Let's consider the following code snippet
void Test()
  {
  int x = 0;

  int& rx = x;
  int* px = &x;

  auto apx = px;    // deduced type is int*
  auto arx = rx;    // deduced type is int
  }

One could draw an analogy from pointer types expecting that the deduced type of arx is int&, but it is int in fact.
What is the rule in Standard which governs that? What is the reason behind it?
Sometimes I get caught by it in a case like this:
const BigClass& GetBigClass();
...
auto ref_bigclass = GetBigClass();   // unexpected copy is performed

A: Use auto&:
auto& ref_bigclass = GetBigClass();

References are supposed to be transparent: any operation on them happens on the object they refer to, there is no way to 'get' reference itself.
UPD: This is covered in 7.1.6.4/6:

Once the type of a declarator-id has been determined according to 8.3, the type of the declared variable using the declarator-id is determined from the type of its initializer using the rules for template argument deduction.

And template argument deduction is defined in 14.8.2.1/3:

If template parameter type P is a reference type, the type referred to by P is used for type deduction.

P.S. Note that this is different for decltype: decltype(rx) will yield int& type (7.1.6.2/4).

A: The simplest way to think about it is comparing it to template argument deduction.
Given:
template<typename T>
void deduce(T) { }

If you call:
deduce(px);

then the template argument T will be deduced as int* and if you call
deduce(rx);

then T will be deduced as int, not int&
You get the same types deduced when using auto.

One could draw an analogy from pointer types expecting that the deduced type of arx is int&

You'd have to have a fairly confused model of the C++ language to make that analogy. Just because they are declared in syntactically similar ways, as Type@ with a type and a modifier doesn't make them work the same way. A pointer is a value, an object, and it can be copied and have its value altered by assignment. A reference is not an object, it's a reference to some object.  A reference can't be copied (copying it copies the referent) or altered (assigning to it alters the referent).  A function that returns a pointer returns an object by value (the object in question being a pointer object), but a function that returns a reference (like your GetBigClass()) returns an object by reference. They're completely different semantics, trying to draw analogies between pointers and references is doomed to failure.


text:
Q: можно ли спросить у rsync-сервера на удаленном хосте хеш-сумму директории есть набор удаленных хостов на которых крутится rsync-сервер. Он принимает и складывает папки с файлами в определенную директорию.
такие файлы и папки отправляются с сервера на nodejs с помощью rsync клиента.
Вопрос: можно ли со стороны сервера nodejs спросить хеш-сумму какой то конкретной директории у rsync-сервера на удаленном хосте?
цель Необходимо для реализации мониторинга версий бизнес а также системных решений, по сути система обновления с обратной связью. Просто в информационной системе была уже реализована передача необходимых файлов на удаленные сервера компании с помощью rsync.
хеш-сумма нужна чтобы сравнить с хеш-суммой записанный в бд сервиса системы обновления, таким образом выяснить верная ли версия того или иного отчета 1с, например, в филиале.
upd: Может посоветуйте другую утилиту которая бы справилась с подобной задачей если ее спросить? (всегда есть вариант написать свою, но хотелось бы оставить велики на потом)
upd: А если пытаться отдать, на удаленный сервер rsync, файл и в случае если он у него есть - не вернет ли он в качестве обратной связи что то типа "ей у меня такое уже есть, в передаче нет необходимости"? Это по сути было бы решением проблемы, так как скорее всего rsync сравнивает по хеш-суммам, и в этом случае можно было бы понять что все ок, а если нет, то мы, во первых, знаем об этом, а во вторых, сразу передаем правильные файлы.

На данный момент сервер nodejs отправляет файлы с помощью пакета rsync это выглядит примерно так:
var Rsync = require('rsync');

// Build the command
var rsync = new Rsync()
  .shell('ssh')
  .flags('az')
  .source('/path/to/source')
  .destination('server:/path/to/destination');

// Execute the command
rsync.execute(function(error, code, cmd) {
    // we're done
});

A:
можно ли со стороны сервера nodejs спросить хеш какой то конкретной директории у rsync-сервера на удаленном хосте?

нет, так нельзя. можно только сделать хеш самому.
Первый вариант: hash-files
Установка
npm install hash-files

Использование
var hashFiles = require('hash-files');

// options is optional
hashFiles(options, function(error, hash) {
    // hash will be a string if no error occurred
});

или в командной строке:
$ ./bin/hash-files -f '["package.json"]' -a sha256
a29089cc5e3f8bf6ae15ea6b9cd5eaefb14bbb12e3baa2c56ee5c21422250c75

Второй вариант: сам nodejs
crypto.createHash(algorithm)
const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');

const hash = crypto.createHash('sha256');

const input = fs.createReadStream(filename);
input.on('readable', () => {
  var data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});

A: насколько мне известно, ни одна реализация rsync-сервера/клиента не поддерживает требуемой вами возможности. другие задачи они решают.
но, судя по приведённому вами коду, для связи с серверами используется протокол ssh. следовательно, вы можете просто запустить программу подсчёта контрольных сумм нужных файлов непосредственно на сервере
md5sum /путь/к/файлу1 /путь/к/файлу2 /путь/к/каталогу/*

и проанализировать ответ:
хэш-сумма  /путь/к/файлу1
хэш-сумма  /путь/к/файлу2
хэш-сумма  /путь/к/каталогу/файл3
хэш-сумма  /путь/к/каталогу/файл4
...

программа md5sum служит для вычисления контрольной суммы по алгоритму md5, но в пакет gnu/coreutils входит множество других программ, работающих и с другими крипто-алгоритмами.

реализаций же клиентов ssh для node.js более чем много: раз, два, три и т.д.

A: Хеш-сумму директории спросить нельзя, но можно спросить какие файлы изменились не выполняя собственно операции копирования. Нужно лишь указать флаг dry-run:
rsync.set('dry-run'); // оно же rsync.dry();

Затем из вывода команды получить список изменившихся файлов. Если вы явно этого не запрещали, то сравнение будет происходить именно так как вы хотите, то есть с помощью контрольных сумм.
Получить только список файлов без ничего можете указав опцию out-format например в таком виде:
out-format="%f"


text:
Q: android - adb more than one device/emulator I genymotion emulator and my phone connected , I want to run and debug my application over wifi , I found the instruction to do so but I get this error when I enter this code :
adb tcpip 5555

I get this error :
error: more than one device/emulator
How can I make my device as default or something like that to solve this problem ?

A: Do following thing which will help you,
You getting the message just because you are connected more than one device.
Run commands
adb devices

after the fire above command, you get the list of the device, From the list select your device id which not emulator
and fire following command
adb -s f725aa8b7ce4(deviceId) tcpip 5555

and after this fire
adb connect yourIp 5555

A: You can send commands to a specific device, according to docs:
$ adb devices
List of devices attached
emulator-5554 device
emulator-5555 device

$ adb -s emulator-5555 do_your_command

Also, if only one is emulator or a real device you can just attach -e or -d and send the command to it:

If you have multiple devices available, but only one is an emulator, use the -e option to send commands to the emulator. Likewise, if there are multiple devices but only one hardware device attached, use the -d option to send commands to the hardware device.

A: I was struggling with same issue since months, later while testing in postman I got know that "Appium inspector" is the main reason for this issue. As it creates new session Id and interrupt the running framework server.
Hence, adb kill-server adb start-server resolves the issue as it actually kill the session ID created by Appium inspector and starts new server.


text:
Q: Weighted dataset after IPTW using weightit? I'm trying to get a weighted dataset after IPTW using weightit. Unfortunately, I'm not even sure where to start. Any help would be appreciated.
library(WeightIt)
library(cobalt)
library(survey)

W.out <- weightit(treat ~ age + educ + race + married + nodegree + re74 + re75,
                  data = lalonde, estimand = "ATT", method = "ps")

bal.tab(W.out)

# pre-weighting dataset
lalonde

# post-weighting dataset??

A: The weightit() function produces balance weights. In your case, setting method = "ps" will produce propensity scores that are transformed into weights. More details of how it produces those weights can be found with ?method_ps. You can extract the weights from your output and store them as a column in a data.frame via: data.frame(w = W.out[["weights"]]). The output is a vector of weights with a length equal to the number of non-NA rows in your data (lalonde).
What you actually mean by "weighted dataset" is ambiguous for two reasons. First, any analyses that use those weights will typically not actually produce a new data.set...rather it will weight the contribution of the row to the likelihood. This is substantively different from simply analyzing a dataset that has had each row's values multiplied by its weight and will produce different results for many models. Second, you are asking how to get a weighted dataset that has character vectors in columns. For example, lalonde$race is a character vector. Multiplying 5*"black" doesn't make much sense.
If you are indeed intent on multiplying every value in every row of your data by the row's respective weight, you will need to convert your race variable to numeric indicators, remove it from your data, then you can apply sweep():
library(dplyr)
df <- lalonde %>%
              black = if_else(race == "black", 1, 0),
              hispan = if_else(race == "hispan",1,0),
              white = if_else(race == "white",1,0)) %>%
  select(-race)

sweep(df, MARGIN = 2, W.out[["weights"]], `*`)


text:
Q: Is calling std::copy from multiple threads for different ranges of the same vector safe? I am computing floats from multiple threads and storing the results in non-overlapping ranges of the the same vector<float> as follows:
Before running any of the threads I pre-allocated it using vector::reserve.
In each thread a thread-specific vector of results is computed and then copied into the target container like this:
vector<float>::iterator destination = globalVector.begin() + threadSpecificIndex;
std::copy( localVector.begin(), localVector.end(), destination );

Is this a safe practice?

A: First vector::reserve doesn't actually create any elements.  It just sets the the capacity of the vector.  If you need the elements to be there you need vector::resize or just construct the vector to the size needed.
Secondly the rule of thumb is if you have a shared object between threads and at least one of them is a writer you need synchronization.  Since in this case the "object" is the iterator range and they do not overlap you are okay in this regard.  As long as the vectors size is not changed then you should be okay.
One issue you could have with this is false sharing.  If the same cache line contains variables that different threads are using then those cache lines have to re-synchronized every time a variable in the line is updated.  This can slow down the performance of the code quite a bit.

A: If the vector has fixed size (and it seems like it has from your question), and ranges are not overlapping, then:

*

*vector won't be reallocated

*different threads won't access the same memory

thus I don't see any data races here. (But according to 1st comment to your question, you must ensure, that vector has this fixed size when it is used). You can see also "Data Races" section for std::copy: http://www.cplusplus.com/reference/algorithm/copy/


text:
Q: Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers. i am facing this issue
store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers,

Here My store and root reducer file
import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import rootReducer from "./rootReducer";

const middlewares = [logger];

const store = createStore(rootReducer);

export default store;

This is the first time I'm working with React and Redux. I haven't been able to find error around it.
the above code is a total redux setup please help why this error coming:
import { combineReducers } from "redux";

import cardReducer from "../Services/profileimages/reducer";

export default combineReducers(cardReducer);

and my reducer file
import initialState from "./initialState";
import * as types from "./actionTypes";

const cardReducer = ({ state = initialState, action }) => {
  switch (action.type) {
    case types.FIREBASE_GETTING_IMAGES:
      return {
        cards: action.cards,
      };
    default:
      return state;
  }
};

export default cardReducer;

Haven't been able to find anything around here regarding this error:
import initialState from "./initialState";
import * as types from "./actionTypes";

const cardReducer = ({ state = initialState, action }) => {
  switch (action.type) {
    case types.FIREBASE_GETTING_IMAGES:
      return {
        cards: action.cards,
      };
    default:
      return state;
  }
};

export default cardReducer;

the above code is a total redux setup please help why this error coming

A: From the API doc combineReducers(reducers), the reducers parameter should be

An object whose values correspond to different reducing functions that need to be combined into one. See the notes below for some rules every passed reducer must follow.

Therefore, the correct usage is:
import { combineReducers } from 'redux';

import cardReducer from './cardReducer';

export default combineReducers({
  card: cardReducer,
});

Besides, the cardReducer has the wrong signature. It should be:
const cardReducer = (state = initialState, action) {}


text:
Q: Speech recognition with Flash or Silverlight I'm developing a web user interface to enter some information that is not very complex but needs to be loaded in real time.  I think that the application could make use of speech recognition to facilitate the task.
Te core of the interface is being built with Javascript and jQuery, but can easily include a flash or silverlight component.  I believe that´s probably the way to go...
I don't need to recognize everything that the user says, but only a few prerecorded commands.
Also, I don't want the user to click on a button to specify the begining and the end of the spoken command.  It should be detected live.
Is there anything that does this?  I would be grateful if anyone tells me about a complete solution, free or commercial, as well as any advice on capturing a sound stream from the mic and process it with flash or sliverlight.
Sebastian.-

A: Nicolay told me about this. I made speechle as an example using the flash work I am doing.  It is down for maintenance but other demos are working correctly. You can use the API i am working on at
www.speechapi.com
Or try a demo at
http://www.speechapi.com/live-demos/parrot.html
Some browser related issues I am trying to resolve but should work in firefox/chrome/safari.  Seems IE isn't working at the moment but do try.  Feel free to email me if you have issues.

A: wami.csail.mit.edu


text:
Q: Functors between equivariant derived category and derived category of the quotient Suppose $M$ is a quasi-projective variety, $G$ is a finite group acting on $M$. Let $X$ be the quotient $M/G$ (we assume $X$ to be singular) and $\pi: M\to X$ be the natural projection.
We have $(\pi)^{G}_{*}\circ \pi^{*}=id$, and in the case when $G$ is acting freely, the two functors are left and right adjoints of each other.
My question is:
1.What is the adjoint relation of the two functors in general?
2.I heard that since $X$ is singular, $L\pi^*$ would not be a map from $D^b(X)$ to $D^{b}(Coh_G(M))$. And this has to do with perfect complexes. Can someone explain this a little more and maybe provide some references?
Thanks!

A: The functors are still adjoint and the same relation holds. For details, see for example http://arxiv.org/pdf/1406.4409.pdf (especially the proof of Theorem 3.0.14) and references therein.


text:
Q: Max no of controllers in a thread group in jmeter I have 68 include controllers under a thread group but when I run the test, only 10 of them get executed. Is there a limit on the no of controllers that we can add under a thread group?

A: No limit , error is somewhere else.
Note that 68 include controllers looks a bit too much, is there a reason for this ?


text:
Q: IIS asp.net mvc partial? file upload Given the following code which is extremely generic, I was hoping someone could tell me a bit about what is going on behind the scenes...
[HttpPost]
public ActionResult Load(Guid regionID, HttpPostedFileBase file)
{
    if (file.ContentLength == 0)
        RedirectToAction("blablabla.....");

    var fileBytes = new byte[file.ContentLength];
    file.InputStream.Read(fileBytes, 0, file.ContentLength);
}

Specifically, is the file completely uploaded to the server before my action method is invoked? Or is it the file.InputStream.Read() method call that causes or rather waits for the entire file to upload. Can I do partial reads on the stream and gain access to the "chunks" of the file as it is uploaded? (If the entire fire is uploaded before my method is invoked then it is all a moot point.)
Can anyone point me to some good info on the inner workings here. Is there any difference between IIS6 or II7 here?
Thanks,

A: The while file needs to be sent to the server before the action method is invoked. Quote from the documentation:

Files are uploaded in MIME
  multipart/form-data format. By
  default, all requests, including form
  fields and uploaded files, larger than
  256 KB are buffered to disk, rather
  than held in server memory.
You can specify the maximum allowable
  request size by accessing the
  MaxRequestLength property or by
  setting the maxRequestLength attribute
  of the httpRuntime Element (ASP.NET
  Settings Schema) element within the
  Machine.config or Web.config file. The
  default is 4 MB.
The amount of data that is buffered in
  server memory for a request, which
  includes file uploads, can be
  specified by accessing the
  RequestLengthDiskThreshold property or
  by setting the
  requestLengthDiskThreshold attribute
  of the httpRuntime Element (ASP.NET
  Settings Schema) element within the
  Machine.config or Web.config file.

Server memory won't be consumed on the server but the file contents will be buffered to disk. Once the client has sent the whole file the ASP.NET pipeline will invoke your controller action and you could read the request stream in chunks and save it to another file which will be the definitive location of the uploaded file. The action cannot be invoked before the file has finished uploading as there might be some other fields in the multipart/form-data that come after the file and they won't be assigned in this case.


text:
Q: How do you output the Zend pagination control outside of the view? I'm creating a wrapper class in the Zend framework to encapsulate some data output and the pagination control.
How do I output this line from the view in the controller:
<?= $this->paginationControl($this->oPaginator, 'Sliding', 'pagination-control.phtml')?>

Thanks in advance.
...Answered my own question:
$this->view->oPaginator = $this->oPaginator;
echo $this->view->paginationControl($this->view->oPaginator, 'Sliding', 'pagination-control.phtml');

A: You can access the view object in the controller with $this->view. So you should be able to echo it like this:
echo $this->view->paginationControl($this->view->oPaginator, 'Sliding', 'pagination-control.phtml');

But I think there something wrong with your application if you need to echo this in the controller. Why do you want to do this?


text:
Q: Breakpoints not working correct This morning my breakpoints was working fine.
Now when you add a breakpoint there is a line through the breakpoint "dot". When code is running it skips the breakpoints. (almost a "\" through the breakpoint "dot")
Both the breakpoint and the line are blue/grey in color
Not sure what I did that it is not working.
I do have the following line in manifest
android:debuggable="true"

A: Check for Run > Skip All Breakpoints


text:
Q: Type already defines a member with the same parameter types I have an error saying:
Type 'GameManager' already defines a member called 'Update' with the same parameter types
Error message in Unity
This is my code

A: Ok. like others said what you're trying is using GameObject like a method.
And it's not gonna work that way.
The Error you're getting now is caused by duplicated Update().
Try Change first Update() to Start()
Edited my codes below.
try below codes
void Start()
{
    SelectZombie(selectedZombie);
}

void Update()
{
    if(Input.GetKeyDown("left"))
    {
        GetZombieLeft();
    }
    if(Input.GetKeyDown("Right"))
    {
        GetZombieRight();
    }
    if(Input.GetKeyDown("up")){
    }
}

void GetZombieLeft()
{
    if (selectedZombiePosition == 0)
    {
        SelectZombie(zombies[3]);
    }
    else
    {
        GameObject newZombie = zombies[selectedZombiePosition - 1];
        SelectZombie(newZombie);
    }
}

void GetZombieRight()
{
    if (selectedZombiePosition == 3)
    {
        SelectZombie(zombies[0]);
    }
    else
    {
        SelectZombie(zombies[selectedZombiePosition + 1]);
    }
}

A: Your code looks like this:
void Update() {
    ...
}

void Update() {
    ...
}

You can only have one Update() definition. They should be merged into one.


text:
Q: Inclusion related errors. Compiler does not recognize previously declared structures I am getting strange errors from GCC such as
main.c:117:3: warning: passing argument 2 of 'Adsorbate_Timestep' from incompatible pointer type [enabled by default]
Adsorbate.h:95:6: note: expected 'struct Substrate *' but argument is of type 'struct Substrate *'

Notice the expected argument is identical to the actual one.
I have several header files which define their own structures and declare functions which use those structures, and structures from other header files as well.
SOLVED:
Solution was to make sure each header file has at least a deceleration of each struct (of course the struct defined in the header file need not be declared again).


text:
Q: return View("myHtmlPage.html") in Asp.net MVC Masters,
In my MVC application many pages are static (HTML pages).
I've to create both .cshtml and plain HTML pages.
HTML version is also in use by another module.
When I try with return View("Mypage.html") it fails.
Is there any way to consume plain "HTML" pages for my View.
Please help.

A: What I did in the past was to register ".html" pages to be interpreted as dynamic pages, too. (I.e. just like ASPX).
This can be done through your "web.config" file:
....
<
system.web>
    <compilation ...>
        <buildProviders>
            <add extension=".html"
                 type="System.Web.Compilation.PageBuildProvider" />
        </buildProviders>

....and

....
<system.webServer>
    <handlers>
        <remove name="WebServiceHandlerFactory-Integrated" />
        <add name="PageHandlerFactory-Integrated-HTML" path="*.html"
             verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.PageHandlerFactory"
             resourceType="Unspecified" preCondition="integratedMode" />
    </handlers>

this works well with IIS 7 and IIS 7.5 (and probably on above versions, too). If you are using IIS 6, you have to do it through the IIS Management Console.
Hope this helps..


text:
Q: Accuracy always 1 Caffe Regression My dataset contains 400 images 32x32x3 and the labels contain float number (-1,1). Example:
faceCroppedImages/img1.jpg 0
faceCroppedImages/img2.jpg 0.0128
faceCroppedImages/img3.jpg 0.0128
faceCroppedImages/img4.jpg 0.0128
faceCroppedImages/img22.jpg 0.0128
faceCroppedImages/img23.jpg 0.0085
faceCroppedImages/img24.jpg 0.0077
faceCroppedImages/img25.jpg 0.0077
faceCroppedImages/img293.jpg -0.023
faceCroppedImages/img294.jpg -0.023
faceCroppedImages/img295.jpg -0.0204
faceCroppedImages/img296.jpg -0.0179
faceCroppedImages/img297.jpg -0.017
faceCroppedImages/img298.jpg -0.0128

My 'solver.prototxt' is:
net: "train_test_hdf5.prototxt"
test_iter: 100
test_interval: 500
base_lr: 0.003
momentum: 0.9
weight_decay: 0.0005
lr_policy: "inv"
gamma: 0.0001
power: 0.75
display: 100
max_iter: 10000
snapshot: 5000
snapshot_prefix: "lenet_hdf5"
solver_mode: CPU

and 'train_test_hdf5.prototxt' is:
name: "MSE regression"
layer{
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "label"
  hdf5_data_param {
    source: "train_hdf5file.txt"
    batch_size: 64
    shuffle: true
  }
  include: { phase: TRAIN }
}

layer{
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "label"
  hdf5_data_param {
    source: "test_hdf5file.txt"
    batch_size: 128
  }
  include: { phase: TEST }
}
layer {
  name: "conv1"
  type: "Convolution"
  bottom: "data"
  top: "conv1"
  param { lr_mult: 1 }
  param { lr_mult: 2 }
  convolution_param {
    num_output: 20
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
      value: 0
    }
  }
}
layer {
  name: "relu1"
  type: "ReLU"
  bottom: "conv1"
  top: "conv1"
}
layer {
  name: "pool1"
  type: "Pooling"
  bottom: "conv1"
  top: "pool1"
  pooling_param {
    pool: MAX
    kernel_size: 2
    stride: 2
  }
}
layer {
  name: "dropout1"
  type: "Dropout"
  bottom: "pool1"
  top: "pool1"
  dropout_param {
    dropout_ratio: 0.1
  }
}

layer{
  name: "fc1"
  type: "InnerProduct"
  bottom: "pool1"
  top: "fc1"
  param { lr_mult: 1 decay_mult: 1 }
  param { lr_mult: 2 decay_mult: 0 }
  inner_product_param {
    num_output: 500
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
      value: 0
    }
  }
}
layer {
  name: "dropout2"
  type: "Dropout"
  bottom: "fc1"
  top: "fc1"
  dropout_param {
    dropout_ratio: 0.5
  }
}
layer{
  name: "fc2"
  type: "InnerProduct"
  bottom: "fc1"
  top: "fc2"
  param { lr_mult: 1 decay_mult: 1 }
  param { lr_mult: 2 decay_mult: 0 }
  inner_product_param {
    num_output: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
      value: 0
    }
 }
}
layer {
  name: "accuracy1"
  type: "Accuracy"
  bottom: "fc2"
  bottom: "label"
  top: "accuracy1"
  include {
    phase: TEST
  }
}
layer{
  name: "loss"
  type: "EuclideanLoss"
  bottom: "fc2"
  bottom: "label"
  top: "loss"
}

However when I'm testing the data the accuracy is always 1:

I tried using integer labels my multiplying my current labels by 1000, but I'm getting the nan error:

Can you please tell me where I'm doing wrong? I'm a beginner in caffe and neural networks. Any suggestions will be valuable. TIA.

A: No point using "Accuracy" layer for regression task: this layer measures the accuracy of classification output.
For instance, if you are trying to predict one of L labels, num_output of fc2 layer will be L - that is, predicting a probability per class. Then "Accuracy" layer checks that the probability of the l-th entry, corresponding to the expected output l is maximal.
How can you compute such accuracy when fc2 output is only 1 dimensional?
In your case, you can only check the Euclidean loss and see it decreasing for both test and train.


text:
Q: S-K basis Completeness in combinatory logic I was reading the following Wikipedia page on combinatory logic and am puzzled by the example that is given:
https://en.wikipedia.org/wiki/Combinatory_logic#Completeness_of_the_S-K_basis
Using the given transformation T[], the term λx.λy.(y x) is converted to a SKI combinator.
Here is the first rewriting step:
T[λx.λy.(y x)]
= T[λx.T[λy.(y x)]] (by 5)

Where 5. is:
T[λx.λy.E] => T[λx.T[λy.E]] (if x occurs free in E)
I am failing to understand why 5. is being used here. In λx.λy.(y x), isn't x a bound variable (meaning it doesn't occur free in E)?

A: In λx.λy.(y x), x is a bound variable and is thus not free. But in y x, x is free. The proviso of the rule refers to E without the lambdas around it.


text:
Q: JAVA FX TAB function My question is about on disabling new tab if already opened and set the focus on the original content if opened tab is selected again on menu item.

public class TapsMainController extends SANodeController {

    BorderPane BP;
    Tab tb;

    public static synchronized TapsMainController getInstance() {
        return newInstance(TapsMainController.class.getResource("/ph/softartifact/taps/client/fx/bpar/view/TapsMain.fxml"));
    }
    @FXML
    private MenuBar MenuBar;
    @FXML
    private Menu Menu;
    @FXML
    private MenuItem EmpReg;
    @FXML
    private MenuItem EmpApproval;
    @FXML
    private TabPane TB;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        EmpReg.setOnAction(e -> empReg());
        EmpApproval.setOnAction(e -> empApproval());

    }

    @Override
    public void postComponentInit() {

    }

    public void empReg() {
        EmployeeRegistrationController ER = EmployeeRegistrationController.getInstance();
        SingleSelectionModel<Tab> selectionModel = TB.getSelectionModel();
        ER.setSAPlatBridge(new UserPlatBridge(), null, null);
        ER.postComponentInit();
        BP = new BorderPane();
        tb = new Tab();
        selectionModel.select(tb);
        TB.getTabs().add(tb);
        tb.setContent(BP);
        tb.setText("Employee Registration");
        BP.setCenter(ER.getFxmlNode());

    }

    public void empApproval() {
        EmployeeeApprovalController ER = EmployeeeApprovalController.getInstance();
        SingleSelectionModel<Tab> selectionModel = TB.getSelectionModel();
        ER.setSAPlatBridge(new UserPlatBridge(), null, null);
        ER.postComponentInit();
        BP = new BorderPane();
        tb = new Tab();
        selectionModel.select(tb);
        TB.getTabs().add(tb);
        tb.setContent(BP);
        tb.setText("Employee Approval and Revision");
        BP.setCenter(ER.getFxmlNode());
    }

}


text:
Q: How do I insert data into a pre-allocated CSV? Text file (or CSV) is:
Data:,,,,,\n

(but with 100 ","s)
In C or C++ I would like to open the file and then fill in values between the ",".
i.e.-       Data:,1,2,3,4,\n
I'm guessing that I need some sort of search to find the next comma, insert data, find the next comma insert, etc.
I was looking at memchr() for a buffer and was wondering if there is something similar for a text file?
If you could point me in the right direction, I would appreciate it.
(I don't mind reading a book to find something out like this either, I just don't know what book would have this information?)
Thank You.

A: You can't actually do that in C... if you open in read/write mode you'll overwrite characters, not insert them.
http://c-faq.com/stdio/fupdate.html
You need to open the file, read the line into memory, write the new line to a temp file.
After you're done inserting all the lines, copy the temp file over the original file.  I don't think there's any other way to do it.

A: (This is for the C++ case)
Just parse the data into an Linked list with the Objects that hold the data, modify the data and overwrite the file.
You first need to split your data into lines(\n creates a new linked-list Element):
Data:,,,,,\n
Data2:,,,,,\n

will get the strings (pseudolist):
["Data:,,,,,", "Data2:,,,,,"]
So now you need to define your Object for each Line like:
class LineStruct {
   public:
    string head;
    LinkedList<string> data;
};

and fill it.
Then you edit the data-structure and after that you write it back to disk.

A: If you have
Data:,,,,,\n

then there is no space between the , to fill, you have to write out brand new lines.
However if you had
Data:   ,   ,   ,   ,   ,   \n

then you could overwrite just those parts represented by '   '
in C you would seek to the part of the file and write and then seek to the next pos, sorry no code off the top of my head.

A: This is where I would look:

*

*std::getline for reading lines into std::strings

*std::string::find_first_of for finding the comas

*std::stringstream for building the new output-line

As suggested by wmils answer, you will have to either use a temporary file, or hold all the new lines in memory until all lines are processed, and then overwrite the original file.


text:
Q: Calling a class function inside another class function I am trying to call a function inside another class function in Python. However, I am getting the error that global name is not defined. I don't know what to do as I can't figure out what's the issue.
The error is:
NameError: global name 'sendCmdWaitForRaffleResponse' is not defined

Here is the code I have written:
Class T:
    def connect(self,ipAddr,portNum):
      try:
           print "Check1"
           s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

           s.connect((ipAddr,portNum))
           s.settimeout(1000*30)

           response=s.recv(8192)
           print response

           cmd="some command"
           s.send(cmd)
           print 'check'
           response=s.recv(1024)

           print response
           #time.sleep(5)
      except Exception as e:
           print e
  def Send(self,command):
         result ="ok"
         try:
             print "start"
             if command.startswith("#"):
               #print result
               return result

             elif not command:
                 return result

             print 'yes'
             result=sendCmdWaitResponse(command)

         except Exception as e:
             print (e)

         return result

  def sendCmdWaitResponse(self,cmd):
          print "Running"
          s.send(cmd)
          while true:
              response=s.recv(1024)
              response=+ '\n'
              print response

          print "Leaving"
          return sb.getvalue()

if __name__ == "__main__":

 test=T()
 a='some command'
 test.Connect(ipaddr,port)
 test.Send(a)

A: You need self.
         result=self.sendCmdWaitResponse(command)

A: Change
result=sendCmdWaitResponse(command)

to
result=self.sendCmdWaitResponse(command)

A: Your code seems to have many typo: This is the fix I have done. I don't know what is your expected output. Please add the valid code:
import socket
class T():

    def __init__(self, ipAddr, portNum):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connect(self,ipAddr,portNum):
      try:
           print "Check1"
           s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

           s.connect((ipAddr,portNum))
           s.settimeout(1000*30)

           response=s.recv(8192)
           print response

           cmd="some command"
           s.send(cmd)
           print 'check'
           response=s.recv(1024)

           print response
       #time.sleep(5)
    except Exception as e:
      print e

   def Send(self, command):
     result ="ok"
     try:
         print "start"
         if command.startswith("#"):
           #print result
           return result

         elif not command:
             return result

         print 'yes'
         result= self.sendCmdWaitResponse(command)

     except Exception as e:
         print (e)

     return result

    def sendCmdWaitResponse(self,cmd):
      print "Running"
      self.s.send(cmd)
      while True:
          response= self.s.recv(1024)
          response=+ '\n'
          print response

      print "Leaving"
      return sb.getvalue()

if __name__ == "__main__":

    a='some command'
    ipAddr = ""

    port = 1000
    test = T(ipAddr, port)
    test.connect(ipAddr,port)
    test.Send(a)


text:
Q: How to simulate CURL call in Postman? I have a Curl call that works from my linux machine:
curl -XGET --insecure https://1.2.3.4:9200/_cat/ -u admin:admin

How to simulate it in Postman?
Thanks

A: This curl call is consisted by 4 parameters:

*

*HTTP method is GET (-X GET). To simulate in Postman, choose GET (the default value) in the request panel.

*HTTP request is proceeded even if certificate verification is failed (--insecure). To simulate in Postman, turn off "SSL certificate verification" in Postman preference. According to the document, this only works in Postman native app.

*URL is https://1.2.3.4:9200/_cat/. To simulate this, copy and paste it in the address bar of request panel.

*Credential (-u admin:admin). To simulate this in Postman, configure it in the "Authorization" tab of request panel.

Here are some screenshot:
To simulate "GET https://1.2.3.4:9200/_cat/":

To simulate --insecure:

To simulate credential (take Basic auth for example, you can change to other types due to requirement):


text:
Q: Difference between php commandline and server If I run
php -r 'print_r(file_get_contents("http://mirror.facebook.net/centos/timestamp.txt"));'

I get "Tue Oct 28 13:24:01 UTC 2014" (as expected).
But if I have a php file:
<?php
print_r(file_get_contents("http://mirror.facebook.net/centos/timestamp.txt"));

It gives me:
**Warning:** file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known ...

**Warning:** file_get_contents(http://mirror.facebook.net/centos/timestamp.txt): failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known ...

What is the difference between "php -r" and php running the code out of a file

UPDATE
This is not the answer to the question but it did solve my problem so for the sake of future googlers: I don't know which of these two solutions was the key but it was working when I restarted apache.

*

*In resolv.conf set nameserver 8.8.8.8  (which had my router's address)

*There's an SELinux boolean httpd_can_network_connect which must be turned on:

setsebool -P httpd_can_network_connect 1

See this solution and this one.

A: Your PHP CLI is using a different php.ini (or maybe no php.ini at all).  It's also possible you are running a completely different PHP binary than what your server is using.
You can run php -i on the command line, and phpinfo() in a script to determine which php.ini is in use.