text:
Q: Set column of Array to variable value in bigquery scripting I'm trying to get the value of multiple columns in an array and set them as a variable that can be used in the loop to do something else. Thanks.
DECLARE the_array ARRAY<STRUCT<value1 STRING,value2 STRING>>;

SET the_array = (
  SELECT ARRAY_AGG(STRUCT(value1,value2))
  FROM `project.dataset.table`
  WHERE somthing = 'somthing'
);

LOOP
  SET i = i + 1;

  SET var1 = the_array[ORDINAL(????)]; // what do I do here?

  SET var2 = the_array[ORDINAL(???)]; // what do I do here?

  IF i > ARRAY_LENGTH(the_array) THEN
    LEAVE;
  END IF;

 insert into `project.dataset.other_table` values(var1,var2);

END LOOP;

A: If you are looking for correct way of achieving above result - do it in set based way which is most effective way of expressing your logic in SQL
INSERT INTO `project.dataset.other_table`
SELECT value1, value2
FROM `project.dataset.table`
WHERE somthing = 'somthing'

Meantime, if purpose of your question is to learn BigQuery Scripting - see below example
DECLARE the_array ARRAY<STRUCT<value1 STRING,value2 STRING>>;
DECLARE i INT64 DEFAULT 0;
DECLARE var1, var2 STRING;

SET the_array = (
  SELECT ARRAY_AGG(STRUCT(value1,value2))
  FROM `project.dataset.table`
  WHERE somthing = 'somthing'
);

LOOP
  SET i = i + 1;

  IF i > ARRAY_LENGTH(the_array) THEN
    LEAVE;
  END IF;

  SET var1 = the_array[ORDINAL(i)].value1;
  SET var2 = the_array[ORDINAL(i)].value2;

 insert into `project.dataset.other_table` values(var1,var2);

END LOOP;


text:
Q: Actions are assigned to wrong keyframe in Flash CS5 I am working with Flash CS5, and haven't been using Flash since the age of AS2.
I have a movieclip symbol in which I have an Actions layer, in which I have a keyframe in frame 1 and one in frame 20. Each of these should have a stop(); action assigned, but when i select the one in frame 20 and start writing, the little "a" appears on frame 1 of another layer. When I make a keyframe in frame 20 of that layer and try to assign actions it yields the same result. They appear on frame 1.
Is this a bug or am I missing some vital information about AS3?

A: AS3 is in fact more picky (for good reason) about how the code is implemented.
You need to select the keyframe you are intending to put code into, and then use your actions window. And as Markus commented, make sure you're using keyframes, and not empty frames. If you try to write code into an empty frame, it will default it to the most recent keyframe.
Furthermore, If you have multiple layers and say, your code is on layer2 and your objects on layer1, if you have keyframes on layer1, and intend to enter code at frame 20, but your layer selection is layer2, it will yield the same result described above. You'll have to make sure the correct layer is active. The actions window will only display the code from the current layer's most recent keyframe.
Hope that clears some things up!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chunked Response With HttpResult When building out a ServiceStack service, we noticed that the responses are almost identical, except that the HttpResult returns a chunked encoding response.
When using the HttpResult object like this:
return new HttpResult("0", ContentType.PlainText, HttpStatusCode.OK);

we see a response in Fiddler like this:
HTTP/1.1 200 OK
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/plain
Server: Microsoft-IIS/8.0
X-Powered-By: ServiceStack/3.954 Win32NT/.NET
X-Powered-By: ASP.NET
Date: Thu, 20 Jun 2013 13:33:17 GMT

But when using the Response property like this:
Response.ContentType = ContentType.PlainText;
Response.StatusCode = (int) HttpStatusCode.OK;
return "1";

we see a response in Fiddler like this:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/8.0
X-Powered-By: ServiceStack/3.954 Win32NT/.NET
X-Powered-By: ASP.NET
Date: Thu, 20 Jun 2013 14:38:39 GMT
Content-Length: 1

We'd like to use the HttpResult version as that seems to be much cleaner, but need for it to not be encoded. It appears to be chunking the response whenever adding the responseBody object. When that is taken away, the encoding is removed. However, even explicitly setting the AllowsPartialResponse to false does not fix this.

A: If you submit a pull-request with the correct behaviour covered by tests it will get merged pretty quickly.


text:
Q: How to render two Views on a single page- Backbone.js I am new to Backbone.js and I am trying to build a chrome extension to manage the github issues. Now the problem is that I am not getting the 'title' 'comment' 'repo' and 'assignees' and 'milestone' section on a same view. I have made two views one for title, comment and repo-name and another for assignees and milestone because I had to get the repo-name to fetch assignees and milestone.[I am trying to add milestone and assignee feature to https://github.com/rainforestapp/github-chrome ].
Here is my main part of the view.js:
NewIssueView.prototype.onSubmit = function(e) {
  var func, name, repository;
  e.preventDefault();
  name = this.$("[name=repository]").val();
  localStorage['new_issue_last_repo'] = name;
  repository = this.repositories.find(function(r) {
    return r.get('full_name') === name;
  });
  window.assigneec = new ContributorCollection({
    'repo': name
  });
  window.milestonec = new MilestoneCollection({
    'repo': name
  });
  window.th = this.$el;
  window.body = this.$("[name=body]").val();
  window.title = this.$("[name=title]").val();
  window.repository = repository;
  window.temp1 = 0;
  window.temp2 = 0;
  window.assigneec.fetch({
    success: function() {
      return window.temp1 = 1;
    }
  });
  window.milestonec.fetch({
    success: function() {
      return window.temp2 = 1;
    }
  });
  func = function() {
    if (window.temp1 === 1 && window.temp2 === 1) {
      this.newIssueView = new NewIssueView({
        repository: window.assigneec
      });
      //window.th.html(this.newIssueView2.el);
      //console.log(this.newIssueView2.el);
      //this.newIssueView2.render();
      //return window.temp1 = 0;
    }
  };
  return setInterval(func, 500);
};

and template.js
window.HAML['new2_issue'] = function(context) {
    return (function() {
      var $c, $e, $o, full_name, repository, _i, _j, _len, _len1, _ref, _ref1;
      $e = function(text, escape) {
        return ("" + text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/\//g, '/').replace(/"/g, '"');
      };
      $c = function(text) {
        switch (text) {
          case null:
          case void 0:
            return '';
          case true:
          case false:
            return '' + text;
          default:
            return text;
        }
      };
      $o = [];
      $o.push("

\n<form>\n
\n    Assignee:\n    <select class='assignee_select' name='assignee'>");
      _ref = this.repository.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        repository = _ref[_i];
        full_name = repository.get('login');
        $o.push("      <option value='" + ($c(full_name)) + "'>" + ($e($c(repository.get('login')))) + "</option>");
      }
      $o.push("    </select>\n
\n
\n    Milestones:\n    <select class='milestone_select' name='milestone'>");
      _ref1 = this.milestones.models;
      for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
        repository = _ref1[_j];
        full_name = repository.get('title');
        $o.push("      <option value='" + ($c(full_name)) + "'>" + ($e($c(repository.get('title')))) + "</option>");
      }
      $o.push("    </select>\n
\n
\n    <input class='submit' type='submit' value='Create Issue'>\n
\n</form>");
      return $o.join("\n").replace(/\s(\w+)='true'/mg, ' $1').replace(/\s(\w+)='false'/mg, '').replace(/\s(?:id|class)=(['"])(\1)/mg, "");
    }).call(context);
  };

}).call(this);
(function() {
  if (window.HAML == null) {
    window.HAML = {};
  }

  window.HAML['new_issue'] = function(context) {
    return (function() {
      var $c, $e, $o, full_name, repository, _i, _j, _len, _len1, _ref, _ref1;
      $e = function(text, escape) {
        return ("" + text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/\//g, '/').replace(/"/g, '"');
      };
      $c = function(text) {
        switch (text) {
          case null:
          case void 0:
            return '';
          case true:
          case false:
            return '' + text;
          default:
            return text;
        }
      };
      $o = [];
      $o.push("

\n<form>\n
\n    <select class='repo_select' name='repository'>");
      _ref = this.repositories.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        repository = _ref[_i];
        full_name = repository.get('full_name');
        //console.log(full_name);
        if (localStorage['new_issue_last_repo'] === repository.get('full_name')) {
          $o.push("      <option value='" + ($c(full_name)) + "' selected='selected'>" + ($e($c(repository.get('full_name')))) + "</option>");
        } else {
          $o.push("      <option value='" + ($c(full_name)) + "'>" + ($e($c(repository.get('full_name')))) + "</option>");
        }
      }window.HAML['new2_issue'] = function(context) {
    return (function() {
      var $c, $e, $o, full_name, repository, _i, _j, _len, _len1, _ref, _ref1;
      $e = function(text, escape) {
        return ("" + text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/\//g, '/').replace(/"/g, '"');
      };
      $c = function(text) {
        switch (text) {
          case null:
          case void 0:
            return '';
          case true:
          case false:
            return '' + text;
          default:
            return text;
        }
      };
      $o = [];
      $o.push("

\n<form>\n
\n    Assignee:\n    <select class='assignee_select' name='assignee'>");
      _ref = this.repository.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        repository = _ref[_i];
        full_name = repository.get('login');
        $o.push("      <option value='" + ($c(full_name)) + "'>" + ($e($c(repository.get('login')))) + "</option>");
      }
      $o.push("    </select>\n
\n
\n    Milestones:\n    <select class='milestone_select' name='milestone'>");
      _ref1 = this.milestones.models;
      for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
        repository = _ref1[_j];
        full_name = repository.get('title');
        $o.push("      <option value='" + ($c(full_name)) + "'>" + ($e($c(repository.get('title')))) + "</option>");
      }
      $o.push("    </select>\n
\n
\n    <input class='submit' type='submit' value='Create Issue'>\n
\n</form>");
      return $o.join("\n").replace(/\s(\w+)='true'/mg, ' $1').replace(/\s(\w+)='false'/mg, '').replace(/\s(?:id|class)=(['"])(\1)/mg, "");
    }).call(context);
  };

}).call(this);
(function() {
  if (window.HAML == null) {
    window.HAML = {};
  }

  window.HAML['new_issue'] = function(context) {
    return (function() {
      var $c, $e, $o, full_name, repository, _i, _j, _len, _len1, _ref, _ref1;
      $e = function(text, escape) {
        return ("" + text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/\//g, '/').replace(/"/g, '"');
      };
      $c = function(text) {
        switch (text) {
          case null:
          case void 0:
            return '';
          case true:
          case false:
            return '' + text;
          default:
            return text;
        }
      };
      $o = [];
      $o.push("

\n<form>\n
\n    <select class='repo_select' name='repository'>");
      _ref = this.repositories.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        repository = _ref[_i];
        full_name = repository.get('full_name');
        //console.log(full_name);
        if (localStorage['new_issue_last_repo'] === repository.get('full_name')) {
          $o.push("      <option value='" + ($c(full_name)) + "' selected='selected'>" + ($e($c(repository.get('full_name')))) + "</option>");
        } else {
          $o.push("      <option value='" + ($c(full_name)) + "'>" + ($e($c(repository.get('full_name')))) + "</option>");
        }
      }

How to combine this two views on a same page(or how these feature can be achieved).Thanks in advance.


text:
Q: Android fingerprint I am a newbie in android development
I am developing an android app that allow people using fingerprint to check-in. The idea is, for instance, a class need student check-in on time everyday. Student have to register their fingertip to identify with application.
I don't know whether android support my application? I just saw that fingerprint identify using registered user's finger.
Could you please help me some idea?
Thank you so much.

A: Android supports detecting more than one fingerprint.
Eg:Coolpad note 3 detects 5 different fingerprints and we can assign different actions to each fingerprint.
i.e one for unlock screen,one for camera.

*

*Detecting and authentication of different fingerprint is based on how you code your application.So go forward.

You can find here the code for the implentation of Fingerprint authentication in an app

*

*remember one thing that,here you can login in your app only using the fingerprint that you have used for the device's screen lock.

A: Android authorizes or verifies a user if the fingerprint was previously registered through Android settings. Meaning, you can't add new fingerprints through your app.
The KeyStore save all the keys and use the Keystore private key to sign transactions / data. Meaning, you cannot differentiate users through your app.


text:
Q: Decompose an ISO8601 format time stamp with regular expressions I want to extract the minutes and seconds from an time stamp of ISO8601 format. I made some tries with regexp but I have no experience on that.
Could you please help me on this?
Examples:

*

*PT1M46S --> 1 minute, 46 seconds

*PT36S --> 36 seconds

Thanks!

A: Use datevec to turn strings representing hours, minutes etc into corresponding numeric values. See "help datestr" to understand rules for symbols used in second input to datevec, ie. the format string. Here's how you can convert the two examples given, I leave it to you to extend it to cover the entire format.
str = 'PT36S';
str = strrep(str, 'PT', ''); % PT have to go.
if ~ismember('M', str)
% To use a single format string, we must write zero minutes if none are there already
str = ['00M', str];
end

% Date string cannot contain characters y,m,d,H,M or S, so remove these
str = strrep(str, 'S', ' ');
str = strrep(str, 'M', ' ');

% Call datevec with appropriate format string
[~, ~, ~, ~, min, sec] = datevec(str, 'MM SS')

You can extend this to manage hours, days etc by including additional if loops similar to that above. I am not familiar with this standard beyond the examples given so let me know if it's not as simple as that.

A: getPart = @(str, c) str2double(['0' regexp(str, ['\d*(?=' c ')'], 'match', 'once')]);

str = 'PT36S';
seconds = getPart(str, 'S');
minutes = getPart(str, 'M');
hours   = getPart(str, 'H');

This looks for character c, finds the digits behind it and converts them to a double. It adds character '0' in the beginning because if regexp can't find a match it returns an empty string. Adding this converts empty strings to zero while not affecting other numbers. If you want to restrict it to the parts after PT, you can remove that from original string using
str = regexprep(str, '^.*PT', '');


text:
Q: Django Proxy Field Is it possible to make a Django Proxy Field that has access to another field, but doesn't save anything to the database for it's own value(s), and doesn't have a database column for itself?
The use case for this is we'd like to store values in a JsonField, but be able to use the built in validations of Django Fields.  A second benefit of this would being able to add new fields (with validation capability) without affecting the database schema.
The sudo code would probably look something like this:
from django.db import models
from django.contrib.postgres.fields import JsonField

class ProxyInitMixin(object):

    def __init__(self, *args, *kwargs):
        # some logic that will hold values if set on the Model
        # but won't create a column or save anything to the
        # database for this Field.
        super(ProxyInitMixin, self).__init__(*args, **kwargs)

class ProxyIntegerField(ProxyInitMixin, models.Field):
    pass

class ProxyCharField(ProxyInitMixin, models.Field):
    pass

class MyModel(models.Model):
    proxy_int = ProxyIntegerField()
    proxy_char = ProxyCharField()
    data = JsonField()

    def save(self, *args, **kwargs):
        self.data = {
            'foo': self.proxy_int,
            'bar': self.proxy_char
        }
        return super(MyModel, self).save(*args, **kwargs)

A: There are proxy models in django, But I am not sure if it has something like proxy fields.
For your use case, you can do as mentioned below:

*

*Create a list of fields with each field containing name, type, nullable, etc.

*Add a function in your model to return actual django rest framework (DRF) field class instance, corresponding to each field type passed to it.

*Use DRF inbuilt field class validation to validate your field data against specified field type in save().

*In addition to automatic validation, you will also get automatic type conversion. Eg. If user entered number 1 as text: "1" for a integer field then it will automatically convert it back to integer 1. Same way, it will work for float, Bool, Char, etc

`
from django.db import models
from rest_framework.fields import IntegerField, FloatField, BooleanField, DateTimeField, CharField

class MyModel(models.Model):
    FIELDS = [{'field_name': 'proxy_int', 'field_type': 'int', 'null_allowed': 'True'},
              {'field_name': 'proxy_char', 'field_type': 'string', 'null_allowed': 'True'}]

    data = JsonField()

    def field_type(self, field):

        if field.field_type == 'int':
            return IntegerField()
        elif field.field_type == 'float':
            return FloatField()
        elif field.field_type == 'bool':
            return BooleanField()
        elif field.field_type == 'date':
            return DateTimeField()
        elif self.value_type == 'string':
            return CharField()
        return CharField()

    def save(self, *args, **kwargs):
        data = kwargs.get('data', {})
        new_data = {}

        for (field in FIELDS)

            field_name = field['field_name']
            field_type = field['field_type']
            field_value = data.get(field_name, None)

            validated_value = self.field_type(field_type).run_validation(field_value)

            new_data[field_name] = validated_value

        kwargs['data'] = new_data
        return super(MyModel, self).save(*args, **kwargs)`

You may try and figure out django's field classes (Instead of DRF) and use them for validation, if required.
You can inherit this new MyModel class to achieve similar capability in other models and to reuse code.

A: In order to make the field virtual, you need to:

*

*Override the Field.get_attname_column() method, which must return two-tuple attname, None as the value for attname and column.

*Set the private_only parameter to True in the Field.contribute_to_class() method.

A proxy field must also have a reference to the concrete field in order to be able to access to it. Here I will use the concrete_field parameter.
class ProxyMixin(object):
    """
    A mixin class that must be mixed-in with model fields.

    The descriptor interface is also implemented in this mixin
    class to keep value getting/setting logic on the Model.
    """

    def __init__(self, *args, concrete_field=None, **kwargs):
        self._concrete_field = concrete_field
        super().__init__(*args, **kwargs)

    def check(self, **kwargs):
        return [
            *super().check(**kwargs),
            *self._check_concrete_field(),
        ]

    def _check_concrete_field(self):
        try:
            self.model._meta.get_field(self._concrete_field)
        except FieldDoesNotExist:
            return [
                checks.Error(
                    "The %s concrete field references the "
                    "nonexistent field '%s'." % (self.__class__.__name__, self._concrete_field),
                    obj=self,
                    id='myapp.E001',
                )
            ]
        else:
            return []

    def get_attname_column(self):
        attname, column = super().get_attname_column()
        return attname, None

    def contribute_to_class(self, cls, name, private_only=False):
        super().contribute_to_class(cls, name, private_only=True)
        setattr(cls, name, self)

    @property
    def concrete_field(self):
        """
        Returns the concrete Field instance.
        """
        return self.model._meta.get_field(self._concrete_field)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        if self._concrete_field is not None:
            kwargs['concrete_field'] = self._concrete_field
        return name, path, args, kwargs

    def __get__(self, instance, owner=None):
        if instance is None:
            return self

        return getattr(instance, self._concrete_field)

    def __set__(self, instance, value):
        setattr(instance, self._concrete_field, value)

If you are sure that the concrete field represents a dict-like object, then you can change the logic for getting / setting value. Maybe something like this:
def __get__(self, instance, owner=None):
    if instance is None:
        return self

    data = getattr(instance, self._concrete_field) or {}
    return data.get(self.name, self.get_default())

def __set__(self, instance, value):
    data = getattr(instance, self._concrete_field)
    if data is None:
        setattr(instance, self._concrete_field, {})
        data = getattr(instance, self._concrete_field)
    data[self.name] = value


text:
Q: Data type is changed when a dictionary contains int element added by using pd.DataFrame.append() When a dictionary is added to an empty DataFrame using the append function of pandas, the elements of type int are converted and stored in the DataFrame.
As shown in the code below, it looks like the conversion to any data type depends on the other elements in the dictionary.
How can we store int types as int types without this behavior? Do I have to convert the data type of the DataFrame afterwards?
df = pd.DataFrame(columns=["int","float"])
print(df.append({"int":1, "float":0.5},ignore_index=True).dtypes)
"""
int      float64
float    float64
dtype: object
"""

df = pd.DataFrame(columns=["str","int","float"])
print(df.append({"str":"test", "int":1, "float":0.5},ignore_index=True).dtypes)
"""
str       object
int       object
float    float64
dtype: object
"""

A: you can use infer_objects to correct dtypes at the end of appending everything to the dataframe.
Also, you can use concat instead of append which has more functionality
In [47]: df.append({"str":"test", "int":1, "float":0.5},ignore_index=True).infer_objects().dtypes
Out[47]:
str       object
int        int64
float    float64
dtype: object


text:
Q: R - How to split/combine columns for multiple variables I'm quite the novice at R and I haven't been able to find an answer of how to split a column with multiple variables (sample 1-4) into separate columns whilst moving the data it correlates with. Here's an example:
Samples     Content
Sample 1    70.7
Sample 1    91.6
Sample 1    92.6
Sample 1    65.2
Sample 1    80.0
Sample 1    82.1
Sample 1    88.1
Sample 1    92.2
Sample 1    53.3
Sample 1    80.0
Sample 1    60.3
Sample 1    89.7
Sample 1    84.8
Sample 1    94.0
Sample 1    71.8
Sample 1    76.9
Sample 1    91.4
Sample 1    57.9
Sample 1    61.9
Sample 1    71.5
Sample 2    88.7
Sample 2    67.6
Sample 2    61.7
Sample 2    70.8
Sample 2    45.3
Sample 2    55.6
Sample 2    64.6
Sample 2    62.7
Sample 2    72.4
Sample 2    46.8
Sample 2    59.0
Sample 2    63.7
Sample 2    67.0
Sample 2    71.6
Sample 2    48.3
Sample 2    55.6
Sample 2    62.5
Sample 2    60.0
Sample 2    72.9
Sample 2    47.4
Sample 3    42.3
Sample 3    48.2
Sample 3    64.0
Sample 3    33.3
Sample 3    19.0
Sample 3    41.0
Sample 3    53.1
Sample 3    46.5
Sample 3    30.0
Sample 3    43.4
Sample 3    43.7
Sample 3    92.0
Sample 3    53.0
Sample 3    33.0
Sample 3    48.4
Sample 3    43.2
Sample 3    41.8
Sample 3    62.5
Sample 3    33.3
Sample 3    49.3
Sample 4    51.8
Sample 4    57.3
Sample 4    43.3
Sample 4    42.3
Sample 4    37.6
Sample 4    54.9
Sample 4    71.1
Sample 4    33.8
Sample 4    43.1
Sample 4    39.1
Sample 4    63.0
Sample 4    74.0
Sample 4    31.0
Sample 4    48.3
Sample 4    42.9
Sample 4    62.2
Sample 4    35.4
Sample 4    33.8
Sample 4    40.7
Sample 4    41.2

I tried tidyr with no success. I want the output to be something like this;
Sample 1    Sample 2    Sample 3    Sample 4
70.7    88.7    42.3    51.8
91.6    67.6    48.2    57.3
92.6    61.7    64.0    43.3
65.2    70.8    33.3    42.3
80.0    45.3    19.0    37.6
82.1    55.6    41.0    54.9
88.1    64.6    53.1    71.1
92.2    62.7    46.5    33.8
53.3    72.4    30.0    43.1
80.0    46.8    43.4    39.1
60.3    59.0    43.7    63.0
89.7    63.7    92.0    74.0
84.8    67.0    53.0    31.0
94.0    71.6    33.0    48.3
71.8    48.3    48.4    42.9
76.9    55.6    43.2    62.2
91.4    62.5    41.8    35.4
57.9    60.0    62.5    33.8
61.9    72.9    33.3    40.7
71.5    47.4    49.3    41.2

Many thanks, if a solution is identified, is there an answer if I wanted to do the reciprocate?
Extra - Is there any way to preform a t-test on data which is stacked in one column such as the first example without having to transform it?

A: *

*You may be having the "duplicate identifiers" issue using tidyr::spread. You need first to generate unique combinations of Sample + identifier, which you can do like this (assuming data frame named df1):
library(tidyverse) # for dplyr + tidyr
df1 %>%
  group_by(Samples) %>%
  mutate(id = row_number()) %>%
  spread(Samples, Content) %>%
  select(-id)

*
"if I wanted to do the reciprocate"

Do you mean go the other way, from the wide form back to the original long form? Then you use gather. Add this to the end of the code above and see what happens:
%>% gather(Samples, Content)

*t-test: there are lots of ways you could run a t-test on the long format data. For example, a base R way to compare Samples 1 and 2 might be:
t.test(df1[df1$Samples == "Sample 1", "Content"],
       df1[df1$Samples == "Sample 2", "Content"])

A: As the number of elements for each 'Sample' is the same, we can use unstack from base R
unstack(df1, Content~Samples)
#    Sample.1 Sample.2 Sample.3 Sample.4
#1      70.7     88.7     42.3     51.8
#2      91.6     67.6     48.2     57.3
#3      92.6     61.7     64.0     43.3
#4      65.2     70.8     33.3     42.3
#5      80.0     45.3     19.0     37.6
#6      82.1     55.6     41.0     54.9
#7      88.1     64.6     53.1     71.1
#8      92.2     62.7     46.5     33.8
#9      53.3     72.4     30.0     43.1
#10     80.0     46.8     43.4     39.1
#11     60.3     59.0     43.7     63.0
#12     89.7     63.7     92.0     74.0
#13     84.8     67.0     53.0     31.0
#14     94.0     71.6     33.0     48.3
#15     71.8     48.3     48.4     42.9
#16     76.9     55.6     43.2     62.2
#17     91.4     62.5     41.8     35.4
#18     57.9     60.0     62.5     33.8
#19     61.9     72.9     33.3     40.7
#20     71.5     47.4     49.3     41.2

No external packages are used

If the number of 'Sample' elements are different, then dcast from data.table can be used (works in both cases)
library(data.table)
dcast(setDT(df1), rowid(Samples)~Samples, value.var = "Content")


text:
Q: How to submit image uploads in Django tests? The Django docs (http://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.Client.post) say to do this:
>>> c = Client()
>>> f = open('wishlist.doc')
>>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
>>> f.close()

But when I do that the field has the error message "The submitted file is empty." That smells like a PIL issue but the form works fine on the actual site.
Reading the file and sending that instead of just a handle doesn't work either and behaves the same as passing an empty string.

A: OK I figured it out. I was using the same dummy image for multiple fields and Django doesn't reset the pointer after validating the first field.
Also the example in the docs doesn't show that images need to be opened in binary mode as well.

A: I think open expects a file path relative to where it's being called from.
I'm not sure where that would be when a test is being run, but maybe try with an absolute path and see if it works?


text:
Q: How to concatinate ENV variables with values and path in Vue.JS I got env.variable below VUE_BASE_API=http://111.123.144.45:5331 (example), after that I export this variable as baseAPI and I want to concatinate with path: '/api/Users/GetUser?Name=' and value from input-> userSearchInputValue.
When I try to concatinate those 3 while I try to fetch data, I fail and get error below in console where between concatinating I get undefined, where it comes from?
Error

 <input
     v-model="userSearchInputValue"
     type="text"
     name=""
     id=""
     placeholder="User"
     @keyup="searchUser(userSearchInputValue)"
/>

searchUser(userSearchInputValue) {
      axios
        .get(
          baseAPI + `/api/Users/GetUser?Name=${userSearchInputValue}`
        )
        .then((data) => {
          console.log(data.data);
        })
        .catch((error) => {
          console.log(error);
        });
    },

Can someone help? Is this somehow possible?

A: As answer to this issue, I found out that you should restart your serve after declaring ENV variables - didn't knew this..


text:
Q: How to display my database file one subject per one subject I'm trying to display my database one subject per one subject.
I want to have text_one, img_one, Separation, text_two and img_two.
But now, it displays text_one, img_one Separation, text_one, img_one,  text_two and img_two.
How can I display my database subject by subject without having any duplicate?
Here's my code:
$product = mysqli_query($connection, "SELECT * FROM `fr` WHERE active = '1' AND product = '1' ");

while($rows = mysqli_fetch_assoc($product)){
if ($rows['text'] != NULL)
        {
            $text .= '
' . $rows['text'] .'
';
        }

        if ($rows['img'] != NULL)
        {
            $img .= '';
        }

$products .= '

' . $text.'

 '.$img.'

';
    }
echo $products;

A: you need to change $first_text .= to $first_text = and same for $img as $first.= will concatenate the result.


text:
Q: Unable to create postgresql view connecting different databases - odoo 11 Unable to create view(postgresql) connecting and fetching data from different databases in Odoo v11.
Creating a view by fetching data from local(logged in) database works fine, but when I connect to a different database to fetch data the view is not created in current database.
def run_query_live(self):
    conn = psycopg2.connect("dbname='****_live' user='postgres' host='localhost' password='******'")
    cur = conn.cursor()
    cur.execute("""CREATE VIEW inl_data_apex AS (SELECT * from table)""")

when I directly execute query with self.env.cr.execute, I am able to see the view created in current logged in database.
But when I connect it to different database, could not see the view in either of the database.


text:
Q: правильно описать OnSaveInstanceState (Java, Android) Использую в приложении два TextView, кнопку Button и Exoplayer. Подскажите как правильно сделать сохранение состояния приложения при нажатии кнопки "Назад" (Back). Суть в следующем: пользователь загружает приложение, нажимает кнопку Play - играет плейер, в текстовые поля загружается информация по restapi запросу, в общем красота. Как только нажимаю кнопку "Назад" (Back) в фоне остается играть плейер (это в принципе неплохо, логика нормальная), а при возврате текстовые поля очищаются и становятся пустыми. Логику OnPause-OnStop-OnDestroy посмотрел, жизненный цикл понятен, по восстановлению OnStart-OnResume - тоже.
Описал процесс таким образом, но что-то пошло не так... Как быть?
public void onSaveInstanceState(Bundle outState){
    outState.putString("ARTIST_NAME",textView.toString());
    outState.putString("TRACK_NAME", trackView.toString());
    outState.putBoolean("DETECT", isEnabled);
    super.onSaveInstanceState(outState);
}

public void onRestoreInstanceState(Bundle savedInstanceState){
    textView.setText(savedInstanceState.getString("ARTIST_NAME"));
    trackView.setText(savedInstanceState.getString("TRACK_NAME"));
    isEnabled = savedInstanceState.getBoolean("DETECT");
    }

A: Да, действительно ссылка сработала.
Описал логическую переменную через "Запись" перед уничтожением:
@Override
    protected void onPause() {
        super.onPause();

        SharedPreferences.Editor editor = psettings.edit();
        editor.putBoolean(APP_PLAYER_ENABLED,isEnabled);
        editor.apply();
    }

После достаю ее следующим образом:
 @Override
    protected void onResume() {
        super.onResume();

        psettings = getSharedPreferences(APP_PREFERENCES,Context.MODE_PRIVATE);
        boolean hasVisited = psettings.getBoolean(APP_PLAYER_ENABLED, false);

        if (!hasVisited){
         ......//здесь пишу свой код на выполнение
        }
    }


text:
Q: Grab the focus from GTK popup menu In my python GTK project, I have a popup menu which pop-ups while typing in a particular text area. But, when type a letter popup menu get the focus and I can't type anymore in the text area until I click on the text area and grab the focus manually. I want to keep the focus to the text area as I type regularly while popup menu comes. Can anyone give tell me a way to do this. I tried widget.grab_focus() method. But it didn't solve my problem.
Also I want to know how to set the position of the popup menu. It always appears near by mouse pointer. I want it to appear near by my application.
Thanks all.

A: I ran into the same problem using the C API, the solution was to invoke the following functions, I presume they're approximately similar to the python equivalents:
gdk_pointer_ungrab(GDK_CURRENT_TIME);
gdk_keyboard_ungrab(GDK_CURRENT_TIME);
gtk_grab_remove(menu);


text:
Q: Can a subclass type variable refer to a superclass object? In Java's class hierarchy, can an object be initialized in such a manner?
subclass object = new superclass();

This assumes that both the subclass and superclass have proper constructors, can compile, etc.  Is this type of object construction possible?

A: No. Only the other way around.
When you have an object of a class you can refer to it by a reference of the same class or a parent class and not the reverse. This is probably not related to just Java.
Otherwise it wouldn't make sense. Suppose you have
class SuperClass {
    public void method1() {};
}

class SubClass {
    public void method2() {};
}

If you do
  SubClass object = new SuperClass();

and then
  object.method2();

then theoretically it should compile, because the reference is of type SubClass, but the object is of type SuperClass so it won't have such a method.


text:
Q: AJAX Cascading dropdown without updatepanel? I want to make a cascading dropdown list without using an UpdatePanel. I need tips for starting out this task. Currently,

*

*I am using asp.net 2.0

*Will I be able to parse JSON in VSS 2005 if I use JQuery ?

*What is the recommended alternate for UpdatePanel in Visual Studio 2005 ?

A: If you use web forms , an alternative way is to create PageMethods and call them from JavaScript and fill the select with jQuery.

A: I will recommend jquery.Create a webservice in your project and call the webservice from jquery and parse the json result on UI.
Check out this link.
If you have any doubt let me know.


text:
Q: Why doesn't cmake find_package search usr/lib by default According to cmake's documentation cmake searches for these paths on Unix
<prefix>/(lib/<arch>|lib*|share)/cmake/<name>*/                 (U)
<prefix>/(lib/<arch>|lib*|share)/<name>*/                       (U)
<prefix>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/         (U)
<prefix>/<name>*/(lib/<arch>|lib*|share)/cmake/<name>*/         (W/U)
<prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/               (W/U)
<prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (W/U)

But usually lot of libraries are also present in <prefix>/usr/lib. Adding /usr to CMAKE_PREFIX_PATH enables cmake's find_package to see it.
Is there a reason cmake doesn't check this by default?
Edit: consolidating info from comments

*

*Its cross compilation

*Its using FindCurl.cmake, there is no CURLconfig.cmake

A: My CMAKE_SYSTEM_NAME was set to 'Generic', and CMAKE_SYSTEM_PREFIX_PATH was not not set by Generic.cmake
When I changed CMAKE_SYSTEM_NAME to Linux, Linux.cmake and UnixPaths.cmake added /usr to CMAKE_SYSTEM_PREFIX_PATH


text:
Q: Container with two indexes (or a compound index) I have a class like this
class MyClass
{
    int Identifier;
    int Context;
    int Data;
}

and I plan to store it in a STL container like
vector<MyClass> myVector;

but I will need to access it either by the extenal Index (using myVector[index]); and the combination of  Identifier and Context which in this case I would perform a search with something like
vector<MyClass>::iterator myIt;
for( myIt = myVector.begin(); myIt != myVector.end(); myIt++ )
{
    if( ( myIt->Idenfifier == target_id ) &&
        ( myIt->Context == target_context ) )
        return *myIt; //or do something else...
}

Is there a better way to store or index the data?

A: Boost::Multi-Index has this exact functionality if you can afford the boost dependency (header only). You would use a random_access index for the array-like index, and either hashed_unique, hashed_non_unique, ordered_unique, or ordered_non_unique (depending on your desired traits) with a functor that compares Identifier and Context together.

A: We need to know your usage. Why do you need to be able to get them by index, and how often do you need to search the container for a specific element.
If you store it in an std::set, your search time with be O(ln n), but you cannot reference them by index.
If you use an std::vector, you can index them, but you have to use std::find to get a specific element, which will be O(n).
But if you need an index to pass it around to other things, you could use a pointer. That is, use a set for faster look-up, and pass pointers (not index's) to specific elements.

A: Yes, but if you want speed, you'll need to sacrifice space.  Store it in a collection (like an STL set) with the identifier/context as key, and simultaneously store it in a vector.  Of course, you don't want two copies of the data itself, so store it in the set using a smart pointer (auto_ptr or variant) and store it in the vector using a dumb pointer.


text:
Q: Query for banks in DBpedia Using http://dbpedia.org/sparql, I want to receive the geographic coordinates of all bank buildings. The list of classes tells me that I should query for Bank.
Yet, the following code yields nothing:
SELECT DISTINCT ?label ?lat ?long
WHERE {
[]
 rdf:type dbpedia-owl:Bank ;
 geo:lat ?lat ;
 geo:long ?long ;
 rdfs:label ?label.
      FILTER (LANGMATCHES(LANG(?label), 'en'))
}

If instead I query for any sibling to Bank, (e.g. Brewery or LawFirm), I see at least some results. What's wrong with above code?

A: If you look into a dbpedia page for a bank, you can see that instead on rdf:type, banks have a property dbpedia-owl:industry that has dbpedia:Bank (Refah bank) or dbpedia:Financial_services (Cyprus bank) as a value. So if you rewrite your query as the following, you will get some results:
SELECT DISTINCT ?label ?lat ?long
WHERE {
    [] dbpedia-owl:industry dbpedia:Bank ;
    geo:lat ?lat ;
    geo:long ?long ;
    rdfs:label ?label.
    FILTER (LANGMATCHES(LANG(?label), 'en'))
}

If you add dbpedia:Financial_services, other organisations such as London stock exchange will also appear:
SELECT DISTINCT ?bank
WHERE {
    ?bank dbpedia-owl:industry ?place ;
    geo:lat ?lat ;
    geo:long ?long ;
    rdfs:label ?label.
    FILTER (?place in (dbpedia:Financial_services, dbpedia:Bank) &&
    LANGMATCHES(LANG(?label), 'en'))
}

Again, by examining the London stock exchange, you can see that there is a product property that separates these financial institutions. So this will give you banks, but it might not cover all the banks available:
SELECT DISTINCT ?label ?lat ?long
WHERE {
    [] dbpedia-owl:industry ?place ;
    geo:lat ?lat ;
    geo:long ?long ;
    rdfs:label ?label;
    dbpedia-owl:product ?product.
    FILTER ( ?place in (dbpedia:Financial_services, dbpedia:Bank)
    && ?product in (dbpedia:Bank, dbpedia:Private_banking, dbpedia:Professional_Banking, dbpedia:Retail_banking, dbpedia:Investment_banking, dbpedia:Commercial_bank)
    && LANGMATCHES(LANG(?label), "en"))
} ORDER BY DESC(COUNT(DISTINCT ?product))


text:
Q: Implementing check boxes in react I am trying to implement product list table.
What i have done is as under,
    import React, { Component } from 'react';
    import { Row, Col, Card, CardBody } from 'reactstrap';
    import { withRouter, Link } from 'react-router-dom';
    import { activateAuthLayout, onLoad } from '../../../store/actions';
    import { connect } from 'react-redux';
    import Settingmenu from '../Subpages/Settingmenu';
    //images
    import default_image from '../../../images/users/user-1.jpg';

    const ListProducts = props => {
        if (props.is_loading === true)
            return (

                    Loading....

            );

        return (
            props.products.map(product => {
                return <TableRow
                    key={product.id}
                    product={product}
                    is_checked={props.is_checked}
                    handleIndividualCheck={props.handleIndividualCheck}
                />
            })
        );

    }

    class TableRow extends Component {

        constructor(props) {
            super(props);
            this.state = {}
        }

        render() {
            console.log(this.props);
            let quantities = this.props.product.variants.map(a => a.inventory_quantity),
                total_count = quantities.reduce((a, b) => a + b, 0) + ' in stock ';
            return (

                        <input
                            type="checkbox"
                            checked={this.props.is_checked}
                            onChange={this.props.handleIndividualCheck}
                        />

{this.props.product.title}

                    {total_count}
                    {this.props.product.product_type || 'n/a'}

                        {this.props.product.vendor}

            )
        }
    }

    class ProductLists extends Component {
        constructor(props) {
            super(props);
            this.state = {};
        }

        render() {
            console.log(this.props)
            return (

                            <input onClick={this.props.handleSelectCheckbox} type="checkbox" />
                            Products
                            Inventory
                            type
                            Vendor

                        <ListProducts
                            products={this.props.products}
                            is_loading={this.props.is_loading}
                            is_checked={this.props.is_checked}
                            handleIndividualCheck={this.props.handleIndividualCheck}
                        />

            );
        }
    }

    class EcommerceProductEdit extends Component {

        constructor(props) {
            super(props);
            this.state = { checked: false }
        }

        componentDidMount() {
            this.props.activateAuthLayout();
            if (this.props.user !== null && this.props.user.shop_id)
                this.props.onLoad({
                    payload: this.props.user
                });
        }

        handleSelectCheckbox = event => {
            this.setState({ checked: !this.state.checked });
        };

        handleIndividualCheck = event => {
            console.log(event);
        }

        render() {

            return (
                <React.Fragment>

                                <Row className="align-items-center">
                                    <Col sm="6">

Products

<Link to="#"></Link>

Products

                                    </Col>
                                    <Col sm="6">

                                            <Settingmenu />

                                    </Col>
                                </Row>

                            <Row>
                                <Col xl="3" md="6">
                                    <Card className="bg-pattern">
                                        <CardBody>

24

Total Projects

                                        </CardBody>
                                    </Card>
                                </Col>
                                <Col xl="3" md="6">
                                    <Card className="bg-pattern">
                                        <CardBody>

18

Completed Projects

                                        </CardBody>
                                    </Card>
                                </Col>
                                <Col xl="3" md="6">
                                    <Card className="bg-pattern">
                                        <CardBody>

06

Pending Projects

                                        </CardBody>
                                    </Card>
                                </Col>
                                <Col xl="3" md="6">
                                    <Card>
                                        <CardBody>
                                            <form>

                                                    Search

                                                        <input type="text" className="form-control" placeholder="Search..." aria-describedby="project-search-addon" />

                                                            <button className="btn btn-danger" type="button" id="project-search-addon"></button>

                                            </form>
                                        </CardBody>
                                    </Card>
                                </Col>
                            </Row>

                            <Row>
                                <Col lg="12">
                                    <Card>
                                        <CardBody>

                                                <ProductLists
                                                    {...this.props}
                                                    handleIndividualCheck={this.handleIndividualCheck}
                                                    is_checked={this.state.checked}
                                                    handleSelectCheckbox={this.handleSelectCheckbox}
                                                />

                                                        <Link className="page-link" to="#" tabIndex="-1" aria-disabled="true">Previous</Link>

<Link className="page-link" to="#">1</Link>

<Link className="page-link" to="#">2</Link>

<Link className="page-link" to="#">3</Link>

                                                        <Link className="page-link" to="#">Next</Link>

                                        </CardBody>
                                    </Card>
                                </Col>
                            </Row>

                </React.Fragment>

            );
        }
    }

    const mapStatetoProps = state => {
        const { user, is_logged_in } = state.Common;
        const { products, is_loading } = state.Products;
        return { user, is_logged_in, products, is_loading };
    }

    export default withRouter(connect(mapStatetoProps, { activateAuthLayout, onLoad })(EcommerceProductEdit));

I need to now when user check unchecked some of the lists to perform operation. How do I do that ?
Do it make the array of checked / unchecked items after the are checked/unchecked, or is there other way that i can do with this.props.products object lists ?
Any kin d of suggestion are highly appreciated.
Also In EcommerceProductEdit component did mount after performing
  this.props.onLoad({
                payload: this.props.user
            });

why i am not being able to get this.props.product in constructor but only in render ?
Thanks

A: Your idea to keep an array of checked items is close, though I'd suggest using a map so you have O(1) constant time lookups of checked item status.
Gist
Keep a map of checked item id's, the onChange passes the input id and checked value, and the id is used to retrieve the checked value.
Changes to Manage Checked State
Update handleIndividualCheck to destructure checked and input id from the event and update the checked state.
class EcommerceProductEdit extends Component {

    constructor(props) {
      super(props);
      this.state = {
        checked: {}, // <-- Object to store id's as keys and checked status as values
      };
    }

    ...

    handleIndividualCheck = event => {
      const { checked, id } = event.target;
      this.setState(prevState => ({
        checked: {
          ...prevState.checked,
          [id]: checked
        },
      }));
    }

    render() {
      return (
        ...
        <ProductLists
          {...this.props}
          handleIndividualCheck={this.handleIndividualCheck}
          is_checked={this.state.checked}
          handleSelectCheckbox={this.handleSelectCheckbox}
        />
        ...
      );
    }
}

Update ListProducts to check the is_checked prop by product id
const ListProducts = props => {
  ...

  return (
    props.products.map(product => {
      return <TableRow
        key={product.id}
        product={product}
        is_checked={props.is_checked[product.id]} // <-- is_checked now checked value from checked map!
        handleIndividualCheck={props.handleIndividualCheck}
      />
    )
  );
}

Update TableRow input to name the input with the product id
<input
  type="checkbox"
  id={propduct.id} // <-- Pass product id to input id for event
  checked={this.props.is_checked}
  onChange={this.props.handleIndividualCheck}
/>

Change to Handle Performing Operation on Unchecked Item

I need to now when user check unchecked some of the lists to perform operation. How do I do that?

You can check if an input was unchecked right in the handler and perform operation.
handleIndividualCheck = event => {
  const { checked, id } = event.target;
  this.setState(prevState => ({
    checked: {
      ...prevState.checked,
      [id]: checked
    },
  }));

  if (!checked) {
    // perform operation on product by id
  }
}


text:
Q: Javascript nested for loop function sumArray(array, n) I am doing an exercise that goes through some validations and there is one that I have not been able to achieve that is true...
The function receives an array and an integer and the goal is that when adding 2 of the numbers in the array, they must return true if the result is equal to the integer that is received as an argument.
It is not valid to add the same number twice, it is only allowed to add different numbers.
The ones that I still can't pass correctly are these:
array = [2,5,7,10,11,15,20]
n = 13
In this case, when adding 2 and 11, the result is equal to 13, so the code should return true.
I tried to nest 2 for loops, which is what they suggest me to solve the exercise...
function sumArray(array, n) {
  for(var i = 0; i < array.length; i++){
    for(var j = 0; j < array.length; j++){
      if(i + j === n && i !== j){
        return true;
      }
      else{
        return false;
      }
    }
  }
};

A: You're adding the indices of an array, not the values of it.
For example, let's say we have the array [7,8,9]. Your goal is to add 7+8, 7+9, 8+9, right?
However, this code:
  for(var i = 0; i < array.length; i++){
    for(var j = 0; j < array.length; j++){
      if(i + j === n && i !== j){

will instead do 0+0, 0+1, 0+2, 1+0, 1+1, 1+2, 2+0, 2+1, 2+2. This is because you're adding i + j rather than the values of the array elements contained at indices i and j. Instead, you want to do array[i] + array[j]. This will give you 7+7, 7+8, 7+9, 8+7, 8+8, 8+9, 9+7, 9+8, 9+9.
Bonus tip: if(array[i] + array[j] === n && i !== j){ will solve the problem, but there's actually a more efficient way to set up your for loops so that you don't need to have the second conditional.

A: actually you're just using the indicators of the array length not the array values,
so you need to change you're code using values instead of the indecators
here is an example of result when i use the the array[i] + array[j] instead of i+j

function sumArray(array, n) {
  for(var i = 0; i < array.length; i++){
    for(var j = 0; j < array.length; j++){
      if(array[i] + array[j] === n && i !== j){
        console.log(array[i]+'+'+array[j]+true);
      }
      else{
        console.log(array[i]+'+'+array[j]+false);
      }
    }
  }
};
array=[1,2,3,4,9,8,11]
sumArray(array, 13)


text: Q: Random unitary matrices distribution different from Haar random I am trying to study a problem which requires a distribution on U(4) which is not Haar random distribution. Basically I want to have the numerical code to randomly generate $4\times4$ unitary matrices with a distribution $P(U_1*U_2) \ne P(U_1)$. Further, is it possible to define a series of distributions $P_{\lambda}$ such that for a specific $\lambda$, it gives me the Haar random distribution?


text:
Q: SwiftUI: Pause and Resume animation The idea is this: an object has a start position (A) and an end position (B). When the start button is pressed, the object moves from Ax, Ay to Bx, By. At an arbitrary point in time, you can stop its movement and continue.
I tried to implement this with a timer that moves the object every n time periods. It works, but the problem is that the timer eats up a lot of memory and when ten objects are created, the application freezes.
I do not ask you to do the task for me, but I will be very grateful if you tell me where to dig
Code currently in use
typealias RemainingDurationProvider<Value: VectorArithmetic> = (Value) -> TimeInterval
typealias AnimationWithDurationProvider = (TimeInterval) -> Animation
extension Animation {
  static let instant = Animation.linear(duration: 0.0001)
}
struct PausableAnimationModifier<Value: VectorArithmetic>: AnimatableModifier {
  @Binding var binding: Value
  @Binding var paused: Bool
  private let targetValue: Value
  private let remainingDuration: RemainingDurationProvider<Value>
  private let animation: AnimationWithDurationProvider
  var animatableData: Value
  init(binding: Binding<Value>, targetValue: Value, remainingDuration: @escaping RemainingDurationProvider<Value>, animation: @escaping AnimationWithDurationProvider, paused: Binding<Bool>) {
    _binding = binding
    self.targetValue = targetValue
    self.remainingDuration = remainingDuration
    self.animation = animation
    _paused = paused
    animatableData = binding.wrappedValue
  }
  func body(content: Content) -> some View {
    content
      .onChange(of: paused) { isPaused in
        if isPaused {
          withAnimation(.instant) {
            binding = animatableData
          }
        } else {
          withAnimation(animation(remainingDuration(animatableData))) {
            binding = targetValue
          }
        }
      }
  }
}
extension View {
  func pausableAnimation<Value: VectorArithmetic>(binding: Binding<Value>, targetValue: Value, remainingDuration: @escaping RemainingDurationProvider<Value>, animation: @escaping AnimationWithDurationProvider, paused: Binding<Bool>) -> some View {
    self.modifier(PausableAnimationModifier(binding: binding, targetValue: targetValue, remainingDuration: remainingDuration, animation: animation, paused: paused))
  }
}
struct TestView: View {
  @State private var isPaused = false
  @State private var offsetX: Double = .zero
  @State private var startOffsetX: Double = .zero
  @State private var endOffsetX: Double = 200.0
  @State private var offsetY: Double = .zero
  @State private var startPositionY: Double = .zero
  @State private var endPositionY: Double = 500.0
  private let duration: TimeInterval = 6
  private var remainingDurationForX: RemainingDurationProvider<Double> {
    { currentAngle in duration * (1 - (currentAngle - startOffsetX) / (endOffsetX - startOffsetX)) }
  }
  private var remainingDurationForY: RemainingDurationProvider<Double> {
    { currentAngle in duration * (1 - (currentAngle - startPositionY) / (endPositionY - startPositionY)) }
  }
  private let animation: AnimationWithDurationProvider = { duration in
      .linear(duration: duration)
  }
  var body: some View {
    VStack {
      ZStack {
        VStack {
          HStack {
            Rectangle()
              .frame(width: 50, height: 50)
              .offset(x: offsetX, y: offsetY)
              .pausableAnimation(binding: $offsetX,
                        targetValue: endOffsetX,
                        remainingDuration: remainingDurationForX,
                        animation: animation,
                        paused: $isPaused)
              .pausableAnimation(binding: $offsetY,
                        targetValue: endPositionY,
                        remainingDuration: remainingDurationForY,
                        animation: animation,
                        paused: $isPaused)
            Spacer()
          }
          Spacer()
        }
      }
      HStack {
        ControllButton(text: "Start", action: {
          offsetX = startOffsetX
          offsetY = startPositionY
          withAnimation(animation(duration)) {
            offsetX = endOffsetX
            offsetY = endPositionY
          }
        })
        ControllButton(text: "NewPosition", action: {
          startOffsetX = endOffsetX
          startPositionY = endPositionY
          endOffsetX = 300
          endPositionY = 30
        })
        ControllButton(text: isPaused ? "Resume" : "Pause", action: {
          isPaused = !isPaused
        })
        ControllButton(text: "Stop", action: {
          offsetX = .zero
          offsetY = .zero
        })
      }
      .padding(.bottom)
    }
  }
}
struct ControllButton: View {
  var text: String
  var action: () -> ()
  var body: some View {
    Button(text) {
      action()
    }
    .padding()
    .background(Color.yellow)
    .frame(height: 35)
    .cornerRadius(10)
  }
}

A: Not sure the exact intent of your code, but here's something you could try:
struct ContentView: View {
    @State var recs: [(AnyView, UUID)] = []
    @State var isPaused: Bool = true
    @State var shouldUpdate: Bool = false

    var body: some View {
        VStack {
            ZStack {
                ForEach(recs, id: \.1) { $0.0 }
            }
            Spacer()
            HStack {
                Button(isPaused ? "Start" : "Pause") {
                    isPaused.toggle()
                }
                Button("Add") {
                    recs.append(
                        (AnyView(
                            Rectangle()
                                .frame(width: 50, height: 50)
                                .pausableAnimation(
                                    startingPosition: .init(x: .random(in: 0..<300), y: 0),
                                    endingPosition: .init(x: .random(in: 0..<300), y: .random(in: 300..<700)),
                                    isPaused: $isPaused,
                                    shoudUpdate: $shouldUpdate
                                )
                        ), UUID())
                    )
                }
                Button("Update") {
                    shouldUpdate = true
                }
                Button("Reset") {
                    isPaused = true
                    recs.removeAll()
                }
            }
            .buttonStyle(.borderedProminent)
            .tint(.orange)
        }
    }
}

extension CGPoint {
    func isCloseTo(_ other: CGPoint) -> Bool {
        (self.x - other.x) * (self.x - other.x) + (self.y - other.y) * (self.y - other.y) < 10
    }
}

struct PausableAnimation: ViewModifier {
    @State var startingPosition: CGPoint
    @State var endingPosition: CGPoint
    @Binding var isPaused: Bool
    @Binding var shouldUpdate: Bool
    private let publisher = Timer.TimerPublisher(interval: 0.1, runLoop: .main, mode: .default).autoconnect()
    @State private var fired = 0

    func body(content: Content) -> some View {
        content
            .position(startingPosition)
            .animation(.linear, value: startingPosition)
            .onReceive(publisher) { _ in
                if !isPaused && !startingPosition.isCloseTo(endingPosition){
                    startingPosition.x += (endingPosition.x - startingPosition.x) / CGFloat(20 - fired)
                    startingPosition.y += (endingPosition.y - startingPosition.y) / CGFloat(20 - fired)
                    fired += 1
                }
            }
            .onChange(of: shouldUpdate) { newValue in
                if newValue == true {
                    updatePosition()
                    shouldUpdate = false
                }
            }
    }

    func updatePosition() {
        endingPosition = .init(x: .random(in: 0..<300), y: .random(in: 0..<700))
        fired = 0
    }
}

extension View {
    func pausableAnimation(startingPosition: CGPoint, endingPosition: CGPoint, isPaused: Binding<Bool>, shoudUpdate: Binding<Bool>) -> some View {
        modifier(
            PausableAnimation(
                startingPosition: startingPosition,
                endingPosition: endingPosition,
                isPaused: isPaused,
                shouldUpdate: shoudUpdate
            )
        )
    }
}

Basically the idea here is in each PausableAnimation, a TimerPublisher is created to fire every 0.1 second. Anytime the publisher fires, it will move from startingPosition and endingPosition by 1/20 of the distance between them.
I used a CGPoint to keep both x and y information in a single variable. However, using two separate variables shouldn't change much of the code beside needing to pass in more data in the initializer.
I wrapped the modified view in a (AnyView, UUID), so I can add more of them into an array and display them through ForEach, dynamically.
Feel free to play around, I hope the idea is clear.


text:
Q: Arcgis map not loading in lightning component Following is the very simple example I am trying to integrate in salesforce1 but its not showing. Let me know what I am doing wrong here.
End result to produce - http://jsfiddle.net/6hfq0ggg/
Following is the code in my lightning component -
<aura:component implements="force:appHostable">
    <ltng:require styles="/resource/arcgis/esri.css" />
    <ltng:require scripts="/resource/arcgis/init.js" afterScriptsLoaded="{!c.myAction}" />

</aura:component>

Code in controller -
({
    myAction : function(component, event, helper) {
        setTimeout(function(){
            var map;
            require(["esri/map", "dojo/domReady!"], function(Map) {
                map = new Map("mapDiv", {
                    center: [-56.049, 38.485],
                    zoom: 3,
                    basemap: "streets"
                });
            });
        }, 2000);
    }
})

I also uploaded arcgis.zip file in static resources containing two files, i.e esri.css, init.js.
Please let me know what I am doing wrong here.

A: A few things - all easy:

*

*use a single ltng:require for scripts and CSS is cleaner

*remove the setTimeout entirely. That will only cause you heartache (access checks will fail, timing issues, generally documented as an unneeded and unwise thing to do)

Now the harder part (not that hard):

*

*you are only including the bootstrapping resources in your ltng:require and static resource and that call to require() is attempting to pull in other resources (e.g. jsapi_en-us.js, svg.js, etc) that live on an external CDN which is not currently allowed as per our documented content security policy enforced sandbox.

The web resources that are being blocked will show up in the Networks tab in Chrome dev tools and errors should also be visible in the js console in your browser. ArcGIS is going to be a challenge to integrate into Lighning Components currently because of that CSP lockdown. We are working on a security feature (my current project in fact) to make this go away in Spring '16 (safe harbor of course) but I know that does not help you now. When I have been stymied by this kind of thing I have resorted to using an iframe with a Visuapforce page inside it in my Lightning Component which while it seems gross actually works quite well. Because VF pages are served from a namespaced domain they are allowed to directly reference external resources. If you need to communicate with the code inside the VF page from the LC or vice Verna it is not hard to use window.postMessage() to open a secure communication channel.


text:
Q: Python neural network throws error for indexing My code is as follows
import scipy.io as sio
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix

X=sio.loadmat('pyInput.mat')
y=sio.loadmat('pyTarget.mat')

X_train, X_test, y_train, y_test = train_test_split(X, y)

StandardScaler.fit(X_train)
X_train = StandardScaler.transform(X_train)
X_test = StandardScaler.transform(X_test)

mlp = MLPClassifier(hidden_layer_sizes=(10,10,10))
mlp.fit(X_train,y_train)

predictions = mlp.predict(X_test)

print(confusion_matrix(y_test,predictions))
print(classification_report(y_test,predictions))

When I run this in spyder, my error is
return [X[idx] for idx in indices]
I tried defining x_train, x_test, y_train, and y_test manually by creating the proper split matrices myself in matlab. However, I then get an error that says
fit() missing 1 required positional argument: 'X'\

for the StandardScaler.fit(X_train) part.
If I remove the StandardScaler part completely, then my error is
float() argument must be a string or a number, not 'dict'

That error comes from a line in the validation.py file within Anaconda's packages, and the specific line is 402.
array=array.astype(np.float64)

My matrices (when not manually split) are 100x200 and the target is 100x1.


text:
Q: Force one of two python class attributes to be always be assigned a value? Is there a way in python such that given a python class:
class Foo(object):
    apple = None
    orange = None
    def __init__(self, apple=None, orange=None)
        super(Foo, self).__init__()
        self.apple = apple
        self.orange = orange

after a Foo object is init, one of the two attributes (apple, orange) must always be assigned to a value other than None, and that at no time should both attributes be assigned to something other than None.
In other words:
                      orange is None    |    orange is not None
                                        |
apple is None              NO           |         YES
________________________________________|___________________________
                                        |
apple is not None          YES          |         NO

How would one do this in python?

A: In the constructor, it's simple enough to raise a ValueError if they are both None or both set. The problem is later on in the code.
Following the principle of least surprise, I think you should mark the variables private and use setter methods (not property setter, plain old methods). This clearly suggests you're doing extra logic when the value is set, and it gives you an obvious place to add extra logic later if needed. Using getter property methods would be fine, though. So something like this:
class Foo(object):
    def __init__(self, apple=None, orange=None):
        super(Foo, self).__init__()
        if apple is None and orange is None:
            raise ValueError('apple and orange cannot both be None')
        if apple is not None and orange is not None:
            raise ValueError('apple and orange cannot both be set')

        self._apple = apple
        self._orange = orange

    @property
    def apple(self):
        return self._apple

    @property
    def orange(self):
        return self._orange

    def setAppleClearOrange(self, value):
        if value is None:
            raise ValueError('Cannot set both to None')
        self._orange = None
        self._apple = value

    def setOrangeClearApple(self, value):
        if value is None:
            raise ValueError('Cannot set both to None')
        self._apple = None
        self._orange = value

Yes, it's a bit verbose, but it's obvious what your intentions are, which is actually more important.

A: Something like
if !((self.apple==None)^(self.orange==None))
    // some error

Might do the trick... ^ is the XOR operator, which returns true if one, but not both, of the operands are true.

A: objs = filter(None, [apple, orange, ...])
if len(objs) == 0:
   raise Exception("At least 1 object of [apple, orange] must be different from None.")
elif len(objs) > 1:
    raise Exception("At most 1 object of [apple, orange] should be different from None.")

A: You could override __setattr__() for that class, and have it handle that logic for you. See http://docs.python.org/2/reference/datamodel.html#object.setattr
Something like
class FooBar(object):
    def __setattr__(self, key, val):
        if key == 'apple' or key == 'orange':
            # Decide what to do about it
        self.__dict__[key] = val

Note that you need to access the key through the object's __dict__ to avoid an infinite loop, because __setattr__() replaces the normal assignment mechanism.
Also, note that this will check every assignment to these two variables, including in your own code. If that's not what you want, then put some test in __init__(), as others suggested.

A: Here is a version that will set the other aspect to None if necessary. You'll have to define what should happen if they are both set to None
class Foo(object):
    def __init__(self, apple=None, orange=None):
        # make sure exactly 1 of apple/orange is not None
        if sum(x is None for x in (apple, orange)) != 1:
            raise ...
        self._apple = apple
        self._orange = orange

    @property
    def apple(self):
        return self._apple

    @apple.setter
    def apple(self, value):
        if value is not None:
            self._orange = None
        elif self._orange is None:
            raise ...
        self._apple = value

    @property
    def orange(self):
        return self._orange

    @orange.setter
    def orange(self, value):
        if value is not None:
            self._apple = None
        elif self._apple is None:
            raise ...
        self._orange = value

A: assert (apple is None) != (orange is None)

If you put that code in the __init__ method, and your precondition is false, an AssertionError will be thrown.


text:
Q: CGColorSpace name profile let red = UIColor.red
print(red.cgColor.colorSpace!)

The output is
<CGColorSpace 0x60000332d260> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range).
How can I get the single values like profile the name sRGB IEC61966-2.1 as string?

A: BTW, I think, it solves your problem:
let color = UIColor.red
let value = String(describing: color.cgColor.colorSpace)
let profileName = value.split(separator: ";")[2].trimmingCharacters(in: .whitespacesAndNewlines)
print(profileName)

sRGB IEC61966-2.1


text:
Q: how to hide column in export How to hide the select all(checkbox) column in excel or csv export.
{
    checkboxSelection: true,
    suppressMenu: true,
    suppressSorting: true,
    suppressFilter: true,
    width: 30,
    pinned: true,
    suppressExcelExport :true,
    headerCellRenderer: this.selectAllRenderer
},

A: below code will solve your problem
var columnsForExport=[];
var allColumns=gridOption.columnApi.getAllColumns();

allColumns.forEach((element:any) => {
    if(element.colId!="#"){
        columnsForExport.push(element.colId)
    }
});

A: As for now, the suppressExcelExport: true property works only for the entire grid, not the columns!
However there is a nice workaround which will enable any custom column property (e.g. suppressExcelExport) to act like a real working property as you asked.
All you need is calling this function on a button click or add context menu item:
function exportActiveColumns() {
    let allColumns = gridOptions.columnApi.getAllColumns();
    let exportColumns = allColumns .filter(col => !col.userProvidedColDef.suppressExcelExport);
    gridOptions.api.exportDataAsExcel({
        columnKeys: exportColumns,
    });
}

Make sure suppressExcelExport is false for the grid, otherwise there will be no result after calling exportDataAsExcel api.
Exact same thing works for CSV.


text:
Q: R (dplyr/tidyverse) | Using mutate_at to construct a series of new variables using if_else statements I'm relatively new to this site and to the world of programming, so my apologies if this has already been asked.
Here's a modified version of a data frame I'm currently working with (truncated to make things easier to diagnose):
  COUNTRY          b_2010 c_2010 b_2011  c_2011
1 Australia          50     62     67     56
2 Austria            50     48     48     95
3 Belgium            50     26     67     25
4 Bulgaria           50     54     42     64

Let's assume that I want to create a series of variables indicating that a country has a value equal to or greater than 50 for each existing variable in a given year.
I can do so by running something like this:
dataframe %>% mutate(d_2010 = if_else(b_2010 & c_2010 >= 50, "A", "B"),
                     d_2011 = if_else(b_2011 & c_2011 >= 50, "A", "B"))

This should produce the indicator variables I'm looking to construct, but the process will get awfully taxing if I have a lengthy time series. I'm sure there's a way to go about doing this more efficiently (using mutate_at or some other function), but I haven't been able to figure it out.
Can someone out there help me out?
Thanks!

A: In my eyes for "each existing variable in a given year" would be something like this:
dataframe %>% mutate(d_2010 = if_else(b_2010 >= 50 & c_2010 >= 50, "A", "B"),
                     d_2011 = if_else(b_2011 >= 50 & c_2011 >= 50, "A", "B"))

If this is the goal then I would calculate the new variables in a first step and join them later to the origin dataframe. Something like this:
df <- dataframe %>%
  gather(starts_with("b_"), starts_with("c_"), key = Key , value = Value) %>%
  mutate(Year = paste0("d_"str_sub(Key, 3, 6))) %>% # creat your new variable
  group_by(COUNTRY, Year) %>%
  summarise(d =  ifelse(prod(Value >=50), "A", "B")) %>% # calculate the value
  spread(Year, d)

# join both
dataframe <- dataframe %>%
  left_join(df)


text:
Q: Is the for i in range used correctly in my python code? I'm new to python coding at the moment I'm doing some while/for/if exercises to learn how it works. I copied below one of the codes I prepared that is working fine except it prints out the number at which current_position = target_position and statement "Target achieved" instead just the "Target achieved". How can I change it so it prints out all the values of current_position util it is equal to target position and then "Target achieved".
current_position = 0

jump_value = int(input("Enter the jump number :"))
target_position = int(input("Enter the target number :"))

while current_position != target_position:
    for i in range(0,1):
        current_position = current_position + jump_value
        if current_position >= 100:
            current_position = current_position % 100
        print("You are at:", current_position)
        if current_position == target_position:
            print("Target achieved")
    if current_position == 0:
        print("Target not found", target_position)
        break


text:
Q: How to add text to some options of a select box? In a form, I have a select box whose some options are pre selected by ajax according to a previous value entered.
I would like to add additional text to the options (only those which have been pre selected by ajax according to the previous value).
for (i in data) {
$("#my_select_box_id").val(data[i][0])..attr('selected',true); //that works

//I would like to use something like that but it's not working
$("#my_select_box_id").text(data[i][1]);
}

I think I have to get the options pre selected,but that's not working too :
$("#my_select_box_id option[value=data[i][0]).text(data[i][1]);

A: $("#my_select_box_id").html(data[i][1]);

To make it selected, you can use:
$("#my_select_box_id").attr("selected", "selected");

*Edit, I'm actually not sure if it will select the option item when you use the above call, W3C specifies that it will on page-load... Can you report back?
--
To select the option elements you want, and to change the label, try:
$("#my_select_box_id option[value=" + data[i][0]+"]").html(data[i][1]);


text:
Q: Contour integral mystery: why is the answer different from Maple/Matlab? The mystery is that here is a fairly standard contour integral which can be done by the residue theorem. Yet when I tried to evaluate it using numerical softwares like Maple or Matlab, the answer is different (in this case, by a factor of 2).
Even the lecturer doesn't know what's going on. Any explanation would be much appreciated.
The integral in question is:
$$\int_{-\infty}^\infty {\sin x \over x(\pi^2-x^2)}\textrm{d}x.$$
Here is the summary of the working the lecturer went through in class.
STEP 1) Consider this complex integral instead:
$$\int_\Gamma {e^{iz}\over z(\pi^2-z^2)}\textrm{d}z,$$
where the integral is calculated using a upper-semicircular contour, indented at $0,\pm\pi$.
(sorry they won't let me post images).
Later on we will just take the imaginary part of the answer.
STEP 2) The poles at $\pm\pi, 0$ are all simple. The integral are the sum of those along the x axis, with the limit as the radii of the 3 indents $\to0$.
STEP 3) The integral along the big arc tends to $0$ by the ML inequality.
STEP 4) The residue at $\pm\pi$ are  $$\mp {e^{\pm i\pi}\over 2\pi^2}=\pm{1\over2\pi^2}$$
The residue at $0$ is
$${1\over \pi^2}$$
STEP 5) This implies that the sum of the 3 "indent" integrals is
$$\sum_{k=1}^3 \int_{\text{indents}}f(z) d z=-i\pi\sum\text{residues}=-{i\over\pi}$$
(the minus sign comes from the fact that the indent integrals are oriented the 'wrong' way.)
STEP 6) Finally, equate the imaginary parts to get the answer
$$\int_{-\infty}^\infty {\sin x\over x(\pi^2-x^2)}\textrm{d}x={1\over \pi}.$$
All well and good, except that Matlab, Maple and Mathematica are all saying
$$\int_{-\infty}^\infty {\sin x\over x(\pi^2-x^2)}\textrm{d}x={2\over \pi}.$$
So what's going on??? I can't seem to find anything wrong with the working above.
Thanks.


text:
Q: Gap between input and button In an ASP.Net MVC application, I tried to use input-group for an input and button pair. I want it to look like this (like in getbootstrap.com):

But it looks like this in my application:

There is a huge space between input and button. Here is my HTML:

            <input id="empNoTxt" type="text" class="form-control" placeholder="Sicil Numarası" />

                <button class="btn btn-success" type="button"> Sorgula</button>

A: I find the solution from another site:
https://jasenhk.wordpress.com/2014/06/09/mvc-bootstrap-input-group-button-space/
There is a default css file which is called "Site.css" in MVC projects. You should remove the following lines:
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

A: I don't think there is any thing wrong with your html... here is a working example of your code with the same button in three different container sizes.

                <input id="empNoTxt" type="text" class="form-control" placeholder="Sicil Numarası" />

                    <button class="btn btn-success" type="button"> Sorgula</button>

                <input id="empNoTxt" type="text" class="form-control" placeholder="Sicil Numarası" />

                    <button class="btn btn-success" type="button"> Sorgula</button>

                <input id="empNoTxt" type="text" class="form-control" placeholder="Sicil Numarası" />

                    <button class="btn btn-success" type="button"> Sorgula</button>

make certain that your referencing the correct version of bootstrap.

A: Use this

          <input type="text" class="form-control" placeholder="Search for...">
            <button class="btn btn-default" type="button">Go!</button>


text:
Q: Compare two xml variables in sql query and get the difference? @oldXML = <root><row USER_KEY="1" USER_NAME="test" USER_ID="12345" USER_STATUS=" " USER_GENDER="F" /></root>

@newXML = <root><row USER_KEY="1" USER_NAME="test" USER_ID="00000" USER_STATUS=" " USER_GENDER="F" />
</root>

I have like nearly 100 columns like that...I am not sure how to compare these tags and store them in my audit table with the filed name and previous value and changed value
In above values I have modified only USER_ID value. I am not sure how the string split function help me here. Please suggest....
Thanks in advance..

A: Try something like this -
DECLARE
      @oldXML NVARCHAR(MAX)
    , @newXML NVARCHAR(MAX)

SELECT
      @oldXML = '<root><row USER_KEY="1" USER_NAME="test" USER_ID="12345" USER_STATUS=" " USER_GENDER="F" /></root>'
    , @newXML = '<root><row USER_KEY="1" USER_NAME="test" USER_ID="00000" USER_STATUS=" " USER_GENDER="F" /></root>'

;WITH cte AS
(
    SELECT id, t.rn, token = SUBSTRING(name, 1, CHARINDEX('" ', t.name) - 1)
    FROM (
        SELECT
              name =
                SUBSTRING(
                      t.string
                    , number + 2
                    , ABS(CHARINDEX('="', t.string, number + 1) - number - 1))
            , rn = ROW_NUMBER() OVER (PARTITION BY t.id ORDER BY (SELECT 1))
            , id
        FROM (
            SELECT id = 1, string = @newXML

            UNION ALL

            SELECT id = 2, @oldXML
        ) t
        CROSS JOIN [master].dbo.spt_values n
        WHERE [type] = 'p'
            AND number <= LEN(t.string) - 1
            AND SUBSTRING(t.string, number, 2) = '="'
    ) t
)
SELECT t2.token
FROM (
    SELECT *
    FROM cte
    WHERE id = 1
) t1
LEFT JOIN (
    SELECT *
    FROM cte
    WHERE id = 2
) t2 ON t1.rn = t2.rn AND t1.token != t2.token
WHERE t2.token IS NOT NULL


text:
Q: Nested loops and cloning of lists I have a list of dicts
lst = [{"activity":"tx"},{"activity":"fl", "ids":['123','456','789','432']}, {"activity":"ia"}]

I would like to clone these lists and add them to a master list, where the number is based on the unique "ids" in the "fl" dict.
desired outcome:
master = [[{"activity":"tx"},{"activity":"fl", "ids":'123'}, {"activity":"ia"}],
          [{"activity":"tx"},{"activity":"fl", "ids":'456'}, {"activity":"ia"}],
          [{"activity":"tx"},{"activity":"fl", "ids":'789'}, {"activity":"ia"}],
          [{"activity":"tx"},{"activity":"fl", "ids":'432'}, {"activity":"ia"}]]

A: This can be done with a simple loop on lst[1]['ids']
ans = [[lst[0], {"activity":"fl", "ids": id}, lst[2]] for id in lst[1]['ids']]

print(ans)
[[{'activity': 'tx'}, {'activity': 'fl', 'ids': '123'}, {'activity': 'ia'}],
 [{'activity': 'tx'}, {'activity': 'fl', 'ids': '456'}, {'activity': 'ia'}],
 [{'activity': 'tx'}, {'activity': 'fl', 'ids': '789'}, {'activity': 'ia'}],
 [{'activity': 'tx'}, {'activity': 'fl', 'ids': '432'}, {'activity': 'ia'}]]


text:
Q: Mass email tracking bounces,opens,clicks Most services offered online today that claim to "track" e-mails,But every one using image.
Is there any way to track the mail?
most of the mail servers blocking the images, after clicking the "download image" they show images,this is not exact tracking.(most of the peoples not like to download the images)
I'm searching other ways.
how this is work with out downloading image
img src="www.mysite.com/?promo=offer1">

A: You could request a read receipt, but again no guarantee of it being sent.
In short - no there is no way to track an email itself once it has left your local MTA.
If this is for a web promotion, the usual thing is to add a promo identifier to any links back to your website (e.g. "www.mysite.com/specialoffer1" or "www.mysite.com/?promo=offer1") so you can see who has visited as a result of receiving the email.


text:
Q: basic orientation change code to relayout UI components in Corona SDK using graphics 2.0 Anyone able to spot the issues here?  When I run this and toggle between portrait and landscape it does not work as expected (re width of rectangles following changing size of the effective width)
Try to get what the basic (simple) concept/approach is to handle autosizing UI elements to support Portrait and Landscape...
display.setStatusBar( display.HiddenStatusBar )
local WIDTH_PERCENT = 0.8
local myGroup = display.newGroup()

local myRoundedRect = display.newRoundedRect(myGroup, 0,0, display.contentWidth * WIDTH_PERCENT, 50, 25)
myRoundedRect.strokeWidth = 3
myRoundedRect:setFillColor(0,1,0)
myRoundedRect:setStrokeColor(1,0,0)
myRoundedRect.y = 25

local myRoundedRect2 = display.newRoundedRect(myGroup, 0,0, display.contentWidth * WIDTH_PERCENT, 50, 25)
myRoundedRect2.strokeWidth = 3
myRoundedRect2:setFillColor(0,0,1)
myRoundedRect2:setStrokeColor(1,0,0)
myRoundedRect2.y = 75

local function positionItems()
    myRoundedRect.width = display.contentWidth * WIDTH_PERCENT
    myRoundedRect2.width = display.contentWidth * WIDTH_PERCENT

    myRoundedRect.x = display.contentWidth/2
    myRoundedRect2.x = display.contentWidth/2
end
positionItems()

local function onOrientationChange( event )
    positionItems()
end
Runtime:addEventListener( "orientation", onOrientationChange )

UPDATE:
It seems to be an issue with setting the width programatically of a Rectangle after it is already in place.  I'm assume this is the basic operation that corona supports.  So what I'm seeing with the below code is:

*

*If initially set to say a width of 1000 for the square as you toggle orientation it decreases in size each time until you can't see it

*If you set initially to say 10 you get a really weird pattern indeed

*After you reset the size of the rectangle and then read it back it doesn't have seemed to changed in value, but then that still doesn't explain the above two points

Code:
display.setStatusBar( display.HiddenStatusBar )

local WIDTH_PERCENT = 0.5
local INITIAL_BOX_WIDTH = 1000    -- pre immediate width/height setting by the "positionItems" functions

local myGroup = display.newGroup()

local myRoundedRect = display.newRoundedRect(myGroup, 0,0, INITIAL_BOX_WIDTH,INITIAL_BOX_WIDTH, 25)
myRoundedRect.strokeWidth = 1
myRoundedRect:setFillColor(0,1,0)
myRoundedRect:setStrokeColor(1,0,0)

local function positionItems()
    local displayW, displayH = display.contentWidth, display.contentHeight

    myRoundedRect.width = displayW * WIDTH_PERCENT
    myRoundedRect.height = displayH * WIDTH_PERCENT

    myRoundedRect.x =displayW/2
    myRoundedRect.y =displayH/2

    print("Set width to " ..  displayW * WIDTH_PERCENT .. " . Read value back from Rec = " .. myRoundedRect.width)

end
positionItems()

local function onOrientationChange( event )
    positionItems()
end
Runtime:addEventListener( "orientation", onOrientationChange )

Config (below - or just nothing gives same issue)
local aspectRatio =display.pixelHeight/display.pixelWidth
application =
{
    content =
    {
        width = aspectRatio > 1.5 and 320 or math.ceil(480 /aspectRatio),
        height = aspectRatio<1.5 and 480 or math.ceil (320*aspectRatio),
        scale = "letterbox",
    }
}

build
settings =
{
    orientation =
    {
         default = "portrait",
       supported = { "portrait","landscapeLeft", "landscapeRight","portraitUpsideDown"
         },
    },

}

A: In the onOrientationChange function, the events that get passed are as follows:
"portrait"
"landscapeLeft"
"portraitUpsideDown"
"landscapeRight"
"faceUp"
"faceDown"

You would need to say something like this:
local function onOrientationChange(event)
  if event.phase=="landscapeLeft" then
  --Do code here
  end
end

Good luck hope this helps.

A: Tracked down the issue to:
a) weird pattern just the large radius value I used in newRoundedRect
b) the core shrinking Rect seems to be a bug with newRoundedRect, as when moving to newRect things then start working as expect


text:
Q: Rails 3 Initialization Order Can someone please point me in the right direction for the order in which rails modules get instantiated.
The main things I'm trying to find are:
1) When do gems get loaded?
2) When do config/initializers/* get loaded?
3) When do named routes in routes.rb get processed?

A: Check out this insanely detailed (and long) piece of documentation on the initialization process:
http://guides.rubyonrails.org/initialization.html

A: I started a console in Rails 3 and here is the order:

*

*script/rails

*config/boot.rb

*config/application.rb

*config/environment.rb

*config/initializers/*.rb (In alphabetic order)

A: Answering your question is easy by adding some puts statements in your Rails application. (It seems like a lot of people are reluctant to dig in and do this, but I really recommend it!) So, by experimentation and observation alone, here is the order of the things you mentioned:

*

*boot.rb

*config/initializers/*

*routes.rb
Here is a little more detail:
1. boot.rb
This loads the application gems by using bundler:
require 'rubygems'
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])

2. config/initializers/*
They run in alphabetical order.
If you are curious what triggers this, take a look at engine.rb in the railties source code. (It is useful to know that a Rails Application is a subclass of a Rails Engine.)
initializer :load_config_initializers do
  config.paths["config/initializers"].existent.sort.each do |initializer|
    load(initializer)
  end
end

3. routes.rb
By observation, I see that route drawing (specification) occurs next.
But looking at the details is more involved, so if you are interested I would read SO: Controlling routes loading order from Engines and perhaps take a look at the :add_routing_paths initializer in engine.rb.

A: I really don't know but logically in this order

*

*gems

*initializers

*routes

1) The only way I know how to edit gems is by editing the source file themselves. Moreover rails itself and basically everything with rails is a gem so I'm sure they are loaded first
2) Initializers are probably loaded second, or at least considering the three things you mentioned, because they might load information or modules that routes with resources and associations need.
3) Process of elimination

In terms of inner order it's probably abc
Don't take this seriously though :)


text:
Q: jsPDF show loading while processing. Promise does not wait I'm using JSPDF and autotables plugin for PDF reports. While the PDF generation is happening I'm trying to show a loading image. Unfortunately, the loading is ignored even when trying with async().

function createPDF(){
  return new Promise(resolve => {
   var doc = new jsPDF();
    doc.autoTable({
        body: [
            ['Elmo', 'Hello'],
            ['Bert', 'The Muppet Show.']
        ]
    });

    // mimik time for processing
    setTimeout(function(){
      console.log('wait time for loading image')
    }, 8000);

    doc.save('table.pdf');
    resolve('resolved');

    });
}

async function asyncPDF() {
  document.getElementsByClassName('img__loading')[0].style.display = 'block';
  var result = await createPDF();
  document.getElementsByClassName('img__loading')[0].style.display = 'none';
}

document.getElementById('save').addEventListener("click", asyncPDF );
.img__loading{
  display: none;
}

<button id="save">save</button>

The question is why is the loading image not showing up? And why does it start working when wrapping the save() and resolve() inside the timeout?
  setTimeout(function(){
      doc.save('table.pdf');
      resolve('resolved');
  }, 8000);

A: Use promise.then instead of async .And for testing your setTimeout was wrong place.You need to wrap with resolve .While on click your async function trigger all the inner calls.so loading as been immediately disappear after present that why wrap with in then function.then only detect the event finished from promise

function createPDF(){
  return new Promise(resolve => {
   var doc = new jsPDF();
    doc.autoTable({
        body: [
            ['Elmo', 'Hello'],
            ['Bert', 'The Muppet Show.']
        ]
    });

      console.log('wait time for loading image')

    doc.save('table.pdf');
    setTimeout(()=>{
    resolve('resolved');
    },3000)

    });
}

function asyncPDF() {
  document.getElementsByClassName('img__loading')[0].style.display = 'block';
  createPDF().then(()=>{
  document.getElementsByClassName('img__loading')[0].style.display = 'none'})
}

document.getElementById('save').addEventListener("click", asyncPDF );
.img__loading{
  display: none;
}

<button id="save">save</button>

A: You've wrap it into Promise which is good but it's resolved immediately just because there no place where it should wait. setTimeout works because you call resolve after certain amount of time.
In jsPDF site you can find API of save method:
http://raw.githack.com/MrRio/jsPDF/master/docs/jsPDF.html#save
Option that you can be interested in is returnPromise.
So that's should do the job:
await doc.save('table.pdf', {returnPromise: true});

Unfortunately I'm not familiar with jsPDF library nor autotable plugin so forgive any library related errors.

A: I think the loader doesn't have enough time. Your pdf related stuff is done too quickly, promise resolves and loader hides, so it works as follows:
// show loader
// creating pdf took several milliseconds
// hide loader

When you use setTimeout you put off the promise resolving for 8 seconds.
setTimeout(function(){
      doc.save('table.pdf');
      resolve('resolved'); // resolve is also postponed
  }, 8000);

So the loader is shown for 8 seconds. User has enough time to see it.
Also, it a good practice to use setTimeout to unload the main thread from some heavy operation as long as you are manipulation DOM at the same time. However, using WebWorkers would be the best solution

A: The right answer is:
doc.save('export.pdf', { returnPromise: true }).then(() => {
  // Code will be executed after save
});

Use a setTimeout to fake a promise is a bad practice.


text:
Q: How to send information to database without reloading page? so, i´m trying to send some information to database with AJAX/PHP but without success, i´ve seen some codes from here but they are not working and I just get this error
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
HTML
<form action="javascript:void;" id="putz" class="putz" method="POST" onsubmit="send()" enctype="multipart/form-data" >

                <input type="text" name="name" id="name" required>
                Name

                <input type="text" name="email" id="email" required>
                Email

                <input type="text" name="pass" id="pass" required>
                Password

Photo

                <input type="file" name="photo" style="margin-right: 140px; color: red;">

              <button id="submit" type="submit">Submit</button>
            </form>

And here is my ajax/javascript
</script>

and the send.php code
 <?php
    include_once('conn.php');
    $name = $_POST['name'];
    $email = $_POST['email'];
    $pass = $_POST['pass'];
    $photo = $_FILES['photo']['name'];
    $tmp_name = $_FILES['photo']['tmp_name'];
    move_uploaded_file($tmp_name, "img/foto_perfil/" . $photo);
    $sql = "INSERT INTO user (name, email, photo, pass) VALUES ('$name', '$email','$photo', '$pass')";
    mysqli_query($conn, $

A: *

*You didn't have the JQuery library referenced prior to your
invocation of $.ajax().

*You are referring to the actual HTML Elements as the data to pass
when you should be passing the values of those elements.

*You also have trailing commas after the last key/value pair in your
data object and after the data key itself.

*I would also rename any/everything that you named name as this can
cause conflicts with the Global window.name property.

*(FYI) You aren't using the label element correctly. You either wrap
it around the form element that it is a label for or you give it a
for attribute with a value of the id of the form element that it
is a label for.

function send() {
  // Get the values of the elements, not the elements themselves:
  var userName = document.getElementById( "userName" ).value;
  var email = document.getElementById( "email" ).value;
  var pass = document.getElementById( "pass" ).value;

  $.ajax({
    type: 'post',
    url: 'send.php',
    data: {
      userName: userName,
      email: email,
      pass: pass
    }
  });
}

<form action="#" id="putz" class="putz"
      method="POST" onsubmit="send()" enctype="multipart/form-data" >

    <input type="text" name="userName" id="userName" required>
    Name

    <input type="text" name="email" id="email" required>
    Email

    <input type="text" name="pass" id="pass" required>
    Password

Photo

    <input type="file" name="photo" style="margin-right: 140px; color: red;">

  <button id="submit" type="submit">Submit</button>
</form>


text:
Q: Is the apple-app-site-association implementation safe? By implementing universal links, you end up with an apple-app-site-association file that you put in the root of your server. The file contains both bundleID and teamID. Is this safe?
I can clearly download e.g. Google's one and get their IDs since the scenario is always the same.

A: There is no security risk from displaying the bundle ID and team ID. It is not possible to use these two pieces of information for anything (either productive or dangerous) without also having access to your Apple Developer account password.