text:
Q: Convert powershell table to json with column 1 as key and column 2 as value I'm trying to produce a JSON dictionary from a powershell object with formatting that the ConvertTo-Json cmdlet doesn't provide by default.
For example the ConvertTo-Json will take the output of
(get-counter '\Process(*)\% Processor Time').CounterSamples | select InstanceName, CookedValue

which looks like:
InstanceName        CookedValue
------------        -----------
idle             92.02923730929
process1                      3
process2                      1
process3                      0
process4                      2
process5                      0
process6                      2
process7                      0
....                       ....

and produce a JSON object that looks like this:
[
{
    "InstanceName":  "idle",
    "CookedValue":  92.02923730929
},
{
    "InstanceName":  "process1",
    "CookedValue":  3
},
{
    "InstanceName":  "process2",
    "CookedValue":  1
},
...
]

Would it be possible to instead format the JSON object like this?:
{
    idle: 92.02923730929,
    process1: 3,
    process2: 1,
    process3: 0,
    process4: 2,
    process5: 0,
}

Thanks

A: Create a new object with properties made up of the sample property values:
$properties = @{}
(Get-Counter '\Process(*)\% Processor Time').CounterSamples |ForEach-Object {
    $properties[$_.InstanceName] = $_.CookedValue
}
New-Object psobject -Properties $properties |ConvertTo-Json

Since you could have multiple instances with the same process name, you might want to extract the process name and instance number from the counter Path instead:
$properties = @{}
(Get-Counter '\Process(*)\% Processor Time').CounterSamples |ForEach-Object {
    $InstanceName = if($_.Path -match 'process\((.*#\d+)\)'){
        $Matches[1]
    }
    else {
        $_.InstanceName
    }
    $properties[$InstanceName] = $_.CookedValue
}
New-Object psobject -Property $properties |ConvertTo-Json

A: just pipe it to ConvertTo-Json
(get-counter '\Process(*)\% Processor Time').CounterSamples | select InstanceName, CookedValue | ConvertTo-Json

I cannot answer your second question of reformatting the JSON output


text:
Q: String copy in C with and without pointer There are two versions of string copy functions written in C. My question is why the version1 need "!= '\0'" but the version2 doesn't. What if I have a character 0 to be copied using version2, will the '0' terminate coping process?
void version1(char to[], char from[])
{
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

char *version2(char *dest, const char *src)
{
    char *addr = dest;
    while (*dest++ = *src++);
    return addr;
}

In addition, why an input like "1230456" will not terminate the coping since '0' appears in the middle of the string?

A: This is because in C comparison to zero is optional. When you use an expression in a context requiring a logical expression, C would insert an implicit comparison to zero for you.
You can rewrite the first function as follows without changing the semantic:
while ((to[i] = from[i]))
    ++i;

Moreover, you can rewrite the second function as follows:
while ((*dest++ = *src++) != '\0');

A: There is exactly that same != 0 test in the second version, but it's impicit: The result of the expression *dest++ = *src++ becomes the value checked by the while, and in C, all tests boil down to a comparison with zero.
By the same token, in the first example, the while line could be rewritten:
while (to[i] = from[i])

and not change the meaning.

A: Both versions make the same check, in the second version you just don't see it. You can try to remove != '\0' from the first version, it should still work.

A: version1 does not NEED the != '\0' but it is better programming practice to include it. It just so happens that '\0' is equal to zero and so version2 will work, but, if you happen to come across a system where '\0' is NOT zero, version2 will not work.

A: One thing perhaps not mentioned yet is that the reason the zero termination gets copied in the second example is because of the post increment ensures that the value is copied BEFORE it gets checked for a zero value, which terminates the loop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Localization at maximal ideal of tensor product of algebras Let $k$ be an algebraically closed field. Set $R=k[x_1,...,x_n]/I$ and $S=k[y_1,...,y_m]/J$ finite generated $k$-algebras.
By Hilbert Nullstellensatz, the maximal ideals of $R\otimes_k S$ are of the form $m\otimes_k S+R\otimes_k n$ with $I\subseteq m=(x_1-a_1,...,x_n-a_n)$ and $J\subseteq n=(y_1-b_1,...,y_m-b_m)$, where $a_i,b_i\in k$.

Is the natural map $R_m\otimes_k S_n\rightarrow (R\otimes_kS)_{m\otimes_k S+R\otimes_k n}$ an isomorphism?

Also, is $R_m\otimes_k S_n$ local ring?
Similarly, we can consider prime ideals $I\subseteq p$ and $J\subseteq q$. Then $p\otimes_k S+R\otimes_k q$ is prime ideal of $R\otimes_k S$ since $k$ is algebraically closed, see Tensor product of domains is a domain. What is the localization of $R\otimes_k S$ at this prime ideal?
Thank you in advance.

A: This  is not true. We just need to show in general, $R_m\otimes_k S_n$ is not local.
Assume $k$ is algebraically closed. Let $R=k[x]$ and $S=k[y]$. Set $m=(x)$ and $n=(y)$. Then we have

$R_m\otimes_k S_n\cong T^{-1}k[x,y]$, where $T=\{fg\mid f\in k[x],g\in k[y], f(0)\neq 0,g(0)\neq 0\}$

Claim: $T^{-1}(x+y+1)$ is maximal ideal of $T^{-1}k[x,y]$. The spectrum of $T^{-1}k[x,y]$ corresponds to the prime ideal of $k[x,y]$ which has empty intersection with $T$.  If $T^{-1}(x+y+1)$ is not maximal, there exists prime ideal $p$ containing $(x+y+1)$ such  that $p\cap T=\emptyset$. Note that $p=(x-a,y-b)$ since $\dim(k[x,y])=2$. $p\cap T=\emptyset $ implies that $a=b=0$. This contradicts with $(x+y+1)\subseteq p$. The claim follows.
Since $T^{-1}(x,y)$ is also maximal ideal of $T^{-1}k[x,y]$. We get $T^{-1}k[x,y]$ is not local.
The above example that $k[x]_{(x)}\otimes_k k[y]_{(y)}$ is not local works for any field.
Assume that $T^{-1}k[x,y]$ is local. We have the maximal ideal of $T^{-1}k[x,y]$ is $T^{-1}(x,y)$. It is clear that $x+y+1\notin T^{-1}(x,y)$. Hence it is invertible in $T^{-1}k[x,y]$. Thus we get
$$
(x+y+1)\alpha/fg=1/1, \text{ for some }\alpha\in k[x,y] \text{ and } fg\in T.
$$
Then we get $(x+y+1)\alpha=fg$, this contradicts with $k[x,y]$ is UFD.


text:
Q: Get a YAML file with HTTP and use it as a variable in an Ansible playbook Background
I have a YAML file like this on a web server. I am trying to read it and make user accounts in the file with an Ansible playbook.
users:
  - number: 20210001
    name: Aoki Alice
    id: alice
  - number: 20210002
    name: Bob Bryant
    id: bob
  - number: 20210003
    name: Charlie Cox
    id: charlie

What I tried
To confirm how to read a downloaded YAML file dynamically with include_vars, I had written a playbook like this:
- name: Add users from list
  hosts: workstation
  tasks:
    - name: Download yaml
      get_url:
        url: http://fqdn.of.webserver/path/to/yaml.yml
        dest: "/tmp/tmp.yml"
      notify:
        - Read yaml
        - List usernames

  handlers:
    - name: Read yaml
      include_vars:
        file: /tmp/tmp.yml
        name: userlist

    - name: List usernames
      debug:
        var: "{{ item }}"
      loop: "{{ userlist.users }}"

Problem
In the handler Read yaml, I got the following error message. On the target machine (workstation.example.com), /tmp/tmp.yml is downloaded correctly.
RUNNING HANDLER [Read yaml] *****
fatal: [workstation.example.com]: FAILED! => {"ansible facts": {"userlist": []},
"ansible included var files": [], "changed": false, "message": "Could not find o
r access '/tmp/tmp. yml' on the Ansible Controller.\nIf you are using a module a
nd expect the file to exist on the remote, see the remote src option"}

Question
How can I get a YAML file with HTTP and use it as a variable with include_vars?

A: Another option would be to use the uri module to retrieve the value into an Ansible variable, then the from_yaml filter to parse it.
Something like:
- name: Add users from list
  hosts: workstation
  tasks:
    - name: Download YAML userlist
      uri:
        url: http://fqdn.of.webserver/path/to/yaml.yml
        return_content: yes
      register: downloaded_yaml
    - name: Decode YAML userlist
      set_fact:
        userlist: "{{ downloaded_yaml.content | from_yaml }}"

Note that uri works on the Ansible Controller, while get_url works on the target host (or on the host specified in delegate_to); depending on your network configuration, you may need to use different proxy settings or firewall rules to permit the download.

A: The include_vars task looks for files on the local (control) host, but you've downloaded the file to /tmp/tmp.yml on the remote host. There are a number of ways of getting this to work.
Perhaps the easiest is just running the download task on the control machine instead (note the use of delegate_to):
  tasks:
    - name: Download yaml
      delegate_to: localhost
      get_url:
        url: http://fqdn.of.webserver/path/to/yaml.yml
        dest: "/tmp/tmp.yml"
      notify:
        - Read yaml
        - List usernames

This will download the file to /tmp/tmp.yml on the local system, where it will be available to include_vars.  For example, if I run this playbook (which grabs YAML content from an example gist I just created)...
- hosts: target
  gather_facts: false
  tasks:
    - name: Download yaml
      delegate_to: localhost
      get_url:
        url: https://gist.githubusercontent.com/larsks/70d8ac27399cb51fde150902482acf2e/raw/676a1d17bcfc01b1a947f7f87e807125df5910c1/example.yaml
        dest: "/tmp/tmp.yml"
      notify:
        - Read yaml
        - List usernames

  handlers:
    - name: Read yaml
      include_vars:
        file: /tmp/tmp.yml
        name: userlist

    - name: List usernames
      debug:
        var: item
      loop: "{{ userlist.users }}"

...it produces the following output:
RUNNING HANDLER [Read yaml] ******************************************************************
ok: [target]

RUNNING HANDLER [List usernames] *************************************************************
ok: [target] => (item=bob) => {
    "ansible_loop_var": "item",
    "item": "bob"
}
ok: [target] => (item=alice) => {
    "ansible_loop_var": "item",
    "item": "alice"
}
ok: [target] => (item=mallory) => {
    "ansible_loop_var": "item",
    "item": "mallory"
}

Side note: based on what I see in your playbook, I'm not sure you want
to be using notify and handlers here. If you run your playbook a
second time, nothing will happen because the file /tmp/tmp.yml
already exists, so the handlers won't get called.

A: With @Larsks 's answer, I made this playbook that works correctly in my environment:
- name: Download users list
  hosts: 127.0.0.1
  connection: local
  become: no
  tasks:
  - name: Download yaml
    get_url:
      url: http://fqdn.of.webserver/path/to/yaml/users.yml
      dest: ./users.yml

- name: Add users from list
  hosts: workstation
  tasks:
  - name: Read yaml
    include_vars:
      file: users.yml
  - name: List usernames
    debug:
      msg: "{{ item.id }}"
    loop: "{{ users }}"

Point
Run get_url on the control host
As @Larsks said, you have to run the get_url module on the control host rather than the target host.
Add become: no to the task run on the control host
Without "become: no", you will get the following error message:
TASK [Gathering Facts] ******************************************************
fatal: [127.0.0.1]: FAILED! => {"ansible_facts": {}, "changed": false, "msg":
 "The following modules failed to execute: setup\n setup: MODULE FAILURE\nSee
 stdout/stderr for the exact error\n"}

Use connection: local rather than local_action
If you use local_action rather than connection: local like this:
- name: test get_url
  hosts: workstation
  tasks:
  - name: Download yaml
    local_action:
      module: get_url
      url: http://fqdn.of.webserver/path/to/yaml/users.yml
      dest: ./users.yml
  - name: Read yaml
    include_vars:
      file: users.yml
  - name: output remote yaml
    debug:
      msg: "{{ item.id }}"
    loop: "{{ users }}"

You will get the following error message:
TASK [Download yaml] ********************************************************
fatal: [workstation.example.com]: FAILED! => {"changed": false, "module_stde
rr": "sudo: a password is required\n", "module_stdout":"", "msg":"MODULE FAIL
URE\nSee stdout/stderr for the exact error", "rc": 1}

get_url stores a file on the control host
In this situation, the get_url module stores users.yml on the control host (in the current directory). So you have to delete the users.yml if you don't want to leave it.


text:
Q: How to add radio button behavior to  I just want to add a radio button behavior(check only one item, change color when is checked, remove checked color when the other is checked.) to
How can I do this in javascript? Here is my on click event.
$(document).on('click', '[data-change-option]', function(e) {
  e.preventDefault();
  console.log(e.target);
  var optionIndex = parseInt($(this).data('changeOption')), optionValue = $(this).data('changeValue');

  if(optionSelectors.optionExistInSelect(optionSelectors.selectors[optionIndex].element, optionValue)) {
    $(optionSelectors.selectors[optionIndex].element).val(optionValue).trigger('change');
  }
});

A: Reset all items of the type to the base color, than change the clicked one to the active color:

$(document).on('click', '[data-change-option]', function() {
  $('[data-change-option]').css('color', '');

  $(this).css('color', 'red');
});

Link 1

Link 2

Link 3


text:
Q: How to replace the first 8 characters of a file in notepad++? I'm using regex in notepad++ and I need to replace only the first 8 characters of each file, not from each line, just the first 8 characters in the first line. I need this:
Now:
40932182ErikG
asdadasdada
rewqrasdasdasdas

I need this:
0       ErikG
asdadasdada
rewqrasdasdasdas

I found that this "^.{0,8}" let me replace the first 8 characters of each line but I only need to replace from the first line.
Thank you!

A: You may use
Find What: ^.{0,8}((?s:.*))
Replace With: 0    $1
The point is to match the first 0 to 8 chars, and then capture the rest of the file into a group to restore it later with the $1 placeholder.
Pattern details

*

*^ - start of the line

*.{0,8} - 0 to 8 chars other than line break chars

*((?s:.*)) - Capturing group 1: any 0+ chars, up to the end of the file (greedy match, ?s: enables the DOTALL modifier, . matches newlines, too, now).


text:
Q: CakePHP: Escape single quotes within an implode function delimited with commas I have a routine in my controller that retrieves the values from a single database column and builds a quoted array out of them:
$suppliers=$this->Model->find('list',array('fields'=>array('Model.supplier', 'Model.supplier')));
$strSuppliers="'".implode("','", $suppliers)."'";
$this->set('suppliers', $strSuppliers);

$strSuppliers is then fed to a jQuery script that creates an auto-complete dropdown list in the "suppliers" field in my Edit view:
<script>
  $(function() {
    var availableTags = [<?php echo $suppliers ?>];
    $( "#MsrSupplier" ).autocomplete({
    source: availableTags
   });
 });
</script>

The output of the variable is something like 'Tom', 'Dick', 'Harry', etc.
This works fine, unless any of the retrieved values contain single quotes. 'Tom's', 'Dick', 'Harry' breaks the array, and I'm having difficulty understanding how to escape the single quotes so that my dropdown will continue to function when they're present. I've tried changing the delimiter and swapping single quotes for double quotes, like so:
$strSuppliers='"'.implode("','", $suppliers).'"';

But that didn't work. What else might I try here?

A: Check out json_encode() for PHP to output a JSON string, and then look at JSON.parse() for use in your jQuery.
Instead of using implode() to generate your string, use json_encode() and then have JSON.parse() decode that for use in whatever application you need.
Edit: Added some code for clarity:
$strSuppliers = json_encode($suppliers);

and then in your jQuery:
var jsonStr = '<?php echo $suppliers; ?>';
var availableTags = JSON.parse(jsonStr);

EDIT 2: As ndm pointed out in the comments, you can do this more cleanly by directly assigning the Javascript variable to the output of json_encode():
var availableTags = <?php echo $suppliers; ?>;


text:
Q: How to include opencv source files as a cmake dependency without installing it? I have opencv installed in my system but I do not want to use the installed version. The installed version (from distro repository) was compiled with gcc 7.
I want to compile a C++ project with opencv and dlib as dependency using older gcc compiler installed in a separate path. I have downloaded the opencv sources and extracted it into a seperate folder. What is the proper way to include it cmake so that it is compiled and included as a dependency during compilation?
This is my project structure.
projects/
  |--> project1/
  |      |--> main.cpp
  |      |--> CMakeLists.txt
  |
  |--> dlib/
  |
  |--> opencv-3.3.1/

My CMakeLists.txt looks like this.
cmake_minimum_required(VERSION 2.8.12)

project(project1)
add_subdirectory(../dlib/dlib dlib_build)
add_subdirectory(../opencv-3.3.1/dlib opencv_build)

add_executable(project1 main.cpp)
target_link_libraries(project1 dlib::dlib opencv)

A: To specify a different compiler, pass in the -DCMAKE_CXX_COMPILER -DCMAKE_CC_COMPILER  parameters in to cmake, each referencing the appropriate path and command.
When you are adding sources within the add_library function, tell it exactly where the sources are.
so...
list(${CUSTOM_OPENCV} APPEND
"/custom/path/source1.cpp"
"/custom/path/source2.cpp"
)

add_library(my_app ${CUSTOM_OPENCV})

That might be how I would do it.  You might even want to pass in the custom path through a cmake parameter to make your project a little more robust for future uses.


text:
Q: Number of passengers on a bus/Departuring busses in Poisson process problem
Buses leave a bus station according to  a Poisson process
  $\{B_t\}$ of rate $\lambda$, while travellers reach the same station according to (an independent) Poisson process $\{T_t\}$ of rate $\mu$. Travellers get on the bus and leave the station as soon as a bus departures.
$(1)$ Let $N$ be the random variable, expressing the number of passengers on a departuring bus. Find $P(N=k),~k=0,1,2,\ldots$
$(2)$ Let $\Lambda$ be the random variable, expressing the number of  departuring buses till the time the $1000$th traveller has reached the station. Find $P(\Lambda=k),~k=0,1,2,\ldots$

Attempt.
(1) In order for $N$ to be $k$ there must be $k$ travellers reaching the bus station and no bus leaving in between. The time needed for k travellers to reach the station is $W\sim Gamma(k,\mu)$, so $$P(N=k)=P(B_W=0)=\int_{0}^{+\infty}P(B_w=0)f_W(w)dw=\int_{0}^{+\infty}e^{-\lambda w} \frac{\mu^k}{(k-1)!}w^{k-1}e^{-\mu w}dw.$$
(2) The time needed for the $1000$th traveller to reach the station is $W\sim Gamma(1000,\mu)$, so $$P(\Lambda=k)=P(B_W=k)=\int_{0}^{+\infty}P(B_w=k)f_W(w)dw=\int_{0}^{+\infty}e^{-\lambda w}\frac{(\lambda w)^k}{k!} \frac{\mu^{1000}}{999!}w^{999}e^{-\mu w}dw.$$
Am I on the right path? Thank you!

A: For the first part:
At time $W\sim \Gamma(k,\mu)$, $k$ travellers have arrived to the bus station. Thus we know that if $B_W = 0$, then at least $k$ passengers will leave with the first bus*. So you are really evaluating $P(N\geq k)$. Your final integral in (1) should be easily computed by recognising what looks like the density of another gamma distribution.
To generalise the thinking from the 'first bus' to 'a bus', it is of course important that a Poisson process $L$ satisfies, that $L(t)-L(s)$ is equal in distribution to $L(t-s)$ and that it is independent of $L(l)_{l\leq s}$. Just have this in mind: Showing it for the first bus is enough.
For the second part:
Seems all fine.
*: Maybe some additional considerations should be given to this, after all the Poisson processes only have càdlàg sample paths.

A: For sake of completeness I post my answer, based on the useful remarks made by @Furrer:
(1) $$P(N\geq k)=P(B_W=0)=\int_{0}^{+\infty}e^{-\lambda w} \frac{\mu^k}{(k-1)!}e^{-\mu w}dw=\Big(\frac{\mu}{\lambda+\mu}\Big)^k$$
and $$P(N=k)=P(N\geq k)-P(N\geq k+1)=\frac{\lambda}{\lambda+\mu}~\Big(1-\frac{\lambda}{\lambda+\mu}\Big)^k$$
(geometric distribution)
(2) $$P(\Lambda= k)=P(B_W=k)=\int_{0}^{+\infty}e^{-\lambda w}\frac{(\lambda w)^k}{k!} \frac{\mu^{1000}}{999!}w^{999}e^{-\mu w}dw=\binom{999+k}{k}\Big(\frac{\lambda}{\mu+\lambda}\Big)^k\Big(1-\frac{\lambda}{\mu+\lambda}\Big)^{1000}.$$
Question: if I have to plug in numbers for $\lambda,~\mu$, they have to be on the same time unit, for example both rates expressed in days, or both in months?


text:
Q: How to do joins in LINQ on multiple fields in single join I need to do a LINQ2DataSet query that does a join on more than one field (as
var result = from x in entity
join y in entity2
       on x.field1 = y.field1
and
          x.field2 = y.field2

I have yet found a suitable solution (I can add the extra constraints to a where clause, but this is far from a suitable solution, or use this solution, but that assumes an equijoin).
Is it possible in LINQ to join on multiple fields in a single join?
EDIT
var result = from x in entity
             join y in entity2
             on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

is the solution I referenced as assuming an equijoin above.
Further EDIT
To answer criticism that my original example was an equijoin, I do acknowledge that, My current requirement is for an equijoin and I have already employed the solution I referenced above.
I am, however, trying to understand what possibilities and best practices I have / should employ with LINQ. I am going to need to do a Date range query join with a table ID soon, and was just pre-empting that issue, It looks like I shall have to add the date range in the where clause.
Thanks, as always, for all suggestions and comments given

A: The solution with the anonymous type should work fine. LINQ can only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.
If you don't like the version with the anonymous type for some specific reason, you should explain that reason.
If you want to do something other than what you originally asked for, please give an example of what you really want to do.
EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.
Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something similar - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a where clause (after a second from clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue.

A: you could do something like (below)
var query = from p in context.T1

        join q in context.T2

        on

        new { p.Col1, p.Col2 }

        equals

         new { q.Col1, q.Col2 }

        select new {p...., q......};

A: Using the join operator you can only perform equijoins.  Other types of joins can be constructed using other operators.  I'm not sure whether the exact join you are trying to do would be easier using these methods or by changing the where clause.  Documentation on the join clause can be found here.  MSDN has an article on join operations with multiple links to examples of other joins, as well.

A: If the field name are different in entities
var result = from x in entity
   join y in entity2 on
          new {
                field1=   x.field1,
               field2 =  x.field2
             }
          equals
         new {
                field1= y.field1,
                field2=  y.myfield
              }
select new {x,y});

A: Just to complete this with an equivalent method chain syntax:
entity.Join(entity2, x => new {x.Field1, x.Field2},
                     y => new {y.Field1, y.Field2}, (x, y) => x);

While the last argument (x, y) => x is what you select (in the above case we select x).

A: I think a more readable and flexible option is to use Where function:
var result = from x in entity1
             from y in entity2
                 .Where(y => y.field1 == x.field1 && y.field2 == x.field2)

This also allows to easily change from inner join to left join by appending .DefaultIfEmpty().

A: As a full method chain that would look like this:
lista.SelectMany(a => listb.Where(xi => b.Id == a.Id && b.Total != a.Total),
                (a, b) => new ResultItem
                {
                    Id = a.Id,
                    ATotal = a.Total,
                    BTotal = b.Total
                }).ToList();

A: I used tuples to do that, this is an example for two columns :
 var list= list1.Join(list2,
                       e1 => (e1.val1,e1.val2),
                       e2 => (e2.val1,e2.val2),
                       (e1, e2) => e1).ToList();

A: var result = from x in entity
   join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }

A: var result = from x in entity
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }
             select new
             {
               /// Columns
              };

A: var result = from x in entity1
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }

You need to do this, if the column names are different in two entities.

A: Declare a Class(Type) to hold the elements you want to join. In the below example declare JoinElement
 public class **JoinElement**
{
    public int? Id { get; set; }
    public string Name { get; set; }

}

results = from course in courseQueryable.AsQueryable()
                  join agency in agencyQueryable.AsQueryable()
                   on new **JoinElement**() { Id = course.CourseAgencyId, Name = course.CourseDeveloper }
                   equals new **JoinElement**() { Id = agency.CourseAgencyId, Name = "D" } into temp1

A: from d in db.CourseDispatches
                             join du in db.DispatchUsers on d.id equals du.dispatch_id
                             join u in db.Users on du.user_id equals u.id
                             join fr in db.Forumreports on (d.course_id + '_' + du.user_id)  equals  (fr.course_id + '_'+ fr.uid)

this works for me


text:
Q: Error on Serialization I'm getting this error when I try to proceed on parsing the JSON. Does anyone know what I gotta do to fix it?

Error 1:  Cannot subscript a value of type 'AudiobookJSON' (aka 'Array<Dictionary<String, Any>>') with an index of type 'String'

Error on Print
File Model: Audiobook.swift:
import Foundation

struct Audiobook : Codable {
    let id: Int
    let descricao: String
    let urlImagem: String

    init(dictionary: AudiobookJSON) {
        self.id = dictionary["id"] as! Int//////ERROR MESSAGE ////////
        self.descricao = dictionary["descricao"] as! String/////ERROR MESSAGE
        self.urlImagem = dictionary["urlImagem"] as! String////ERROR MESSAGE
    }

}

Folder Networking: APIClient.swift:
import Foundation

typealias AudiobookJSON = [[String: Any]]

struct APIClient {

    static func getAudiobooksAPI(completion: @escaping ([Audiobook]?) -> Void) {

        let url = URL(string: "https://alodjinha.herokuapp.com/categoria")

        let session = URLSession.shared

        guard let unwrappedURL = url else { print("Error unwrapping URL"); return }

        let dataTask = session.dataTask(with: unwrappedURL) { (data, response, error) in

            guard let unwrappedDAta = data else { print("Error unwrapping data"); return }

            do {

                //let json = try JSONSerialization.jsonObject(with: unwrappedDAta, options: .allowFragments) as! [String:Any]
                //let posts = json["data"] as? AudiobookJSON
                let posts = try JSONDecoder().decode([Audiobook].self, from: unwrappedDAta)

                print(posts)

                completion(posts)

            } catch {
                print("Could not get API data. \(error), \(error.localizedDescription)")
            }
        }
        dataTask.resume()
    }
}

A: As I can see that AudiobookJSON is an array of key-value pairs that's why you are getting error: So you have to use codable like that:
First: you have to make Codable type struct like that(your codable struct variable names should be same as you are getting in response):
struct Audiobook: Codable {
    let id: Int?
    let descricao: String?
    let urlImagem: String?

}

Second: when you get the response then parse directly using codale like that:
guard let unwrappedDAta = data else { print("Error unwrapping data"); return }

do {

    let posts = try JSONDecoder().decode([Audiobook].self, from: unwrappedDAta)

    print(posts)
    completion(posts)

} catch let message {
    print("JSON serialization error:" + "\(message)")
}

You can directly use the response like:
for audio in posts {
  print("audio.id")
  print("audio.descricao")
  print("audio.urlImagem")
}


text:
Q: Converting video to .mp4 with Node.js I want to be able to do something like this:
var converter = require('converter');

converter.convert({
  from: 'avi',
  to: 'mp4',
  path: '/myvideo.avi',
  newPath: '/newvideo.mp4',
  error: function(err) {},
  success: function() {
    console.log('success!');
  }
});

Thanks!

A: Well, for one converter converts between xml, json, and yaml. So, you won't be able to convert an avi to an mp4 with that.
However, I have used node to spawn a child ffmpeg process for this very thing. Just an fyi, if you do choose to use ffmpeg via a child process and want to watch the log for progress and debugging, you will need to watch stderr. Ffmpeg reserves stdout to optionally stream the output of the conversion.

A: FFMPEG is good thing for play with video.
Try this command.
exec("ffmpeg -i filePath/fileName.ext filePath/newFileName.mp4");

You can set your other preset also.


text:
Q: How to create an HTML page that says Hello World n times in n different colors from python, I want to create an HTML page that says Hello World n times in n different colors where n is read from a config file in a different repository
and Spawn the page via python program
it would be more helpful we can use Javascript for the colors. I am able to display the hello world n number of times, but I dont know how to change the colors.
Here is the code I have written so far:
 import  ConfigParser
 import webbrowser

 configParser = ConfigParser.RawConfigParser()
 configParser.read("/home/suryaveer/check.conf")
 num = configParser.get('userinput-config', 'num')
 num2 = int(num)
 hello = """"hello world """
 hello2 = hello*num2
 message = """

"""+hello2+"""

 """
 f = open('x.html', 'w')
 f.write(message*num2)
 f.close()
 webbrowser.open("file:///home/suryaveer/x.html")

A: In order to style each "hello world" differently, they must be in different HTML blocks. You can achieve this wrapping each instance of "hello world" in a span.
hello = """"hello world """

This will add no visible content to your page, but will allow each instance to be accessed and styled individually.
If you want to do it all in Python, you could add an inline style to the span when you create it.
colors = [color1, color2, ... colorN]  # List of n colors

hello2 = ""
for c in colors:
    hello2 += """"hello world """.format(c)

Let me know if you need more help or want to know about other options (Javascript)

A: Finally I solved my problem
```
import  ConfigParser
import webbrowser
import random
def test():
    r = lambda: random.randint(0, 255)
    return('#%02X%02X%02X' % (r(),r(),r()))
configParser = ConfigParser.RawConfigParser()
configParser.read("/home/suryaveer/check.conf")
num = configParser.get('userinput-config', 'num')
num2 = int(num)
message = """<p style='color:{};'>hello world</p>"""
print "number read from file : " + str(num2)
f = open('out.html', 'w')
for i in range(0, num2):
    print message
    f.write(message.format(test()))
f.close()
webbrowser.open("file:///home/suryaveer/out.html")

```


text:
Q: Access enumerator of an enum formerly declared as protected For my project I'd like to widen the visibility of an enum formerly declared as protected in the baseclass.
class A {
protected:
    enum E { e = 0 };
};

class B : public A {
public:
    using A::E;
};

int main()
{
    B::E enum1; // okay
    enum1 = B::e; // fails: test.cpp:3:14: error: A::E A::e is protected
}

The reasons for this are simple:

*

*I don't control the base class, hence I cannot just make E public

*I don't want a huge switch-case statement for translating between a new enum in B and A::E
I'd expect(ed) the code to compile just fine.
I'm curious. What's the scientific explanation why the code fails to compile?

A: Making A::E public doesn't affect the names of the enumerators, so e is still protected.
Try with an additional using or add a static const E e = A::e to class B.

A: This is perfectly sane C++ code using C++11's scoping semantics:
int main()
{
    B::E enum1; // okay
    enum1 = B::E::e; // also okay
}


text:
Q: Google Line Chart hAxis formatting problematic in Firefox See image hAxis labels:

The hAxis labels are wrapping onto two lines, their values are, for example, 10.09 with no spaces. But on narrower screens its wrapping onto two lines, this is in Firefox.
In Chrome it works much better. This is how it looks in Chrome:

var options = {
    height: 314,
    areaOpacity: 0.18,
    enableInteractivity: false,
    isStacked: true,
    hAxis: {
        textStyle: {
            color: '#919fa9',
            fontName: 'Proxima Nova',
            fontSize: 11,
            italic: false
        }
    },
    vAxis: {
        slantedText: true,
        minValue: 0,
        textPosition: 'out',
        title: 'Revenue',
        titleTextStyle: {
            fontSize: 14
        },
        textStyle: {
            color: '#919fa9',
            fontName: 'Proxima Nova',
            fontSize: 11,
            italic: false
        },
        baselineColor: '#eff1f2',
        gridlines: {
            color: '#eff1f2',
            count: 15
        }
    },
    lineWidth: 2,
    colors: ['#00a8ff'],
    curveType: 'function',
    pointSize: 5,
    pointShapeType: 'circle',
    pointFillColor: '#008ffb',
    backgroundColor: {
        fill: '#ffffff',
        strokeWidth: 0,
    },
    chartArea: {
        left: 60,
        top: 10,
        width: '100%',
        height: 260
    },
    fontSize: 11,
    fontName: 'Proxima Nova',
    tooltip: {
        trigger: 'selection',
        isHtml: true
    },
    seriesType: 'bars',
    series: {
        0: { color: '#2db56e' },
        1: { color: '#cc0000' },
        2: {
            type: 'line',
            color: '#00a8ff',
            pointSize: 4,
            pointShapeType: 'circle'
        }
    }
};

How can I improve the appearance of the Firefox version? Because at present its very hard to read

A: try setting the following option to 1 --> hAxis.maxTextLines
hAxis: {
  maxTextLines: 1,
  ...

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['date', 'revenue'],
    ['10.01', 20],
    ['10.02', 30],
    ['10.03', 40],
    ['10.04', 50],
    ['10.05', 60],
    ['10.06', 70],
    ['10.07', 80],
    ['10.08', 90],
    ['10.09', 100],
    ['10.10', 120],
    ['10.11', 130],
    ['10.12', 150],
    ['10.13', 200],
    ['10.14', 220],
    ['10.15', 230],
    ['10.16', 240],
    ['10.17', 250],
    ['10.18', 260],
    ['10.19', 270],
    ['10.20', 280],
    ['10.21', 280],
    ['10.22', 290],
    ['10.23', 320],
    ['10.24', 340],
    ['10.25', 350],
    ['10.26', 360],
    ['10.27', 370],
    ['10.28', 380],
    ['10.29', 390],
    ['10.30', 400],
    ['10.31', 420]
  ]);

  var options = {
    height: 314,
    areaOpacity: 0.18,
    enableInteractivity: false,
    isStacked: true,
    hAxis: {
      maxTextLines: 1,
      textStyle: {
        color: '#919fa9',
        fontName: 'Proxima Nova',
        fontSize: 11,
        italic: false
      }
    },
    vAxis: {
      slantedText: true,
      minValue: 0,
      textPosition: 'out',
      title: 'Revenue',
      titleTextStyle: {
        fontSize: 14
      },
      textStyle: {
        color: '#919fa9',
        fontName: 'Proxima Nova',
        fontSize: 11,
        italic: false
      },
      baselineColor: '#eff1f2',
      gridlines: {
        color: '#eff1f2',
        count: 15
      }
    },
    lineWidth: 2,
    colors: ['#00a8ff'],
    curveType: 'function',
    pointSize: 5,
    pointShapeType: 'circle',
    pointFillColor: '#008ffb',
    backgroundColor: {
      fill: '#ffffff',
      strokeWidth: 0,
    },
    chartArea: {
      left: 60,
      top: 10,
      width: '100%',
      height: 260
    },
    fontSize: 11,
    fontName: 'Proxima Nova',
    tooltip: {
      trigger: 'selection',
      isHtml: true
    },
    seriesType: 'bars',
    series: {
      0: { color: '#2db56e' },
      1: { color: '#cc0000' },
      2: {
        type: 'line',
        color: '#00a8ff',
        pointSize: 4,
        pointShapeType: 'circle'
      }
    }
  };

  var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
  chart.draw(data, options);
});


text:
Q: java.lang.IllegalArgumentException: Service not registered: lp@f7269a6 I'm getting this exception but I don't know what is the reason for this.
I have searched for this error and I've seen that some people have registered a service, but I don't know which service it is.
This is the result of flutter doctor:

This is the message that results everytime when I run my app:

Update: I was looking for answer to my problem and I found that if I add these lines to my android\app\build.gradle everything works and the message doesn't show again.
implementation 'com.google.android.gms:play-services-basement:17.5.0'
implementation 'com.google.firebase:firebase-analytics:18.0.0'


text:
Q: Get link to original image with Picasa API Hi i need to get link to original image which i uploaded. I'm using this code but link whick i have is on resized image, how can i get link to original once using API (i don't want to manipulate with url bcz its wrong). Thx in advance. Here the code
        public void UploadImages(string[] filenames)
    {
        foreach (string file in filenames)
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
            System.IO.FileStream fileStream = fileInfo.OpenRead();
            PicasaEntry entry = (PicasaEntry)service.Insert(
new Uri("https://picasaweb.google.com/data/feed/api/user/default/albumid/default"), fileStream, "image/jpeg", file);
            fileStream.Close();
            urls.Add(entry.Media.Content.Url);
        }
    }


text:
Q: VLCj transcoding and file saving I want to develop a webcam recording java application shall shall work seamlessly on Windows, Linux and Mac. I am using the VLCj CaptureTest.java class provided by caprica software. I have a few queries and problems:

*

*Capture device MRL are give for Windows (dshow://) and Linux (v4l2:///dev/video0) but none for Mac.

*Only audio media option is given for Linux i.e. :input-slave=alsa://hw:0,0
What about Windows and Mac ?
I also have problems in transcoding that are very tricky. No video is shown when I run the class, a black window is shown and only an audio file is created for the following sout :
String[] options = {              ":sout=#transcode{vcodec=mp4v,vb=800,scale=1,acodec=mpga,ab=128,channels=2,samplerate=44100}:file{dst=" + fileName + "},dst=display}",
              ":input-slave=alsa://hw:0,0"
    };

Video and audio are shown and heard but no file is created for the following sout:
String[] options = {
              ":sout '#transcode{vcodec=mp4v,acodec=mpga,vb=800,ab=128,deinterlace}:duplicate{dst=display,dst=file{dst=" + fileName + "}'",
              ":input-slave=alsa://hw:0,0"
  };

and
String[] options = {
              ":sout '#transcode{vcodec=mp4v,acodec=mpga,vb=800,ab=128,deinterlace}:standard{access=file,mux=ts,dst=" + fileName + "}'",
":input-slave=alsa://hw:0,0"
            };

I had been searching Google and Stackoverflow but I didnt get what I need. Apologies for my lack of knowledge in VLCj

A: the main reason is recording a video depends on the input video and we should choose the right codec (or transcode) for this type of video.
Probably, You can try at first record the input video with VLC that produce the string option and then only choose the correct the option which make video visible!!!!!


text:
Q: Using ActiveRecord.create with belongs_to associations I'm using Rails 3.1 and have a simple transaction class that references a User model:
class User < ActiveRecord::Base
   has_many :transactions, :foreign_key => 'sender_id'
end

class Transaction < ActiveRecord::Base
   belongs_to :sender, :class_name => 'User'
   belongs_to :recipient, :class_name => 'User'
   attr_accessible :amount
end

The database schema is
create_table "transactions", :force => true do |t|
   t.decimal "amount"
   t.integer "sender_id", :null => false
   t.integer "recipient_id", :null => false
end

create_table "users", :force => true do |t|
end

I would like to create a set of initial transactions in the seeds.rb, but the underlying INSERT is never generated with foreign keys for the sender_id and recipient_id.  The signature of the method is:
ruby-1.9.2-p290 :022 >   Transaction.method(:create) =>
   #<Method: Transaction(id: integer,
                         amount: decimal,
                         sender_id: integer,
                         recipient_id: integer)
   (ActiveRecord::Base).create>

I've tried both
Transaction.create(
  amount:                0.50,
  sender:                User.first,
  recipient:             User.last,
)

and
Transaction.create(
  amount:                0.50,
  sender_id:             User.first.id,
  recipient_id:          User.last.id,
)

In each case, the INSERT statement is
SQL (0.6ms)  INSERT INTO `transactions` (`amount`, `recipient_id`, `sender_id`)
             VALUES (0.75, NULL, NULL)

I'm new to rails, so I'm sure this is a misunderstanding on my part, but I have not been able to find a solution from my reading of the rails docs.

A: Simple solution.  I just needed to change the attr_accessible line in the Transaction model to
attr_accessible :amount, :sender, :recipient

and all is well.


text:
Q: TypeError: coercing to Unicode: need string or buffer, list found: how to create a loop I'm working on a python script that will add a folder and all of its contents to a zip file using both zipfile and os.
z = ZipFile("mynewfile.zip", "w")
z.write(os.walk(directory))
z.printdir()
z.close()

Unfortunatly I've found that this is considered a list when using os.walk, which causes the error:
TypeError: coercing to Unicode: need string or buffer, list found: how to create a loop

Looking around at this error, I think I need a loop to cycle through each item in the list. My problem is that I can't figure out how to translate previous answers for my specific needs.
e.g TypeError: coercing to Unicode: need string or buffer, list found
I have also tried
for root dirs files in os.walk(directory)
    z.write(files)

which also causes the same error to occur.
However using
for root dirs files in os.walk(directory)
    z.write(root)

displays all the folders within the directory, but no files. I'm not sure why this does not count as a list.
I assume I need to somehow combine these 2 ideas, any help doing so would be greatly appeciated.

A: The following code should do it. Since files is a list. You simply iterate over that list and write the filenames to the zipfile. In the code below I'm also using the context manager with with that I don't need to close the file manually, because it does that for me.
from zipfile import Zipfile

for root, dirs, files in os.walk(directory):
    for f in files:
        with Zipfile('new_zip.zip', 'w') as z:
            z.write(f)


text:
Q: Unary operator ++ cannot be applied to an operand of type Int Why does the following swift code bring me the error "Unary operator '++' cannot be applied to an operand of type 'Int'" ???  (using swift-1.2 on Xcode-6.3.2)
struct Set {

    var player1Games: Int
    var player2Games: Int

    init() {
        self.player1Games = 0
        self.player2Games = 0
    }

    func increasePlayer1GameScore () {
        player1Games++   // error: Unary operator '++' cannot be applied to an operand of type 'Int'
    }

    func increasePlayer2GameScore () {
        player2Games++   // error: Unary operator '++' cannot be applied to an operand of type 'Int'
    }

}

A: Use the mutating keyword before a function declaration to indicate you're mutating the class variables.
OR
Change your struct to a class.
This should fix your issues :).

A: In Swift 3 and later, the reason for this error is that the ++ and -- operators have been removed from the language. It's recommended to use x += 1 instead.
See this very good answer for more detail on why this has happened.

A: The error message is a bit misleading. What you need to do is add mutating before func to specify that it will modify the struct:
struct MySet {

    var player1Games: Int
    var player2Games: Int

    init() {
        self.player1Games = 0
        self.player2Games = 0
    }

    mutating func increasePlayer1GameScore() {
        player1Games++
    }

    mutating func increasePlayer2GameScore() {
        player2Games++
    }

}

Note: Set is a type in Swift, I would suggest to use a different name for your struct.


text:
Q: Getting map tiles for osmdroid without mobile atlas creator I am writing a new android app that requires offline maps. I have been trying to use mobile atlas creator to get the map tiles, however mobile atlas creator has been marked by open street maps as a misuser of their services. You can be seen when trying to download a map using mobile atlas creator and getting blocked off tiles. I would like to know if there are any other options for generating map tiles for osmdroid for use on a android or if there are a better option for offline maps on a android device.

A: You can use 'Maperitive' (http://maperitive.net/)
It works in much the same way, but you'll have to package the generated map tiles into a .zip file manually to use them with osmdroid.

A: Change the map source in mobile atlas creator to Mapquest. Download all you want, check the folder (unzipped) name and rename it to MapquestOSM if you're using osmdroid to render.


text:
Q: Set a UIView as the background of a UITabBar I know how to customize the background color or the background image of a UITabBar:
tabBar.barTintColor = [UIColor ...];     // set background color
tabBar.backgroundImage = [UIImage ...];  // set background image

Unfortunately I have not found any option how to set a UIView as the background of a tab bar in the docs. Is there a way how I can achieve that?


text:
Q: Is the documentation of Merb as poor as it seems? I've read only good things about Merb, but the documentation on the website is basically the api reference, and right now there is no books already published.
Any resources about Merb?
I guess that I'll start to read the code, but it'd be nice to have another sources of information

A: The wonderful PeepCode have got a Merb PDF and screencast available for $9.

A: The source code is really readable, pretty compact and full of comments.
Then, each merb part have a complete README full of informations too.
You can read all this on github: http://github.com/wycats/merb/

A: I think merb has been pretty bad about good example code, tutorials and updating dated information. I really like the project, but have been stung by this several times. Now that it has reached a semi stable 1.0 I really hope that some people step up and get a bunch of the docs up to date, add warnings to old docs and point it towards newer information. It should be great to see how they deal with supporting the project now that it is 1.0

A: There's the Merb Wiki and also a community book project, you can see it at http://book.merbist.com/ and the source is on github: http://github.com/mattetti/merb-book/tree/master.

A: You are correct. As the website will tell you, Merb is a hacker's framework. Yehuda called it an experimentation ground in a recent infoq interview . There is a lack of good examples because the system has changed a lot since its inception. Dec pointed out the github pages. They are the best source of current documentation that I know of. With the release of 1.0 the API has become stable, which will hopefully lead to less broken code examples.
I can also highly recommend the #merb IRC channel on FreeNode. Friendly, smart people.


text:
Q: How to exclude some results of itertools permution by condition? I'm trying to solve the problem from the Rosalind.

Return: The total number of signed permutations of length n, followed by a list of
  all such permutations (you may list the signed permutations in any order).

I have an idea for a solution in Python, but I cannot implement it to the end. Consider for example that n = 2.
    numbers = [1, -1, 2, -2]
    ordering = permutations(numbers,n)

So now I've got some tuples as a result:

(1, -1) (1, 2) (1, -2) (-1, 1) (-1, 2) (-1, -2) (2, 1) (2, -1) (2, -2) (-2, 1)
  (-2, -1) (-2, 2)

I need to exclude those that have elements of equal modulus. For example, (-1, 1). Is it possible to implement this, and if possible, how?

A: A pythonic solution using list comprehension:
filtered_perms = [(x,y) for x,y in ordering if abs(x) != abs(y)]

Edit:
Code that works fine with python 3.7:
import itertools as itt

# create permutation generator object
perms = itt.permutations([-2, -1, 1, 2], 2)

# here generator is turned into a list with certain permutations excluded
filtered_perms = [(x,y) for x,y in perms if abs(x) != abs(y)]

# print whole list
print(filtered_perms)

# print first permutation
print(filtered_perms[0])

# print length of the list
print(len(filtered_perms))

Edit2:
To fix the problem with no elements in ordering:
ordering = list(itertools.permutations([-2, -1, 1, 2],2))

after that, ordering will be a list of all elements from itertools.permutations.

A: The filter function is probably what you're looking for.
list(filter(lambda pair: abs(pair[0]) != abs(pair[1]), ordering))

The condition might be wrong, I'm not sure what you mean by equal modulus.

A: The solutions proposed before are right, but if in the case that you want to process the resulting list after generating the permutations would be a nice idea to have a generator instead of a list. For that, I recommend you to design your own generator function based on itertools.permutations:
def signed_permutations(iterable, r=2):
    for item in permutations(iterable, r):
        if abs(item[0]) != abs(item[1]):
            yield item

And you can use it as:
for item in signed_permutations(numbers):
    do_something(item)

Or if you just want to create a list:
sigperm = list(signed_permutations(numbers))


text:
Q: Configure an app for deployment for as many device as possible I wanna to deploy a simple Iphone/Ipad application. Wanna to configure the application in Xcode so that I can deploy it and it will work on as many devices (IOS operating systems) possible. How should I configure the app to achieve this?

A: Make the app universal and set the Deployment Target to 3.0 as in the following screenshot.

To add support for the armv6 architecture, go to the Build Settings tab and modify the value of Architectures into $(VALID_ARCHS) as in the following screenshot.

Then remove armv7 from Required Device Capabilities in the Info tab as in the following screenshot.

A: Use only features available in iOS 3.13 and lower.


text:
Q: Fetching URLs with JS from file? Simple question from a noob :). The line below is from a javascript im trying to understand. The script is fetching data from a csv file to build a table based on a price slider. This line is the url that makes the visitor go to a specific website (a button i a table cell). My question is: What kind of file is in the /links/ directory and what exactly does '+line[6]+' mean?
content+='<a href="http://www.exampel.com/links/'+line[6]+'"

In a browser, the url looks like this (example): http://www.exampel.com/links/comapanyA

A: Without the actual file, I don't think it is discernible what exact type of file it is.
But, I can answer the "what exactly does '+line[6]+' mean?":
The plus signs on either side are string concatenation. So you are adding the results of "line[6]" to the url string.
"line[6]" is an array, with the sixth element being called by the index number "6".


text:
Q: include gwt-graphics into a Eclipse WebApp-Project I try to include the gwt-graphics library into a WebApp-Project made with Eclipse.
This is the description: https://code.google.com/archive/p/gwt-graphics/wikis/Manual.wiki
"Download gwt-graphics.jar and add it to the class path of your GWT project. In addition, you have to add the following line to the GWT module file:  After these two steps, you are ready to use GWT Graphics in your GWT project!"
I have done this and after I start the app in super-dev-mode, I got an error from the compiler:
"[ERROR] Unable to find 'org/vaadin/gwtgraphics/GWTGraphics.gwt.xml' on your classpath; could be a typo, or maybe you forgot to include a classpath entry for source?"
I am not sure how I can solve this.

A: Did you add it to the class path? If not, you can right click to the jar file and do Add to Classpath


text:
Q: Is it safe to use void** in special cases? Still undefined behavior? I want to create a function that frees the memory pointed to by the pointer and assigns this pointer to NULL. So I have to declare the argument as void** (an indirect pointer), I know that void* is safe for converting pointers, and using void** is undefined behavior. But I think that should be no problem in this situation.Will this function safely free any memory allocated by malloc() without undefined behavior?  Ask the hackers to help or suggest a better way.
C code:
#include <stdio.h>
#include <stdlib.h>

// If I use safeFree(&mac_arr); ,
// it will warn "Incompatible pointer types passing ' int **' to parameter of type ' void **'"
// So I used #define, don't care about this.

#define SAFE_FREE(p) safeFree((void **)&(p))

void safeFree(void ** ptr);

int main(void) {
    int *mac_arr = malloc(sizeof *mac_arr);
    SAFE_FREE(mac_arr);
    return 0;
}

void safeFree(void ** ptr){
    if (ptr != NULL && *ptr != NULL) {
        free(*ptr);
        *ptr = NULL;
    }
}

A: The behavior of such code is not defined by the C standard.
In main, mac_arr is an int *. The parameter safeFree receives is a pointer to void *. But int * and void * are not compatible types as defined by the C standard. They may have different sizes, alignment requirements, and representations. So converting the address of mac_arr from int ** to void ** and using *ptr for an lvalue of type void * is not portable.
It might "work" in many C implementations.
The SAFE_FREE macro you are contemplating is not a great remedy for pointer problems. While it sets the current pointer to an object to null, it has no way of affecting other pointers to the same object, such as links in linked lists or links in other data structures.
(It also does not need to test *ptr != NULL. free is specified to do nothing when it is passed a null pointer, so you would just be doubling up on a test that is already performed.)

A: The pointer types int ** and void ** are incompatible. The type cast just masks the incompatibility.
You could define:
#define SAFE_FREE(p) ((void)(free(p), (p) = NULL))


text:
Q: Office 365 REST API - Adding a Contact with JSON in C# I am trying to use the Office API to sync contacts from a few different sources. I have been having a problem trying to make a POST request with my JSON object to create a new contact. I have been looking at the MSDN pages but I feel like I should clarify I'm relatively new to C#, this is my first time trying to use REST protocols, and async methods in C#.
I have my code below, I tried to create a class that will add a new contact with a hard coded JSON string. I have tried a few various ways of trying to complete this request. Every request I have attempted gives me a 401 or 400 Error. I left a couple lines that I felt were closest to the solution but if those are not on the right track I have no problem trying something else. There is also a function that I believe could be useful but I couldn't really find documentation on how to use it:
await client.Me.Contacts.AddContactAsync();

Again I said I am pretty new to this so if there is a way to create an IContact item from the JSON and use the above method or to just pass the JSON directly either would be extremely useful. Even links to documentation that could be useful I would love to see. I'm a pretty stuck on this problem I've never posted a question before but I'm stumped on this.
Below is the documentation for the Contacts API maybe it will make more sense to you guys than me.
http://msdn.microsoft.com/en-us/library/office/dn792115(v=office.15).aspx
If anybody can figure out how to make a post request from that JSON it will be much appreciated.
using Microsoft.Office365.Exchange;
using Microsoft.Office365.OAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ContactSynchronization
{
    class OfficeAPIWrite
    {
        private static string odata = "@odata.type";
        private static string type = "#Microsoft.Exchange.Services.OData.Model.Contact";

        const string ServiceResourceId = "https://outlook.office365.com";
        static readonly Uri ServiceEndpointUri = new Uri("https://outlook.office365.com/ews/odata/Me/Contacts");

        static string _lastLoggedInUser;
        static DiscoveryContext _discoveryContext;

        public static async Task OfficeWrite()
        {
            try
            {
                var client = await EnsureClientCreated();

                string json = new JavaScriptSerializer().Serialize(new
                {
                    odata = type,
                    GivenName = "Mara",
                    Surname = "Whitley",
                    EmailAddress1 = "mara@fabrikam.com",
                    BusinessPhone1 = "425-555-1313",
                    Birthday = "1974-07-22T07:00:00Z"
                });

                try
                {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceEndpointUri);
                    request.Content = new StringContent(json);
                    request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }
                catch (System.Net.WebException e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            catch (Microsoft.Office365.OAuth.AuthenticationFailedException)
            {
                MessageBox.Show("Authentication Failed Exception was thrown");
            }
        }

        public static async Task<ExchangeClient> EnsureClientCreated()
        {
            if (_discoveryContext == null)
            {
                _discoveryContext = await DiscoveryContext.CreateAsync();
            }

            var dcr = await _discoveryContext.DiscoverResourceAsync(ServiceResourceId);

            _lastLoggedInUser = dcr.UserId;

            return new ExchangeClient(ServiceEndpointUri, async () =>
            {
                return (await _discoveryContext.AuthenticationContext.AcquireTokenSilentAsync(ServiceResourceId, _discoveryContext.AppIdentity.ClientId, new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier(dcr.UserId, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.UniqueId))).AccessToken;
            });
        }

        public static async Task SignOut()
        {
            if (string.IsNullOrEmpty(_lastLoggedInUser))
            {
                return;
            }

            if (_discoveryContext == null)
            {
                _discoveryContext = await DiscoveryContext.CreateAsync();
            }

            await _discoveryContext.LogoutAsync(_lastLoggedInUser);
        }
    }
}

A: Well I guess I figured out a work around. This uses a ContactObject that I created and newtonsoft's JSON serializer. I was hoping to see an example of the microsoft ExchangeClient in action, the only reason I am posting this is to help others that might have similar issues posting to the office API, the below code will run successfully. I'm still looking though if anybody can show me the correct way to use the ExchangeClient functions.
    // your request must include these, and a given name,
    // everything else is optional
    private const string odata = "@odata.type";
    private const string type = "#Microsoft.Exchange.Services.OData.Model.Contact";

    public static async Task CreateContact(ContactObject officeContact, string userEmail, string userPassword)
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://outlook.office365.com/ews/odata/Me/Contacts"));

        // Add the Authorization header with the basic login credentials.
        var auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userEmail + ":" + userPassword));
        request.Headers.Add("Accept", "application/json");
        request.Headers.Add("Authorization", auth);

        var createResponse = new JObject();
        createResponse[odata] = type; // this needs to be here for this to work
        if (!String.IsNullOrEmpty(officeContact.officeDisplayName)) createResponse["DisplayName"] = officeContact.officeDisplayName;
        if (!String.IsNullOrEmpty(officeContact.officeGivenName)) createResponse["GivenName"] = officeContact.officeGivenName;
        if (!String.IsNullOrEmpty(officeContact.officeMiddleName)) createResponse["MiddleName"] = officeContact.officeMiddleName;
        if (!String.IsNullOrEmpty(officeContact.officeNickName)) createResponse["NickName"] = officeContact.officeNickName;
        if (!String.IsNullOrEmpty(officeContact.officeSurname)) createResponse["Surname"] = officeContact.officeSurname;
        if (!String.IsNullOrEmpty(officeContact.officeEmailAddress1)) createResponse["EmailAddress1"] = officeContact.officeEmailAddress1;
        if (!String.IsNullOrEmpty(officeContact.officeEmailAddress2)) createResponse["EmailAddress2"] = officeContact.officeEmailAddress2;
        if (!String.IsNullOrEmpty(officeContact.officeEmailAddress3)) createResponse["EmailAddress3"] = officeContact.officeEmailAddress3;
        if (!String.IsNullOrEmpty(officeContact.officeHomePhone1)) createResponse["HomePhone1"] = officeContact.officeHomePhone1;
        if (!String.IsNullOrEmpty(officeContact.officeHomePhone2)) createResponse["HomePhone2"] = officeContact.officeHomePhone2;
        if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone1)) createResponse["BusinessPhone1"] = officeContact.officeBusinessPhone1;
        if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone2)) createResponse["BusinessPhone2"] = officeContact.officeBusinessPhone2;
        if (!String.IsNullOrEmpty(officeContact.officeMobilePhone1)) createResponse["MobilePhone1"] = officeContact.officeMobilePhone1;
        if (!String.IsNullOrEmpty(officeContact.officeOtherPhone)) createResponse["OtherPhone"] = officeContact.officeOtherPhone;
        if (!String.IsNullOrEmpty(officeContact.officeId)) createResponse["Id"] = officeContact.officeId;
        if (!String.IsNullOrEmpty(officeContact.officeCompanyName)) createResponse["CompanyName"] = officeContact.officeCompanyName;

        request.Content = new StringContent(JsonConvert.SerializeObject(createResponse));
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.SendAsync(request);

        try
        {
            response.EnsureSuccessStatusCode();
        }
        catch (System.Net.WebException)
        {
            MessageBox.Show("BAD REQUEST");
        }
    }


text:
Q: How to use apply function in R to remove loop I have a matrix
A <- matrix(c(1,2,1,2,4,4,6,7,6),nrow=3,ncol=3)

So basically I am replacing each element with the frequency of it occurring as seen in the corresponding column and taking the product of all the elements in the row.
My approach
fr <- c(paste("fr", 1:97, sep = ""))
for(i in 1:3){assign(fr[i],table(A[,i]))}
prob=matrix(c(rep(1,3)),3, byrow = T)
for (i in 1:3)
{
   for (j in 1:3)
{
    prob[i]<-prob[i]*get(fr[j])[as.character(A[i,j])]
}
}

Is there any way to solve this without writing loops, using the matrix structure?
I think we can use the apply
I am using R language

A: Your matrix:
A <- matrix(c(1,2,3,4,5,6,1,4,6), ncol=3, byrow=T)

Apply colwise a function that calculates the probability table:
B <- apply(A, 2, function(x) prop.table(table(x))[as.character(x)])
#           [,1]      [,2]      [,3]
# [1,] 0.6666667 0.3333333 0.3333333
# [2,] 0.3333333 0.3333333 0.6666667
# [3,] 0.6666667 0.3333333 0.6666667

Calculate the product rowwise:
apply(B, 1, prod)
#[1] 0.07407407 0.07407407 0.14814815


text:
Q: correctly save data of the form (x,y) in a csv file I guess this is very rather trivial.
I have a list of x and y values created as follows:
import numpy as np
x = np.linspace(0, 1, 1001)
y = 3*np.sin(x)**3 - np.sin(x)

How can I save the (x,y) values in .csv file, that is, in the form
x1, y1
x2, y2

etc. I think it has to do with delimiter keyword.
Thanks in advance.

A: You can use python csv package to write and save it to a .csv file. Use zip to create a single list of values from both x and y.
import csv

new_list = zip(x, y)
with open('file1.csv', 'wb+') as csvfile:
     filewriter = csv.writer(csvfile)
     filewriter.writerows(new_list)

A: Something like:
import numpy as np
x = np.linspace(0, 1, 1001)
y = 3*np.sin(x)**3 - np.sin(x)

np.savetxt('filename', np.vstack((x,y)).T, delimiter=', ')

This uses numpy.savetxt and numpy.vstack is used to prepare the data.
Default behaviour on arrays of dtype=np.float64 is using scientific-notation. You can control this using the fmt-parameter of numpy.savetxt.
Default-output looks like:
0.000000000000000000e+00, 0.000000000000000000e+00
1.000000000000000021e-03, -9.999968333348416283e-04
...


text:
Q: How to make a stopwatch timer For some reason the stopwatch looks to be alright, but when compared to the real deal it goes way too fast. I don't understand what I should do. Is it the timeInterval that I should change? I would like it to show millisecond, second and minutes, but everything I try just makes it worse.. Thank you
import UIKit
class ViewController: UIViewController {

    // Outlets
    @IBOutlet weak var minutes: UILabel!
    @IBOutlet weak var seconds: UILabel!
    @IBOutlet weak var milliSecondsLabel: UILabel!

    @IBOutlet weak var resetButton: UIButton!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var pauseButton: UIButton!

    // Variables
    var timer = Timer()
    var time: Int = 0
    var running: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        roundButtons()

    }

    @IBAction func resetTimer(_ sender: Any) {
        timer.invalidate()
        time = 0
        updateUI()
        running = false
    }

    @IBAction func startTimer(_ sender: Any) {
        if running {
            return
        } else {
            timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timerDidEnd), userInfo: nil, repeats: true)
            running = true
        }

    }

    @IBAction func pauseTimer(_ sender: Any) {
        timer.invalidate()
        running = false
    }

    func roundButtons() {
        resetButton.layer.cornerRadius = resetButton.frame.height / 2
        startButton.layer.cornerRadius = startButton.frame.height / 2
        pauseButton.layer.cornerRadius = pauseButton.frame.height / 2
    }

    @objc func timerDidEnd() {
        time += 1
        updateUI()
    }

    func updateUI() {

        var min: Int
        var sec: Int
        var mil: Int

        min = time / (60*60)
        sec = (time/60)%60
        mil = time & 60

        minutes.text = String(min)
        seconds.text = String(sec)
        milliSecondsLabel.text = String(mil)
    }
}

A: I'd suggest two things:

*

*Don't try to count the time elapsed yourself. Capture the start time and calculate the elapsed time from that. You can use Date method timeIntervalSince, or, because that's not guaranteed to return monotonically increasing values, use CACurrentMediaTime, like below.

*Rather than having a timer with an arbitrary 100 updates per second, instead use a CADisplayLink, which is optimally timed for device screen refresh rates.
E.g.:
class ViewController: UIViewController {

    // Outlets
    @IBOutlet weak var minutesLabel: UILabel!
    @IBOutlet weak var secondsLabel: UILabel!
    @IBOutlet weak var milliSecondsLabel: UILabel!

    @IBOutlet weak var resetButton: UIButton!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var pauseButton: UIButton!

    // Variables
    private weak var displayLink: CADisplayLink?
    private var startTime: CFTimeInterval?
    private var elapsed: CFTimeInterval = 0
    private var priorElapsed: CFTimeInterval = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        setFonts()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        roundButtons()
    }

    @IBAction func resetTimer(_ sender: Any) {
        stopDisplayLink()
        elapsed = 0
        priorElapsed = 0
        updateUI()
    }

    @IBAction func startTimer(_ sender: Any) {
        if displayLink == nil {
            startDisplayLink()
        }
    }

    @IBAction func pauseTimer(_ sender: Any) {
        priorElapsed += elapsed
        elapsed = 0
        displayLink?.invalidate()
    }
}

private extension ViewController {
    func startDisplayLink() {
        startTime = CACurrentMediaTime()
        let displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
        displayLink.add(to: .main, forMode: .common)
        self.displayLink = displayLink
    }

    func stopDisplayLink() {
        displayLink?.invalidate()
    }

    @objc func handleDisplayLink(_ displayLink: CADisplayLink) {
        guard let startTime = startTime else { return }
        elapsed = CACurrentMediaTime() - startTime
        updateUI()
    }

    func updateUI() {
        let totalElapsed = elapsed + priorElapsed

        let hundredths = Int((totalElapsed * 100).rounded())
        let (minutes, hundredthsOfSeconds) = hundredths.quotientAndRemainder(dividingBy: 60 * 100)
        let (seconds, milliseconds) = hundredthsOfSeconds.quotientAndRemainder(dividingBy: 100)

        minutesLabel.text = String(minutes)
        secondsLabel.text = String(format: "%02d", seconds)
        milliSecondsLabel.text = String(format: "%02d", milliseconds)
    }

    func roundButtons() {
        resetButton.layer.cornerRadius = resetButton.bounds.height / 2
        startButton.layer.cornerRadius = startButton.bounds.height / 2
        pauseButton.layer.cornerRadius = pauseButton.bounds.height / 2
    }

    func setFonts() {
        minutesLabel.font = UIFont.monospacedDigitSystemFont(ofSize: minutesLabel.font.pointSize, weight: .regular)
        secondsLabel.font = UIFont.monospacedDigitSystemFont(ofSize: secondsLabel.font.pointSize, weight: .regular)
        milliSecondsLabel.font = UIFont.monospacedDigitSystemFont(ofSize: milliSecondsLabel.font.pointSize, weight: .regular)
    }
}

That yields:

Completely unrelated, but anything dependent upon the size of views (e.g. the corner rounding) really belongs in viewDidLayoutSubviews, not viewDidLoad.


text:
Q: Threads to remove items from a Queue in C I just want to add items to a Queue, and a thread to remove them when something is in the queue. I was going with the approach of taking something off the stack and then just waiting like 10 seconds, then doing it again. Im just not sure how to approach throwing it into the thread. Im using C on PuTTy. I have the functions defied. didnt want to copy thme over to save space. delete() just remove the first one in. How would I have the Thread pause for 10 seconds. Sleep actually pauses the command window.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <conio.h>

#define MAXQUEUE 100

    struct queue
    {
        char name[256];
        struct queue *link;
    };

void *thread_routine(void *arg) {
    int tr;
    while(tr!=0) {
        sleep(10);
        delete();
    }

}

struct queue *start=NULL;

int i=0;

void main() {

    pthread_t thread1;
    pthread_t thread2;
    void *thread_result;
    int status;
    status = pthread_create(&thread1, NULL, thread_routine, NULL);
    if (status != 0) {
        printf ("thread create failed\n");
        exit(1);
    }
    /* wait for the thread to finish */

    status = pthread_join(thread1, &thread_result);
    if (status != 0) {
        printf ("thread join failed\n");
        exit(1);
    }
    printf ("child thread finished: result = %d\n", (int) thread_result);

    int ch;
    while(ch!=4) {
        printf("\nSelect an option:\n");
        printf("1 to add an item to the queue\n");
        //printf("2 to delete an item from the queue\n");
        printf("3 to print the queue\n");
        printf("4 for Exit\n");
        scanf("%d",&ch);
        switch(ch) {
            case 1:
                add();
                break;
            case 2:
                delete();
                break;
            case 3:
                print();
                break;
            case 4:

                break;
            default:
                printf("Incorrect option\n");
                break;
        }
    }
}

A:
Sleep actually pauses the command window.

That's because you joined the thread aka wait for it to finish.  Leave the thread detached and perhaps make an infinite loop for reading options.
Also, I would suggest using a mutex and condition variable for notifying the thread of when a new item gets inserted.  Doing it the "sleep" way should work though but it probably won't immediately delete the item as you expect.

A: Maybe you can use a alarm signal instead of sleep(). just set a handler for the signal and make sure no thread block it.


text:
Q: Python not so 'smart' for redundant operations Unlike many cases of c++, Python apparently is not as smart to optimize redundant operations, even between constants.
I did a simple benchmark to test math.cos in and out of a loop.
In this first case, I do Python calculate cos (3) 10 million times:
from datetime import *
from math import *

ini = datetime.now()
for a in range(10000000):
    x = cos(0)
fim = datetime.now()
print(fim - ini)

The result is about 0:00:01.360958.
Now, just replacing x = cos(0) by x = 1 (or just putting cos(0) in a variable outside the loop), the time about 3 times faster: 0:00:00.429995
Now, if the cos (0) operation always generates a constant (1), why does Python not optimize execution with a cache, thus avoiding repeating the same cos operation constantly?
One of Python's philosophies is to make easier the programmer's life. But in this case what is happening is just the opposite.

A: Because you have to program that yourself. This is what the creator of C++ meant when he said : "Higher level language." in quite literally ALL of his books. (No seriously, it's always there in the beginning.)  I don't think Python is meant to make the programmers life easier per say, but be less "expensive" than higher level languages.


text:
Q: How do you simplify this expression to show it follows an exponential distribution? I am trying to show that W = ln(X) - ln(α) follows an exponential distribution where I am using the Pareto distribution as the primary function.
The Pareto PDF is $f(x;α,φ) = \frac{φα^φ}{x^{φ+1}}$, x > α.
I have used the change of variable method to find the inverse of W, which is $X = e^w+α = g^{-1}(w)$, with $\frac{dx}{dw} = e^w$
After substituting $g^{-1}(w)$ into the Pareto PDF and multiplying by $\frac{dx}{dw}$ , I obtained $\frac{e^wφα^φ}{(e^w+α)^{φ+1}}$.
My question is: How do I simplify that expression to show it follows an exponential distribution? Algebra is one of my weak points.

A: I think after you correct your inverse the problem will seem much less painful.
$$
W = \log(X) - \log(\alpha) \implies
\exp(W + \log(\alpha)) = X
\implies
\alpha \exp(W) = X
$$
Good luck!


text:
Q: Customizing native web components styling by the consumer I've got a bunch of web components built where a consumer may be consuming one or many of these components.
They are used by adding a script tag to the components minified JS and then using the web component in your code like so: <my-cool-component data="someData" />.
CSS is built into these components, however, I need to add functionality to allow the consumers to customize the color theme, and I'm wondering if my approach here could be improved, or if there is a better approach all together.
Right now I have it setup so that when someone consumes any of the components, like my-cool-component and they have a window.coolComponentOptions set like this:
window.coolComponentOptions = {
  PRIMARY_BUTTON_BACKGROUND_COLOR: 'tomato',
  PRIMARY_BUTTON_COLOR: '#fff',
  URL_COLOR: 'tomato',
  FONT: 'Arial',
  SECONDARY_BUTTON_BACKGROUND_COLOR: 'lightblue',
  ... // Obviously this could grow tremendously
}

I do a check inside of my-cool-component and see if the coolComponentOptions exist and if so I map them to the CSS variables and use them inside of any of the components.
Alternatively I could make these values props on the component itself like <my-cool-component primary-btn-color="tomato" /> but this could cause the consumer to have an element with tons of attributes, and when they consume <other-cool-comp /> they will need to repeat these attributes again.
I'm curious if there are any other (better) options than the way I am doing it with the window variable, or if that approach could be improved upon or is completely acceptable?

A: CSS variables  can be global CSS definitions.
And shadowParts give you even more global CSS / shadowDOM styling.
Very good explainer by Monica Dinculescu, former Google Web Components team member
https://meowni.ca/posts/part-theme-explainer/


text:
Q: mapping a memory region from kernel I have a register which needs to be accessed from more then one driver.
It is a global read-only register resides in FPGA space
The register address is exported via device tree.
The first call to "request_mem_region" is ok, but any consecutive call fails.
Is there a way to share a register between drivers ?
Linux Kernel release is 4.14 , using petalinux
Thanks,
Ran

A: You need to remap the memory region with something like ioremap() after you have requested it.
Then, as Tsyvarev and others mentioned, create and export a function in your "parent" driver that returns the mapped memory.
Here is some rough code:
void * mapped_mem;

void * map_addr(unsigned int phy_addr, char * name) {

    struct resource * resource;
    void * mapped_mem;

    resource = request_mem_region(phy_addr, page_size * 4, name);
    // check for errors

    mapped_mem= ioremap_nocache(phy_addr, page_size * 4);
    // check for errors
    return mappedMem;

    //handle errors
}

void * get_mapped_addr(void) {
    return mapped_mem
}

EXPORT_SYMBOL( get_mapped_addr);

Now, mapped_mem should actually be tracked as part of your devices private info, but I figure thats beyond the scope of the question. Also, make sure to check for all possible errors. Make sure that request_mem_region() returns something >0 and not Null.


text:
Q: How to compile and run openmpi code using jupyterhub i am unable to load some of linux programming commands into jupyterhub, like mpicc, mpirun etc..
actually i want to run my openmpi code from jupyterhub.
From terminal i am able to run this code, but not from the notebook.

#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#define  MASTER 0

int main (int argc, char *argv[])
{
int   numtasks, taskid, len;
char hostname[MPI_MAX_PROCESSOR_NAME];

MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
MPI_Comm_rank(MPI_COMM_WORLD,&taskid);
MPI_Get_processor_name(hostname, &len);
printf ("Hello from task %d on %s!\n", taskid, hostname);

if (taskid == MASTER)
   printf("MASTER: Number of MPI tasks is: %d\n",numtasks);
MPI_Finalize();
}

Please guide me how to run mpi code from jupyterhub and how to load other linux command like module etc.
Regards,
Zain


text:
Q: how to make use of subclass in c# So Im making tetris and I need to make 7 blocks. The problem is is that I have to copy paste the code in 7 different classes(and then changing the grid) so I thought maybe using subclass would be much easier. The problem is I dont know how to do that.
this is my general block class:
public class Block
{
    Color Color;
    const int x = 4;
    const int y = 4;
    bool[,] vorm;

    Texture2D block;
    float FallTimer;
    public bool FallingBlock = false;
    Random Random = new Random();

    ZBlock zBlock = new ZBlock();
    TBlock tBlock = new TBlock();
    SBlock sBlock = new SBlock();
    OBlock oBlock = new OBlock();
    JBlock jBlock = new JBlock();
    LBlock lBlock = new LBlock();
    IBlock iBlock = new IBlock();

    public void HandleInput()
    {
        if (Tetris.inputHelper.KeyPressed(Keys.Down))
        {
            FallTimer = 0;
            for (int i = 0; i < blokvorm.GetLength(0); i++)
            {
                for (int j = 0; j < blokvorm.GetLength(1); j++) ;
                // blokvorm[i, j] += 15;
            }
        }
    }

    public void speed(GameTime gameTime)
    {
        double SpeedCounter = 3;
        int LevelCounter = 1;
        if (LevelCounter < Tetris.GameWorld.level)
        {
            SpeedCounter -= 0.5;
            LevelCounter++;
        }
        FallTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (Math.Round(FallTimer, 1) == SpeedCounter)
        {
            FallTimer = 0;
            //BlockPosition.Y += 15;

        }
    }

    public bool[,] blokvorm
    {
        get
        {
            vorm = new bool[x, y];
            for (int i = 0; i < x; i++)
                for (int j = 0; j < y; j++)
                {
                    vorm[i, j] = false;
                }

                    int r = Random.Next(7);
            if (r == 0)
            {
                vorm = ZBlock.zblock();
            }
            else if (r == 1)
            {
                vorm = TBlock.tblock();
            }
            else if (r == 2)
            {
                vorm = SBlock.sblock();
            }
            else if (r == 3)
            {
                vorm = OBlock.oblock();
            }
            else if (r == 4)
            {
                vorm = JBlock.jblock();
            }
            else if (r == 5)
            {
                vorm = LBlock.lblock();
            }
            else if (r == 6)
            {
                vorm = IBlock.iblock();
            }
            return vorm;
        }
    }

    public TBlock TBlock
    {
        get { return tBlock; }
    }
    public ZBlock ZBlock
    {
        get { return zBlock; }
    }
    public SBlock SBlock
    {
        get { return sBlock; }
    }
    public OBlock OBlock
    {
        get { return oBlock; }
    }
    public JBlock JBlock
    {
        get { return jBlock; }
    }
    public LBlock LBlock
    {
        get { return lBlock; }
    }
    public IBlock IBlock
    {
        get { return iBlock; }

    }

    public void Draw(SpriteBatch spriteBatch, ContentManager Content)
    {
        block = Content.Load<Texture2D>("Block");
        spriteBatch.Begin();
        if (!FallingBlock)
        {
            for (int i = 0; i < blokvorm.GetLength(0); i++)
            {
                for (int j = 0; j < blokvorm.GetLength(1); j++)
                    if (blokvorm[i, j])
                        spriteBatch.Draw(block, new Vector2(30 + (i * 15), 30 + (j * 15)), Color.White);
            }
            spriteBatch.End();
        }
    }
}

}
So How can I use this class to create other 7 block classes(T, L, I, O etc) easily?
Edit: My block all looks like this:
{

    const int x = 4;

    const int y = 4;

    public bool[,] tblock()

    {
        vorm = new bool[x, y];
        for (int i = 0; i < x; i++)
            for (int j = 0; j <y; j++)
            {
                vorm[i, j] = false;
                vorm[0, 1] = true;
                vorm[1, 1] = true;
                vorm[1, 0] = true;
                vorm[2, 1] = true;
            }

        Color = Color.Indigo;
        return vorm;
    }
    public void RotationLinks(InputHelper inputhelper)
    {
        bool[,] nieuw = new bool[x, y];
        if (inputhelper.KeyPressed(Keys.Left))
        {
            for (int a = 0; a < 4; ++a)

                for (int b = 0; b < 4; ++b)

                    nieuw[a, b] = vorm[x - a - 1, b];

            vorm = nieuw;

        }
    }

}

}
So to make other 6 I copied theh whole code and change the grid value. Is there a possible way to make it easier using bock class?