text:
Q: Setting parent-children relationships in constructor without leaking "this" variable I am writing some physics code that organizes objects into a hierarchical relationship, with each object of class Body having one parent (a subclass handles the root conditions) and zero to many children.  However, in order to instantiate a new Body, I must add it to its parent, and thus the constructor leaks "this" to the addChild method of its parent.
Currently the addChild method of Body is private; the only way to access it outside of Body's constructor is via Body.setParent.  However, I am concerned that there may be edge cases in which this still may expose a non-fully instantiated object.  The code below is simplified to only the relevant elements:
import java.util.Set;
import java.util.TreeSet;

public class Body {
    private Body parent;
    private Set<Body> children;

    public Body(Body parent) {
        // instantiates everything else first
        this.children = new TreeSet<Body>;
        this.parent = parent;

        parent.addChild(this);
    }

    public void setParent(Body parent) {
        this.parent.removeChild(this);
        this.parent = parent;
        parent.addChild(this);
    }

    private void addChild(Body child) {
        children.add(child);
    }

    private void removeChild(Body child) {
        children.remove(child);
    }
}

As expected, this code is "Leaking this in constructor," but there does not appear to be any way to set up the tree structure otherwise.  Is there another design pattern which could be used to avoid the potential of Body being visible before its constructor finishes running?

A: It is a good idea to keep the constructor simple.  In your case it is complicated by interacting with another object.  One reason is error handling which can be difficult in constructors.
Instead of using a constructor with a parameter, remove the parameter and call it like this.
var newBody = new Body();
newBody.setParent(parent);

The constructor would look like this.
public Body() {
    this.children = new TreeSet<Body>;
}

And change the setParent method to check for no current parent.
public synchronized void setParent(Body newParent) {
    if (parent != null)
        parent.removeChild(this);
    parent = newParent;
    if (newParent != null)
        newParent.addChild(this);
}

Notice that I also changed the name of the setParent parameter to not collide with the class variable.  Hard to find errors occur when you forget to use "this" in order to distinguish which "parent" you are referring to.
The constructor code I removed was really just a duplication of the setParent method anyway.
I added synchronized to the method so that you are assured that multiple calls to this method are done synchronously, otherwise the hierarchy could get damaged.
Of course, there are many ways to accomplish this.  But this is a simple way that I would use.


text:
Q: How to split a sorted list by element length I have a list of lists and it is sorted by the length of the children lists. e.g.
[[str], [str1, str2], [str1, str2], [str1, str2, str3], [str1, str2, str3],...]

I would like to split this list into sublists that only contain the children with the same length.
e.g.
[[[str], [str], [str]],  [[str1, str2], [str1, str2], [str1, str2]], ...]

I was wondering if there is a more efficient approach than mine below with hopefully a little less code.
child_list = []
new_list = []
old_list = [['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010'],
            ['e3a0b000', 'e3a0e000'], ['e92d4030', 'e59f5054'],
            ['e59f3038', 'e3530000'], ['e1a0c00d', 'e92dd800']]

# length of child
length = 1
for idx, i in enumerate(old_list):
    if idx == len(old_list)-1:
        child_list.append(i)
        new_list.append(child_list.copy())
    elif length == len(i):
        child_list.append(i)
    elif length < len(i):
        new_list.append(child_list.copy())
        del child_list[:]
        child_list.append(i)
        length = len(i)

Output:
[[['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010']],
 [['e3a0b000', 'e3a0e000'], ['e92d4030', 'e59f5054'],
  ['e59f3038', 'e3530000'], ['e1a0c00d', 'e92dd800']]]

A: You can use itertools.groupby in order to group the lists in old by length. Note that if the original lists are already ordered according to their length as in your example, sorting here is not necessary.
from itertools import groupby
[list(v) for k,v in groupby(sorted(old_list, key=len), key=len)]

 Output
[[['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010']],
 [['e3a0b000', 'e3a0e000'],
  ['e92d4030', 'e59f5054'],
  ['e59f3038', 'e3530000'],
  ['e1a0c00d', 'e92dd800']]]

A: groupby is probably the most intuitive in this case, however, you can solve the problem differently using a dictionary datastructure:
from collections import defaultdict
data = [["str"], ["str1", "str2"], ["str1", "str2"], ["str1", "str2", "str3"], ["str1", "str2", "str3"]]
dct = defaultdict(list)
for el in data:
    dct[len(el)].append(el)

print(dct.values())

Out:
[[['str']],
 [['str1', 'str2'], ['str1', 'str2']],
 [['str1', 'str2', 'str3'], ['str1', 'str2', 'str3']]]

Benchmark results: Using the dictionary based solution is faster:
from itertools import groupby
from collections import defaultdict

data = [["str"], ["str1", "str2"], ["str1", "str2"], ["str1", "str2", "str3"], ["str1", "str2", "str3"]]

def solve_with_groupby(data):
     return [list(v) for k,v in groupby(sorted(data, key=len), key=len)]

def solve_with_dict(data):
    dct = defaultdict(list)
    for el in data:
        dct[len(el)].append(el)
    return dct.values()

result:
In [10]: timeit solve_with_groupby(data)
100000 loops, best of 3: 5.75 µs per loop

In [11]: timeit solve_with_dict(data)
100000 loops, best of 3: 2.56 µs per loop

A: Just use groupby:
>>> l = [[1]*i for i in range(1, 5) for _ in range(3)]
>>> l
[[1], [1], [1], [1, 1], [1, 1], [1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
>>> result = [list(g) for _, g in groupby(l, key=len)]
>>> result
[[[1], [1], [1]], [[1, 1], [1, 1], [1, 1]], [[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]

Alternatively if they are not ordered, you can use defaultdict:
>>> import random
>>> random.shuffle(l)
>>> l
[[1, 1, 1], [1, 1, 1, 1], [1], [1], [1, 1], [1, 1], [1, 1, 1], [1, 1, 1], [1, 1], [1], [1, 1, 1, 1], [1, 1, 1, 1]]
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for e in l:
...     d[len(e)].append(e)
...
>>> result = list(d.values())
>>> result
[[[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1], [1], [1]], [[1, 1], [1, 1], [1, 1]]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Зеркальное копирование с помощью rsync Есть следующая система:
Около 20 хостов, с которых копируются 3 директории сертбота - renewal, live, archives. Все копируется на один резервный хост, на который переключается проект, в случае падения основного сервера. Если со старыми сертами доменов сертботу живется хорошо, то вот от конфигов в renewal ему рвет крышу, и тест вебсервера(nginx) фейлится. Бекапится все с помощью скрипта с rsync-ом. Есть ли возможность сделать зеркальное копирование директории renewal? Т.е. если я удалю домен test.com, должен удалиться домен на основном хосте, а при попытке сделать бекап, rsync чекает, что такого файла нет и тоже его удаляет на резервном хосте.

A:
rsync чекает, что такого файла нет и тоже его удаляет на резервном хосте

для этого служит опция --delete программы rsync:
$ rsync --delete прочие-опции-и-параметры

при её наличии, если на стороне-получателе присутствует файл/каталог, а на стороне-источнике такового нет, то файл/каталог будет удалён на стороне-получателе.
согласно man-странице программы rsync, момент удаления при наличии такой опции не определён. это можно изменить, употребив вместо (или вместе) одну из уточняющих опций:

*

*--delete-before — удалять до начала передачи содержимого файлов

*--delete-during — удалять во время передачи

*--delete-after — удалять после завершения передачи

*--delete-delay — практически то же, что и --delete-after, за исключением использования более нового не-инкрементального алгоритма составления списка файлов на удаление.

при использовании перечисленных опций настоятельно рекомендуется сначала добавить опцию --dry-run (-n), чтобы увидеть, какие действия будут произведены программой.

доп. чтение: $ man rsync


text:
Q: getting Fatal error of PDO::fetchColumn() I have a small function to count rows in a table, but when I run the function, I am getting "Fatal error: Call to a member function fetchColumn() on a non-object in P:\wamp\www\test\class\db.class.php on line 34". Below is my code:
<?php
class db {
    public $pdo;
    public function __construct() {
        $this->pdo = new PDO("mysql:dbname=" . database_name . ";host=" . database_host . "", database_user, database_pass, array(
            PDO::ATTR_PERSISTENT => true
        ));
    }

    public function countdata($field, $table, $where = "1") {
        $ar = $this->pdo->query("SELECT COUNT(`".$field."`) FROM `" . $table . "` WHERE " . $where . "");
        $cnt=$ar->fetchColumn(0);
        return $cnt;
    }
?>

A: try this
   $cnt=$ar->fetch();

Or this by giving an alias
   $ar = $this->pdo->query("SELECT COUNT(`".$field."`) as counts FROM `" . $table . "` WHERE " . $where . "");
   $cnt=$ar->fetchColumn(0);

A: you Might want to make sure $db-query()
You should check that your call to $db->query returns a valid PDO object


text:
Q: How to pass parameter to mssql query in node js I am changing my application's database from MySQL to MSSQL. I send parameters like below for MySQL database.
var sql = require('./db.js');
sql.query("select * from table where field1 = ? or field2 = ? ", [field1val, field2val], function (error, results) {
   if(error){
       //handle error
   }
   else{
      //handle the results
   }
}

How to do this in MSSQL or is it even possible to do this way? (I am using mssql module).
The stored procedure is the only way to achieve it? If so, how to do that in Nodejs mssql module?
What is the best practice to run a query in SQL server if we can't send parameter (which escapes the string in mysql automatically)?

A: I do parameterized SQL queries like this:
var sql = require('mssql');
var myFirstInput = "foo bar";
var mySecondInput = "hello world";

sql.input('inputField1', sql.VarChar, myFirstInput);
sql.input('inputField2', sql.VarChar, mySecondInput);

sql.query("SELECT * FROM table WHERE field1 = @inputField1 OR field2 = @inputField2")
.then(function(results)
{
    //do whatever you want with the results
    console.log(results)
})
.catch(function(error)
{
   //do whatever when you get an error
   console.log(error)
})

What happens here is that the sql.input('inputField1', sql.VarChar, myFirstInput) will change out the @inputField1 with the variable named myFirstInput. Same thing will happen for @inputField2 with mySecondInput.
This will help it from SQL injections

A: You can use try like this
var id = 1234

var query = (SQL
            `SELECT fname, lname, email
             FROM users
             WHERE id = ${id}`
            )

var sql = require('./db.js');
sql.query("select * from table where field1 = ${field1val} or field2 = ${field2val} ", [field1val, field2val], function (error, results) {
   if(error){
       //handle error
   }
   else{
      //handle the results
   }
}

A: var sql = require('./db.js');
sql.query(`select * from table where field1 = ${field1val} or field2 = ${field2val}`, function (error, results) {
   if(error){
       //handle error
   }
   else{
      //handle the results
   }
}

I think, it works for you :)


text:
Q: Service to identify incoming fax request in a windows machine. Is there any possibility to identify incoming fax request from a fax machine or its associated services.
I need to develop an application, which need to identify an incoming fax request along with sender information and stored in a common database. Is it possible to create some kind of service(windows service or windows application) to identify incoming message from a fax machine or any fax associated process or read file from a location where incoming fax message are stored.
Thanks in advance.

A: using com component Microsoft Fax Service Extended Com Type library, there's example written in c++, you can translate it to c#:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms693385(v=vs.85).aspx
and here is a c# example:
https://www.codeproject.com/tips/1041737/work-with-fax-using-faxcomexlib


text:
Q: Reading uncommitted data inside transaction (MS SQL Server 2008) I have written a program in C# to read data from to tables, transform it and write it to four other tables.
Three of the destination tables has an not null integer pointing to the primary key on the last destination table. I call this V.
When my program have read a chunk of data to memory and transformed it, it will use the SqlBulkCopy to write to the table V. Upon completion it will use a select-statement to retrieve the primary keys.
These primary keys will be assigned properly to the three other destination tables in memory. Finally the last three tables will be written to the database using SqlBulkCopy in one transaction.
However, if the program writes successfully to the table V, but fails to write the other three tables I have a bunch of dirty data.
Can I somehow map the data going into table V with their primary keys, inside a transaction surrounding the all the code?
I would be sincerely happy for any suggestion to solve my problem.

A: Place a foreign key on the three tables' columns that are referring back to the primary key on table V.  That will make certain there is no dirty data.  You may have to rework your logic and the order the tables are written in, but adding the foreign key should clean up the process and make it work smoother after refactoring.


text:
Q: Getting a particular position in canvas after zoom the canvas android I need to click on particular item on the canvas while zooming and moving functionalities also enable for canvas. I can calculate the rectangle position while moving the canvas. There I just calculate the touch movement distance by (CurrenTouchXPosition - StartXPosition).
public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction();

    int x = (int) event.getX();
    int y = (int) event.getY();

    float moveOffsetX = (event.getX() - start.x);
    float moveOffsetY = (event.getY() - start.y);

Then,
switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());
            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            break;
        case MotionEvent.ACTION_UP:
            Log.d(TAG, "action up");
                secondRectUpperX = secondRectUpperX + moveOffsetX;
                secondRectBottomX = secondRectBottomX + moveOffsetX;
                secondRectUpperY = secondRectUpperY + moveOffsetY;
                secondRectBottomY = secondRectBottomY + moveOffsetY;

This can identify the new canvas position of the rectangle. This works perfectly. I can identify the touch event of particular item while moving the canvas by this logic.
  But now i need to calculate the rectangle position relative to the canvas, after zoom the canvas. Whats the maths behind the zooming. If anyone knows please help in this.
Thank you.

A: Finally I come up with a solution.
I translate my touch position screen coordinates to canvas coordinates.
switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            ...
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            ...
            break;
        case MotionEvent.ACTION_UP:
            float []m = new float[9];
            matrix.getValues(m);
            float transX = m[Matrix.MTRANS_X] * -1;
            float transY = m[Matrix.MTRANS_Y] * -1;
            float scaleX = m[Matrix.MSCALE_X];
            float scaleY = m[Matrix.MSCALE_Y];
            lastTouchX = (int) ((event.getX() + transX) / scaleX);
            lastTouchY = (int) ((event.getY() + transY) / scaleY);
            lastTouchX = Math.abs(lastTouchX);
            lastTouchY = Math.abs(lastTouchY);

Thanks for Andres Cardenas Pardo's answer here
I could able to get the touch position coordinates according to the canvas coordinates. Since i know the coordinates of my drawn object, i check whether the touch position is within the range of drawn object.
if((lastTouchX>=firstRectUpperX && firstRectBottomX>=lastTouchX) && (lastTouchY>=firstRectUpperY && firstRectBottomY>=lastTouchY)) {
    isbtn1Clicked = true;

}


text:
Q: Expanding the power series $$g_2(\epsilon^1 \phi_1+ \epsilon^2 \phi_2+ \epsilon^3 \phi_3+\cdots)^2+ g_3(\epsilon^1 \phi_1+ \epsilon^2 \phi_2+ \epsilon^3 \phi_3+\cdots)^3+g_4(\epsilon^1 \phi_1+ \epsilon^2 \phi_2+ \epsilon^3 \phi_3+\cdots)^4+\cdots$$
I want to expand the above equation in such way to get  coefficients of $\epsilon^7$.
How long I have to do? Is there any way to get quick solution?
Edit: I need the coefficients of $\epsilon^7$ from the above equation i mentioned. The dots (...) mean the equation goes on with increasing dummy index and power index.

A: When multiplying two formal power series (not worrying about convergence), we have that the coefficient of $x^n$ in the product of
$$
(a_1x^1+a_2x^2+a_3x^3+\dots)(b_1x^1+b_2x^2+b_3x^3+\dots)
$$
is
$$
\sum_{k=1}^{n-1}a_kb_{n-k}
$$
This can be used to inductively compute the coefficients of each power of $x$ in
$$
\left(a_1x^1+a_2x^2+a_3x^3+\dots\right)^n
$$
This should be enough to compute the coefficient of $\epsilon^7$ as long as all subseries are included up to
$$
g_7\left(\epsilon^1\phi_1+\epsilon^2\phi_2+\epsilon^3\phi_3+\dots\right)^7
$$
and each of those include all terms with powers of $\epsilon$ less than or equal to $7$.

A: You will need as many terms as the power, so in this case you should go to $g_7$. The reason is that your functions contain at lowest order $\epsilon^1$ so expanding the addition will lead to terms at the outer power (i.e. $n$ in $(...)^n$) and higher.

A: Use geometric power series & Pascal's Triangle (Binomial Theorem).
First you convert your series to make it look like $(a+b)^n$ as much as possible, especially the higher power terms (see example).
Second, you use Binomial Theorem,
$(a+b)^n = \sum^{n}_{0} {n \choose k}a^{n-k}b^{k}$.
For example,
$(1+x+x^2+x^3+x^4)^3 = (\frac{1-x^5}{1-x})^3$, now you can use $(1-x^5)$ in the second step. Consider $\frac{1}{1-x}$ separately to match the exponents, and manipulate backwards to get the original series.

A: Consider how there can be a contribution to $\epsilon^7$ for example from the $g_4(\ldots)^4$ term:
You need foru factors together containing $\epsilon^7$, that is you need four (natural) exponents that sum to $7$. The possibilities are $$\tag17=1+1+1+4=1+1+2+3=1+2+2+2,$$ so we obtain summands $g_4\phi_1\phi_1\phi_1\phi_4\epsilon^7$, $g_4\phi_1\phi_1\phi_2\phi_3\epsilon^7$, $g_4\phi_1\phi_2\phi_2\phi_2\epsilon^7$. But: the summands in the pratiotions given in $(1)$ may occur in any order and the number of orders can be obtained by combinatorics. For example $1+1+1+4$ can be written in foru different orders, depending on where the $4$ is; $1+1+2+3$ can be written in $4\cdot 3=12$ orders as we can place the $3$ anywhere and then the $2$ anywhere else.
In summary, we obtain
$$ g_4(4\phi_1^3\phi_4+12\phi1^2\phi_2\phi^3+4\phi_1\phi_2^3)\epsilon^7.$$
Do the same with all powers up to $g_7(\ldots)^7$ and add. More is not needed because every summand in expanding $g_k(\ldots)^k$ will have $\epsilon^k$ and above.

A: Just check which terms of each power give rise to terms up to $\epsilon^7$ (for the square, need to go to $\epsilon^4$; for the cube, to $\epsilon^3$, ...). Feed the truncated stuff to your neighborly computer algebra package (like Maxima ow Wolfram Alpha) and cut the resullting mess at the right point.
If the $g_k$s come from a known function, ditto the $\phi_i$s, just ask for a power series expansion.


text:
Q: Python plot shows wire output I use python code
    ### Show the MSE for 0 to 60 degree
plt.figure(figsize=(15,6))
angle = Angle_MSE.values[:, 0]
MSE = Angle_MSE.values[:, 1]
plt.plot(angle, MSE, marker = 'o', color = 'red')
plt.legend(['MSE'], loc='upper right', fontsize= 15)
plt.title('MSE of angle prediction for each angle', fontsize= 25)
plt.ylabel('MSE of predictions', fontsize= 25)
plt.xlabel('Actual Angle', fontsize= 25)
plt.yticks(np.arange(0, 10000, step=1000))
plt.xticks(np.arange(0, 181, step=10))

Although it gives me the correct plot, it also shows information like this

How to remove the information it shows up?
Thanks in advance!

A: Ending the last line in a semicolon should do:
 plt.xticks(np.arange(0, 181, step=10));

Can't seem to find the relevant documentation page, but a semicolon is used to suppress the output of the commands in the interactive environments.

A: If you are running some code in jupyter notebook, the result of the last line is printed out.
The last line here is plt.xticks(np.arange(0, 181, step=10)) and xticks returns a list of info about each x-tick set up.
A solution is to finish with a statement or an expression which returns None, so that nothing is printed.
As another answer suggests, this can be accomplished by adding a semicolon (;) at the end. A semicolon separates two statements, so this way the last statement becomes empty and nothing is printed.


text:
Q: Syntax sugar for signal slot Recently I searched internet for good signal-slot library and wonder why on Earth we need such a cumbersome syntax for connecting member methods to signals?
Usually we have to write something like this:
mySignal.connect(&MyClassName::myMethodName, this);

or like that:
mySignal += std::bind(&MyClassName::myMethodName, this, std::placeholders::_1);

There is obvious duplication and unnessesary typing. Is it possible in modern C++ to implement such functionality in, for example, C# way:
mySignal += myMethodName

and automatically capture pointer to member function and this pointer from context?

A:
Is it possible in modern C++ to implement such functionality in, for example, C# way? [...]

No, that's not possible in C++. The syntax for taking the address of a member function requires qualifying the function name with the class name (i.e. &MyClassName::myMethodName).
If you don't want to specify the class name, one possibility is to use lambdas. In particular, if you can afford a C++14 compiler, generic lambdas allow writing:
mySignal.connect([this] (auto x) -> { myMethodName(x) });

Sadly, you can't get much terser than this. You can use default lambda capture to save some syntactic noise:
mySignal.connect([&] (auto x) -> { myMethodName(x) });

However, Scott Meyers warns against the pitfalls of default lambda capture modes in his new book Effective Modern C++. From the readability point of view, I'm not sure this improves things a lot compared to your first option.
Besides, things soon become awkward if you want your lambda to perfectly forward its argument(s) to myMethodName:
mySignal.connect([&] (auto&& x) -> { myMethodName(std::forward<decltype(x)>(x)) });

If you don't mind macros (I usually do), you can employ a preprocessor-based solution as suggested by Quentin in their answer. However, I would prefer using a perfect-forwarding lambda in that case:
#define SLOT(name) \
        [this] (auto&&... args) { name (std::forward<decltype(args)>(args)...); }

Which you could use like so:
e.connect(SLOT(foo));

Here is a live demo on Coliru.

A: Shall the preprocessor have a shot at it ?
#include <type_traits>
#define CONNECT(method) \
    connect(&std::remove_pointer_t<decltype(this)>::method, this)

Cane be used as follows :
mySignal.CONNECT(myMethodName);


text:
Q: material ui - Drawer is semi transparent in dark mode - mui5 Starting mui5, I noticed that the drawer in dark mode has become semi transparent. How to change the opacity of the drawer (not the backdrop).

  <SwipeableDrawer
    open={props.drawerOpened}
    onClose={props.toggleDrawer(false)}
    onOpen={props.toggleDrawer(true)}
    PaperProps={{
      sx: {
        opacity: 1,
      }
    }}
  >

The opacity: 1 above did not work.


text:
Q: Can I develop ios apps with xamarin on windows? I don't have any mac and I want to develop a mobile app on a cross-platform.
Do I have a chance to develop an app for Android at the same time for IOS without mac os?

A: There is website called MacInCloud that can be used. Xamarin actually recommends it for their Dev Days events for developers that don't have a mac. From their website:

In order to test the part of iOS , for those who do not have a MAC , you can use one of the weekly plans MacInCloud https://www.macincloud.com/checkout/managed.html ( Europe Server , OS El Capitain ) with the option Enable Remote Build Port enabled.

It might work for what you need.


text:
Q: How can I find my object with lodash by id? I have a userData object (which comes from a redux store) that contains this:
"packs": [
          {
            "name": "Docos",
            "id": "101",
            "price": 1000,
            "gifted": false
          },
          {
            "name": "Entertainment Plus",
            "id": "102",
            "price": 1000,
            "gifted": false
          }]

I am trying to find the 1st one like this:
 let pack = _.find(this.props.userData.packs, 'id', "101")

But when I run it it says pack is undefined? why?

A: read lodash documentation and watch examples
_.find

Arguments
collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.

1 shorthand
_.find(this.props.userData.packs, {id: '101'})

2 shorthand
_.find(this.props.userData.packs, ['id', '101'])

A: According to Lodash documentation, the correct syntax would be one of the followings:
_.find(this.props.userData.packs, function(p) { return p.id === '101'; });

The _.matches iteratee shorthand.
_.find(this.props.userData.packs, { 'id': '101' });

The _.matchesProperty iteratee shorthand.
_.find(this.props.userData.packs, [ 'id': '101' ]);

Read more from lodash docs: https://lodash.com/docs/4.16.6#find


text:
Q: Is there a way to specify which /res folders are auto-generated when creating a new Android project? When I create a new Android project in Eclipse, all of the default folders are auto generated.  This is a nice feature.  However, there are multiple /res folders that I don't need and I would like to disable auto generating them.  For example right now I am only developing for:
10" mdpi tablets, minSdkVersion=16, targetSdkVersion=19
The following /res/drawable and /res/values folders are auto generated:
drawable-hdpi, drawable-ldpi, drawable-mdpi, drawable-xhdpi, drawable-xxhdpi, values, values-v11, values-v14, values-w820dp
And I only need:
drawable-mdpi, values
Is there a way to specify which /res folders are auto-generated when creating a new Android project?

A: No. There isn't. If you don't need them, just delete them; however, I would recommend keeping them incase you need them in the future.


text:
Q: Image segmentation of Map I want to extract map contours using OpenCV.
I applied Bilateral filter and amplified the image.
So I could get better contrasted image.
And I've tried Watershed and meanshiftsegmentation.
But they all require manual operation such as seeds.
And it is hard to apply morph transformation and dilate to the image I've attached because it has different colors and letters.
I'd like you to tell me how to do segmentation automatically.
Thanks.
The Original image is here.

The Enhanced image is here.
And this is the what I've done using HSV color difference.


text:
Q: CMake multiple version of fortran *.mod files Fortran uses so-called mod files. They work similarly to a library. They are, however, important during compile stage of the objects. Now I am writing a CMake build for an older Fortran project. CMake luckily can recognise module dependencies. When CMake is compiling objects for a target they are stored in separed folder like:

CMakeFiles/target_name.dir/src/

Mod files are not. Instead, they are stored in the compiler execution directory. In order to make compile and link stage work I add:
 target_include_directories( ${EXECUTABLE}
   PRIVATE
     ${CMAKE_CURRENT_LIST_DIR}
   )

So in the end *.o files are stored in separate directories and *.mod are in the build directory. This has worked well for me for some time. But now I have a project where it is not possible. I have multiple targets that are compiled out of the same source files using different precompiled options. There are no problems with *.o files because they are stored in separate directories. But if *.mod files are changed by these directives they cannot be stored in the same build directory.
I was thinking to move *.mod files into a separate directory after each compile stage and linking them with ${CMAKE_CURRENT_LIST_DIR}/PRECOMPILER_OPTION_A, but still I would have a problem with race conditions if I would use parallel make.
Is there a solution where I can specify the compiler execution path per target? Or are you aware of some other solution that would work?

A: I found a solution here.
Basically the easiest solution is to manage Fortran_MODULE_DIRECTORY separatly for each target:
add_library(A OBJECT source.f90)
set_target_properties(A PROPERTIES Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/A)
target_include_directories(A PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/A)

add_library(B OBJECT source.f90)
set_target_properties(B PROPERTIES Fortran_MODULE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/B)
target_include_directories(B PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/B)


text:
Q: Not able to POST form data I have a Bootstrap form which contains Various fields which need to be entered by User.On Submission of this form I want it to send data to WebService.
But it is not sending user input data of the form.Here is the HTML Markup.
<form class="form-horizontal" role="form" action="~/RegisterUser" method="post">

         First Name

            <input type="text" class="form-control" id="FirstName" placeholder="FirstName" required />

</form>

and When I am seeing in chrome I am getting Request URL:http://localhost:54990/RegisterUser as Request URL.
Is there anything I am missing on the form or input field creation.
My Service is correct and I am able to get the debugger breakpoint over there with no data that was posted from User.

A: You always give all fields that should be accessed after posting a form a name-attribute. So do something like
<input type="text" class="form-control" id="FirstName" name="FirstName" placeholder="FirstName" required />`

then you can access it by using
$_POST['FirstName'] or however you want to access the values posted.

A: Your input doesn't have a name. Only named inputs can be successful.


text:
Q: Matching values in different datasets by groups in R I have the following two datasets:
df1 <- data.frame(
  "group" = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5),
  "numbers" = c(55, 75, 60, 55, 75, 60,  55, 75, 60,  55, 75, 60,  55, 75, 60))

df2 <- data.frame(
  "group" = c(1, 1, 2, 2, 2, 3, 3, 4, 5),
  "P1" = c(55, NA, 60, 55, 75, 75, 55, 55, 60),
  "P2" = c(55, 75, 55, 60, NA, 75, 55, NA, 60),
  "P3" = c(75, 55, 60, 75, NA, 75, 60, 55, 60))

In df1 each group has the same three numbers (in reality there are around 500 numbers).
I want to check whether the values in the column "numbers" in df1 are contained in the columns P1, P2, and P3 of df2. There are two problems I am stuck with. 1. the values in the numbers column of df1 can occur in different groups in df2 (defined by the group column in df1 and df2). 2. the datasets have different lengths. Is there a way to merge both datasets and have the following dataset:
df3 <- data.frame(
  "group"    = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5),
  "numbers"  = c(55, 75, 60, 55, 75, 60, 55, 75, 60, 55, 75, 60, 55, 75, 60,),
  "P1new"    = c(1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1),
  "P2new"    = c(1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1),
  "P3new"    = c(1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1))

where P1new (P2new and P3new respectively) contain the value 1 if df2$P1 contains the value in df1$numbers within the correct group (as I said numbers can reoccur in different groups). For example, P3 has the value 75 in group 1 but not in group 5. So in group 1 P3new would have a 1 and in group 5 P3new would have a 0.
This question is similar to Find matching values in different datasets by groups in R
 but I could not adapt the code according to my objectives. So, I would really appreciate any help.

A: Interesting question. Here's a way with dplyr functions:
library(dplyr)
df2 %>%
  group_by(group) %>%
  summarise(across(P1:P3, ~ list(unique(na.omit(.x))))) %>%
  inner_join(df1, .) %>%
  rowwise() %>%
  mutate(across(P1:P3, ~ +(numbers %in% .x)))

   group numbers    P1    P2    P3
   <dbl>   <dbl> <int> <int> <int>
 1     1      55     1     1     1
 2     1      75     0     1     1
 3     1      60     0     0     0
 4     2      55     1     1     0
 5     2      75     1     0     1
 6     2      60     1     1     1
 7     3      55     1     1     0
 8     3      75     1     1     1
 9     3      60     0     0     1
10     4      55     1     0     1
11     4      75     0     0     0
12     4      60     0     0     0
13     5      55     0     0     0
14     5      75     0     0     0
15     5      60     1     1     1

A: Another possible solution:
library(tidyverse)

map_dfc(names(df2[-1]),
        ~ df1 %>%
          group_by(group) %>%
          mutate(!!.x := +(numbers %in% df2[df2$group == cur_group_id(), .x])) %>%
          ungroup %>%
          select(all_of(.x))) %>%
  bind_cols(df1, .)

#>    group numbers P1 P2 P3
#> 1      1      55  1  1  1
#> 2      1      75  0  1  1
#> 3      1      60  0  0  0
#> 4      2      55  1  1  0
#> 5      2      75  1  0  1
#> 6      2      60  1  1  1
#> 7      3      55  1  1  0
#> 8      3      75  1  1  1
#> 9      3      60  0  0  1
#> 10     4      55  1  0  1
#> 11     4      75  0  0  0
#> 12     4      60  0  0  0
#> 13     5      55  0  0  0
#> 14     5      75  0  0  0
#> 15     5      60  1  1  1

Or, without purrr, another possibility:
library(dplyr)

df1 %>%
  inner_join(df2) %>%
  group_by(group) %>%
  mutate(across(starts_with("P"), ~ +(numbers %in% .x))) %>%
  ungroup %>%
  distinct


text:
Q: Kendo-Scheduler clear selection How to clear the selected events on kendo scheduler. I have a button outside the scheduler clear selection and removes all selections. I need to clear the selections on kendo on click of this button.

A: Did you try passing null as parameter to the select method?
select method

A: While this does clear the selection, it doesn't refresh the change event. Clicking on the last event selected will not fire the change event. You have to click on another event first.


text:
Q: Allow access to folder only from specific IP Address (or domain) and Port using .htaccess I am trying to secure access to a PHP page in a folder and only allow access to it from a specific IP Address and domain name but only on a specific port. I have seen a number of questions here but not including the PORT access.
I have added the following in the .htaccess file within the folder.
order allow,deny
deny from all
allow from 111.222.333.44:12345

However, this seems to be invalid.
What would be the correct way of doing it?


text:
Q: Tracking game progress with Google Analytics We are in the process of creating an Android game in which we want to use Google Analytics to track the users progress and engagement.
I have read through the Custom Dimensions/Metrics docs and got some good insights on how Analytics can be used for games. I am not completely sure though how to model our usecase though.
The game is a board game where we have three different modes in which you can play the game. In addition we have 10 different difficulty levels that can be applied on a mode.

*

*Mode 1 progresses linear though the difficulty

*Mode 2 lets the user choose a difficulty

*Mode 3 has no difficulty. It is a local player vs player.

The questions i want to ask are:

*

*How often to users play a particular mode?

*Which mode is the most popular?

*What difficulty level do they play in a particular mode?

*What is the finishing rate for a certain difficulty level in a mode?

I guess a clever combination of custom dimensions and metrics could answer those questions. If anybody is willing to hint me in the right direction i would be very thankful.


text:
Q: Java - Paint using class objects I am building a game for a class I'm working on and I need to paint some circles and rectangles. My problem is that there will be an unknown number of each the circles and rectangles, depending on user input. For example,if the user says 5, there will be 25 circles. What I wanted to do was make a circle class and rectangle class so I could just change the x and y coordinates using a loop.
Is it possible to make such a class "circle" and class "rectangle" with a parameterized constructor (x and y coordinates) to accomplish this?
FYI - This is a pegboard game where you drop a ball on the top and the ball bounces off pegs until being caught in the rectangle holders. I believe the true name of this game is called pachinko. Similar to this image, but just a rectangle instead of a triangle setup.
https://i.ytimg.com/vi/b3B8qiXyTJ8/maxresdefault.jpg
Lastly, I must use only swing and/or javafx (which I am unfamiliar with)

A: You can, indeed, create classes for Rectangle and Circle, each with their respective x and y coordinates. Such a class might look something like this:
public class Rectangle
{
    int x;
    int y;

    public Rectangle(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

When you want to create a new instance of this class, you would simply use:
Rectangle myRect = new Rectangle(0,25);

The above code would create an instance of Rectangle which has the x and y coordinates set to 0 and 25 respectively.
Hope this helps.
EDIT 1
Your loop could then do something like this to initiate your rectangles in a loop as you suggested:
Rectangle[] myRectangles = new Rectangle[25];
int x = 0;
int y = 0;
for (int i = 0; i < 25; i++)
{
    x = x+25;
    y = y+20;
    myRectangles[i] = new Rectangle(x,y);
}

A: Okay Guys, I figured this one out. For what I wanted to do, I simply had needed a paintComponent() method inside another class, then made my other class Ball() use this paintComponent() by requesting a Graphics object inside a my paintBall() method's parameters, then using this graphics object to paint my Ball class object. My answer seems wordy, but look at the Ball class below and you'll get it.
package main;
import java.awt.Graphics;

public class Ball{

private int x = 5;
private int y = 30;

// This method will help to animate the current object,
// The xPos and yPos will change, then frame will be repainted
public void setPos(int xPos, int yPos)
{
    x = xPos;
    y = yPos;
}

public void drawBall(Graphics g)
{
    g.setColor(Color.GREEN);
    g.fillOval(x, y, 30, 30);
}

}
So basically, i just had to create an instance of Ball inside my main class, like so:
Ball myBall = new Ball();
myBall.drawBall(g); // where g is the graphics object from paintComponent() in the main class.

A: NO YOU'RE DOING IT WRONG NEVER EVER EVER USE paintComponent();
Play around with this.
    package pet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.*;

public class pet extends JPanel implements MouseListener{
public static JFrame frame = new JFrame("frame");
public pet() throws IOException{
 setPreferredSize(new Dimension(870, 675));         //configuring panel
 addMouseListener(this);
}
public static void main(String[] args) throws IOException{
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComponent newContentPane = new pet();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
    frame.addMouseListener(new pet());
}
public void paintRectangleAtPoint(Graphics g, int x, int y, String shoutout){
g.setColor(Color.BLACK);
g.drawRect(x, y, 100,100);
System.out.println("See, you can send variables in, too "+ shoutout");
}
public void paintStuff(Graphics g, int x, int y){
g.setColor(Color.BLACK);
g.drawOval(x, y, 100,100);
}
@Override
public void mouseClicked(MouseEvent e) {
paintStuff(frame.getGraphics(),e.getX(), e.getY());
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
PaintRectangleAtPoint(frame.getGraphics(),100, e.getY(), "entered");
}
@Override
 public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}


text:
Q: How to use contentful-management to add an asset to an entry in one api call? I would like to add an asset along with an entry. I'm using a form to enter some data and upload an image all in one API call. I'm using cloudinary to store images, but Contentful-Management is giving me a 409 status code and a 'Version Mismatch' error.
These are the steps I'm taking below (add any if you've seen a step I've overlooked, it's much appreciated)
#1. Get space by space id
#2. Get environment
#3. Create Entry
#4. Create a new asset
#5. Assign uploaded image as an entry field

'data' is all the data I need to make a post for a properting posting, and the uploadHref is the link to a single image from  Cloudinary.
       const postProperty = (data: Partial<Property>, uploadHref: string) => {
            const SPACE_ID = process.env.NEXT_CONTENTFUL_SPACE_ID;
            const client = createClient({
              accessToken: process.env.NEXT_CONTENTFUL_PERSONAL_ACCESS_TOKEN as string,
            });
            // # 1 Get space by space id
            client.getSpace(SPACE_ID).then((space: Space) => {
              // # 2 Get environment
              space.getEnvironment("master").then(async (environment: Environment) => {
                // # 3 Create Entry
                environment
                  .createEntry("propertyListings", {
                    fields: {
                      id: {
                        "en-US": faker.datatype.number(4) + "-" + data.streetAddress,
                      },
                      firstName: {
                        "en-US": data.firstName,
                      },
                      lastName: {
                        "en-US": data.lastName,
                      },
                      email: {
                        "en-US": data.email,
                      },
                      phone: {
                        "en-US": data.phone,
                      },
                      price: {
                        "en-US": data.price,
                      },
                      streetAddress: {
                        "en-US": data.streetAddress,
                      },
                      city: {
                        "en-US": data.city,
                      },
                      state: {
                        "en-US": data.state,
                      },
                      zipcode: {
                        "en-US": data.zipcode,
                      },
                      latitude: {
                        "en-US": Number(data.latitude as number),
                      },
                      longitude: {
                        "en-US": Number(data.longitude as number),
                      },
                      bedrooms: {
                        "en-US": data.bedrooms,
                      },
                      bathrooms: {
                        "en-US": data.bathrooms,
                      },
                      sqft: {
                        "en-US": Number(data.sqft),
                      },
                      carSpaces: {
                        "en-US": data.carSpaces,
                      },
                      type: {
                        "en-US": data.type,
                      },
                      datePosted: {
                        "en-US": data.datePosted,
                      },
                      petFriendly: {
                        "en-US": data.petFriendly,
                      },
                      images: {
                        "en-US": [],
                      },
                    },
                  })
                  .then(entry => {
                    entry.publish();
                    return environment.getEntry(entry.sys.id)
                  })
                  .then(function (entry: Entry) {
                    // #4 Create a new asset in my Contentful media section
                    environment
                      .createAssetWithId(faker.datatype.number(4).toString(), {
                        fields: {
                          title: {
                            "en-US": data.streetAddress,
                          },
                          file: {
                            "en-US": {
                              contentType: "image/jpeg",
                              fileName: data.streetAddress + ".jpeg",
                              upload: uploadHref,
                            },
                          },
                        },
                      })
                      .then(async (asset) => await asset.processForAllLocales())
                      .then(async (asset) => await asset.publish())
                      .then(function (asset) {
                        // # 5 Assign uploaded image as an entry field
                        entry.fields["images"]["en-US"] = {
                          sys: {
                            id: asset.sys.id,
                            linkType: "Asset",
                            type: "Link"
                          },
                        };

                        return entry.update()
                       })
                      .then(entry => entry.publish())

                      console.log('Entry object value: ', entry)
                      return entry.update()
                  })
                  .catch(err => console.log("Error Message!: ", err))
              });
            });
          };

A: Contentful DevRel here.
If you're running into VersionMisMatch most you are not re-assigning resources after creation or update. Contentful's API responds every write operation with a new entry version, this way it's prevented to overwrite newer data.
I rewrote your example (untested) to reassign returned entry and asset objects with the results from the API.
async function createEntryWithAsset() {
    const space = await client.getSpace(SPACE_ID);
    const environment = await space.getEnvironment("master");

    /**
     * Entry creation and publish
     */
    let entry = await environment.createEntry("propertyListings", {
        /* ... */
    });
    // reassign `entry` to have the latest version number
    entry = await entry.publish();

    /**
     * Asset creation and publish
     */
    let asset = await environment.createAssetWithId(
        faker.datatype.number(4).toString(),
        {
          /* ... */
        }
    );
    // reassign `asset` to have the latest version number
    asset = await asset.processForAllLocales();
    asset = await asset.publish();

    /**
     * Update entry with new asset
     */
    entry.fields["images"]["en-US"] = {
        sys: {
          id: asset.sys.id,
          linkType: "Asset",
          type: "Link",
        },
    };
    entry = await entry.update();
    entry = await entry.publish();
}

createEntryWithAsset();


text:
Q: Como unificar datas com dataframe no Python Boa tarde pessoal, estou com a seguinte situação. Tenho uma planilha com as seguintes colunas: nome, sobrenome, datas(de 2011 até 2021)
Segue a tabela para visualizarem:

Como vêem, essas datas estão fora de ordem. Como posso ordená-las sem mudar de posição as colunas nome e sobrenome?
Eu cheguei a executar o código da seguinte maneira:
df_json_meses = df_json1.iloc[:, 58:64] # Coluna referente aos meses de ago até dez/2020

df_json_meses2 = df_json1.iloc[:, 52:55] # Coluna que se refere aos meses jan a maio/2021

df_json_meses3 = df_json1.iloc[:, 99] # coluna referente ao mês de jun/2021

df_json_meses4 = df_json1.iloc[:, 55:57] # coluna referente aos meses Jul e Ago/2021

df_json_soma_meses = pd.concat([df_json_meses, df_json_meses2 , df_json_meses3,

df_json_meses4], axis=1)
df_json_nome = df_json1.iloc[:, :2]

df_json_unico = pd.concat([df_json_nome, df_json_soma_meses], axis=1)

Consegui organizar conforme eu queria, só que me atende para esse relatório, agora se eu gerar um novo relátorio, e gerar novas colunas ou menos colunas e a quantidade for menor ou maior que eu setei no código, eu terei que alterar na mão? Se sim, eu não quero isso. Como posso automatizar esse código da melhor forma possível?
Segue o resultado final do relatório:

Agradeço imensamente quem puder ajudar.

A: Partindo do seguinte conjunto de dados como exemplo:
df = pd.DataFrame({
    'Nome': ['João', 'José'],
    'Sobrenome': ['Da Silva', 'Soares'],
    '2011-02': [10, 20],
    '2009-08': [90, 200],
    '2011-12': [1, 5],
    })
print(df)

# output:
#    Nome Sobrenome  2011-02  2009-08  2011-12
# 0  João  Da Silva       10       90        1
# 1  José    Soares       20      200        5

Primeiro, reordene todas as colunas com df.sort_index (como as datas estão no formato YYYY-MM, o algoritmo de ordenamento padrão dá conta de ordená-las em ordem crescente):
df = df.sort_index(axis=1)
print(df)

# output:
#    2009-08  2011-02  2011-12  Nome Sobrenome
# 0       90       10        1  João  Da Silva
# 1      200       20        5  José    Soares

As colunas de datas ficaram ordenadas - só falta trazer as colunas Nome e Sobrenome para a frente. Podemos fazer isso usando df.pop e df.insert para retirar a coluna e reinseri-la no começo do dataframe:
df.insert(0, "Sobrenome", df.pop('Sobrenome'))
df.insert(0, "Nome", df.pop('Nome'))
print(df)

# output:
#    Nome Sobrenome  2009-08  2011-02  2011-12
# 0  João  Da Silva       90       10        1
# 1  José    Soares      200       20        5

Por fim, caso você queira que as colunas de data estejam em ordem decrescente, basta passar o argumento ascending=False ao chamar o método df.sort_index.


text:
Q: C# Break Other Function Loop in Another Function I am having two functions - one is runs some commands on my serial port within a loop, the other one is an event handler that should stop the execution of the loop in the first method. Here is some sample code.
public void btm_Processing_Click(object sender, EventArgs e)
{
    for (int i = 1; i <= x ; i++)
    {
        // My processing commands are here .
    }
}

And here is my stop button event handler.
private void btm_Stop_Click(object sender, EventArgs e)
{
    var dialogResult = MessageBox.Show("Do you want to stop processing?",
                                       "Error",
                                       MessageBoxButtons.YesNo);

    if (dialogResult == DialogResult.Yes)
    {
        // Here is where I want to break that loop.
    }
    else
    {
        // Do other things.
    }
}

I am not sure how I can do this.

A: The best way to do this would be to use a BackgroundWorker thread to execute your loop, then you can cancel it later from the main thread later.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
The easier way would be the make a global variable that you set
private volatile bool isWorking = false;
public void btm_Processing_Click(object sender, EventArgs e)
{
    isWorking = true;
    for (int i = 1; i <= x ; i++)
    {
        //My Processing Commands are Here
        if(!isWorking)
            break;
    }
}

private void btm_Stop_Click(object sender, EventArgs e)
{
    DialogResult dialogResult = MessageBox.Show("Do You Want To Stop Processing ? ", "Error", MessageBoxButtons.YesNo);
    isWorking = dialogResult != DialogResult.Yes;
}

A: Set a break variable;
private volatile bool shouldStop = false;

private void btm_Processing_Click(object sender, EventArgs e)
{
    for (int i = 1; i <= x ; i++)
    {
        //My Processing Commands are Here

        if (shouldStop)
        {
            shouldStop=false;
            break;
        }
    }
}

private void btm_Stop_Click(object sender, EventArgs e)
{
    var dialogResult = MessageBox.Show("Do you want to stop processing?",
                                       "Error",
                                       MessageBoxButtons.YesNo);

    if (dialogResult == DialogResult.Yes)
    {
        shouldStop = true;
    }
    else
    {
        // Do other things.
    }
}


text:
Q: .NET Setting Thirdparty dll version dependencies with manifest file I developed a .NET dll that depends on a third party dll with version 10.1.2 and has publickeytoken etc.
Now, this third party dll is release with new version 11.0. and i want to make use of this new version from my .net dll. I dont want to recompile against new version of third party dll. Instead can i have manifest xml file for my dll to dynamically define the third party dll version?
Is that the purpose of manifest files?

A: Basically, i added the following to app.config
<dependentAssembly>
    <assemblyIdentity name="Microsoft.AnalysisServices.AdomdClient"
                      publicKeyToken="89845dcd8080cc91"
                      culture="neutral" />
<bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.0.0" />
  </dependentAssembly>

And that took care.Thanks Hans.


text:
Q: Difference between pass-by-value and pass-by-reference A MS help page about the difference between pass-by-value and pass-by-reference seems quite clear to me:
http://msdn.microsoft.com/en-us/library/8b0bdca4.aspx
However, a user comment at the end has confused me somewhat. It says (among other things) this:

if you don't use the ref or out keywords, then arguments to methods
  are passed by value.

The comment seems quite wrong to me. Is it?
(I posted part of the comment out of context: Here's the full comment:)

The text says: "... but when a class instance is passed, a reference
  is passed. ..." This is incorrect, as you can see in:
C# Language specification Version 4.0 (a Microsoft free download)
  5.1.4 Value parameters A parameter declared without a ref or out
  modifier is a value parameter.
So, in the example above, the class instance is passed by value, and
  not by reference.

It is the full comment which is really confusing me... The class instance is passed by value and not by reference? Does that not imply that the instance bytes are pushed onto the stack?

A: The comment is true. Without ref or out, the variable is passed by value. However, with objects, what you are passing by value is a reference.
The only time you would want to pass an object-reference by reference is if you are assigning a new object to the parameter within the method and you want that reassignment to affect the caller's copy of the reference.
You aren't ever really passing an object around. Instead you are passing around references to an object. With that in mind, this byval/byref business applies to the object-reference, not the object itself.
Jon Skeet has a great post about this topic.

A: The complete comment is misleading. The object's reference is passed by value.

A: The comment is completely correct. The confusion here is that value types and reference types are pretty much unrelated to passing an argument by value or by reference.
When you pass a value type as a non-ref parameter, you pass its value. That's clear enough. For a reference type, though, you are still only passing a value: You are passing the value of the reference itself.
If the parameter is ref/out, though, then you are actually saying that the parameter is an alias for the variable that is actually being passed in. In that case, it doesn't matter if it's a value type or a reference type; a reference to the variable is being passed, not just a value.


text:
Q: Apache No 'Access-Control-Allow-Origin' header I tried to search between old questions but i didn't find how to figure out my issue
I have a LF site; all works pretty good; when i go on http://localhost:8080/ i have no problem and no error is shown on firebug and/or chrome console
I configured then, an Apache HTTP Server. All seems to me correct but when i try the URL http://localhost I see my site but some resources are not loaded. In chrome console (but also in firebug) I get the following error:

2(index):1 Font from origin 'http://localhost:8080' has been blocked
  from loading by Cross-Origin Resource Sharing policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost' is therefore not allowed access.

I don't know how to figure out this issue. It seems to me an Apache configuration mistake.
This is my virtual host configuration:
<VirtualHost *:80>
    #CORS
    <Directory "/var/www/">
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
    # Always set these headers.
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Max-Age "1000"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
    # Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]

    ProxyPass /c http://localhost:8080/c
    ProxyPassReverse /c http://localhost:8080/c
    ProxyPass /si http://localhost:8080/si
    ProxyPassReverse /si http://localhost:8080/si
    ProxyPass /image http://localhost:8080/image
    ProxyPassReverse /image http://localhost:8080/image
    ProxyPass /documents http://localhost:8080/documents
    ProxyPassReverse /documents http://localhost:8080/documents
    ProxyPass /html http://localhost:8080/html
    ProxyPassReverse /html http://localhost:8080/html
    ProxyPass /sprite http://localhost:8080/sprite
    ProxyPassReverse /sprite http://localhost:8080/sprite
    ProxyPass /combo http://localhost:8080/combo
    ProxyPassReverse /combo http://localhost:8080/combo
    ProxyPass / http://localhost:8080/web/mySimpleLog
    ProxyPassReverse / http://localhost:8080/web/mySimpleLog
    ErrorLog logs/mySimpleLog-error_log
    CustomLog logs/mySimpleLog-access_log common
</VirtualHost>

It seems to me all correct... is there any other option i should put?
Do you have any idea where I'm wrong?
Thank you
Angelo

A: You're setting your CORS headers only on port 80, but the cross-origin part is from port 80 to port 8080 -- you should move the Header set ... outside of virtual host context or duplicate it in your 8080 vhost.


text:
Q: Security group does not appear to belong to the same VPC as the input subnets This is my terraform file to create a Fargate ECS service.
variable "aws_region" { }
variable "flavor" { }  # test or prod
variable "task_worker_service_name" { }
variable "task_cpu" {}
variable "task_memory" {}
variable "az_count" {}

terraform {
  required_version = "= 0.12.6"
}

provider "aws" {
  version = "~> 2.21.1"
  region = "${var.aws_region}"
}

data "aws_availability_zones" "available" {}

data "aws_iam_policy_document" "ecs_service_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "Service"
      identifiers = [ "ecs.amazonaws.com" ]
    }
  }
}

data "aws_iam_policy_document" "task_worker_iam_role_policy" {
  statement {
    actions   = [ "sts:AssumeRole" ]
    principals {
      type = "Service"
      identifiers = [
        "ecs-tasks.amazonaws.com"
      ]
    }
  }
}

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "Service"
      identifiers = [ "ecs-tasks.amazonaws.com" ]
    }
  }
}

resource "aws_iam_role" "ecs_service_role" {
  name = "${var.flavor}-task-ecs-service-role"
  path = "/"
  assume_role_policy = "${data.aws_iam_policy_document.ecs_service_policy.json}"
}

resource "aws_iam_role_policy_attachment" "ecs_service_role_attachment" {
  role = "${aws_iam_role.ecs_service_role.name}"
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceRole"
}

resource "aws_vpc" "ecs" {
    cidr_block  = "10.0.0.0/16"
    enable_dns_hostnames = true
    enable_dns_support = true
    instance_tenancy = "default"

    tags = {
      Name = "ecs"
    }
}

resource "aws_security_group" "vpc_ecs_task_worker" {
    name        = "${var.flavor}-vpc_ecs_task_worker"
    description = "ECS Allowed Ports"

    ingress {
        from_port       = 32768
        to_port         = 65535
        protocol        = "tcp"
        cidr_blocks     = ["0.0.0.0/0"]
    }

    egress {
        from_port       = 0
        to_port         = 0
        protocol        = "-1"
        cidr_blocks     = ["0.0.0.0/0"]
    }

}

resource "aws_iam_role" "ecs_task_execution_role" {
  name = "${var.flavor}-ecs-task-worker-task-execution-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

resource "aws_iam_role" "task_worker_iam_role" {
    name = "${var.flavor}-task-worker-role"
    path = "/"
    assume_role_policy = data.aws_iam_policy_document.task_worker_iam_role_policy.json
}

# Create var.az_count private subnets, each in a different AZ
resource "aws_subnet" "private" {
  count             = "${var.az_count}"
  cidr_block        = "${cidrsubnet(aws_vpc.ecs.cidr_block, 8, count.index)}"
  availability_zone = "${data.aws_availability_zones.available.names[count.index]}"
  vpc_id            = "${aws_vpc.ecs.id}"
}

resource "aws_ecs_task_definition" "task_worker" {
  family = "${var.flavor}-${var.task_worker_service_name}"
  network_mode = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu = var.task_cpu
  memory = var.task_memory
  execution_role_arn = aws_iam_role.ecs_task_execution_role.arn
  task_role_arn = aws_iam_role.task_worker_iam_role.arn
  container_definitions = <<JSON
[
{
      "dnsSearchDomains": null,
      "logConfiguration": null,
      "entryPoint": null,
      "portMappings": [],
      "command": null,
      "linuxParameters": null,
      "cpu": ${var.task_cpu},
      "environment": [],
      "resourceRequirements": null,
      "ulimits": null,
      "dnsServers": null,
      "mountPoints": [],
      "workingDirectory": null,
      "secrets": null,
      "dockerSecurityOptions": null,
      "memory": null,
      "memoryReservation": ${var.task_memory},
      "volumesFrom": [],
      "stopTimeout": null,
      "image": "us-west-2.amazonaws.com/task:4383669",
      "startTimeout": null,
      "dependsOn": null,
      "disableNetworking": null,
      "interactive": null,
      "healthCheck": null,
      "essential": true,
      "links": null,
      "hostname": null,
      "extraHosts": null,
      "pseudoTerminal": null,
      "user": null,
      "readonlyRootFilesystem": null,
      "dockerLabels": null,
      "systemControls": null,
      "privileged": null,
      "name": "task-worker"
    }
  ]
JSON
}

resource "aws_ecs_cluster" "task_pool" {
  name = "${var.flavor}-task-pool"
}

resource "aws_ecs_service" "task_service" {
  name = "${var.flavor}-task-worker-service"

  cluster = "${aws_ecs_cluster.task_pool.id}"

  task_definition = "${aws_ecs_task_definition.task_worker.arn}"

  launch_type = "FARGATE"

  desired_count = 2

  network_configuration {
    subnets = "${aws_subnet.private[*].id}"
    security_groups = ["${aws_security_group.vpc_ecs_task_worker.id}" ]
    assign_public_ip = "true"
  }

}

When I tried to apply it I got this error:
 InvalidParameterException: Security group sg-0e5f55bea9222dd00 does not appear to belong to the same VPC as the input subnets.

sg-0e5f55bea9222dd00 corresponds to the newly created security group aws_security_group.vpc_ecs_pdf_conversion.
I don't understand why this error message is thrown. The ingress and egress seem ok to me. How can I fix it?

A: Looks like, you are missing VPC reference in the security group creation section.
It should look like something below.
resource "aws_security_group" "vpc_ecs_task_worker" {
name        = "${var.flavor}-vpc_ecs_task_worker"
description = "ECS Allowed Ports"
vpc_id      = "${aws_vpc.ecs.id}"

ingress {
    from_port       = 32768
    to_port         = 65535
    protocol        = "tcp"
    cidr_blocks     = ["0.0.0.0/0"]
}

egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
}}

In your code vpc_id section is missing.


text:
Q: Analog scope has infinite resolution (vertical)? An old dude told me that I should go for analog ones since those digital even 14bit ones couldn't resolute as well as the old class scopes, aka. analog scopes. Is this true....

A: In an ideal world, where your oscilloscope doesn't introduce any noise, and it produces a zero-width line on the screen (and let's suppose you're able to see it then!) and assuming that your coating is an infinite set of points, yes.
But, the answer is no, because your scope is made of real components, which will add noise (which adds to the signal's noise), and the beam width is finite (and while its center-line position might be thought as continuous, you still must face with the phosphor coating of the screen, which is at the end a discrete array of molecules. Still this would be the the very upper limit, assuming a very sharp line and no noise).
"14-bit resolution" means 16384 levels. Assume you have a nice screen scope, 16-cm high. Can you spot 10 um of difference?

A: If the dude has eagle eyes and photo memory,... the old analog scope can't compete with a DSO in terms of functionality, not sure if he can take an advantage of signal looking at phosphorus glowing screen rather than on LCD.

A: Let's take a scope (analog or digital) with a very low input noise like \$ 1nV/ \sqrt{Hz} \$ ...
Getting 1nV/rtHz on 1MegOhm input resistance is not a "stick an opamp in and be done with it" job, most likely you're looking at 5-10 matched low noise JFETs in parallel, aaand... we just lost the 10pF input capacitance spec...
Low noise requires low impedances, and big transistors, thus high capacitance. "Low noise and slow" is no problem. "Low noise and high speed" tends to involve exotic RF parts, 50R impedances, and money.
Also you have the input attenuator problem. If you connect the input coax straight into the input amp, then your maximum sensitivity setting is going to be quite low-noise, however it will tend to burn when probing voltages that are a bit too high. So, add some input protection circuits, and...
Yeah, about that attenuator, obviously it should be before the input amp to make sure it doesn't clip, but that increases noise when attenuating, so here, have a bunch of RF relays at 20 bucks a pop to make the optimum combination between attenuating before or after the input amp, maybe use a variable gain chip, etc.
That's why all scopes below say, $1000, have tons of noise, although some suck a lot more than others. Analog or digital, it's all in the input amp and attenuator, and it all comes down to money.
So, a scope with \$ 5nV/ \sqrt{Hz} \$ and 200MHz bandwidth will have 70µV noise. Analog or digital.
Now if we have a 8-bit ADC we'll tune the full scale amplitude so that this noise corresponds to half a LSB. So, the vertical range on our screen would be 9mV, let's say 1mV/div.
Most analog or digital scopes on 1mV/div already have quite a bit of fuzz on the trace.
So, duuuuuude, if you want less noise, you have options:

*

*Magic button #1: "Bandwidth limit" if the signal allows it.

*Magic button #2: "Set averaging to 1024 traces" if the signal is periodic, in which case the digital scope utterly destroys the analog one:

*

*Export a few thousand periods on a USB key, load it up in python, average and plot (when I'm frustrated that the scope doesn't let me zoom into the averaged waveform, there is signal inside those pixels!).

*If the signal is low frequency, make a simple preamp+lowpass filter with an opamp. By virtue of having a lower bandwidth, it will have lower noise in the first place, and you can use lower noise parts like an ADA4898-1... or just use a soundcard.

*Or buy a much more expensive 12 bit scope, which is the only way if your signal is non-repetitive (no averaging) and fast (no bandwidth limit button). But if the signal is non-repetitive, then the analog scope is useless also.

A: Here's the short answer.
Technically an analog oscilloscope has infinite vertical resolution because it is driving by analog deflector plates instead of an ADC with quantized levels.
But you also have to consider the oscilloscope's noise floor. Both analog and digital oscilloscopes will have some level of baseline noise that will drown out the vertical resolution. That's why an 8 bit oscilloscope usually offers plenty of vertical resolution.

A: TEK 556 dual-beam has 500 micron spot size (been years since I used it). You can measure RC taus with only 1 division deflection.
My favorite plugin, for TEK7904, is the 7A22 plugin with 10uV/division floor, selectable bandwidths from 1KHz to 1MHz upper corner, and a number of DC-blocking high-pass corners for the lower corner. Using this to examine magnetic field coupling thru copper foil, to learn the limits of magnetic shielding.


text:
Q: how to check word is or not full filled in this div using javascript  this is my code:

and i fill space full in the div , but later , i will fill chinese word and english word in the div , and chinese word and english word has different length from each other,
so how to check the the word is or not full filled in the div ,
and not more(overflow) or less ,
thanks

A: You can't do that. You will either have to use a bitmap font (for each letter an image with the same size) or a fixed width font (monospaced font, e.g. Courier New and Lucida Console).
Or you can cut the text by setting overflow:hidden property for the div.


text:
Q: Corrupt memory with LockBits (DirectShow webcam) I'm doing some image manipulation in .NET (VB 2010). I'm using the following code (which doesn't do anything yet):
Sub Manipulate(IMG As Bitmap)
    ' Dim foo(100000) As Integer  - will need it later...

    Dim bd = IMG.LockBits(New Rectangle(0, 0, IMG.Width, IMG.Height),
                          Imaging.ImageLockMode.ReadWrite,
                          Imaging.PixelFormat.Format24bppRgb)
    Dim absstride = Math.Abs(bd.Stride)
    Dim numbytes = absstride * IMG.Height
    Dim bytes(numbytes - 1) As Byte
    Dim flipped = bd.Stride < 0
    Dim ptr = If(flipped, bd.Scan0 - numbytes + absstride, bd.Scan0)
    System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, numbytes)

    ' I'm going to put sg here

    System.Runtime.InteropServices.Marshal.Copy(bytes, 0, ptr, numbytes)
    IMG.UnlockBits(bd)
End Sub

This works perfectly for simple purposes (eg. brightening the image), but my algorithm needs some big variables (see 'foo' above). When declaring it (uncomment that line), I suddenly get exceptions:
depending on the size of 'foo'...
...either the first Marshal.Copy() throws
AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
...or the declaration of 'bytes' throws
FatalExecutionEngineError: The runtime has encountered a fatal error. The address of the error was at 0x6819d142, on thread 0x3690. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
...or no exceptions at all and everything works fine.
What is going on?
Additional info: I get the image objects from webcam using DirectShow.

A: As Hans pointed out, I have to make a deep copy of the bitmap and everything works. Otherwise I'm using an image that is already disposed. This is a silent error though, until I declare some big variables, which use up the disposed memory, that's when the GC throws some seemingly random errors.


text:
Q: Congruence involving Bernoulli numbers I need to show that $$2B_{2m}\equiv1\pmod{4}$$ for $m\ge2.$ This should be something easy using (at most) Claussen and von Staudt's theorem, but I haven't been successful yet. Writing $B_{2m}=U_{2m}/V_{2m},(U_{2m},V_{2m})=1,V_{2m}>0$ I know $$V_{2m}\equiv2U_{2m}\pmod4,$$
but since $2\mid V_{2m},$ this is not very useful. I also wanted to try Hensel's lifting lemma for $f(x)=2x-1$ (because $2B_{2m}\equiv1\pmod2$ holds), but $f'(x)\equiv0\pmod2,$ so this is not the right way as well. Any other tips?
Remark. I needed this result for finishing the following problem.

Let $q$ be a prime number such that $2q+1$ is composite. Show that the numerator of the Bernoulli number $B_{2q}$ is divisible by a prime of the form $4n+3$.

The congruence mentioned above is a final step in my solution.

A: Note that for $n\geq 2$
$$0=2\sum_{k=0}^{2n}\binom {2n+1}kB_k=1-2n+\binom{2n+1}{2}\frac{1}{3}+\sum_{k=2}^{n-1}\binom{2n+1}{2k}(2B_{2k})+(2n+1)(2B_{2n}).$$
Now if $2B_{2m}\equiv 1\pmod{4}$ for $m=2,\dots,n-1$ then
$$(2n+1)(2B_{2n})\equiv -1+2n-3\binom{2n+1}{2}
-\sum_{k=2}^{n-1}\binom{2n+1}{2k}\\=-4^n-4n^2+2n+1\equiv 2n+1\pmod{4}.$$
and, since $(2n+1)$ is odd, it follows that $2B_{2n}\equiv 1\pmod{4}$.

A: By Faulhaber's formula for the $2m$-th powers,$$2^{2m}+1=\frac1{2m+1}\left(2^{2m+1}+\frac{2^{2m}}2+\cdots
+(2m+1)2B_{2m}\right).$$
All terms but the term are multiples of $4$ so we get $1\equiv 2B_{2m}
\pmod4$.


text:
Q: Setting 'limits' in rails views An application has users which can have one of three different account types. Let's call them Small, Medium, Large
I'm trying to figure out the best way to set limits depending on the account type. I looked into cancan but it seems to just have basic authentication options like read, manage, etc. whereas I am mostly going to be doing things like:
if user_has_hit_upload_limit?
  # display a message
else
  # display the upload form

What's the best way to do this? Am I correct in thinking cancan isn't ideal for this?
I started making a model class that sets all the limits and does all the checks, then added methods to ApplicationHelper to call that class, which is in turn called by the views.
Does this seem reasonable or not good? Is there a better way?

A: CanCan is for authorization based on abilities defined for users.  It's probably not what you want for a quota type system like you described.  Assuming you kept track of current usage and the user's quota both in the user model you could write a helper like this:
def user_has_hit_upload_limit?
  current_user && current_user.upload_count < current_user.upload_limit
end

The hard part is actually tracking the usage and that will depend on what you are trying to do within your application.
You could still use CanCan define an ability that had a block condition but IMHO that's more complexity then it really needed.


text:
Q: Alter fixed and random effects using Fixef and VarCorr in package simr with a ZIP glmmTMB I am trying to alter the fixed and random effects of a zero-inflated Poisson model using R's glmmTMB function. I want to input the altered fixed effects into the powerSim function. Here is the data:
sample <- as.data.frame(cbind(1:50, (rep(1:10, each = 5))))

#randomize interventions by clinic
ru1 <- cbind(rbinom(10, 1, 0.5), 1:10)
ru2 <- cbind(rbinom(10, 1, 0.5), 1:10)

#merge randomization id with original sample
sample <- merge(sample, ru1, by = "V2") %>% merge(ru2)

#add days
sample <- as.data.frame(cbind(sample, scale(rep(-546:546, each = 50))))

#order by clinic and prescriber
sample <- sample[order(sample$V2, sample$V1.x),]

#simulate ZIP distribution for days supply
set.seed(789)
sample <- cbind(sample, ifelse(rbinom(54650, 1, p = 0.5) > 0, 0, rpois(54650, 5)))

#rename variables
sample <- rename(sample, pres = V1.x, clinic = V2, aj = V1.y, def = V1,
                 days = `scale(rep(-546:546, each = 50))`,
                 dayssply = `ifelse(rbinom(54650, 1, p = 0.5) > 0, 0, rpois(54650, 5))`)

#days truncated
sample$days_ <- ifelse(0 > sample$days, 0, sample$days)

#model
m1 <- glmmTMB(dayssply ~ aj*days_ + (1|clinic/pres), zi = ~ aj*days_,
        data = sample, family = poisson)

After a lot of trial and error, I finally figured out how to specify the conditional fixed effect using the fixef function:
fixef(m1)$cond [["aj"]]

But when I try to change it to the desired fixed effect for the power analysis, I get the error that "cond is not the name of a fixed effect." Not sure if this is a syntax related issue, or if fixef doesn't work for zero-inflated models.
I would also like to alter the variances for the random effects using VarCorr.


text:
Q: Need to synchronize Windows Service with non-admin user process I am using a (.NET2.0) service to periodically carry out privileged actions and return the result to shared memory, via IPC, with a non-admin user's (.NET2.0) process.
I have been using globally named mutexes while developing from my administrator account but when I come to try the application on a limited account I get the error:

Additional information: Access to the path 'Global\timersyncu33sc3c2sd42frandomlynamedmutexoijfvgf9v3f32' is denied.

Is there some other way a non-privileged user can interact with a Service? Or should I just share the period of polling and update time and hope those values get written/read atomically?

A: I would talk to the service using WCF. This eliminates the privileges/identity problem.
However since your code is in .NET 2.0 you could use Remoting or NamedPipes to talk to the service.

A: I found the following method of granting access to my limited users as they log on and fire up their GUI. Note the function getUsername(/*somehow*/); had several incarnations and I'm not listing the implementation that worked on XP, I'm sure there are other ways though 3 of the 4 I found didn't work for me.
void grantMutexToCurUser(Mutex ^%fpMutex) {
    try {
        fpMutex = Mutex::OpenExisting( ServerGUIBridge::NAMEDMUTEXFORTIMERSYNC,
            static_cast<MutexRights>(
            MutexRights::ReadPermissions | MutexRights::ChangePermissions) );

        MutexSecurity^ mSec = fpMutex->GetAccessControl();
        String^ user;

        try {
            user = getUsername(/*somehow*/);
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Granting mutex access to: "
                + user , "grantMutexToCurUser" );
        } catch (Exception ^ex) {
            Trace::WriteLine( "getUsername: " + ex->Message, "grantMutexToCurUser" );
        }

        // First, the rule that denied the current user the right to enter and
        // release the mutex must be removed.
        MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(MutexRights::Synchronize
            | MutexRights::Modify), AccessControlType::Deny );
        mSec->RemoveAccessRule( rule );

        // Now grant the user the correct rights.
        rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(MutexRights::Synchronize
            | MutexRights::Modify), AccessControlType::Allow );
        mSec->AddAccessRule( rule );

        fpMutex->SetAccessControl( mSec );

        // Open the mutex with (MutexRights.Synchronize | MutexRights.Modify), the
        // rights required to enter and release the mutex.
        fpMutex = Mutex::OpenExisting( ewfmon::ServerGUIBridge::NAMEDMUTEXFORTIMERSYNC );
        //noThrowRelease(fpMutex);
    }
    catch ( UnauthorizedAccessException^ ex )
    {
        Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Unable to change permissions: "
            + ex->Message, "grantMutexToCurUser" );
    }
}


text:
Q: template deduction fails in std::forward? #include <utility>
#include <iostream>

struct Data {
    uint8_t m_x;
    double m_y;
    uint32_t m_z;
    Data(uint8_t x, double y, uint32_t z) : m_x(x), m_y(y), m_z(z) {
        std::cout << "constructor called" << std::endl;
    }
};

template <class Data, typename... Args>
class Layer1 {
public:
    void foo(Args&&... args) {
        Data(std::forward(args)...);
    }
};

int main() {
    Layer1<Data, uint8_t, double, uint32_t> layer1;
    layer1.foo(1, 1.1, 2);
}

When I compile the code above, gcc 8.2 outputs:
$ g++ -Wall test_forward.cpp -o test_forward -O3 -std=c++17
test_forward.cpp: In instantiation of 'void Layer1<Data, Args>::foo(Args&& ...) [with Data = Data; Args = {unsigned char, double, unsigned int}]':
test_forward.cpp:39:22:   required from here
test_forward.cpp:31:16: warning: unused variable 'layer2' [-Wunused-variable]
   Layer2<Data> layer2;
                ^~~~~~
[hchan@heilinux cpp]$ g++ -Wall test_forward.cpp -o test_forward -O3 -std=c++17
[hchan@heilinux cpp]$ g++ -Wall test_forward.cpp -o test_forward -O3 -std=c++17
test_forward.cpp: In instantiation of 'Layer1<Data, Args>::MyData::MyData(Args&& ...) [with Data = Data; Args = {unsigned char, double, unsigned int}]':
test_forward.cpp:32:3:   required from 'void Layer1<Data, Args>::foo(Args&& ...) [with Data = Data; Args = {unsigned char, double, unsigned int}]'
test_forward.cpp:39:22:   required from here
test_forward.cpp:27:51: error: no matching function for call to 'forward(unsigned char&)'
   MyData(Args&&... args) : i(0), data(std::forward(args)...) {}
                                       ~~~~~~~~~~~~^~~~~~
In file included from /opt/rh/devtoolset-8/root/usr/include/c++/8/bits/stl_pair.h:59,
                 from /opt/rh/devtoolset-8/root/usr/include/c++/8/utility:70,
                 from test_forward.cpp:1:
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:74:5: note: candidate: 'template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_Tp>::type&)'
     forward(typename std::remove_reference<_Tp>::type& __t) noexcept
     ^~~~~~~
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:74:5: note:   template argument deduction/substitution failed:
test_forward.cpp:27:51: note:   couldn't deduce template parameter '_Tp'
   MyData(Args&&... args) : i(0), data(std::forward(args)...) {}
                                       ~~~~~~~~~~~~^~~~~~
In file included from /opt/rh/devtoolset-8/root/usr/include/c++/8/bits/stl_pair.h:59,
                 from /opt/rh/devtoolset-8/root/usr/include/c++/8/utility:70,
                 from test_forward.cpp:1:
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:85:5: note: candidate: 'template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_Tp>::type&&)'
     forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
     ^~~~~~~
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:85:5: note:   template argument deduction/substitution failed:
test_forward.cpp:27:51: note:   couldn't deduce template parameter '_Tp'
   MyData(Args&&... args) : i(0), data(std::forward(args)...) {}
                                       ~~~~~~~~~~~~^~~~~~
[hchan@heilinux cpp]$ g++ -Wall test_forward.cpp -o test_forward -O3 -std=c++17
[hchan@heilinux cpp]$
[hchan@heilinux cpp]$
[hchan@heilinux cpp]$
[hchan@heilinux cpp]$ g++ -Wall test_forward.cpp -o test_forward -O3 -std=c++17
test_forward.cpp: In instantiation of 'void Layer1<Data, Args>::foo(Args&& ...) [with Data = Data; Args = {unsigned char, double, unsigned int}]':
test_forward.cpp:23:22:   required from here
test_forward.cpp:17:20: error: no matching function for call to 'forward(unsigned char&)'
   Data(std::forward(args)...);
        ~~~~~~~~~~~~^~~~~~
In file included from /opt/rh/devtoolset-8/root/usr/include/c++/8/bits/stl_pair.h:59,
                 from /opt/rh/devtoolset-8/root/usr/include/c++/8/utility:70,
                 from test_forward.cpp:1:
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:74:5: note: candidate: 'template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_Tp>::type&)'
     forward(typename std::remove_reference<_Tp>::type& __t) noexcept
     ^~~~~~~
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:74:5: note:   template argument deduction/substitution failed:
test_forward.cpp:17:20: note:   couldn't deduce template parameter '_Tp'
   Data(std::forward(args)...);
        ~~~~~~~~~~~~^~~~~~
In file included from /opt/rh/devtoolset-8/root/usr/include/c++/8/bits/stl_pair.h:59,
                 from /opt/rh/devtoolset-8/root/usr/include/c++/8/utility:70,
                 from test_forward.cpp:1:
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:85:5: note: candidate: 'template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_Tp>::type&&)'
     forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
     ^~~~~~~
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/move.h:85:5: note:   template argument deduction/substitution failed:
test_forward.cpp:17:20: note:   couldn't deduce template parameter '_Tp'
   Data(std::forward(args)...);
        ~~~~~~~~~~~~^~~~~~

For some reason, it seems like the template deduction fails.  If I change Data(std::forward(args)...) to Data(std::forward<Args>(args)...), it works.
I wonder why compiler fails to deduce the argument types and what compiler is actually thinking of the type (i.e. no matching function for call to 'forward(unsigned char&)').
Basically, I am trying understand why more hint is needed (i.e. explicitly states <Args>).
Thanks!


text:
Q: chown doesn't work through script I have a script:
#! /bin/bash
sudo chown -R $USER:$USER /opt/Folder

The chown doesn't seem to execute.
If I just write the above line from terminal ,it runs fine though!
I have read this but doesn't help.
The name of the script is mysetup.sh and I am running as  sudo sh mysetup.sh.
It doesn't give any output.
If I run it like sudo bash -x mysetup.sh , I am receiving:
sudo chown -R root:root /opt/Folder
This problem does not related to this,since the USER is set.

A: You're trying to change the contents of /opt/Folder to your own userid, aren't you.
Here's your command once again:
sudo chown -R $USER:$USER /opt/Folder

This works from the command line because the $USER variable is evaluated before the command is executed, and it is therefore executed as this (assuming your username is george):
sudo chown -R george:george /opt/Folder

On the other hand, when you run a command with sudo, amongst other things the $USER variable takes the value of the target user, which in this case is root. So by running sudo bash mysetup.sh you are running mysetup.sh as root, so the command runs with $USER set to root and is evaluated like this
sudo chown -R root:root /opt/Folder

The solution in your case is to avoid running the entire script itself under sudo, and let the script use sudo where necessary to run specific commands with elevated privileges. In other words, use bash mysetup.sh instead of sudo bash mysetup.sh.

A: You haven't mentioned your distribution and version of Linux (or unix) you are running, so I am going on a tangent here, assuming this following line is in your /etc/sudoers
Defaults requiretty

hence you can not run sudo without a tty. And when you try to run it from the script, your sudo doesn't run, effectively crippling your chown command.
Try adding -t or -tt switches to your sudo command. These will create a pseudo terminal to run your sudo chain of commands and hopefully will succeed but this option has its side effects as well, not to be discussed here. You can search for them if you want to.
If you have access to sudo configuration, you take out the line mentioned above for the best of solutions but with this action, you are eliminating one level of barricades, despite how weak it is.


text:
Q: Primefaces datatable issue - Persist Filter,Sort order and pagination We are developing an application using JSF2 with Primefaces version5.2.5
WE are using primefaces datatable in multiple places in our application. For each row in the datatable, we have an edit button and clicking on the button redirect to the "edit page", once the user saves the data in the edit page again it redirects to the main page( datatable page). We are facing couple of issues when using the datatable.
1) If the user sorts the record based on some column,going to edit page,saving the data and redirecting to the mainpage, sorting order is not maintained in the datatable when the page is getting reloaded
2) Similarly if i edit some record from second page in datatable, and after edit, its going to first page.
3) If the user applies some column filtering and editing some filtered record and when redirect to main page its not retaining the filter value, filter values are getting cleared.
Note: We are using GroupConversationScoped for the bean and we are not using ajax call for update.


text:
Q: python conditional list creation from 2D lists Say I've got a list of lists. Say the inner list of three elements in size and looks like this:
['apple', 'fruit', 1.23]

The outer list looks like this
data = [['apple', 'fruit', 1.23],
        ['pear', 'fruit', 2.34],
        ['lettuce', 'vegetable', 3.45]]

I want to iterate through the outer list and cull data for a temporary list only in the case that element 1 matches some keyword (aka: 'fruit'). So, if I'm matching fruit, I would end up with this:
tempList = [('apple', 1.23), ('pear', 2.34)]

This is one way to accomplish this:
tempList = []
for i in data:
   if i[1] == 'fruit':
      tempList.append(i[0], i[2])

is there some 'Pythonic' way to do this in fewer lines?

A: [(i, k) for i, j, k in data if j == 'fruit']

A: List comprehensions, using tuple indexing or slicing
tempList = [(i[0], i[2]) for i in data if i[1] == 'fruit']
tempList = [i[:1]+i[2:] for i in data if i[1] == 'fruit']

Also, generator expressions if you don't need a list, just the sequence.
(here with tuple unpacking)
>>> tempListGen = ((a,c) for a,b,c in data if b == 'fruit')
>>> tempListGen
<generator object <genexpr> at 0x0266FD50>
>>> print sorted(tempListGen)
[('apple', 1.23), ('pear', 2.34)]

(tested with Python 2.7)

A: Tuple assignment could make the code easier to understand, paired with a list comprehension for compactness:
tempList = [(item, price) for item, kind, price in data if kind == 'fruit']

A: The List Comprehension!
tempList = [(i[0], i[2]) for i in data if i[1] == 'fruit']

Will give the same result in fewer lines and will probably execute faster.

A: [[x[0], x[2]] for x in data if x[1] == 'fruit']


text:
Q: He is believed to was responsible I would like to turn the following sentence into passive voice.

Most people think he was responsible for the problems.

What I infer from the sentence is that people still think so and the problems were experienced in the past.
First of all, I'd like ask if the first sentence is grammatically correct?

1.He is believed to was responsible for the problems.

or

2.He was believed to have been responsible for the problems.
3.He was believed to be responsible for the problems.

( can I stress the past tense "was" in the original tense by saying " he was believed to..." , if they make a sense )
or
Should I have to stick to present perfect or bare infinitive as follows but in this case I doubt they may not convey that problems were in the past.

4.He is believed to has been responsible for the problems.
5.He is believed to be responsible for the problems.

Could you compare these 5 sentences above in terms of meaning they convey please?

A: The complement of believed in the usage in your question is either
--an infinitive-phrase with to at its head and the verb-to-be  (to be, to have been) and its predicate complement:

He is believed to be responsible.
He is believed to have been responsible.

or
--the predicate complement with the verb-to-be omitted:

He is believed responsible.

A: Yes, the first sentence

Most people think he was responsible for the problems.

is completely correct grammatically, as is your analysis of its exact meaning.
This phrasing

He is believed to was responsible for the problems.

starts off well, but the grammar breaks down at the "was".  It looks as though you stuck the beginning of one sentence onto the end of another (which most people do when learning a language -- I certainly did!).
The "to" is the first part of the infinitive form.  So you have to complete it with an infinitive form.  You can't use "was" or "has" because there is no "to was" or "to has".  There's "to be", "to have", and "to have been"
So sentences 2, 3, and 5 are grammatical, but 4 suffers from the same kind of problem sentence 1 has:  it needs an infinitive form (because of the "to") but doesn't have one.  1 has past ("was"), 4 has 3rd person present ("has").
If you change 4 to read "to have been", that's the passive-voice version.


text:
Q: Iframe Access PHP File In Codeigniter i want to make iframe in codeigniter which access a php file in my local folder. Like this

But the display always redirect it to 404 page. How can i fix it?
Thank you very much.

A: If you're using CI you are ill-advised to call a php file directly. Create a controller instead and call that instead. Something like:
    <?php

    require_once dirname(__FILE__) . "/base.php";

        class fck extends BaseController {

        function __construct() {
            parent::__construct();
            $this->load->model('myModel');
        }

        function browse($type,$dir)  {
            $data['directory'] = $this->myModel->loadDirContent($type,$dir);
            $this->load->view("fck/browse", $data);
        }
    }
    ?>

Your iframe then looks like this:

Note that after 'browse' in the URI above you are effectively submitting data. First what is read out as "$type" by the browse function, i.e. "files" then the path itself, i.e. data that contains dashes. This is no longer part of an URL so to speak.


text:
Q: Understanding the behavior of Reflect.fields on cpp target can you help me with understanding the behavior of Reflect.fields?
I have this code:
var obj:Dynamic={arr:["aaa","bbb","ccc"]};
trace(Reflect.fields(obj));
trace(Reflect.fields(obj.arr));

JS target output:
[arr]
[0,1,2]

CPP target output (Android NDK):
[arr]
[]

Why CPP target didn't return [0,1,2]?

A: As mentioned in the API documentation on Reflect.fields()

This method is only guaranteed to work on anonymous structures.

So the behavior on array is not specified.


text:
Q: az container exec when using Docker compose Is it possible to execute command in a container which is running under Azure WebApp service by Docker Compose?
When I create single container by az container create ..., then it works.
But when I create set of containers by Docker compose script using az webapp create --multicontainer-config-type compose ..., then it does not work.
From logs I see that there is running container myWebApp_myContainer_1 so I try:
az container exec -g myResourceGroup -n myWebApp_myContainer_1 --exec-command "/bin/bash"

With this result:

The Resource 'Microsoft.ContainerInstance/containerGroups/myWebApp_myContainer_1'
  under resource group 'myResourceGroup' was not found.

Then I try:
az container exec -g myResourceGroup -n myWebApp --container-name myWebApp_myContainer_1 --exec-command "/bin/bash"

With this result:

The Resource 'Microsoft.ContainerInstance/containerGroups/myWebApp' under resource group 'myResourceGroup' was not found.

Note that it is normally possible to execute commands in containers started by Docker compose script on local Docker (out of Azure).
Update I don't like to install SSH server into Docker images. It is a bad approach. I'm looking for a way of direct exec like az container exec does.
Thank you for any hint.

A: For your issue, when the web app created from a Docker image, it's just a web app, not a container. So you cannot use the command az container exec to connect to it.
If you really want to connect to the web app that created from a Docker image, there are two ways as I know to achieve it.
The one is that I describe in the comment, you should install the OpenSSH server in the Docker image. Then ssh into the web app from the port exposed to the Internet.
The other one as you wish is using the command az webapp remote-connection. For more details, you can read Open SSH session from remote shell.


text:
Q: Can you explain why the plot is stopping at J (at index 10) I am running this program to find the distribution of characters in a specific text.
# this is a paragraph from python documentation :)
mytext = 'When a letter is first k encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):'

d = dict()
ignorelist = ('(',')',' ', ',', '.', ':', '_')

for n in mytext:
    if(n not in ignorelist):
        n = n.lower()
        if n in d.keys():
            d[n] = d[n] + 1
        else:
            d[n] = 1
xx = list(d.keys())
yy = list(d.values())

import matplotlib.pyplot as plt
plt.scatter(xx,yy, marker = '*')
plt.show()

Both the list has 25 elements. For some strange reason the plot is coming like this. It ends in 'J' in x axis.

If I zoom it the right side gets visible but there is no points plotted.

A: Note that this will be fixed as of matplotlib version 2.2
It seems you have found a bug in the new categorical feature of matplotlib 2.1. For single letter categories it will apparently limit its functionality to 10 items. If categories consist of more letters, this does not happen.
In any case, a solution is to plot numerical values (just as one would have needed to do prior to matplotlib 2.1 anyways). Then set the ticklabels to the categories.
# this is a paragraph from python documentation :)
mytext = 'When a letter is first k encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):'

d = dict()
ignorelist = ('(',')',' ', ',', '.', ':', '_')

for n in mytext:
    if(n not in ignorelist):
        n = n.lower()
        if n in d.keys():
            d[n] = d[n] + 1
        else:
            d[n] = 1

xx,yy = zip(*d.items())

import numpy as np
import matplotlib.pyplot as plt

xx_sorted, order = np.unique(xx, return_inverse=True)

plt.scatter(order,yy, marker="o")
plt.xticks(range(len(xx)), xx_sorted)
plt.show()