text:
Q: Meaning of "identify" in the given context Please help me figure out the meaning of the words "identify" in the following context:

The Seventh Plan made a significant effort to identify and promote
  'beneficiary-oriented programme' with the intention of extending
  direct benefits to women.

You will find more context here.

A: This sentence seems to incorporate some business jargon, and is not particularly clear.  For instance, I believe "programme" is singular, so we would expect either "promote a programme" or "promote programmes", but the above example seems incorrect.  That is also an unusual spelling, I typically see "program" or "programs", so I wonder if this has a special meaning in context.  (Perhaps this is just the British spelling, which I think should follow the rules for pluralization.)
We can simplify the example a little if we replace some of the more complex phrasing:

[They] made a significant effort to identify and promote [programs] with the intention of [benefiting women].

In this case, we can see that the author is trying to combine two actions: identifying programs that benefit women, and promoting those programs.  It would be more clear to break those two ideas up:

They made a significant effort to identify [programs] with the intention of [benefiting women], and then they made a significant effort to promote [those programs].

However, this phrasing is common for a speaker who is trying to convey an idea quickly to an audience that is already familiar with the topic.  For instance, a company might "sell and install solar panels", even though those are two very different activities.
Now that we have simplified the ideas, "identify" should be clear and the standard definition applies.  "They" are looking at many programs and deciding which programs fit the requirements.  Those programs are "identified" as being worth attention and promotion.


text:
Q: PHP Fatal error: Call to undefined function geoip_open() Magento onestep checkout is giving this error

PHP Fatal error:  Call to undefined function geoip_open()

on this line of code$geoip = geoip_open($pathToDB, GEOIP_STANDARD);
and the whole function is this
 public function processGeoIP($ip)
    {
        include_once Mage::getBaseDir() . DS . 'lib' . DS . 'Magestore' . DS . 'Onestepcheckout' . DS . 'Geoip' . DS . 'geoipcity.inc';
        include_once Mage::getBaseDir() . DS . 'lib' . DS . 'Magestore' . DS . 'Onestepcheckout' . DS . 'Geoip' . DS . 'geoipregionvars.php';
        $pathToDB = Mage::helper('onestepcheckout/geoip')->getDatabasePath();

        $geoip = geoip_open($pathToDB, GEOIP_STANDARD);
        $data = array('ip' => $ip);

        $address = geoip_record_by_addr($geoip, $ip);

        if ($address) {
            $data['code']        = $address->country_code;
            $data['country']     = $address->country_name;
            $data['region']      = (isset($GEOIP_REGION_NAME[$address->country_code][$address->region]) ? $GEOIP_REGION_NAME[$address->country_code][$address->region] : $address->region);
            $data['city']        = $address->city;
            $data['postal_code'] = $address->postal_code;
            $data['country_id'] = $address->country_code;
            $data['region_id'] = $this->getRegionIdByCode($address->region, $address->country_code);
        }

        geoip_close($geoip);
        return $data;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does React not render my array of components? I have a JSON API response that I would like to map into a list of Child-Components, called <ReservationBox />, like this:

    render() {
        // ... other code ...

        let res_list = [];

        fetch(request)
        .then(response => response.json())
        .then(reservations => {
            console.log(reservations)
            res_list = reservations.map((res) => <ReservationBox key={res.id} court={res.court} date={res.day} start_time={res.start} end_time={res.end} />);
            console.log(this.res_list);
        });

        return (
            <div>
                {heading}
                {res_list}
            </div>
        );
    }

Now, my reservations log correctly, and also the res_list appears correctly in the console as an array of React Components, but it won't render in the parent component.
Any idea or help will be highly appreciated, because I could not find anything on this. Thanks in advance!

A: res_list isn't available to you where you want to return it. In the then() block, put the returned array into state and use this state then in the return block.


text:
Q: how does $let access variables defined outside its expression in mongoDB? From the reference
$let (aggregation)
we cat use $let to access variables defined outside its expression:
{
  $let:
    {
      vars: { low: 1, high: "$$low" },
      in: { $gt: [ "$$low", "$$high" ] }
    }
}

In the vars assignment block, "$$low" refers to the value of an externally defined variable low and not the variable defined in the same vars block. If low is not defined outside this $let expression block, the expression is invalid.
My question: how to define the variable low externally? use var or other choice?

A: I missed your declared variable at the top originally. You don't need to do anything, the actual value will be "interpolated" into the aggregation pipeline document "before" it is sent to the server:
var fenFactor = 100;
db.sales.aggregate( [
   {
      $project: {
         finalTotal: {
            $let: {
               vars: {
                  total: { $add: [ '$price', '$tax' ] },
                  discounted: { $cond: { if: '$applyDiscount', then: 0.9, else: 1 } }
               },
               in: { $multiply: [ "$$total", "$$discounted", fenFactor ] }
            }
         }
      }
   }
] );

So just use the variable directly and it will become part of the document as sent.
You might also consider that $let is a bit terse here where you do not need to re-use the variables. Perhaps just do it inline instead:
    var fenFactor = 100;

    db.sales.aggregate([
       { "$project": {
         "finalTotal": {
            "$multiply": [
                { "$add": [ "$price", "$tax" ] },
                { "$cond": [ "$applyDiscount", 0.9, 1 ]},
                fenFactor
            ]
         }
      }}
    ]);

A: There is only limited ways to create a aggregation variable in MongoDB as of Now.Apart form system variables users can only create variables in  $let, $redact, $map  operations.
(See Manual : http://docs.mongodb.org/manual/reference/aggregation-variables/)
Now Answer for your question is, you can refer variables defined in a $map or $redact  within a $let, that is what they meant in MongoDB manual.
Here I'm giving an example of using $map variable in $let :
 > db.grades.find()
  { "_id" : 3, "quizzes" : [ 3, 8, 9 ] }
  { "_id" : 1, "quizzes" : [ 5, 6, 7 ] }

//Using a simple $map:
db.grades.aggregate([{
  $project: {
    adjustedGrades: {
      $map: {
        input: "$quizzes",
        as: "grade",
        in: { $add: [ "$$grade", 2 ] }
      }
    }
  }
}]);

//Result:
{ "_id" : 3, "adjustedGrades" : [ 5, 10, 11 ] }
{ "_id" : 1, "adjustedGrades" : [ 7, 8, 9 ] }

Now defining a $let to use variable $$grade defined in this $map:
db.grades.aggregate([{
  $project: {
    adjustedGrades: {
      $map: {
        input: "$quizzes",
        as: "grade",
        in: {
          $let: {
            vars: { varin: "$$grade" },
            in: { $add: [ "$$varin", 4 ] }
          }
        }
      }
    }
  }
}]);

//Result:
{ "_id" : 3, "adjustedGrades" : [ 7, 12, 13 ] }
{ "_id" : 1, "adjustedGrades" : [ 9, 10, 11 ] }


text:
Q: Creating new graph basing on cluster anylise - R library("network")
library("networkD3")
library("igraph")

df1 <- read.table(text = "src   target
                  cllient1  cllient2
                  cllient1  cllient4
                  cllient1  cllient6
                  cllient2  cllient3
                  cllient4  cllient1
                  cllient4  cllient3
                  cllient5  cllient6
                  cllient6  cllient5", header = TRUE)

lesmis <- graph_from_data_frame(df1)
wc <- cluster_walktrap(lesmis)
members <- membership(wc)
lesmis <- igraph_to_networkD3(lesmis, group = members)

D3_network_LM <- networkD3::forceNetwork(Links = lesmis$links, Nodes = lesmis$nodes,
                                         Source = 'source', Target = 'target',
                                         NodeID = 'name', Group = 'group',
                                         opacity = 1,zoom = TRUE)
networkD3::saveNetwork(D3_network_LM, "test.html", selfcontained = TRUE)

So close we got a network. After that we create new graph by merging several vertices into one. In our case those vertices that belong to particular community.
lesmis <- graph_from_data_frame(df1)
cg <- contract.vertices(lesmis, members)
ay <- as_long_data_frame(cg)
View(ay)

we got new graph,
from    to
1   2

We may built again new graph where now these nodes are the groups, but their names are 1 and 2, my question is how we can add clients names to this new graph. So that, when hovering  , we may get not only the number of the node(group) but also the list of client that belongs to this new node(group).

A: Your example code doesn't work for multiple reasons (I edited it a bit to fix some obvious problems), but I think the following achieves what you're trying to do...
library(network)
library(networkD3)
library(igraph)

df <- read.table(header = TRUE,
                 text = "src   target
                         cllient1  cllient2
                         cllient1  cllient4
                         cllient1  cllient6
                         cllient2  cllient3
                         cllient4  cllient1
                         cllient4  cllient3
                         cllient5  cllient6
                         cllient6  cllient5")

df_graph <- graph_from_data_frame(df)

wc <- cluster_walktrap(df_graph)
members <- membership(wc)

df_graph_cntrctd <- contract(df_graph, members, vertex.attr.comb = toString)

df_graph_cntrctd_D3 <- igraph_to_networkD3(df_graph_cntrctd)

networkD3::forceNetwork(Links = df_graph_cntrctd_D3$links,
                        Nodes = df_graph_cntrctd_D3$nodes,
                        Source = 'source', Target = 'target',
                        NodeID = 'name', Group = 'name',
                        opacity = 1, zoom = TRUE)


text:
Q: How to find the integral for $\int 2^{\sin{x}}\cos{x}\;\mathrm{d}x$? What would be the ideal approach in finding the integral for:
$$
\int 2^{\sin{x}}\cos{x}\;\mathrm{d}x
$$

A: Let $u=\sin x$, $du=\cos x\, dx$, and $dx=\frac{du}{\cos x}$, then
\begin{align}
\require{cancel}
\int 2^{\sin{x}}\cos{x}\;dx&=\int 2^{u}\cancel{\cos{x}}\;\frac{du}{\cancel{\cos x}}\\
&=\int 2^u\; du\\
&=\int e^{u\ln 2}\; du\qquad;\;\;a^b=e^{b\ln a}\\
&=\frac{e^{u\ln 2}}{\ln 2}+C\qquad\quad;\;\int e^{ax}\; dx=\frac{e^{ax}}{a}+C\\
&=\frac{e^{\sin x\ln 2}}{\ln 2}+C\\
&=\frac{2^{\sin{x}}}{\ln 2}+C
\end{align}

A: Put $\cos{x}$ under derivative:

 $$\int 2^{\sin{x}}\cos{x}\;\mathrm{d}x = \int 2^{\sin{x}}\;\mathrm{d}{\sin{x}} = \int 2^u\;\mathrm{d}{u} = \dfrac{2^u}{\ln{2}} = \dfrac{2^{\sin{x}}}{\ln{2}}$$

A: Hint: let $u = sinx$ , then transfer it to integral with respect to $u$.

A: Hint
Rewrite $2^{\sin(x)}$ as $e^{\sin(x) \log(2)}$ and recognize that $\cos(x)$ is almost the derivative of the exponent.


text:
Q: How to insert JSON into an accordion menu dynamically? I need to make a multi-level accordion dynamic menu with JSON. I downloaded a template and I'm trying to adapt my JSON file in this menu, but when I create the sub-menu it returns only an undefined value.
$.getJSON("menu.json", function(data) {
  createHtml(data.menu);
});

function createHtml(menuJson) {
  var html = '';

  $.each(menuJson, function(i, item) {
    if (item.sub) {

      html += '
'+
                '<input type="checkbox" checked/>'+
                '  '+
                item.name+'
'
      html += createHtml(item.sub);
      html += '

';
    } else {
      html += '
  '+item.name+'
';
    }
    return html;
  })
  $(".cd-accordion-menu").html(html);

}

HTML:

        <input type="checkbox" name ="group-1" id="group-1" checked>
        Group 1

                <input type="checkbox" name ="sub-group-1" id="sub-group-1">
                Sub Group 1

Image

Image

Image

                <input type="checkbox" name ="sub-group-2" id="sub-group-2">
                Sub Group 2

                        <input type="checkbox" name ="sub-group-level-3" id="sub-group-level-3">
                        Sub Group Level 3

Image

Image

How can I modify the function to get better adpater to the template?

A: The logic is flawed with this menu. You are returning inside of a forEach, which makes no sense and you are setting the html for the menu so the main menu and the recursive calls. That is also wrong.
The return needs to be outside the forEach and the setting of the menu call needs to be done somewhere else.
$.getJSON("menu.json", function(data) {
  var html = createHtml(data.menu);
  $(".cd-accordion-menu").html(html); //set html here
});

function createHtml(menuJson) {
  var html = '';
  $.each(menuJson, function(i, item) {
    if (item.sub) {
      html += '
' +
        '<input type="checkbox" checked/>' +
        '  ' +
        item.name + '
'
      html += createHtml(item.sub);
      html += '

';
    } else {
      html += '
  ' + item.name + '
';
    }
  })
  return html; //return html outside of the loop
}


text:
Q: void function not printing because cant return value but when i make string or int function it print null or return value at the end automatically New to dart, take following code as example, //void function doesnt work and int/string function either returns null that is printed or value return which is automatically printed as can be seen in the output.
class Microphones{
  String? name;
  String? color;
  int? model;
  String printEverything(){
    print(name);
    return " ";
  }
  int? printint(){
    print(model);
}
}

void main() {
  var mic1=Microphones();
  print(mic1.name);
  mic1.name="Yeti";
  mic1.color="black";
  mic1.model=26;

  print(mic1.name);
  print(mic1.color);
  print(mic1.model);
  print(mic1.printEverything());
  print(mic1.printint());
}

output:
null
Yeti
black
26
Yeti

26
null

i highly appreciate your replies/help in this regard.

A: All methods in Dart retuns null by default if you are not returning anything (either by having an empty return in methods specified to return void or not having any return at all in methods returning void or a nullable type like int?).
But return-type in the method signature specifies how the caller of the method should see the value. And here we have void which is described in the Dart language tour as:

A special type that indicates a value that's never used.

https://dart.dev/guides/language/language-tour#a-basic-dart-program
So we specify void to signal to the user of our method, that the returned value should never be used. And the Dart analyzer and compiler will then try very hard to make sure you are not ending up using the returned value typed void.
Advanced section for the curious
But that does not mean it is impossible to use a returned value specified to be void by the method signature:
void someMethod() {
  void someVoidVariable = 'Hey, I am a String!';
  return someVoidVariable;
}

void someOtherMethod() => 'Hey, I am also a String!';

void main() {
  print(someMethod() as String); // Hey, I am a String!
  print(someOtherMethod() as String); // Hey, I am also a String!
}

In the first example, we force Dart to see our String as void. That is completely fine since all types can be seen as void. We are then allowed to return this void value since someMethod() is suppose to return void.
The reason for this forcing is that Dart would complain about (which makes sense because what we are doing is very much stupid and should never be in a real program):
void someMethod() {
  return 'Hey, I am a String!';
  // ERROR: A value of type 'String' can't be returned from the function
  // 'someMethod' because it has a return type of 'void'.
}

Or this since we can't cast to void using as:
void someMethod() {
  return 'Hey, I am a String!' as void; // ERROR: Expected a type name.
}

We are then casting that void back to a String to let Dart allow us to use the returned value in print() (since Dart otherwise would prevent us from trying to use the void typed value).
In the second example, I show the one of the reasons for why things are working like they does. In Dart, we can write these two method which are going to do the exact same (note I changed the return type to String for this example):
String someOtherMethod() {
  return 'Hey, I am also a String!';
}

String someOtherMethod() => 'Hey, I am also a String!';

So the second way is a shorthand for if we just want to execute a single statement and return its value.
But what about:
void someOtherMethod() => 'Hey, I am also a String!';

If we followed the traditional rules, this would not be allowed since we cannot return a String since we have typed void. But sometimes, we also want to use this simple syntax to just execute a method and don't want to care about what that method would end up returning.
E.g. this:
final someList = <String>[];
void removeStringFromList(String string) => someList.remove(string);

Where the remove method on List is actually returning a bool which indicate if the element was inside the list.
So Dart ignores this problem when we use the => by just casting the result to void in this case. So in our last example, the returned bool is actually returned to the caller of removeStringFromList but because its type has been cast to void, the caller of removeStringFromList is prevented (in a lot of ways) from using the value.


text:
Q: How to provide expression as value inside an ssm document? I would like to add a server to an ausostaling-group using SSM document, if the group has n instances running - i want to have (n+1).
Since this stack is managed by cloudformation, i just need to increase the 'DesiredCapacity' variable and update the stack. so i created a document with 2 steps:

*

*get the current value of 'DesiredCapacity'

*update stack with value of 'DesiredCapacity' + 1

I didnt find a way to express this simple operation, i guess im doing something wrong ...
SSM Document:
schemaVersion: '0.3'
parameters:
  cfnStack:
    description: 'The cloudformation stack to be updated'
    type: String
mainSteps:
  - name: GetDesiredCount
    action: 'aws:executeAwsApi'
    inputs:
      Service: cloudformation
      Api: DescribeStacks
      StackName: '{{ cfnStack }}'
    outputs:
      - Selector: '$.Stacks[0].Outputs.DesiredCapacity'
        Type: String
        Name: DesiredCapacity
  - name: UpdateCloudFormationStack
    action: 'aws:executeAwsApi'
    inputs:
      Service: cloudformation
      Api: UpdateStack
      StackName: '{{ cfnStack }}'
      UsePreviousTemplate: true
      Parameters:
        - ParameterKey: WebServerCapacity
          ParameterValue: 'GetDesiredCount.DesiredCapacity' + 1 ### ERROR
          # ParameterValue: '{{GetDesiredCount.DesiredCapacity}}' + 1 ### ERROR (trying to concat STR to INT)
          # ParameterValue: '{{ GetDesiredCount.DesiredCapacity + 1}}' ### ERROR

A: There is a way to do calculation inside an SSM document using python runtime.
The additional python step do the following:

*

*Python runtime get variables via the the 'InputPayload' property

*The 'current' (str) key added to the event object

*The python function script_handler called

*The 'current' extracted using event['current']

*Converting string to int and adding 1

*return a dictionary with the 'desired_capacity' key and value as string

*expose the output ($.Payload.desired_capacity referred to the 'desired_capacity' of the returned dictionary)

    schemaVersion: '0.3'
    parameters:
      cfnStack:
        description: 'The cloudformation stack to be updated'
        type: String
    mainSteps:
      - name: GetDesiredCount
        action: 'aws:executeAwsApi'
        inputs:
          Service: cloudformation
          Api: DescribeStacks
          StackName: '{{ cfnStack }}'
        outputs:
          - Selector: '$.Stacks[0].Outputs.DesiredCapacity'
            Type: String
            Name: DesiredCapacity

      - name: Calculate
        action: 'aws:executeScript'
        inputs:
          Runtime: python3.6
          Handler: script_handler
          Script: |-
            def script_handler(events, context):
              desired_capacity = int(events['current']) + 1
              return {'desired_capacity': str(desired_capacity)}
          InputPayload:
            current: '{{ GetDesiredCount.DesiredCapacity }}'
        outputs:
          - Selector: $.Payload.desired_capacity
            Type: String
            Name: NewDesiredCapacity

      - name: UpdateCloudFormationStack
        action: 'aws:executeAwsApi'
        inputs:
          Service: cloudformation
          Api: UpdateStack
          StackName: '{{ cfnStack }}'
          UsePreviousTemplate: true
          Parameters:
            - ParameterKey: WebServerCapacity
              ParameterValue: '{{ Calculate.NewDesiredCapacity}}'


text:
Q: Why are styles overwritten if I apply more styles to text in separate methods? I'm programming my custom styles for my disassembler. Unfortunately, it seems like it always overwrites the style to the latest characters and the other styles are lost. Here my code which calls my styling:
        if (Base)
        {
            ITypeBase Instr = new ITypeBase();
            Instr = BaseTypeSplit(bits, Instr);

            Disassemble._dis.updateOP(CheckOpcode(Instr.opcode) + " ");
            Disassemble._dis.updateREG(CheckReg(Instr.rt));
            Disassemble._dis.updateCOMMA(", ");
            Disassemble._dis.updateIMM(CheckImm(Instr.imm));
            Disassemble._dis.updateREGB("(" + CheckReg(Instr.@base) + ")");
        }

Yes, my main code calls the scintilla Box from another class. I use my constructor from the other class (_dis = this;) to access it.
And here my functions which do the styling:
    public Disassemble()
    {
        InitializeComponent();
        _dis = this;
     }

    public static Disassemble _dis;

    public void updateOP(string message)
    {
        int length = scintilla1.TextLength;
        int length2 = message.Length;
        int sum = length + length2;

        scintilla1.Styles[1].Font = new Font("Arial", 25, FontStyle.Bold);
        scintilla1.Styles[1].ForeColor = Color.FromArgb(255, 128, 0);
        scintilla1.Text += message;

        int n = length;

        while (length < sum)
        {
            scintilla1.GetRange(n).SetStyle(1);
            n = length + 1;
            length += 1;
        }
    }

    public void updateREG(string message)
    {
        int length = scintilla1.TextLength;
        int length2 = message.Length;
        int sum = length + length2;

        scintilla1.Styles[2].Font = new Font("Arial", 25, FontStyle.Bold);
        scintilla1.Styles[2].ForeColor = Color.FromArgb(128, 0, 0);
        scintilla1.Text += message;

        int n = length;

        while (length < sum)
        {
            scintilla1.GetRange(n).SetStyle(2);
            n = length + 1;
            length += 1;
        }
    }

    public void updateREGB(string message)
    {
        int length = scintilla1.TextLength;
        int length2 = message.Length;
        int sum = length + length2;

        scintilla1.Styles[5].Font = new Font("Arial", 25, FontStyle.Bold);
        scintilla1.Styles[5].ForeColor = Color.FromArgb(172, 172, 172);
        scintilla1.Text += message;

        int n = length;

        while (length < sum)
        {
            scintilla1.GetRange(n).SetStyle(5);
            n = length + 1;
            length += 1;
        }
    }

    public void updateCOMMA(string message)
    {
        int length = scintilla1.TextLength;
        int length2 = message.Length;
        int sum = length + length2;

        scintilla1.Styles[3].Font = new Font("Arial", 25, FontStyle.Bold);
        scintilla1.Styles[3].ForeColor = Color.FromArgb(0, 0, 0);
        scintilla1.Text += message;

        int n = length;

        while (length < sum)
        {
            scintilla1.GetRange(n).SetStyle(3);
            n = length + 1;
            length += 1;
        }
    }

    public void updateIMM(string message)
    {
        int length = scintilla1.TextLength;
        int length2 = message.Length;
        int sum = length + length2;

        scintilla1.Styles[4].Font = new Font("Arial", 25, FontStyle.Bold);
        scintilla1.Styles[4].ForeColor = Color.FromArgb(0, 0, 255);
        scintilla1.Text += message;

        int n = length;

        while (length < sum)
        {
            scintilla1.GetRange(n).SetStyle(4);
            n = length + 1;
            length += 1;
        }
    }

And this is what I get, always:

As you see, it only styles the latest characters and the other styled characters lose their styling and are overwritten.
I've tried some (horrible) ways, but they also didn't result in what I wanted. Does someone have an idea what could be the cause of this? For additional information, I use Visual Studio 2012, .NET 4.5

A: So, found my own solution. Instead of putting it into separate methods, I decided to put it into one and put all my while loops in there. This is my result and it worked successfully:
    public void updateBase(string opcode, string rt, string comma, string imm, string @base)
    {
        int tlen = scintilla1.TextLength; // 12
        int olen = opcode.Length;
        int rlen = rt.Length;
        int clen = comma.Length;
        int ilen = imm.Length;
        int blen = @base.Length;
        int n = 0;

        scintilla1.Text += opcode;
        scintilla1.Text += rt;
        scintilla1.Text += comma;
        scintilla1.Text += imm;
        scintilla1.Text += @base;

        int sumt = tlen + olen;

        while (tlen < sumt)
        {
            n = tlen - 1;
            tlen += 1;
            scintilla1.GetRange(n).SetStyle(1);
        }

        sumt = tlen + rlen;

        while (tlen < sumt)
        {
            n = tlen /*+ 1*/;
            tlen += 1;
            scintilla1.GetRange(n).SetStyle(2);
        }

        sumt = tlen + clen;

        while (tlen < sumt)
        {
            n = tlen /*+ 1*/;
            tlen += 1;
            scintilla1.GetRange(n).SetStyle(3);
        }

        sumt = tlen + ilen;

        while (tlen < sumt)
        {
            n = tlen /*+ 1*/;
            tlen += 1;
            scintilla1.GetRange(n).SetStyle(4);
        }

        sumt = tlen + blen;

        while (tlen < sumt)
        {
            n = tlen /*+ 1*/;
            tlen += 1;
            scintilla1.GetRange(n).SetStyle(5);
        }

    }

And here the result:


text:
Q: Failure to mock.patch dictionary of methods called in list comprehension I'm currently using the following set up to manage a variable set of methods that could be applied to data, but when I try and mock the method to make sure it is returning any list (I have already set up tests of the methods themselves), I end up with KeyErrors.
Is there something I'm missing here in my understanding of how mocking works in Python? I had figured if I mock a method, it shouldn't matter if I pass in an empty dictionary or not; that it should just return True at that point.
File 1
def method_1(data):
    return data['header_1'] > 1

def method_2(data):
    return data['header_2'] > 1

def method_3(data):
    return data['header_3'] > 1

File 2
from module import file1 as f1

method_dict = {
    'method_1' : f1.method1,
    'method_2' : f1.method2,
    'method_3' : f1.method3
}

tasks_1 = ['method_1']
tasks_2 = ['method_2', 'method_3']

def function_A(data, tasks):
    results = [method_dict[task](data) for task in tasks]
    index = [i for i, result in enumerate(results) if result is True]
    return [tasks[i] for i in index]

Test File
from module import file2 as f2
from unittest import TestCase
from unittest.mock import patch

class TestFile2(TestCase):
    @patch('module.file1.method_1')
    def test_file_2(self, mock_method_1):
        mock_method_1.return_value = True
        results = f2.function_A({}, 'tasks_1')
        expected = ['method_1']
        self.assertEqual(results, expected)
. . .

Error
test/test_determine_failure_modes.py:100:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
module/file2.py:82: in function_A
    results = [task[task](data) for task in tasks]
module/file2.py:82: in <listcomp>
    results = [tasks[task](data) for task in tasks]
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

data = {}

    def method_1(data):
>       return data['header_1'] > 1
E       KeyError: 'header_1'

module/file1.py:2: KeyError

A: Your patch should read @patch('module.file2.f1.method_1')
I'll walk you through why:
test_determine_failure_modes.py imports file1 as f1. Then file1 is read and it defines method1 in it's locals. That becomes available on the symbol f1.
So the symbol tables look like:
file1: {'method1': <function>, <METHOD_1>, ...}
f1: {'method1': <function>, <METHOD_1>, ...}

Then you patch file1.method1 and you get this symbol table
file1: {'method1': <function>, MOCK, ...}
f1: {'method1': <function>, <METHOD_1>, ...}

Then you call f1.method1 and get the actual function.
It looks like you use method_dict to reference the function, so you still need to go a little deeper. Fortunately, unittest.mock.patch has a utility for mocking dict contents like so:
with patch.dict(f2.method_dict, {'method1': your_mock_here}):
    your_test_here()

One other way is to defer resolving the method name until after it's mocked.
method_dict = {
    'method_1' : lambda data: f1.method1(data),
    'method_2' : lambda data: f1.method2(data),
    'method_3' : lambda data: f1.method3(data)
}

Here, the lookup for f1.method1 doesn't happen until after it has been mocked. In the earlier case, you put a reference to the function when file2 was read. Here the reference isn't resolved until the method is actually called.


text: Q: Where can I find /Applications/XAMPP/Xamppfiles/? I have been told that in order to change the admin from "daemon" to anything else, I need to access /Applications/XAMPP/Xamppfiles/ on my Mac. All that I see in my Applications folder is the application XAMPP and no other folders. I've tried to find it in terminal and in the finder folder. How could I access this folder?


text:
Q: C: scanf input single character and validation I've encountered a problem when validating a single-char scanf input in C and I cannot find an existing solution that works...
The scenario is: a method is taking a single letter 'char' type input and then validating this input, if the criteria is not met, then pops an error message and re-enter, otherwise return this character value.
my code is:
char GetStuff(void)
{
    char c;
    scanf("%c", &c);
    while(c != 'A' || c != 'P')
    {
          printf("invalid input, enter again (A for AM or P for PM): ");
          scanf ("%c", &dtChar);
    }
    return c;
}

however, i got the infinite loop of error message no matter what input I type in. I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried:

*

*putting a white space before/after %c like:
scanf(" %c", &c);

*write a separate method or include in this GetStuff method to clean the newline like:
void cleanBuffer(){
  int n;
  while((n = getchar()) != EOF && n != '\n' );
}

Can anyone help me with this problem please? Thank you in advance.

A: Please consider the following snippet:
#include <stdio.h>
#include <ctype.h>

char GetStuff(void)
{
    char c;
    do {
          printf("Please enter A for AM or P for PM: ");
          scanf ("%c", &c);
          // clean input buffer (till the end of line)
          while(getchar()!='\n');
    } while(toupper(c) != 'A' && toupper(c) != 'P');
    return c;
}

int main(void)
{
    printf("Your input is'%c'\n", GetStuff());
    return 0;
}

Note the points:

*

*condition while(c != 'A' || c != 'P') will be always true (just because one character cannot be 'A' and 'P' at the same time), so use while(c != 'A' && c != 'P') instead

*No need for two scanf if you use do..while loop

*After entering a char with scanf it is recommended to clean all characters from buffer, e.g. with while(getchar()!='\n'); (this will clean all input including incorrect and redundant characters)

*use toupper to avoid making 4 comparison (actually single c=toupper(c) inside loop can minimize your while as while(c != 'A' && c != 'P') )

UPDATE:
To add message "Invalid input" and adding some other useful improvement subjected befor... new code is as:
#include <stdio.h>
#include <ctype.h>

void CleanBuffer(){
    int n;
    while((n = getchar()) != EOF && n != '\n' );
}

char GetStuff(void)
{
    char c;
    do {
          printf("Please enter A for AM or P for PM: ");
          scanf (" %c", &c);
          c = toupper(c); // here letter become uppercase
          CleanBuffer();
    } while( (c != 'A' && c != 'P')?printf("Invalid input! "):0 );
    return c;
}

int main(void)
{
    printf("You have entered: %c\n", GetStuff());
    return 0;
}

Note: function will return 'A' or 'P' in uppercase, so if this is not needed change the code as in example before update (use two toupper and do not change c after scanf). Also you can use tolower as an option (of course with comparing to 'a' and 'p').

A: Inside loop you are taking input in  dtChar but your loop condition checks variable c which is not updated in the loop, that is causing infinite loop
Also you would change your condition
while(c != 'A' || c != 'P')

to
while(c != 'A' && c != 'P')

If you want user to enter either 'A' or 'P'

A: #include <stdio.h>

char GetStuff(void) {
    char c;
    scanf("%c", &c);
    getchar();
    while ((c != 'A') && (c != 'a') && (c != 'P') && (c != 'p')) {
        printf("invalid input, enter again (A for AM or P for PM): ");
        scanf ("%c", &c);
        getchar();
    }
    return c;
}

int main(void) {
    printf("Calling GetStuff()...\n");
    char x = GetStuff();
    printf("User entered %c\n", x);
    return 0;
}

You are using while (c != 'A' || c != 'P') as your loop conditional, but this will always return true. What you meant to use is the && "and" operator, instead of the || "or" operator.
Also, call getchar() after your scanf statements, to capture the newline. This should work the way you want it to.

A: Another possible solution. As others mentioned the condition was to be done with &&. Anyway the big problem is how to remove what's left on the console input line. Since the console works by lines, we remove everything up to the next '\n'. If the user already left something on the input line before calling GetStuff(), it would be useful to add a call to SkipRestOfTheLine() before the while loop.
In general I suggest to start with a while(1) loop, before making it nicer (such as in the cleanBuffer() you posted).
#include <stdlib.h>
#include <stdio.h>

void SkipRestOfTheLine(void)
{
    while (1) {
        int c = fgetc(stdin);
        if (c == EOF || c == '\n')
            break;
    }
}

char GetStuff(void)
{
    while (1) {
        int c = fgetc(stdin);
        if (c == EOF)
            exit(EXIT_FAILURE); // Deal with this case in an appropriate way
        if (c == 'A' || c == 'P')
            return c;
        printf("invalid input, enter again (A for AM or P for PM): ");
        SkipRestOfTheLine();
    }
}

int main(void)
{
    char c = GetStuff();
    return 0;
}

A: #include <stdio.h>
int main(){
char c;
do{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%s", &c);
}while ((c != 'A') && (c != 'P'));
return 0;
}

A: try this,
   char GetStuff(void)
    {
        char c;
        scanf("%c", &c);
        while (((c != 'A') || (c != 'a')) && ((c != 'P') || (c != 'p'))==1)
        {
              printf("invalid input, enter again (A for AM or P for PM): ");
              scanf ("%c", &dtChar);
        }
        return c;
    }

I hope this works, some time because of not given proper bracket it is stuck in the loop.


text:
Q: How do I fix "Nios2 software build tools for eclipse" build errors? I have a Quartus Cyclone3 project with NIOS2 processor. I have noticed 3 errors while building the eclipse project, though I am pretty sure it should be working well.
Description: make[1]:  [public.mk] Error 1
Resource:   FW_SCT_SIM_NIOSII
Type: C/C++ Problem
Description: make:   [public.mk] Error 1
Resource:   FW_SCT_SIM_NIOSII_BSP
Type: C/C++ Problem
Description: make:   [../FW_SCT_SIM_NIOSII_BSP/-recurs-make-lib] Error 2
Resource:   FW_SCT_SIM_NIOSII
Type: C/C++ Problem
what are the reasons for the errors and how should I fix the problem?
are they fatal, or I can leave them like that?
Console messages look like this:
**** Build of configuration Nios II for project FW_SIM_NIOSII_BSP ****
make all
      0 [main] pwd 34688 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer.  Please report this problem to the public mailing list cygwin@cygwin.com
0 [main] sh 35264 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer.  Please report this problem to the public mailing list cygwin@cygwin.com
0 [main] echo 32640 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer.  Please report this problem to the public mailing list cygwin@cygwin.com
Makefile not up to date.
0 [main] echo 18444 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer.  Please report this problem to the public mailing list cygwin@cygwin.com
D:.../FW_SIM_NIOSII.sopcinfo has been modified since the BSP was generated.
0 [main] echo 26440 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer.  Please report this problem to the public mailing list cygwin@cygwin.com
Generate the BSP to update the Makefile, and then build again.
0 [main] echo 44376 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer.  Please report this problem to the public mailing list cygwin@cygwin.com
0 [main] echo 28532 find_fast_cwd: WARNING: Couldn't compute FAST_CWD pointer.  Please report this problem to the public mailing list cygwin@cygwin.com
...
and so on (a lot of mess)
make: *** [public.mk] Error 1

A: Ok, so I did this and that and finally found the cure.
Project RBM click -> Index -> Freshen all files
  and
Project RBM click -> Index -> Rebuild
That's how I got rid of those errors. But I did get much more new ones. They look like this: Type 'alt_u32' could not be resolved line 28 Semantic Error
So I tried a few things and got rid of them by going
Project RBM click -> Source -> Format
This removes the errors.
But I'm still curios about how and why did this happen.


text:
Q: Is it possible to share CARTO datasets with password? It's my understanding that only CARTO maps can be password-protected, not datasets. I'm currently using the datasets like so:
const source = new carto.source.Dataset(dataset);
const style = new carto.style.CartoCSS(cartoLayerCss);
const layer = new carto.layer.Layer(source, style, {
  ...
});

this.client
      .addLayer(layer)
      .then(() => {
         ...
}

Am I forced to

*

*make the dataset private

*create a map out of it

*set a password on that map and

*bind the pw-protected map via vis.json?

A: CARTO Builder and Editor maps can be shared with password. CARTO datasets "can be shared" using tokens with the Auth API (vis.json does not work with CARTO.js v4).


text:
Q: angular 2 table pagination I'm trying to make a paginated table, I send a request to an api but it only returns 10 rows and I get the total row count from header.
Starting from this point I want to paginate my table in 10 rows, thus let's suppose this:

5 rows = 1 button on table (or disabled)
14 rows = 2 buttons on table
40 rows = 4 buttons on table
56 rows = 6 buttons and so forth

So, on every numbered button I want to send a parameter to my API indicating the number of page that will be the same that the number of button but, as you can see, I'm unable see at least one second button
this is my view:

     ResourceId
     Parent Resource Set
     Name
     Description
     Route
     Environment

       {{ resource.resourceId }}
       {{ resource.resourceSetId }}
       {{ resource.name }}
       {{ resource.description }}
       {{ resource.route }}
       {{ resource.environment }}

   total row count {{head}}

 <pagination-controls (pageChange)="page = $event" id="1" maxSize="10" directionLinks="true" autoHide="false"></pagination-controls>

my component:
export class ResourcesComponent implements OnInit {
  resources : Resources[];
   data;
   head;
 constructor(private router: Router, private resourcesv: ResourcesService) { }
   getResources() {
      this.resourcesv.getResources().subscribe(resources => this.resources =resources);
   }
   ngOnInit() {
        this.getResources();
        this.resourcesv.fetchdata().subscribe((data)=>{ this.data = data.json,
        this.head = data.headers.get('x-rowcount');
      return this.head;
   });
  }
 }

and my service :
 @Injectable()
 export class ResourcesService {
  private resourcesurl = "http://localhost:9111/v1/resources";
  constructor(private http: Http) { }
  getResources() {
    let headers = new Headers();
    headers.append("api_key", "123456");
    return this.http.get(this.resourcesurl, { headers: headers }).map(this.extractData).catch(this.handleError);
   }
   fetchdata() {
   let headers = new Headers();
   headers.append("api_key", "123456");
   return this.http.get(this.resourcesurl, { headers: headers })
  .map((res) => res)
  }
  private extractData(res: Response) {
   let body = res.json();
    return body.data || {};
  }
  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
     const body = error.json() || '';
     const err = body.error || JSON.stringify(body);
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  }  else {
    errMsg = error.message ? error.message : error.toString();
   }
   console.error(errMsg);
   return Observable.throw(errMsg);
  }
 }

I want to set a certain amount of buttons according to the number of records that are returned in the custom header
any idea?


text:
Q: assigning snmpget output to a variable Can you help me assign the snmpget output to a variable and then write it to the RESULTS file.
#!/bin/sh

workingdir="/home/dperera/ping-tests" # LOG=$workingdir/RESULT.csv

infile=$workingdir/RTR_LIST # while read device

do

#$device sysName.0 > /dev/null
#if [ "$?" = "0" ] ; then
    rtr = snmpget -v2c -c xxxxx $device mib-2.47.1.1.1.1.11.1  >> $LOG
    echo "$device, $rtr" >> $LOG
#   fi
done < $infile

A: You may use tee for it, tee would write the output to both stdout and log file. Modify your command as followed would assign the output of $(snmpget ...) to rtr, and write to $LOG as well.
rtr=$(snmpget -v2c -c xxxxx $device mib-2.47.1.1.1.1.11.1 | tee -a $LOG)

Mind that -a for tee would allow the output append to the given $LOG, rather than overwrite it.

A: I bet the following command line returns you an error code :
rtr = snmpget -v2c -c xxxxx $device mib-2.47.1.1.1.1.11.1  >> $LOG

First, remember that in bash, you cannot let spaces before and after your = symbol. Plus, remember that you want the return value of the command, so you need to use the $.Therefore, this should work :
rtr=$(snmpget -v2c -c xxxxx $device mib-2.47.1.1.1.1.11.1)

After this, writing your variable into a log file can simply be done with :
echo rtr >> your.file

Did not try it by myself, but should be fine.
Hope it helped !


text:
Q: Cannot find module 'vscode' I've been attempting to make use of the vscode module for the development of my custom language server, but I've been running into some issues. The following error appears whenever I try to run the server:
Error: Cannot find module 'vscode'
Require stack:
- /Users/garrettc/src/elastic-lsp/vscode-extension-samples/elastic-lsp/server/out/server.js
    at Function._resolveFilename (internal/modules/cjs/loader.js:934:15)
    at internal/modules/cjs/loader.js:779:27
    at Function._load (electron/js2c/asar_bundle.js:5:12684)
    at Module.require (internal/modules/cjs/loader.js:1006:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (/Users/garrettc/src/elastic-lsp/vscode-extension-samples/elastic-lsp/server/out/server.js:11:18)
    at Module._compile (internal/modules/cjs/loader.js:1125:30)
    at Object..js (internal/modules/cjs/loader.js:1155:10)
    at Module.load (internal/modules/cjs/loader.js:982:32)
    at internal/modules/cjs/loader.js:823:14 {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/garrettc/src/elastic-lsp/vscode-extension-samples/elastic-lsp/server/out/server.js'
  ]
}

I've looked around and seen this error come up several times, but no fix has worked for me. npm install within the root, server and client folders, but nothing has changed.


text:
Q: Convert Excel formats to pdf - Powershell My question's about the error at saving file at this convert script:
https://github.com/idf/batch_dump/blob/master/office_convert.ps1
#Error
Exception when calling "InvokeMember" with "6" argument (s): "Object does not match destination type."
In the line: 28 character: 1
+ $workbook = $objExcel.Workbooks.PSBase.GetType().InvokeMember('Open', ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : TargetException

saving C:\Test\CD_FEV_1.pdf

You can not call a method on a null value expression.
In the line: 30 character: 1
+ $workbook.ExportAsFixedFormat($xlTypePDF, $filepath, $xlQualityStanda ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You can not call a method on a null value expression.
In the line: 31 character: 1
+ [void]$workbook.PSBase.GetType().InvokeMember('Close', [Reflection.Bi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

As i haven't experience in powershell i don't understand the metod they call at script.

A: I'm still new to powershell myself, so can't answer specifically what was causing the error, however I think I found the solution.  It seemed to be with only the Excel conversion.  The Word and PPT conversions worked flawless.  I've changed the code for that portion and it seems to be working now:
$folderpath =  $(get-location)
 Add-type -AssemblyName office
#Convert Word formats to pdf
$wdFormatPDF = 17
 $word = New-Object -ComObject word.application
 $word.visible = $false
 $fileTypes = "*.docx","*doc"
 $wordFiles = Get-ChildItem -path $folderpath -include $fileTypes -Recurse
foreach ($d in $wordFiles) {
 $path = ($d.fullname).substring(0,($d.FullName).lastindexOf("."))
 "Converting $path to pdf ..."
 $doc = $word.documents.open($d.fullname)
 $doc.saveas([ref] $path, [ref]$wdFormatPDF)
 $doc.close()
 }
$word.Quit()
#Convert Excel formats to pdf
$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$excelFiles = Get-ChildItem -Path $folderpath -include *.xls, *.xlsx -recurse
$objExcel = New-Object -ComObject excel.application
$objExcel.visible = $false
foreach($wb in $excelFiles)
{
 $filepath = Join-Path -Path $folderpath -ChildPath ($wb.BaseName + ".pdf")
 $workbook = $objExcel.workbooks.open($wb.fullname, 3)
 $workbook.ActiveSheet.PageSetup.Orientation = 2
 $objExcel.PrintCommunication = $false
 $workbook.ActiveSheet.PageSetup.FitToPagesTall = $false
 $workbook.ActiveSheet.PageSetup.FitToPagesWide = 1
 $objExcel.PrintCommunication = $true
 $workbook.Saved = $true
"saving $filepath"
 $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
 $objExcel.Workbooks.close()
}
$objExcel.Quit()
#Convert Powerpoint formats to pdf
$ppFormatPDF = 2
 $ppQualityStandard = 0
 $p = new-object -comobject powerpoint.application
$p.visible = [Microsoft.Office.Core.MsoTriState]::msoTrue
 $ppFiletypes = "*.pptx","*ppt"
 $ppFiles = Get-ChildItem -path $folderpath -include $ppFiletypes -Recurse
foreach ($s in $ppFiles) {
 $pppath = ($s.fullname).substring(0,($s.FullName).lastindexOf("."))
 "Converting $pppath to pdf ..."
 $ppt = $p.presentations.open($s.fullname)
$ppt.SavecopyAs($pppath, 32) # 32 is for PDF
 $ppt.close()
 }
$p.Quit()
 $p = $null
[gc]::collect()
 [gc]::WaitForPendingFinalizers()


text:
Q: Constructor injection versus setter injection for Parent property I'm trying to figure out the best way to use dependency injection for some legacy code which will take a long to refactor and has to be done gradually. Most of the old classes use a "Parent" property for determining various things and the parent property was often pass in via a constructor argument as follows:
constructor TParentObject.Create;
begin
  FChildObject := TChildObject.Create(Self);
end;

constructor TChildObject.Create(AParent: TParentObject)
begin
  FParent := AParent;
end;

This is fairly typical of our legacy code base. However when moving to interfaces and constructor injection, the Parent is not known by the Spring4D framework when creating the Child object. So it will just get a new parent but not the existing one. Of course I can create a property getter/setter but this would indicate an "optional" property for the class which is really a mandatory property. See the code below for more explanation:
unit uInterfaces;

interface

uses
  Spring.Collections;

type

  IChildObject = interface;

  IParentObject = interface
  ['{8EA8F9A2-E627-4546-8008-0A77DA2B16F1}']
    function GetSomethingRequiredByChild: string;
    procedure SetSomethingRequiredByChild(const Value: string);
    property SomethingRequiredByChild: string read GetSomethingRequiredByChild write SetSomethingRequiredByChild;
    function GetChild: IChildObject;
    property Child: IChildObject read GetChild;
  end;

  // This introduces a property getter/setter
  // However it also implies that Parent can be NIL which it cannot
  IChildObject = interface
  ['{ECCA09A6-4A52-4BE4-A72E-2801160A9086}']
    function GetParent: IParentObject;
    procedure SetParent(const Value: IParentObject);
    property Parent: IParentObject read GetParent write SetParent;
  end;

  TParentObject = class(TInterfacedObject, IParentObject)
  private
    FChild: IChildObject;
    FSomethingRequiredByChild: string;
    function GetChild: IChildObject;
    function GetSomethingRequiredByChild: string;
    procedure SetSomethingRequiredByChild(const Value: string);
  public
    constructor Create;
  end;

  TChildObject = class(TInterfacedObject, IChildObject)
  private
    FParent: IParentObject;
    function GetParent: IParentObject;
    procedure SetParent(const Value: IParentObject);
  public
    // This requries a Parent object, but how does the Spring4D resolve the correct parent?
    constructor Create(const AParent: IParentObject);
  end;

implementation

uses
  Spring.Services;

{ TParentObject }

constructor TParentObject.Create;
begin
  // Here is the old way...
  FChild := TChildObject.Create(Self); // Old way of doing it

  // This is the Service Locator way...
  FChild := ServiceLocator.GetService<IChildObject>;
  // I would prefer that the Parent is assigned somehow by the Service Locator
  // IS THIS POSSIBLE - or am I dreaming?
  FChild.Parent := Self;
end;

function TParentObject.GetChild: IChildObject;
begin
  Result := FChild;
end;

function TParentObject.GetSomethingRequiredByChild: string;
begin
  Result := FSomethingRequiredByChild;
end;

procedure TParentObject.SetSomethingRequiredByChild(const Value: string);
begin
  FSomethingRequiredByChild := Value;
end;

{ TChildObject }

constructor TChildObject.Create(const AParent: IParentObject);
begin
  FParent := AParent;
end;

function TChildObject.GetParent: IParentObject;
begin
  Result := FParent;
end;

procedure TChildObject.SetParent(const Value: IParentObject);
begin
  FParent := Value;
end;

end.

Maybe there is some methodology which can be used that I'm not aware of to set the parent object using the DI framework?
I hope this question is clear what I'm trying to achieve. I'm happy to provide more description/code example where necessary.

A: First of all you should not use the service locator to replace ctor calls. This is just making things worse. I know people think they are smart by doing that but really you are replacing one simple dependency on another class with a dependency on some global state plus the requirement that some other code out of (the consuming classes) control puts the dependency into the container. That does not result in easier but harder to maintain code.
Plus all the other reasons why you should stay away from it. The service locator might have a limited use in legacy application to introduce a composition root in the middle of an application to start DI from that point on but not in a way you show.
If parent needs the child then just inject it. Now the problem is if you want to create a parent, you first need the child but the child needs the parent. How to achieve that? There are two solutions. However one of them is not pure DI compatible.
I first show the way using a factory provided by the container (needs latest develop branch version as of the time of posting):
unit ParentChildRelationShip.Types;

interface

uses
  SysUtils,
  Spring,
  Spring.Container.Common;

type
  IChildObject = interface;

  IParentObject = interface
    ['{8EA8F9A2-E627-4546-8008-0A77DA2B16F1}']
    function GetChild: IChildObject;
    property Child: IChildObject read GetChild;
  end;

  IChildObject = interface
    ['{ECCA09A6-4A52-4BE4-A72E-2801160A9086}']
    function GetParent: IParentObject;
    property Parent: IParentObject read GetParent;
  end;

  TParentObject = class(TInterfacedObject, IParentObject)
  private
    FChild: IChildObject;
    function GetChild: IChildObject;
  public
    constructor Create(const childFactory: IFactory<IParentObject, IChildObject>);
  end;

  TChildObject = class(TInterfacedObject, IChildObject)
  private
    FParent: WeakReference<IParentObject>;
    function GetParent: IParentObject;
  public
    constructor Create(const AParent: IParentObject);
  end;

implementation

{ TParentObject }

constructor TParentObject.Create;
begin
  FChild := childFactory(Self);
end;

function TParentObject.GetChild: IChildObject;
begin
  Result := FChild;
end;

{ TChildObject }

constructor TChildObject.Create(const AParent: IParentObject);
begin
  FParent := AParent;
end;

function TChildObject.GetParent: IParentObject;
begin
  Result := FParent;
end;

end.

program ParentChildRelation;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Spring.Container,
  Spring.Container.Common,
  ParentChildRelationShip.Types in 'ParentChildRelationShip.Types.pas';

procedure Main;
var
  parent: IParentObject;
  child: IChildObject;
begin
  GlobalContainer.RegisterType<IParentObject,TParentObject>;
  GlobalContainer.RegisterType<IChildObject,TChildObject>;
  GlobalContainer.RegisterFactory<IFactory<IParentObject,IChildObject>>(TParamResolution.ByValue);
  GlobalContainer.Build;
  parent := GlobalContainer.Resolve<IParentObject>;
  child := parent.Child;
  Assert(parent = child.Parent);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.Message);
  end;
  ReportMemoryLeaksOnShutdown := True;
end.

If you don't want to use a container provided factory you explicitly register it yourself. Then the RegisterFactory call is replaced with this one:
  GlobalContainer.RegisterInstance<TFunc<IParentObject,IChildObject>>(
    function(parent: IParentObject): IChildObject
    begin
      Result := GlobalContainer.Resolve<IChildObject>([TValue.From(parent)]);
    end);

And the constructor parameter can be changed to TFunc<...> as it does not need RTTI for this method (that is why you needed IFactory<...> in the other case).
The second version uses field injection and thus is pure DI incompatible - be careful writing code like that as it does not work without using the container or RTTI - like if you want to test these classes it might become hard to compose them without the container. The important part here is the PerResolve which tells the container to reuse the once resolved instance whenever another dependency is needed that it can satisfy.
unit ParentChildRelationShip.Types;

interface

uses
  SysUtils,
  Spring;

type
  IChildObject = interface;

  IParentObject = interface
    ['{8EA8F9A2-E627-4546-8008-0A77DA2B16F1}']
    function GetChild: IChildObject;
    property Child: IChildObject read GetChild;
  end;

  IChildObject = interface
    ['{ECCA09A6-4A52-4BE4-A72E-2801160A9086}']
    function GetParent: IParentObject;
    property Parent: IParentObject read GetParent;
  end;

  TParentObject = class(TInterfacedObject, IParentObject)
  private
    [Inject]
    FChild: IChildObject;
    function GetChild: IChildObject;
  end;

  TChildObject = class(TInterfacedObject, IChildObject)
  private
    FParent: WeakReference<IParentObject>;
    function GetParent: IParentObject;
  public
    constructor Create(const AParent: IParentObject);
  end;

implementation

function TParentObject.GetChild: IChildObject;
begin
  Result := FChild;
end;

{ TChildObject }

constructor TChildObject.Create(const AParent: IParentObject);
begin
  FParent := AParent;
end;

function TChildObject.GetParent: IParentObject;
begin
  Result := FParent;
end;

end.

program ParentChildRelation;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Spring.Container,
  Spring.Container.Common,
  ParentChildRelationShip.Types in 'ParentChildRelationShip.Types.pas';

procedure Main;
var
  parent: IParentObject;
  child: IChildObject;
begin
  GlobalContainer.RegisterType<IParentObject,TParentObject>.PerResolve;
  GlobalContainer.RegisterType<IChildObject,TChildObject>;
  GlobalContainer.Build;
  parent := GlobalContainer.Resolve<IParentObject>;
  child := parent.Child;
  Assert(parent = child.Parent);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.Message);
  end;
  ReportMemoryLeaksOnShutdown := True;
end.

By the way. Watch your references between parent and child when using interfaces. If they reference each other you will get memory leaks. You can solve that by using a weak reference on one side (usually the parent reference in the child).


text:
Q: WCF Data Services (OData) deployment on IIS 5.1 I have developed a WCF Data service using VS 2010, I am able to run it and get the data as feed by running using VS 2010.
I published the service on IIS 5.1 but I m getting http: 404 error.
Can anyone help to deploy the service on IIS 5.1 step by step?

A: I found a bit on it here.


text:
Q: How to render frames precisely without waiting for the thread to finish I have a java App and I am Loading 3 Gif files into BufferedImage Arrays and want to display them.
I have a simple Thread that is executed every e.g. 16ms (~ 60fps) using Thread.sleep()
In this method, I am calling the paintcomponent method to draw on the GUI component.
But I don't want the Thread (Runnable) to wait for the Method to end rendering because the Delay is more than 16ms afterward - even if it is not measurable.
Here's a snippet inside my Runnable JLabel (Currently the fast/efficient method)
@Override
public void run() {
    while (active) {
        repaint(); //Takes 0ms
        i++; // Counter used inside paintComponent()
        Thread.sleep(speed * multiplier));
        if (i + 1 == frames.length) {
            i = 0;
        }
    }
}

@Override
public void paintComponent(Graphics g) {
    g.drawImage(frames[i], 0, 0, x, y, observerFrame);
    g.dispose();
}

I tested it and the repaint methods take 0ms. Probably not measurable.
But isn't it still unprecise? Or maybe inefficient?
So the (simple) math is done inside the Thread. But how do I ensure that the timing is precise? I mean it is still precise enough but it still depends on the speed of the pc
After the Answer of @Reto Höhener I did some research and tried another method.
But it is still inefficient and lags when rendering the images (BufferedImages btw):
This is one big attempt I did where I thought that it would be better:
Timer timer = new Timer(16, this);

Executor executor = Executors.newCachedThreadPool();

//called by executor
@Override
public void run() {
    i++; // Counter used inside paintComponent()
    Thread.sleep(speed * multiplier));
    if (i + 1 == frames.length) {
        i = 0;
    }
}

//called by timer & runs on EDT
@Override
public void actionPerformed(ActionEvent e) {
    repaint();
    executor.execute(this); //Costs no time and has enought time to complete
}

@Override
public void paintComponent(Graphics g) {
    g.drawImage(frames[i], 0, 0, x, y, observerFrame);
    g.dispose();
}

So this way I ensure that

*

*The repaint is done in the EDT

*The math is done by another Thread using executors

Even if I was proud after compiling and running it the results made me cry...
With the first method, the JVM uses ~10% of the CPU. Everything is fine and running on the fps for all 3 Frames.
The second try uses less CPU but is bad performing.
I don't know why but the GUI is responsive but the rendering is slow almost 3x slower.
The goal is to render images in 60 frames per second without lag.
The point here is that I tried an attempt where I thought that it is conceptually better but it did even worse.
So my question is if there is a better and more precise way to achieve this.
Otherwise, I will stay at the Simple Thread based solution.
regards
Nur1

A: First it would probably be helpful to learn just a little bit about the Java Event Dispatching Thread (or AWT Event Queue) concept.
My suggestion would be to use one thread that is only responsible to call a .repaint()-method on your component. Instead of rolling your own thread, consider using javax.swing.Timer for this, it already uses a thread behind the scenes, and is able to coalesce multiple events if they arrive too quickly.
Then use another thread that is only responsible for calculating the information required to paint. One approach is to render into a buffer image. The .paint()- or .paintComponent()-method of your display component then only has to paint that image.


text:
Q: Axes with fixed size arrows I'm trying to get a constant/uniform size on the arrow heads for the "$x$" and "$y$" axis in 2D plots for all my plots but they seem to change depending on the aspect ratio. I have managed to get the tick mark and label fonts constant/uniform, but have not found a solution to the arrow heads "problem". Is there a solution to this?
There seem to be "solutions" to the problem for individual arrows using Line and polygons but none(?) for the automatic arrows on the plot axis?
I tried constructing an arrow head using polygons but it cannot be placed over the axis (only half of the arrow head is visible)
Are there any function/commands that I can use to place a graphical object in a plot, even outside the plotting 'border'?

a = -15;
location = {π + 0.5, 0};
arrow =
  Polygon[{
    location,
    Offset[{a, 5}, location],
    Offset[{0.7 a, 0}, location],
    Offset[{a, -5}, location]
  }];
arr = Graphics[arrow];
Plot[Sin[x], {x, 0, π},
  PlotRange -> {{0, π + 0.5}, {0, 1.5}},
  ImageSize -> Medium,
  Epilog -> {arrow}]

A: ClearAll[arrow]
arrow[ sc_: 1, a_: {15, 5}] := Graphics[Polygon[{{0, 0}, Offset[sc {-1, 1} a, {0, 0}],
          Offset[sc {-7/10, 0} a, {0, 0}], Offset[-sc a, {0, 0}]}]];

Examples:
Plot[Sin[x], {x, 0, π}, PlotRange -> {{0, π}, {0, 1.5}},
  PlotRangePadding -> {{Automatic, Scaled[.1]}, Automatic},
  ImageSize -> 500,
  AxesStyle -> {Arrowheads[{{1/100, 1, arrow[]}}], Automatic}]

 Grid @ Partition[Plot[1 + Sin[x], {x, 0, 2 Pi},
     AxesStyle -> Arrowheads[{{0.3, 1, arrow[]}}],
     ImageSize -> #, AspectRatio -> #2] & @@@ Tuples[{{200, 400}, {1/2, 1}}], 2]

Change arrow[] to arrow[2] to get

A: As far as your specific question about why only half the arrow is show, this is due to the option PlotRangeClipping->True. Setting this option to False gives:
Plot[Sin[x], {x, 0, π},
    PlotRange -> {{0, π + 0.5}, {0, 1.5}},
    ImageSize -> Medium,
    Epilog -> {arrow},
    PlotRangeClipping -> False
]

On the other hand, I think the canonical approach to this issue is to use AxesStyle with an Arrowheads directive, as in @kglr's answer. Unfortunately, the natural approach doesn't work, and I would suggest reporting this to support:
Plot[Sin[x], {x, 0, π},
    PlotRange -> {{0, π + 0.5}, {0, 1.5}},
    ImageSize -> Medium,
    AxesStyle -> {Arrowheads[Medium], Automatic}
]

For some reason, Mathematica gets confused about how much image padding is needed. One workaround is to use my function GraphicsInformation to figure out the default image padding, and then to explicitly set this:
<<GraphicsInformation`

plot = Plot[Sin[x], {x, 0, Pi},
    PlotRange -> {{0, π + 0.5}, {0, 1.5}},
    ImageSize -> Medium
];
pad = "ImagePadding" /. GraphicsInformation[plot]

Plot[Sin[x], {x, 0, π},
    PlotRange -> {{0, π + 0.5}, {0, 1.5}},
    ImageSize -> Medium,
    AxesStyle -> Arrowheads[Medium],
    ImagePadding ->pad
]

{{17., 1.5}, {17., 0.5}}

Another workaround is to create an explicit arrow graphic using Offset, and then to use that graphic inside of the Arrowheads directive as in @kglr's answer.


text:
Q: setContentOffset not working for UIScrollView inside UITableViewCell for the first time I have a horizontal UIScrollView which is added as a subview inside custom UITableViewCell. For some cases, I want to change the scrollview content offset which I achieve by doing this code
cell.horizontalScrollView.setContentOffset(CGPoint(x: 300, y: cell.horizontalScrollView.contentOffset.y), animated: true)

inside the UITableView's cellForRowAtIndexPath function and tableview.reloadData() is called whenever I needed to scroll it programmatically.
The issue is, this does not work for the first time. ie,
When the tableview is loaded for the first time, the scrollviews inside the visible cells does not get scrolled according to the code. Its offset is just at (0,0). ---- (This is the issue!)
But after that, when I scrolled the tableView, then the new cells(reused cells) gets updated and scrollviews position gets changed. (which I needed from the start itself!)
So, I want to change the UIScrollView's initial offset(position) programmatically. How can I achieve that?

A: Atlast, I found the solution after sitting for a couple of days!
Had to implement layoutIfNeeded for the UITableViewCell inside the cellForRowAtIndexPath method before setting the contentOffset for the UIScrollView.
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
    cell.layoutIfNeeded()
    cell.horizontalScrollView.setContentOffset(CGPoint(x: 300, y: cell.horizontalScrollView.contentOffset.y), animated: false)
    return cell
}

A: The best way to implement this is to subclass your cell and then set the content offset in layoutSubviews method.


text:
Q: Using Microsoft.Extensions.Logging can you filter for a single EventID? I'd like to produce a log file that contains only log output from a particular EventId (or EventIds).  Is such functionality supported?

A: If you plug in Serilog as the provider, you can continue logging through Microsoft.Extensions.Logging but apply Serilog's filtering to limit what is sent to the log file.
To do that you'd use the following Serilog configuration:
Log.Logger = new LoggerConfiguration()
    .Filter.ByIncludingOnly("EventId.Id = 9")
    .WriteTo.RollingFile("logs/log-{Date}.txt")
    .CreateLogger();

(Where 9 is whatever event id you want to include.)
You can plug in Serilog with https://github.com/serilog/serilog-aspnetcore, and to compile this example you'll also need to install the Serilog.Sinks.RollingFile and Serilog.Filters.Expressions packages.

A: If you want to config Serilog using the appsettings file you can use something like this:
"Serilog": {
    "Using": ["Serilog.Sinks.File", "Serilog.Settings.Configuration", "Serilog.Expressions"],
    "MinimumLevel": {
        "Default": "Debug"
    },
    "WriteTo": [{
            "Name": "File",
            "Args": {
                "path": "log.txt",
                "rollingInterval": "Day",
                "retainedFileCountLimit": "120",
                "rollOnFileSizeLimit": "true",
                "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
            }
        }
    ],
    "Filter": [{
            "Name": "ByIncludingOnly",
            "Args": {
                "expression": "EventId.Id = 101"
            }
        }
    ]
}

In the using field you have to put all Serilog package that you are importing, then config a sink for writing the logs and finally define a filter.
I almost spent a whole morning trying to achive that so I hope it helps you


text:
Q: thinning/skeletonization algorithm with 4 known neighbors I am searching for a thinning/skeletonization algorithm which works if I only know 4 neighbors not 8.
From all algorithms I could find I assume that I have knowledge about the diagonal neighbors.
So does anybody know about a thinning algorithm which also works if I only know the top, right, bottom, left neighbor?
The outcome should be like this:
http://www.cs.ru.nl/~ths/rt2/col/h9/thinning.GIF
These are not what I am looking for:
http://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Skel.png/220px-Skel.png
The shape should be maintained as in the first example

A: I'd suggest using one of the 8-neighbour algorithms, but feeding it dummy information for the diagonal cells or otherwise modifying the part of the algorithm that considers neighbours.
Since you're not too specific about the kinds of things you're looking at it's hard to offer concrete suggestions. Most algorithms will contain a part that looks like this:
for n in neighbours:
  do stuff

in which case you need to edit neighbours.
Others will apply some kind of mask or kernel function. Edit that kernel.


text:
Q: General Runtime Error being displayed instead of stack trace sharepoint 2010 I am trying to add a GridView to the aspx page ,but when I add it I get the error
I have enabled debugging on the web.config file , but still I get this below error. Since a day I have been trying to add the gridview to the page, it does'nt let me do it. However, I am able to add the same gridview to another aspx page.
Not sure of whats going wrong. Can someone please let me know of how can I get the stack trace which will help me let me know the probl.

A: Janet, you're going to need to disable custom errors as indicated in the error page you're seeing.  Add <customErrors mode="Off" /> in the web.config for your site to see the full details of the error.

A: What this means is that when you are NOT on the local machine, you will be viewing this type of error whenever a runtime error occurs. When you are viewing this in local machine's browser, you can get the real error page. But, If you want to see this on the browser not on local machine, you WILL have to change web.config

customErrors mode="RemoteOnly"

to

customErrors mode="Off"

(Note that mode is case sensitive here, i.e "off" is not same as "Off").


text:
Q: How to run AStyle from inside Sublime? I already tried using the SublimeAStyle Package, but it didn't work. When I pressed the keys, the command would not fire (I checked in the console). Now I am trying to write my own key-shortcut to run the program on my source code. I have this:
{ "keys": ["ctrl+alt+f"], "command": "exec", "args": { "cmd": ["C:\\Program Files\\AStyle\\bin\\astyle.exe", "${file_name}"]} }

but the ${file_name} is not expanding to pass the file name to the command. Is there anything I am doing wrong?


text:
Q: Why applescript doesn't accept file object in localized string command? Following applescript throws error:
set thePath to path to application support from user domain as alias
set mystr to localized string "Add people to this note" in bundle file thePath

And the error is
error "Can't make file (alias \"Macintosh HD:Users:shakes:Library:Application Support:\") into type file." number -1700 from file (alias "Macintosh HD:Users:shakes:Library:Application Support:") to file

What does this error means? localized string expects a file or alias object which thePath is then why this error?
FYI, localized string reference says:
Syntax
localized   string  text    required
from table   text   optional
in bundle   fileSpecifier   optional

A: The folder Application Support is not a file. Remove the file keyword.
set thePath to path to application support from user domain -- as alias is redundant
set mystr to localized string "Add people to this note" in bundle thePath

But the code is meaningless because the folder Application Support is not a bundle either.


text:
Q: How to use Lisp in Android? How I can use a  Lisp library in Android (Eclipse Java)?
For example I like have a "Intelligent apps" with Lisp.

A: You need or common lisp implementation, which can run under android, or some tool to compile common lisp code into JVM Bytecode or native library for android (with NDK). As far as I know, there is no good and free solution for this problem for now.
Clozure Common Lisp can run under android, but you can't really create an application which can be published in play store with it. Or it'll be very difficult. There is even an example for CCL on android.
There is also proprietary Common Lisp implementation from wukix - MOCL, which aims to be able to bring Common Lisp into mobile development world. I had no experience with that, you can give it a try.
As I said, looks like for now there is no easy way to do what you want.

A: LambdaNative is technically a lisp (it is an implementation of Scheme based on Gambit-C Scheme) which implements its own GUI and various other modules.
It uses the same source code to create native applications for Android, iOS, Linux, Mac OS X, Blackberry 10, Windows, OpenBSD and OpenWrt.

A: Try lispworks android/ios runtime:
Sad thing it's not free, but you can ask for evaluation license.
Useful links:
Build iOS/Android Libraries in Common Lisp with LispWorks
LispWorks® for Mobile Runtime
LispWorks User Guide and Reference Manual- 16 Android interface
Mocl is another alternative:
mocl (+ lisp ios android osx)

A: There is also eql5-android, which integrates QML for the UI. It features a few examples.


text:
Q: zkemkeeper SetUserInfo isn't working I want to create new user for the device through zkemkeeper.SetUserInfo(). However when I tried to use this function It always return False and when I look into the error code it said -2, Which means ERROR_IO. Anyone knows how to fix this thing or What could be the cause of this error ?
Here is my code
zk = Dispatch("zkemkeeper.ZKEM")
result = zk.Connect_Net(IP, PORT)
if result == True:
    result = zk.SetUserInfo(machineNumber, 456, "DEFG", 0, 0, True)
    print(result) #it always false here
    erroCode = zk.GetLastError()
    print(erroCode) # -2
    disConnectDevice(zk)


text:
Q: Android: lint id AppLinksAutoVerifyWarning always failing but AppLinks work fine I'm having the problem that the lint test for AppLinksAutoVerifyWarning is always failing with the error message:

App Links Auto Verification Failure
      ../../src/debug/AndroidManifest.xml:17: This host does not support app links to your app. Checks the Digital Asset Links JSON file:
  https://myhost/.well-known/assetlinks.json

I'm using a target specific AndroidManifest for debug builds, as you can see above. For those debug builds I append a .debug suffix to my package name. So debug builds will have package id mypackage.debug and Release builds will get just mypackage. Both builds are signed with the same release key (due to sharedUserId) and I made sure that the fingerprint in the assetlinks.json matches the signed one. For myhost there is a valid ssl certificate.
I uploaded the assetlinks.json file with support for mypackage.debug an mypackage and made sure that it has the correct application/json mimetype.

*

*On the Phone the app linking works fine

*Validating with digitalassetlinks.googleapis.com/v1/statements:list?source.web.site=https://myhost&relation=delegate_permission/common.handle_all_urls does not provide any errors

*Testing the AppLink with adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "http://myhost" works fine

*I recreated, uploaded and tested the assetlinks.json with developers.google.com/digital-asset-links/tools/generator which validates ok and does not produce a json file with different content

*Validated json syntax using textmate

*I also tried moving the intent-filter from the debug AndroidManifest to the main manifest, moving it to other activities which don't have another intent-filter
So everything seems to be fine, just lint isn't working. I could just disable the lint check but I rather would like to have it on so I'm aware when there is a real problem.
One thing I observed: if I change the intent-filter for the app link from https to http the error message from lint changes to: ... has incorrect JSON syntax which is even more strange because android itself and the google validation services seem to validate it fine. (might be related that we forward all traffic from http to https)
current intent-filter is:
  <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW"/>

                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>

                <data
                    android:host="myhost"
                    android:pathPrefix="/open_app"
                    android:scheme="https"/>

   </intent-filter>

A: I just had the same issue, so I looked at the source code for the lint check:
            switch (result.getValue().mStatus) {
            case STATUS_HTTP_OK:
                List<String> packageNames = getPackageNameFromJson(
                        result.getValue().mJsonFile);
                if (!packageNames.contains(packageName)) {
                    context.report(ISSUE_ERROR, host, context.getLocation(host), String.format(
                            "This host does not support app links to your app. Checks the Digital Asset Links JSON file: %s",
                            jsonPath));
                }
                break;

It was failing for me because the package name in the assetlinks.json did not match the one in my manifest. Turns out someone on my team only half finished converting our top level project into a library project, and changed the top level projects package name. But this could also happen if the assetlinks.json has a typo on the package name.


text:
Q: Remove http:// or https:// from variable I am using this code to remove the http:// part of a URL but it doesn't do anything - it just returns the full URL. What am I doing wrong?
<?php $str = the_field('fl_website');$str = preg_replace('#^https?://#', '', rtrim($str,'/'));echo $str; ?>

A: $str = 'http://www.google.com';
$str = preg_replace('#^https?://#', '', $str);

I can see You are doing it similiar way. Maybe the variable is not set as You think it is?


text:
Q: Use geographiclib to generate 3d points Can geographiclib be used to convert (WGS84) latitude-longitude pairs to 3d/Cartesian/xyz points?
If not, is there an alternative method for converting from one to the other without using a spherial approximation?

A: Yes. As the following example shows, the Geographiclib::Geocentric class provides such a conversion:
// Example of using the GeographicLib::Geocentric class
#include <iostream>
#include <exception>
#include <cmath>
#include <GeographicLib/Geocentric.hpp>
using namespace std;
using namespace GeographicLib;

int main() {
  try {
    Geocentric earth(Constants::WGS84_a(), Constants::WGS84_f());
    // Alternatively: const Geocentric& earth = Geocentric::WGS84();
    {
      // Sample forward calculation
      double lat = 27.99, lon = 86.93, h = 8820; // Mt Everest
      double X, Y, Z;
      earth.Forward(lat, lon, h, X, Y, Z);
      cout << floor(X / 1000 + 0.5) << " "
           << floor(Y / 1000 + 0.5) << " "
           << floor(Z / 1000 + 0.5) << "\n";
    }
    {
      // Sample reverse calculation
      double X = 302e3, Y = 5636e3, Z = 2980e3;
      double lat, lon, h;
      earth.Reverse(X, Y, Z, lat, lon, h);
      cout << lat << " " << lon << " " << h << "\n";
    }
  }
  catch (const exception& e) {
    cerr << "Caught exception: " << e.what() << "\n";
    return 1;
  }
}


text:
Q: A Symbol Name was Expect by 'id" I'm trying to make a table for a login system for a simple website project but I'm having this error that I wasn't having the other day. I'm getting the errors at 'id' and unsigned on the 2nd line. The error is "A Symbol Name is Expected Near 'id'. I also get an error by unsigned on the same line that says "unrecognizable statement type". I am using XAMPP.
CREATE TABLE 'users' (
    'id' int(11) unsigned NOT NULL AUTO_INCREMENT,
    'username' varchar(75) NOT NULL,
    'password' varchar(255) NOT NULL,
    'email' varchar(100) NOT NULL,
    'phone' varchar(15) NOT NULL,
    'address' varchar(255) NOT NULL,
    PRIMARY KEY ('id'),
    UNIQUE KEY 'email' ('email')
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;

A: You're using single quotes for identifiers (column and table names). Single quotes are for strings.
Identifiers are either unquoted, or use the MySQL/MariaDB specific `. The SQL standard uses ". Consider turning on ANSI mode for compatibility.
Also consider using the serial shorthand for bigint unsigned not null auto_increment unique.
create table users (
  id serial primary key,
  ...
)


text:
Q: MySQL blocking access to all but a couple of databases only on certain IP address So, a couple of days ago, our master instance of MySQL started blocking me from accessing all but a couple of databases but only when connecting from a specific IP address. I can connect and see all the databases when connecting from any other IP address and I can connect and see all databases when connecting to a slave instance. Credentials are the same regardless. I've never seen anything like this.

A: To gain access to all databases you need to run these commands as a privileged user (eg on the machine itself):
grant all privileges on *.* to YOUR_USER_ID@REMOTE_IP_ADDRESS_YOU_WANT_TO_BE_ALLOWED;
flush privileges;

To get the YOUR_USER_ID@REMOTE_IP_ADDRESS_YOU_WANT_TO_BE_ALLOWED run the select user(); command. This will let you know how you are accessing the database, you can grant privileges accordingly

A: I think what you'll want to do to start exploring this problem is:
http://dev.mysql.com/doc/refman/5.0/en/show-grants.html
show grants for 'user'@'host';

A: Try run this script
GRANT ALL ON . to user@'%' IDENTIFIED BY 'password';
It would allow you to access from any IP Address and any machines and access all databases.
Good Luck :)


text:
Q: WPF: Why does DataTrigger delete my default style? Just learning WPF and can't figure out this behavior. Example:

The Label gets its initial style from a StaticResource on the Window. Then, I have two ways to change the style of the label:

*

*Using a button (via CodeBehind)

*Using a checkbox (via DataTrigger binding).

Once I click the Button, I can no longer change the style via the CheckBox.
Sorry I don't understand why this happens. Thanks in advance to anyone who can help me :-) Here is the code:
XAML:
<Window x:Class="WtfDataTrigger.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WtfDataTrigger"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="Label" x:Key="LabelStyle">
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </Window.Resources>
    <StackPanel>
        <Label Name="Label1" Content="Label1" FontSize="24">
            <Label.Style>
                <Style TargetType="Label" BasedOn="{StaticResource LabelStyle}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=Checkbox, Path=IsChecked}" Value="True">
                            <Setter Property="Foreground" Value="Aqua" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Label.Style>
        </Label >
        <Button Content="Click Me to Change Label Style Using Routed Events" FontSize="18" Click="Button_Click" />
        <CheckBox Name="Checkbox" Content="Check Me to Change Label Style Using Data Trigger" FontSize="18">

        </CheckBox>

    </StackPanel>
</Window>

CodeBehind:
private void Button_Click(object sender, RoutedEventArgs e)
    {
        Label1.Foreground = new SolidColorBrush(Colors.DarkOrange);
    }

A: This is because the binding is lost on the button click.  Once you directly change a value that is binding in XAML the new value removes the binding all together.  You would need to have another trigger possibly and force that to happen.  There is code you can write to continue the binding or re-instantiate the original binding but it's a bit of overkill.  Personally I recommend staying away from the Code behind if you're going to use XAML... I myself force myself to never write code behind period but that's a design choice so it's what you choose to do.
If you have to use code behind and you do wish to stick primarily to XAML then you will need to build custom controls that use DependencyProperties etc and keep them completely generic like every other control.
That's off subject but the bottom line is you've removed the binding by clicking the button and setting the Foreground property directly.  If you must use code behind and wish to keep the binding I wouldn't mind posting the code to accomplish that and you can choose to agree or not but it's a bit of a headache to design that way.


text:
Q: Modular Polynomial Arithmetic I have came across this modular polynomial arithmetic question. I not really understand how the answers were derived.

For the first example right, from what I understand it is the polynomial whose coefficient are from Z_p, {0,1,...,p-1}. So given p = 3, I can get 0,1,2. And if given p = 2, I can get 0,1.
But I not sure how those x are derived. Any ideas? Thanks in advance.

A: It seems to be the list of all polynomials of degree less than $2$, with coefficients in $\mathbf Z/3\mathbf Z$ in the first case; of all polynomials of degree less than $3$, with coefficients in $\mathbf Z/2\mathbf Z$ in the second case.
Indeed, for the first case, a polynomial of degree less than $2$  has the form  $a_0+a_1x$. Plug in the different possible values for  the pairs $(a_0,a_1)$, getting
\begin{matrix}
(0,0)\to \color{red}{0}&(0,1)\to \color{red}{x}&(0,2)\to \color{red}{2x}\\
(1,0)\to \color{red}{1}&(1,1)\to \color{red}{1+x}&(1,2)\to \color{red}{1+2x}\\
(2,0)\to \color{red}{2}&(2,1)\to \color{red}{2+x}&(2,2)\to \color{red}{2+2x}
\end{matrix}
The second case goe along the same lines:
\begin{matrix}
&(0,0,1)&&(0,1,1)\\
&\color{red}{x^2} &&\color{red}{x+x^2}\\
(0,0,0)&&(0,1,0) \\
\color{red}{0}&&\color{red}{x}\\[2ex]
&(1,0,1)&&(1,1,1)\\
& \color{red}{1+x}&&\color{red}{1+x+x^2}\\
(1,0,0)&&(1,1,0)\\
\color{red}{1}&& \color{red}{1+x}
\end{matrix}

A: If n=2, the polynomial has 2 terms, the x and constant term.  If x=3, the polynomial has three terms, $x^2$, $x$, and the constant term.  So the highest degree of the polynomial is $n-1$.


text:
Q: How to insert files above every line with a variable in sed? I have a file with this values:
[mik@mikypc ~]$ cat file.txt
id=cat8760004
id=cat1350003
id=cat9020002

And I want to insert id with the value above every line, so the result will be:
New_id=cat8760004
id=cat8760004
New_id=cat1350003
id=cat1350003
New_id=cat9020002
id=cat9020002

How could I do that?, I have tried with sed, but I cannot replace the variable:
[mik@mikypc ~]$ cat file.txt | sed '/cat\([0-9][0-9]*\)/ i\New_id &'
New_id &
id=cat8760004
New_id &
id=cat1350003
New_id &
id=cat9020002

A: I suggest with GNU sed:
sed 's/.*/New_&\n&/' file.txt

Output:

New_id=cat8760004
id=cat8760004
New_id=cat1350003
id=cat1350003
New_id=cat9020002
id=cat9020002


text:
Q: Why remove() method on Java Set does not work I have the following code:
    Set<Set<Integer>> groups = new HashSet<>();

    for (int[] edge : edges) {
        Set<Integer> match1 = null;
        Set<Integer> match2 = null;

        for(Set<Integer> group : groups) {
            if(group.contains(edge[0])) match1 = group;
            if(group.contains(edge[1])) match2 = group;
        }

        if(match1 != null && match1 == match2) {
            result = edge;
        }else if(match1 != null && match2 != null && match1 != match2) {
            match1.addAll(match2);
            groups.remove(match2);     <---- This does not remove match2 from set
        }else{
            Set<Integer> newGroup = new HashSet<>();
            newGroup.add(edge[0]);
            newGroup.add(edge[1]);
            groups.add(newGroup);
        }

        .........
    }

The groups is a Set of Set of Integers.
However, the groups.remove(match2) method does not remove the set of integers from the groups.
What happened here?

A: Quoting the Set interface documentation:

Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

You are violating this rule when you mutate match1 with the addAll() call while it's still inside the outer Set. The mutation causes the hash code to change without the outer Set knowing about it, so the inner Set is now in the wrong hash bucket and can't be found when you try to remove it in some subsequent iteration.
As a workaround, you can remove it, then call addAll(), then add it again. Internally, this will cause it to be placed in the correct hash bucket for its new hash code.

By the way, it looks like you're implementing a connected component detection algorithm. You can do that more efficiently using a disjoint set forest data structure. There's some good pseudocode in How to store each set in a disjoint set forest.


text:
Q: How to set path for Blazor app hosted in .NET Core I am trying to host a Blazor app via a .NET Core Web Server.I am using FileProvider.I do not know why i keep getting this error :

blazor.webassembly.js:1 WASM: wasm streaming compile failed:
  TypeError: Failed to execute 'compile' on 'WebAssembly': HTTP status
  code is not ok WASM: falling back to ArrayBuffer instantiation Failed
  to load resource: the server responded with a status of 404 (Not
  Found) blazor.webassembly.js:1 WASM: both async and sync fetching of
  the wasm failed blazor.webassembly.js:1 WASM: both async and sync
  fetching of the wasm failed d.printErr @ blazor.webassembly.js:1
  blazor.webassembly.js:1 WASM: failed to asynchronously prepare wasm:
  abort("both async and sync fetching of the wasm failed"). Build with
  -s ASSERTIONS=1 for more info. d.printErr @ blazor.webassembly.js:1 blazor.webassembly.js:1 WASM: abort("both async and sync fetching of
  the wasm failed"). Build with -s ASSERTIONS=1 for more info.
  blazor.webassembly.js:1 WASM: abort("both async and sync fetching of
  the wasm failed"). Build with -s ASSERTIONS=1 for more info.
  d.printErr @ blazor.webassembly.js:1 localhost/:1 Uncaught (in
  promise) abort("abort(\"both async and sync fetching of the wasm
  failed\"). Build with -s ASSERTIONS=1 for more info."). Build with -s
  ASSERTIONS=1 for more info. :5000/favicon.ico:1 Failed to load
  resource: the server responded with a status of 404 (Not Found)

.NET Core Host Startup
public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            IFileProvider provider = new PhysicalFileProvider(@"D:/blazor/BenchUI/dist/");

            DefaultFilesOptions options = new DefaultFilesOptions
            {
                RequestPath = "",
                FileProvider = provider,
                DefaultFileNames = new List<string> { "index-browser.html" }
            };
            app.UseDefaultFiles(options);
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath = "",
                FileProvider = provider,
            });
        }
    }

Html root
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
    <title>BenchUI</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />

</head>
<body>
    <app>Loading...</app>

    <script src="_framework/blazor.webassembly.js"></script>
    <script src="Utilities.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

Folder structure
I have set the root of my fileprovider as dist but there the .NET Dll's are outside that folder .Could my root be wrong ? I do not understand what is wrong since the only error appears to be in blazor.webassembly.js,a script which is added inside the index.html.
I do not understand where to run dotnet [what dll name].dll?Do i need to publish the Client project and the run dotnet Client.dll inside it or do i need to publish the Client Server and Shared.
So far i have tried with dotnet [client name of dll].dll and even `dotnet run (in the csproj location)


text:
Q: Correct syntax for internal XSL map lookup I have a internally defined mapping table in an xsl document and I want to access a value using an xpath from an xml as the key. In XSL2 I was led to believe it is easy as this, but I seem to be getting errors.
<xsl:variable name="map">
 <entry key="One">testOne</entry>
 <entry key="Two">testTwo</entry>
 <entry key="Three">testThree</entry>
</xsl:variable>

<xsl:variable name="testVariable">
 <value-of select="$map/entry[@key=A/B]"/>
</xsl:variable>

If the xml document looks something like:

 Three

testVariable in the xsl document should resolve to 'testThree'

A: You've got two problems here. Firstly it should be xsl:value-of and not just value-of
Secondly, where you use A/B in your xpath condition, this will be relative to the entry element you are searching on, not the A/B in your original XML.
Try this instead:
<xsl:variable name="key" select="A/B"/>
<xsl:variable name="testVariable">
    <xsl:value-of select="$map/entry[@key=$key]"/>
</xsl:variable>

Or better still, write this
<xsl:variable name="key" select="A/B"/>
<xsl:variable name="testVariable" select="$map/entry[@key=$key]"/>

In fact, you don't have to use the key variable at all, just use the current() function to get the current context in your XML document
<xsl:variable name="testVariable" select="$map/entry[@key=current()/A/B]"/>


text:
Q: No rounded corners on React-Bootstrap-NavItem I want to have the same look as the pills style but without the rounded corners
this is what i have so far

    <NavItem eventKey={1} title="Template">Template</NavItem>
    <NavItem eventKey={2} title="Edit">Edit</NavItem>
    <NavItem eventKey={3} title="Preview">Preview</NavItem>

How do I set the border-radius of my NavItem to 0? It does appear in the rules of the li item but it does not change anything.

A: There are many different (and arguably better) ways to handle styling in React, but to use a style block like that you need to add dangerouslySetInnerHTML={{__html: