text:
Q: Are duplicated private member variables preferable to a shared protected member? This is an idiom I have noticed in a C# codebase which I have been working on recently:
class Base
{
   private readonly MemberClass _memberVariable;

   public Base(MemberClass memberValue)
   {
       _memberVariable = memberValue;
   }

   // methods accessing memberVariable...
}

class Derived : Base
{
   private readonly MemberClass _memberVariable;

   public Derived(MemberClass memberValue) : base(memberValue)
   {
       _memberVariable = memberValue;
   }

   // methods accessing memberVariable...
}

Both the base class and its derived class have a member variable which is intialised in their respective constructors, but instead of declaring the member as protected in the base class and having it available in its subclasses, each subclass has its own private copy of the member.
My first reaction to this was that it was an unnecessary duplication. On thinking about it some more, I feel that the duplication might be justified as it reduces the amount of coupling between the base and derived classes and prevents a change in the base class causing inadvertent breakage in its subclasses.
Are protected members "considered harmful" in C#?

A: I would consider protected fields harmful - and I would also consider the data duplication harmful, if the values should always be the same. However, the base class could expose the private field's value via a property instead:
class Base
{
   private readonly MemberClass memberVariable;

   protected MemberClass MemberProperty { get { return memberVariable; } }

   public Base(MemberClass memberValue)
   {
       this.memberVariable = memberValue;
   }

   // methods accessing memberVariable or MemberProperty...
}

class Derived : Base
{
   public Derived(MemberClass memberValue) : base(memberValue)
   {
   }

   // methods accessing MemberProperty...
}

In C# 6, the base class becomes simpler:
class Base
{
   protected MemberClass MemberProperty { get; }

   public Base(MemberClass memberValue)
   {
       this.MemberProperty = memberValue;
   }

   // methods accessing MemberProperty...
}

That's still a protected property backed by a private readonly field - it's just the compiler does all the boilerplate for you.

A:
Are protected members "considered harmful" in C#?

Members in general? No, for sure. There are lots of good reasons to have protected members in C# code.
Furthermore, I think that clearly the code you've used in your example is broken. Having two copies of the exact same value all the time is wasteful and if anything, is likely to create bugs (as soon as you have two fields that are supposed to have the same value, you now have the opportunity for those values to be not the same and thus wind up breaking some code somewhere).

As far as the question of protected fields specifically? I will dissent from Jon's opinion here, at least to a degree: for a readonly field, IMHO it is perfectly fine in some situations.
The main reason for encapsulating such a field in a property would be so that the implementation could be elaborated on later without having to recompile dependent code (assuming that code is in a different assembly).
But IMHO such a field is very likely to never need elaboration on its implementation. Such fields are usually intended as sources for constant value. A getter with something more elaborate than just returning a field value is, while not exactly rare, not all that usual either (the biggest exception I can think of being lazily-initialized values).
For now, most of us are using C# 5 or earlier, and that's likely to be true for some time now. Until the C# 6 syntax is available widely, I'd say that using a readonly protected field is a fine concession to conciseness without a major maintenance/correctness hazard in certain specific scenarios.
Naturally, the more complicated the code gets, the more useful good, safe abstractions will be, and the more likely you should stick with a truly encapsulated read-only property.
But as an absolute rule? No, I don't think it's necessary to have a blanket prohibition against readonly protected fields.


text:
Q: Handling negative numbers in array By looping, I am trying to determine unique and duplicate elements in a given array and display their corresponding frequency. My code is as following:
    #include <stdio.h>
#define Frequency_size 10000
#define N 20
void unique_numbers(int array[], int n){
   int i,j;
   int count = 0;
   printf("List of unique numbers: ");
   for(i = 0; i < n; i++){
      for(j = 0; j < n; j++){
         if(array[i] == array[j] && i != j)
         break;
      }

      if(j == n ){
         printf("%d ",array[i]);
         ++count;
      }
   }
   printf("\n");
   printf("Element count in List of Unique Numbers = %d", count);
}

void non_unique_numbers(int arr[], int size)
{
    int i;
    int freq;
    int totdup = 0;

    int frequency[Frequency_size] = { 0 };
printf("List of Duplicated Numbers: \n");

    for (i = 0; i < size; i++)
        ++frequency[arr[i]];

    for (i = 0; i < Frequency_size ; i++) {
        freq = frequency[i];
        if (freq <= 1)
            continue;

        printf("Number: %d  , Frequency: %d\n", i, freq);

        if (freq >= 2)
            ++totdup;
    }

    printf("Element Count in List of Duplicated Numbers = %d",totdup);

}

int main(){
    int array[]={41, 47, 23, -62, -52, 15, 41, -88, 90, -62, -40, 37, 34, 88, 26, -54, 53, 15, 41, 46};
    unique_numbers(array, N);
    printf("\n\n\n\n");
    non_unique_numbers(array, N);
}

When I run this my output is:
List of unique numbers: 47 23 -52 -88 90 -40 37 34 88 26 -54 53 46
Element count in List of Unique Numbers = 13

List of Duplicated Numbers:
Number: 15  , Frequency: 2
Number: 41  , Frequency: 3
Element Count in List of Duplicated Numbers = 2

But in my array, I also have -62 duplicate 2 times. I also want to display that but I could not manage to handle negative numbers.
Desired output is:
List of Duplicated Numbers:
Number: 15  , Frequency: 2
Number: 41  , Frequency: 3
Number: -62  , Frequency: 2
Element Count in List of Duplicated Numbers = 3

It is because of the for loop of course but I could not manage to modify it. What can I do? I only want to use for loops by the way.

A: Assuming that Frequency_size relates to the maximum absolute value of any number that can be stored in the array, you could try this:
int frequency_array[2*Frequency_size + 1] = { 0 };
int *frequency = &frequency_array[Frequency_size];

// Now you can access frequency[x] from -Frequency_size .. 0 .. +Frequency_Size

printf("List of Duplicated Numbers: \n");

for (i = 0; i < size; i++)
{
  if (arr[i] >= -Frequency_size && arr[i] <= Frequency_size)
  {
    ++frequency[arr[i]];
  }
}

for (i = -Frequency_size; i <= Frequency_size ; i++)
{
  // .. Do the printing stuff here
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: List of values from list of jsons I would like to extract from this kind of list:
[{'time': '2018-10-08T13:26:40.366296729Z', 'ask0': 6604.036},
{'time': '2018-10-08T13:26:45.666245795Z', 'ask0': 6607.34909},
{'time': '2018-10-08T13:26:51.08045435Z', 'ask0': 6607.18674}]

Is there any possibility to create list of asks0 in one line? I tried something like that:
asks = [y for x, y in points.__iter__()]

but it does not work.

A: data = [
    {"time": "2018-10-08T13:26:40.366296729Z", "ask0": 6604.036},
    {"time": "2018-10-08T13:26:45.666245795Z", "ask0": 6607.34909},
    {"time": "2018-10-08T13:26:51.08045435Z", "ask0": 6607.18674},
]

asks = [d["ask0"] for d in data]

# asks will be [6604.036, 6607.34909, 6607.18674]

A: Simply:
points = [{'time': '2018-10-08T13:26:40.366296729Z', 'ask0': 6604.036},
{'time': '2018-10-08T13:26:45.666245795Z', 'ask0': 6607.34909},
{'time': '2018-10-08T13:26:51.08045435Z', 'ask0': 6607.18674}]

[i['ask0'] for i in points]
#[6604.036, 6607.34909, 6607.18674]


text: Q: Dropbox indicator menu went missing in 13.10. How to get it back? I installed Ubuntu 13.10, then installed Dropbox from Ubuntu Software Center. Yet starting Dropbox seems to have no effect, and the Dropbox icon doesn't appear in the top-right indicator area like it normally does. Dropbox is apparently running, but the indicator/menu doesn't show up.


text:
Q: Can we say that : $ (A-B)\cap\overline{B}(0,r)\text{ is weakly compact, }\forall r>0 $ Let $X$ be a separable Banach space and $A,B$ are closed convex subsets of $X$ such that $B\subset A$ and
$$
A\cap\overline{B}(0,r) \text{ and } B\cap\overline{B}(0,r) \text{ are weakly compact, } \forall r>0.
$$
Can we say that :
$$
(A-B)\cap\overline{B}(0,r)\text{ is weakly compact, }\forall r>0
$$
with $A-B=\{a-b:a\in A,b\in B\}$.

A: Doesn't this already fail in finite dimensions? Take $X = \mathbb{R}^2$ and let $A = B =$
the closed region bounded by $y = \sqrt{x^2 + 1}$ and $y = x + 1$, both for $x \geq 0$. The intersection with any ball is closed and therefore compact, but $A - B$ is not closed: it contains points arbitrarily close to $(0, -1)$ but does not contain that point itself.

A: This is not an answer, but I put it here to stop close votes that are apparently based on a misreading of the question.
I do not know the answer to the OP's question, but I will point out that both hypotheses are necessary. For example, drop the hypothesis that $A$ is convex. Then there is a counterexample with $A=B$; namely, $A=\bigcup_n \{(n+1)e_n, ne_n\}$, where $(e_n)$ is the unit vector basis of $\ell_1$. Bounded subsets of $A$ are finite and $A-A$ contains $(e_n)$, which is not preweakly compact.
Secondly, drop the hypothesis that $B\subset A$ but keep the convexity hypotheses. Let $X= C[0,1]$ ($X$ could be any separable non reflexive space that contains an infinite dimensional reflexive subspace). It is known that there are quasi complementary subspaces $X_1$ and $X_2$ that are both isomorphic to $\ell_2$. This means that $X_1 \cap X_2 =\{0\}$ and $X_1 - X_2$ is norm dense in $X$, and hence $(X_1 - X_2) \cap B(0,1)$ is even norm dense in the non weakly compact unit ball of $X$.


text:
Q: Split function - avoid last empty space I have a doubt on how to use the split function.
str = 'James;Joseph;Arun;'
str.split(';')

I got the result ['James', 'Joseph', 'Arun', '']
I need the output as ['James', 'Joseph', 'Arun']
What is the best way to do it?

A: To remove all empty strings you can use a list comprehension:
>>> [x for x in my_str.split(';') if x]

Or the filter/bool trick:
>>> filter(bool, my_str.split(';'))

Note that this will also remove empty strings at the start or in the middle of the list, not just at the end.

*

*Remove empty strings from a list of strings
If you just want to remove the empty string at the end you can use rstrip before splitting.
>>> my_str.rstrip(';').split(';')

A: First remove ; from the right edge of the string:
s.rstrip(';').split(';')

You can also use filter() (which will filter off also empty elements that weren't found at the end of the string). But the above is really the cleanest approach in my opinion, when you want to avoid empty element at the end, resulting from ";" characters occuring at the end of the string.
EDIT: Actually more accurate than the above (where the above is still more accurate than using filter()) is the following approach:
(s[:-1] if s.endswith(';') else s).split(';')

This will remove only the last element, and only if it would be created empty.
Testing all three solutions you will see, that they give different results:
>>> def test_solution(solution):
    cases = [
        'James;Joseph;Arun;',
        'James;;Arun',
        'James;Joseph;Arun',
        ';James;Joseph;Arun',
        'James;Joseph;;;',
        ';;;',
        ]
    for case in cases:
        print '%r => %r' % (case, solution(case))

>>> test_solution(lambda s: s.split(';'))  # original solution
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun', '']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph', '', '', '']
';;;' => ['', '', '', '']
>>> test_solution(lambda s: filter(bool, s.split(';')))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph']
';;;' => []
>>> test_solution(lambda s: s.rstrip(';').split(';'))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph']
';;;' => ['']
>>> test_solution(lambda s: (s[:-1] if s.endswith(';') else s).split(';'))
'James;Joseph;Arun;' => ['James', 'Joseph', 'Arun']
'James;;Arun' => ['James', '', 'Arun']
'James;Joseph;Arun' => ['James', 'Joseph', 'Arun']
';James;Joseph;Arun' => ['', 'James', 'Joseph', 'Arun']
'James;Joseph;;;' => ['James', 'Joseph', '', '']
';;;' => ['', '', '']


text:
Q: Facebook email Permission, OAuth2, doesnt work? since the new Auth Dialog from Facebook (for my App & homepage), I cannot get the dialog to show that my homepage/app needs the users email when connection to my homepage/app.
In the Auth-section of my app I've added "email" to the User & Friend Permissions. Also I've added it to the referal when someone clicks the "Login with facebook"-button.
When someone clicks the Facebook-button, he/she redirects to a page which has the PHP-code with Facebook SDK PHP (latest). Here's how I generate the send-to-url for the dialog:
$login_url = $facebook->getLoginUrl(array('req_perms' => 'email,publish_stream'));
header("Location: ".$login_url);

But when the Dialog pops up, the only permission request it does is "basic information". I need to request the Email. Am I stupid or is it a bug somehow? I've also recreated the App.

A: There in no req_perms parameter anymore, it's called scope in OAuth2.
Read documentation for getLoginUrl to see correct parameters.

A: in new dialog there are 2 kind of permissions normal permissions & extended permissions
you should install app with normal permissions at first then page will redirect automatically
for extended permissions


text:
Q: Can i call a .js file from html file (angularjs) I have a little bit of a problem with an email function. I tried 'nodemailer' package and it worked when I wrote the code in a .js file. When i called the .js file (node emailfile.js) it worked and I received an email (code below).
var nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
  service: 'gmail',
  secure: false,
  port: 25,
  auth: {
    user: 'MYUSERNAME', // this is not an error, I don't want to share my data
    pass: 'ok1994ka'
  },

  tls: {
    rejectUnauthorized: false
  }
});

let HelperOptions = {
  from: '"Sportot App" <fiziohome@gmail.com>',
  to: 'fiziohome@gmail.com',
  subject: 'Hello World',
  text: 'Good day to you!'
};

transporter.sendMail(HelperOptions, (error, info) => {
  if (error) {
    return console.log("error");
  }
  console.log("Epasts aizsūtīts");
});

Now, what I want to do is call this .js file from my HTML file.
<button ion-button block color="danger" (click)=pasts()>Sūtīt e-pastu</button>

And in my html file inside  tags I inserted:
<script src="email.js"></script>

And inserted a line "function pasts(){"inside there is the whole code from email.js file"}". I hope you can understand my question and somebody of you got answer to this. Thank you!

A: You will not be able to call that code directly from the browser. You will need to host that file on a webserver and from Angular you will need to make a http request to the webserver running node.
You need to understand which parts of a web application are client and which parts are server. The Angular app is downloaded by the browser and runs on the client machine. The node side of the application runs on the server and Angular makes requests to the server via http.
There is more to this can can be explained in a Stack Overflow answer as there are many parts to answering how to set this up.


text:
Q: JSON mapping exception I am trying to send json data to my JAVA class but getting an error
"Failed executing POST IntakeFormSections/PostData: org.jboss.resteasy.spi.ReaderException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of org.json.JSONObject out of START_ARRAY token"
Controller:
var datanew =  angular.toJson($scope.data);
 $http({

url :"http://localhost:8080/......IntakeFormSections/PostData",

      method: 'POST',
      data : datanew,
      headers: {'Content-Type': 'application/Json'},

      })};

JAVA Code:
@POST
@Path("/PostData")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)

public String UpdateSiteVisitInfo(JSONObject data) throws JSONException {
System.out.println("++++++++++");
System.out.println(data);
return null;}

A: The JSON is in wrong format.
It should be like this.
[{ "Id": 1, "description": "Submitter Contact Information", "type": "hidden", "required": "false", "subquestions1": [{ "Id": "a", "description": "ID", "type": "text", "name": "id", "patternType": "alphanumeric", "required":"false" }, { "Id": "b", "description": "Name", "type": "text", "name": "user", "patternType": "text", "required":"false", "length":100 }]}]

A: You are passing a list of JSONObjects as datanew, but in controller it is mapped to single JSONObject, please change controller argument type to accept list of JSONObjects.

A: As pointed out, you are sending an array with one JSONObject element. That means you either should have a an argument of JSONObject[] array then retrieve the first element or Send a single object to the endpoint.


text:
Q: Can OS X users get locked on OS X similar to on ubuntu when using git? I have gitlab connected to my mac but when I do git push -u origin master I get 'Permission denied. Please try later' message which is what pops up when the user gets locked it seems.
But here in this post users have used usermod in linux to unlock the user. I need to do something similar. Or if there is any other solution

A: I just had to delete the entry from known_hosts file on my MAC(client) to remove the traces of old config for that particular gitlab server. And also I regenerated my ssh keys back which seemed to work! :)
I used githubs awesome article to regenerate the ssh-keys.


text:
Q: I can not run server Django 2.0 Hello I'm having a problem when trying to run server from an Django 2.0 old project.
this is the error:
      File "/usr/lib/python3.7/site-packages/django/urls/conf.py", line 39, in include
    'Specifying a namespace in include() without providing an app_name
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.'

this is my urls.py
from django.conf.urls import url, include
from django.contrib import admin
from apps.sysgrub.views import LoginUser, LogoutUser

app_name = 'apps'

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^alumno/', include ('apps.alumno.urls', namespace="alumno")),
    url(r'^grupo/', include ('apps.grupo.urls', namespace="grupo")),
    url(r'^maestro/', include ('apps.maestro.urls', namespace="maestro")),
    url(r'^rol/', include ('apps.rol.urls', namespace="rol")),
    url(r'^sysgrub/', include ('apps.sysgrub.urls', namespace="sysgrub")),
    url(r'^$', LoginUser),
    url(r'^logout/$', LogoutUser),
]

and my urls by app
urlpatterns = [
url(r'^index$', index),
url(r'^horarios$', horarios),
url(r'^listar$', Alumno_grupoList.as_view(), name='alumno_listar'),
url(r'^agregar$', AlumnoCreate.as_view(), name='add_student'),

]

thank you so much for your help greetings.

A: The error describes the resolution please remove app name from the urls.py as below
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^alumno/', include ('alumno.urls', namespace="alumno")),
url(r'^grupo/', include ('grupo.urls', namespace="grupo")),
]


text:
Q: Iterating through a table column containing dollar amounts returns NaN when adding I'm trying to add up the dollar amounts in a column. Currently I'm iterating through the rows and when I console.log, it shows the amounts. The problem occurs when I try to add them.
Here's my current code:
   var total,curAmount;
   $('#carrier-details-table tbody tr > td:last-of-type').each(function() {

       if($(this).parent('tr').css('display')=='table-row'){
         curAmount = parseFloat($(this).text().replace(',','').split('$')[1]);
         total += curAmount;
         console.log(curAmount);
       }

   });

Again, curAmount shows the right numbers, but when I console.log(total), it shows NaN. I've also tried changing the$(this).text() to $(this).html() but still nothing. Can someone point me in the right direction?

A: perhaps you need to initialize the variable total  to  0  first:
var total = 0, curAmount;

A: total is initialized as undefined at first hence undefined + 1 == NaN;
You can change that: var total = 0,curAmount;


text:
Q: need suggestion for creating bash script Getting P1 alerts when the status of a table doesn't get updated by logger, we need to be able to log the data and update the status based on the following conditions. For now we are using this script to run it when alerted and look into scheduling it later

*

*Check If there are any tables with status = 1 that are older than 5mins in the following 2 tables
select * from test1 where status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);
select * test2  where status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);

*If we find any records in step# 1 save the output to log from the above query and check if the table specified in TEMP_TABLE_NAME(eg:TEMP_test1) exists, because here temp table automatically gets generated.

*If the temp table doesn't exist update the status to 0 to clear out the alert, update could be needed for just one of the table listed above
Update test1 set status = 0 where ID = ;

*If the TEMP_TABLE_NAME(eg:TEMP_test1) does exist, we need to reach out to concerned team to investigate

*Email the results of the output from step: 1 to xxx@gmail.com for review
I have tried writing below code using google but stucked about stoirng file and how to compare temp table exists or not.
email="pqrs@gmail.com"
pid=$$
logFile="/tmp/alertlog"
emailflag=0

host=XX.XX.XX.XX
user=ABC
passwd=XYZ

alert_on_error () {
    echo $1 >> /tmp/$pid.count
    cat /tmp/$pid.count | mail -s "Error running $0 on `hostname`"  $email
    rm -rf /tmp/$pid.*
    exit 1
}

mysql="mysql --connect-timeout=50 --compress --quick --disable-auto-rehash --skip-column-names -u $user -h $host -p$passwd -A"
    ID1='$mysql -e "select * from test1 where status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);"'
ID2='$mysql -e select * from test2 where status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);"'

A: You can simply put everything in a .sql file and execute it. E.g. create myscript.sql
select * from TEST1 where status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);
select * from TEST2 where status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);
UPDATE TEST1 SET status = 0 WHERE status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);
UPDATE TEST2 SET status = 0 WHERE status = 1 and CREATED < DATE_SUB(NOW(), INTERVAL 5 MINUTE);

Then execute
mysql databasename < myscript.sql >> logfile.txt


text:
Q: How to change preview image of Play Store app when sharing on Facebook? I've changed my application's icon and Feature Graphic,Promo Graphic on google play a week ago but
when I copy the link of my appliaction and share it on facebook, the preview on facebook show the older of my application's icon.So, how can I make it to show the lastest Icon when sharing it?
I know my question is similar to bellow questions:

*

*How to change preview of Play Store app when sharing on Facebook?.

*Google Play Store Facebook Share

A: make sure that the icon is changed in the manifest file


text:
Q: Count 'white' pixels in opencv binary image (efficiently) I am trying to count all the white pixels in an OpenCV binary image. My current code is as follows:
  whitePixels = 0;
  for (int i = 0; i < height; ++i)
    for (int j = 0; j < width; ++j)
      if (binary.at<int>(i, j) != 0)
        ++whitePixels;

However, after profiling with gprof I've found that this is a very slow piece of code, and a large bottleneck in the program.
Is there a method which can compute the same value faster?

A: cv::CountNonZero. Usually the OpenCV implementation of a task is heavily optimized.

A: You can use paralell computing. You divide the image in N parts and run your code in differents threads then you get the result of each threads and after this you can add this results for obtain the finally amount.

A: The last pixel in a row is usually followed by the first pixel in the next row (C code):
limit=width*height;
i=0;
while (i<limit)
{
  if (binary.at<int>(0,i) != 0) ++whitePixels;
  ++i;
}

A: Actually binary.at<int>(i, j) is slow access!
Here is  simple code that access faster than yours.
for (int i = 0; i < height; ++i)
{
uchar * pixel = image.ptr<uchar>(i);
    for (int j = 0; j < width; ++j)
{
  if(pixel[j]!=0)
   {
      //do your job
   }
}
}


text:
Q: How to access subgroup in list with Python I have a list with subgroups within. I made subgrouping based on similarity of fund name. How do I select/identify a group within a list?
mylist = [
    {'American Funds Cnsrv Gr & Inc A', 'American Funds Cnsrv Gr & Inc R-5E', 'American Funds Cnsrv Gr & Inc F-1', 'American Funds Cnsrv Gr & Inc R-6', 'American Funds Cnsrv Gr & Inc R-5', 'American Funds Cnsrv Gr & Inc F-3', 'American Funds Cnsrv Gr & Inc R-4', 'American Funds Cnsrv Gr & Inc F-2'}
    {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'},
    {'American Funds Cnsrv Gr & Inc 529-A', 'American Funds Cnsrv Gr & Inc 529-F-3', 'American Funds Cnsrv Gr & Inc 529-F-2', 'American Funds Cnsrv Gr & Inc 529-F-1'}]

For example how to I call/select 2nd group: {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}
My eventual goal is to keep only one fund from each group that is the best share class, but first I need a way to identify each subgroup.
Thanks

A: You can slice or indice the list index:
mylist = [{'American Funds Cnsrv Gr & Inc A', 'American Funds Cnsrv Gr & Inc R-5E', 'American Funds Cnsrv Gr & Inc F-1', 'American Funds Cnsrv Gr & Inc R-6', 'American Funds Cnsrv Gr & Inc R-5', 'American Funds Cnsrv Gr & Inc F-3', 'American Funds Cnsrv Gr & Inc R-4', 'American Funds Cnsrv Gr & Inc F-2'}, {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}, {'American Funds Cnsrv Gr & Inc 529-A', 'American Funds Cnsrv Gr & Inc 529-F-3', 'American Funds Cnsrv Gr & Inc 529-F-2', 'American Funds Cnsrv Gr & Inc 529-F-1'}]

MFSC = mylist[1]
print(MFSC)

Output:
{'MFS Conservative Allocation R2', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R3', 'MFS Conservative Allocation R4', 'MFS Conservative Allocation R6'}

But the element of list is a set so set element can appear in a different order every time you use them, and cannot be referred to by index or key.
MFSC = list(mylist[1])
print(MFSC)

Output:
['MFS Conservative Allocation R4', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2']


text:
Q: I use the Find function to find words in vba Excel Good morning people, I'm creating an excel Macro to find words and mark the word and the cell as well. I want to find the words I have in my Array. The problem I have is that it marks all the words that it finds, even if it's contained in another word. For example: I have the word skin, and it marks the word "Asking"  so it marks the word skin in the word Asking, and I only want the words "skin" to mark. Is there a way for me to change this?
Here I have my code.
 Dim med_Arr As Integer
    Dim ws As Worksheet
    Dim oRange As Range
    Dim wordToFind As String
    Dim Lista As Variant
    Dim cellRange As Range
    Dim Foundat As String

    For Each ws In ActiveWorkbook.Worksheets ' for
        Set oRange = ws.Range("M:M")
        ws.Activate
        Lista = Array("BRAKE", "OIL", "FALL", "CUT", _
        "EXPOSED", "COPPER", "TREND", "NO ALARM", _
        "NOT ALARM", "ALARM IN", "SORE", "BURN", _
        "SPARK", "FLUID", "PAIN", "BLOOD", "MOULD", _
        "HURT", "ITSELF", "SEVERED", "BLISTER", _
        "SELF RUN", "STAY UP", "SKIN", "STAYING UP", _
        "BUZZER", "HEAT", "LATCH", "SPLIT", "VOICE", _
        "FIRE", "SMOKE", "HOT", "FRAY", "VOLUME", _
        "BED EXIT", "COLLAPSE", "WARNING", "LABEL", _
        "HEART MO", "HHR", "RESPIRATORY MONITOR", _
        "COMMUNICATING", "HR NO", "10 C0", "CONTAMINATION", _
        "INGRESS", "EGRESS", "SAFETY", "INJURED", "DIED", _
        "FELL", "WARM", "TILT", "TIPP", "UNSTABLE", "ARC", _
        "VITAL SIGN", "SHOCK", "FLICKER", "ELECTROCUTED", _
        "SHARP", "SLICE", "LACERAT", "ELECTROMAG", "FLAM", _
        "IN HALF", "MUTILA", "EARLYSENSE", "EARLY SENSE", _
        "ENTRAP", "DROP")

        med_Arr = UBound(Lista) - LBound(Lista) 'LBound (0)
        For i = 0 To med_Arr 'for loop From 0 to Array Length
            wordToFind = Lista(i) 'saves word to find
            Set cellRange = oRange.Find(What:=wordToFind, LookIn:=xlValues, _
                            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                            MatchCase:=False, SearchFormat:=False) ' Finds first cell that contains at least one word and sets it to cell range
            If Not cellRange Is Nothing Then ' cell range exists then
                Foundat = cellRange.Address ' variable that contains address of cell that contains the word
                Do ' create variable textStart and set it to 1
                    Dim textStart As Integer
                    textStart = 1
                    Do
                        textStart = InStr(textStart, cellRange.Value, wordToFind) ' set position of current word found to textStart
                        If textStart <> 0 Then ' if textStart different than zero, then it didn't find anything
                            cellRange.Characters(textStart, Len(wordToFind)).Font.Color = RGB(250, 0, 0) ' font Color-red
                            cellRange.Characters(textStart, Len(wordToFind)).Font.Bold = True 'bold
                            cellRange.Interior.ColorIndex = 40 'background color to 40
                            textStart = textStart + 1 ' increase one to textStart (position)  to check if there's more words to look for in the rest of the paragraph
                        End If
                    Loop Until textStart = 0 ' loop again
                    Set cellRange = oRange.FindNext(After:=cellRange) ' set cellRange and find if there's another word in the rest of the paragraph
                Loop Until cellRange Is Nothing Or cellRange.Address = Foundat ' loop until cellRange is empty or the cellRange adress is equal to the current cell
            End If
        Next i
    Next

I appreciate your time and help.

A: Here's an approach using the VBsript Regexp object:
Option Explicit

Sub RunHighlights()
    Dim ws As Worksheet, c As Range
    'loop over worksheets
    For Each ws In ActiveWorkbook.Worksheets ' for
        For Each c In ws.Range("M1", ws.Cells(Rows.Count, "M").End(xlUp)).Cells
            If Len(c.Value) > 0 Then
                'highlight cell if any matches
                c.Interior.ColorIndex = IIf(HighlightWords(c) > 0, 40, xlNone)
            End If
        Next c
    Next ws
End Sub

'Highlight all words in a cell matching anything in WordList,
'   and return number of matches
Function HighlightWords(c As Range) As Long
    Dim re As Object, txt As String, matches As Object, m, rv As Long
    Set re = CreateObject("VBScript.RegExp")
    re.Pattern = "\b(" & Join(WordList(), "|") & ")\b" 'join word array to create pattern
                                                       '  \b = word boundary
    re.ignorecase = True
    re.MultiLine = True
    re.Global = True 'match whole text

    c.Font.Color = vbBlack 'reset any existing coloring
    Set matches = re.Execute(c.Value)
    For Each m In matches 'loop each match and apply font color
        Debug.Print c.Parent.Name, c.Address, m, m.firstindex, m.Length
        c.Characters(m.firstindex + 1, m.Length).Font.Color = vbRed
        rv = rv + 1
    Next m
    HighlightWords = rv 'return # of matches
End Function

'just returns an array of words to match on
Function WordList()
    WordList = Array("BRAKE", "OIL", "FALL", "CUT", _
        "EXPOSED", "COPPER", "TREND", "NO ALARM", _
        "NOT ALARM", "ALARM IN", "SORE", "BURN", _
        "SPARK", "FLUID", "PAIN", "BLOOD", "MOULD", _
        "HURT", "ITSELF", "SEVERED", "BLISTER", _
        "SELF RUN", "STAY UP", "SKIN", "STAYING UP", _
        "BUZZER", "HEAT", "LATCH", "SPLIT", "VOICE", _
        "FIRE", "SMOKE", "HOT", "FRAY", "VOLUME", _
        "BED EXIT", "COLLAPSE", "WARNING", "LABEL", _
        "HEART MO", "HHR", "RESPIRATORY MONITOR", _
        "COMMUNICATING", "HR NO", "10 C0", "CONTAMINATION", _
        "INGRESS", "EGRESS", "SAFETY", "INJURED", "DIED", _
        "FELL", "WARM", "TILT", "TIPP", "UNSTABLE", "ARC", _
        "VITAL SIGN", "SHOCK", "FLICKER", "ELECTROCUTED", _
        "SHARP", "SLICE", "LACERAT", "ELECTROMAG", "FLAM", _
        "IN HALF", "MUTILA", "EARLYSENSE", "EARLY SENSE", _
        "ENTRAP", "DROP")
End Function


text:
Q: Travis environment variable (Python) I have set up "ENVIRONMENT" as an environment variable in the Travis console, but when Travis runs, it still can't access the variable in Python. Any idea?
  File "/home/travis/build/.../config/env.py", line 12, in set
    builtins.environment = os.environ['ENVIRONMENT']
  File "/home/travis/virtualenv/python3.6.3/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'ENVIRONMENT'

A: I'll attempt an answer, as it's the only reason I can think of.
on Linux/unix bash/ksh, doing:
ENVIRONMENT=somevalue

doesn't propagate the value to children processes. You have to export (in bash):
export ENVIRONMENT=somevalue


text:
Q: JavaScript how to copy a data like the ctr+c in windows I have a button on my website.  This button is called copy.  When the user clicks it, I want to have something be copied.
I already make the JavaScript function like this:
function copyToClipboardCrossbrowser(s, el) {}

where s is the data to be copied.  How please?
Thanks

A: You can't with pure javascript, with Flash however you can work around it: https://github.com/zeroclipboard/ZeroClipboard
Example:
html
<html>
  <body>
    <button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button>
    <script src="ZeroClipboard.js"></script>
    <script src="main.js"></script>
  </body>
</html>

main.js
var client = new ZeroClipboard( document.getElementById("copy-button") );

client.on( "ready", function( readyEvent ) {
  alert( "ZeroClipboard SWF is ready!" );

  client.on( "aftercopy", function( event ) {
    event.target.style.display = 'none';
    alert("Copied text to clipboard: " + event.data["text/plain"]);
  });
});


text:
Q: Tool support for the study of automata and grammars I'm studying Formal languages and compilers, and I'm doing a little bit hard to understand everything.
Is there a tool that allows you to create automata and grammars and perform operations on them?
Operations such as: minimize an automaton by automaton grammar, from grammar to automaton, make an epsilon-free grammar, etc.
Thank you very much

A: The Prolog-based Finite State Automata Utilities mentionned by rici seem a bit outdated and the online demo does not work, but it seems that there is some available precompiled binaries.
I used to make some experimentations with JFLAP a more recent Java based tool that is still maintained.
(BTW, asking for tools is off-topic on SO, as it is not an implementation question.)

A: Take a look at L-FLAT, a Logtalk Toolkit for Formal Languages and Automata Theory. You can run it most Prolog compilers:
https://code.google.com/p/lflat/
It includes several examples of defining and operating on automata. There's also a paper about the system that you can download from:
http://arxiv.org/abs/1112.3783


text:
Q: Convert String to Int on AWS DocumentDB I am currently trying to write a metabase question off AWS Document DB and I am running into an issue where I need to convert a string to an integer.  Unfortunately, it seems like aws documentdb does not support $toInt and I am not sure how to get around it.  Here is the query:
[
    {"$match": {
        "metaData.fileSize" : {"$exists": true}
    }},
    {"$project": {
        "file_size" : "$metaData.fileSize",
        "timestamp": 1,
        "past7Days":
        { "$subtract":
                [ ISODate(), 604800000]
        }
    }},
    {"$project": {
        "file_size" : 1,
        "timestamp": 1,
        "dayofweek": {"$dayOfWeek":["$timestamp"]},
        "past7DaysComp":
        { "$subtract":
                [ "$timestamp", "$past7Days"]
        }
    }},
    {"$group" :
            {
                "_id" : {"dayofweek" : "$dayofweek"},
                "size": {"$avg" : "$file_size"}
            }
    }
]

The group returns nothing for size since it is not of a numeric type.  Any ideas how to convert file_size to integer or double or float?


text:
Q: Jquery issue for adding rows from one table to another i have 2 tables, i want to add rows from one table to another, based on the rows selected using checkbox, its adding rows from one table to another table, but its not adding according to rows, but based on cells, here is what i am using:
when the button is clicked, it loops through all the rows which are checked and removes the first cell which is checkbox and adding rest of the cell wrapped in a row to next table, i assume it would wrap the resulting cells into the row, but thats not the case, because when i select multiple rows, it appends directly at the end of last rows last cell.
$("#btnAddStories").click(function () {
            $checkedStories = $("#dnn_TopStories_grdTopStoriesSearch input[type=checkbox]:checked");
            $.each($checkedStories, function (index, item) {
                $row = $(this).closest("tr").clone().find("td:not('.firstCell')").remove();
                $('#tblTopstories tbody').append($row);
            });
        });

A: Changing answer completely as my previous answer didn't actually answer your question!
the problem is that when you set $row, you're only calling the cells from that row, this happens when you do the .find()
in order to make it work properly, you'd need to change your append to this:
$('#tblTopstories tbody').append($('
', {html: $row});

What that does is it creates a

 and sets the html content to the content of the $row
For clarity of your code, I'd change the name of $row to $cells but that's just personal preference.
Also, potential problems arise when you click the #btnAddStories element, so I would change the .click() to .on('click') and add an .off('click') to the start to prevent ghost clicks. (sometimes the event will fire once on your first click, twice on your second etc, calling .off() before an event is assigned prevents the event handler from being applied multiple times, [this usually when the event handler is assigned inside a function])
$("#btnAddStories").off('click').on('click', function(){
  ...
})


text:
Q: Complex Integral Question I'm trying to evaluate the following integral, in preparation for my exam tomorrow;
$$\int_{0}^{\infty} \frac{\cos(2x) - 1}{x^2} dx$$
However, I'm having a lot of issues with it. I was initially trying an argument involving $e^{2iz}$, but I can't seem to work in that constant.
I know that the contour I should be evaluating is going to be a half annulus, as the singularity occurs at $x = 0$, but I'm really just not sure what I'm aiming for here.
Anything to start me off would be fantastic, thank you!!

A: There are of course many ways to evaluate the integral. If we're using $e^{2iz}$ and the boundary of a half-annulus as the contour, we should use the parity of the integrand and start with
$$\begin{align}
\int_0^\infty \frac{\cos (2x)-1}{x^2}\,dx &= \frac{1}{2} \int_{-\infty}^\infty \frac{\cos (2x)-1}{x^2}\,dx\\
&= \frac{1}{2}\lim_{\substack{\varepsilon\to 0\\ R\to\infty}} \left(\int_{-R}^{-\varepsilon}\frac{\cos (2x)-1}{x^2}\,dx + \int_\varepsilon^R \frac{\cos (2x) - 1}{x^2}\,dx\right)\\
&= \frac{1}{2}\lim_{\substack{\varepsilon\to 0\\ R\to\infty}} \left(\int_{-R}^{-\varepsilon}\frac{e^{2ix}-1}{x^2}\,dx + \int_\varepsilon^R \frac{e^{2ix} - 1}{x^2}\,dx\right),
\end{align}$$
where the last equality is due to the oddness of $\sin$. Now writing $s_r$ for the semicircle of radius $r$, $s_r(t) = re^{it}, 0\leqslant t \leqslant \pi$, Cauchy's integral theorem says
$$\int_{-R}^{-\varepsilon}\frac{e^{2iz}-1}{z^2}\,dz + \int_{\varepsilon}^R \frac{e^{2iz}-1}{z^2}\,dz + \int_{S_R}\frac{e^{2iz}-1}{z^2}\,dz - \int_{s_\varepsilon}\frac{e^{2iz}-1}{z^2}\,dz = 0.$$
In the upper half-plane, we have $\lvert e^{2iz}\rvert = e^{-2\operatorname{Im} z} \leqslant 1$, so $\left\lvert \frac{e^{2iz}-1}{z^2}\right\rvert \leqslant \frac{2}{R^2}$ on $s_R$, and the integral over $s_R$ tends to $0$ as $R\to \infty$. Therefore
$$\begin{align}
\lim_{\substack{\varepsilon\to 0\\ R\to\infty}} \left(\int_{-R}^{-\varepsilon}\frac{e^{2ix}-1}{x^2}\,dx + \int_\varepsilon^R \frac{e^{2ix} - 1}{x^2}\,dx\right)
&= \lim_{\varepsilon\to 0} \int_{s_\varepsilon} \frac{e^{2iz}-1}{z^2}\,dz - \lim_{R\to\infty} \int_{s_R}\frac{e^{2iz}-1}{z^2}\,dz\\
&= \lim_{\varepsilon\to 0} \int_{s_\varepsilon} \frac{e^{2iz}-1}{z^2}\,dz.
\end{align}$$
Since $\frac{e^{2iz}-1}{z^2}$ has a simple pole in $0$, we have
$$\lim_{\varepsilon\to 0} \int_{s_\varepsilon} \frac{e^{2iz}-1}{z^2}\,dz = \pi i \operatorname{Res}\left(\frac{e^{2iz}-1}{z^2}; 0\right) = \pi i(2i) = -2\pi,$$
as can be read off the Taylor series of $e^{2iz}$. Thus
$$\int_0^\infty \frac{\cos (2x)-1}{x^2}\,dx = -\pi.$$

Another way to evaluate the integral uses the trigonometric identity $\cos (2x) - 1 = - 2\sin^2 x$, which then yields
$$\int_0^\infty \frac{\cos (2x)-1}{x^2}\,dx = -2\int_0^\infty \frac{\sin^2 x}{x^2}\,dx.$$
We can now for example integrate by parts,
$$\begin{align}
\int_0^\infty \frac{\sin^2 x}{x^2}\,dx &= \left[-\frac{\sin^2 x}{x}\right]_0^\infty + \int_0^\infty \frac{2\sin x\cos x}{x}\,dx\\
&= \int_0^\infty \frac{\sin (2x)}{x}\,dx\\
&= \int_0^\infty \frac{\sin t}{t}\,dt, \tag{$t = 2x$}
\end{align}$$
and evaluate that integral also via the residue theorem (or with whatever one's favourite method is).
Instead of integrating by parts, we could also have noted that
$$\int_{-1}^1 e^{-ix\xi}\,d\xi = \left[-\frac{e^{-ix\xi}}{ix}\right]_{-1}^1 = \frac{e^{ix} - e^{-ix}}{ix} = 2\frac{\sin x}{x},$$
so $\frac{\sin x}{x}$ is the Fourier transform of $\sqrt{\frac{\pi}{2}}\cdot \chi_{[-1,1]}$, and Plancherel's theorem together with the parity of the integrand gives us
$$2\int_0^\infty \frac{\sin^2 x}{x^2}\,dx = \int_{-\infty}^\infty \frac{\sin^2 x}{x^2}\,dx = \frac{\pi}{2} \int_{-\infty}^\infty \chi_{[-1,1]}(x)^2\,dx = \pi.$$


text:
Q: Delete ALBUM Facebook Graph API? Hi All does anyone know the correct Graph path for deleting an album? I have tried a bunch of things and nothing seems to work?
/me/aid
/aid
/me/object_id/albums
/me/object_id
/me/albums/object_id
/object_id/album"
/object_id/albums
/object_id

obviously replacing aid and object_id with a valid value...
Is it possible to delete an album through the Graph API? thanks!

A: Umm, as far as I can tell, you simply are not allowed to delete an album through the graph API, regardless of permissions.
This has been true for a while.
Recently (its 1/16/12 when I write this), graph API users can't even delete photos.
Here's the Facebook Bug Link:
https://developers.facebook.com/bugs/125524667559003?browse=search_4f14be86ba58f3666689319
Yes, the FB-built apps appear to have special permissions linked to their App IDs to which you do not have access.  I just noticed, for instance, that the iOS app uploads photos to a temporary album while you are typing in the caption for the photo so the final "upload" wait is perceived to be just a few seconds (it just moves the picture to the mobile uploads album and set the privacy).  Access to anything like a temp album is not available through any API I can see.
Filing a bug report is about all you can do.
I would be happy to have this answer down voted as not correct, but I have spent a reasonable amount of time not just looking at the docs, but watching what the iOs app is doing through a proxy server and trying to recreate it.

A: From Facebook's documentation:

You can delete objects in the graph by issuing HTTP DELETE requests to the object URLs, i.e,
DELETE https://graph.facebook.com/ID?access_token=... HTTP/1.1
To support clients that do not support all HTTP methods (like JavaScript clients), you can alternatively issue a POST request to an object URL with the additional argument method=delete to override the HTTP method. For example, you can delete a comment by issuing a POST request to https://graph.facebook.com/COMMENT_ID?method=delete.
You can delete a like by issuing a DELETE request to /POST_ID/likes (since likes don't have an ID).

So the last one of your paths is the correct one '/object_id'. You need to make sure you are either sending your HTTP request as a "DELETE" or as a "POST" with the query parameter method=delete set. For example:
DELETE https://graph.facebook.com/ID?access_token=
or
POST https://graph.facebook.com/ID?method=delete&access_token=
If neither of those work, make sure you have the correct extended permission. I believe the permission you need to delete an album is 'publish_stream'. I have never done it before so I could be wrong on that one.
If you are using the Facebook C# SDK you would do it like this:
var client = new FacebookClient('access_token');
dynamic result = client.Delete('object_id');

A: I think you could read the ID of a certain album by /me/albums/ and after that run the delete on https://graph.facebook.com/ID
On my try it worked just fine...

A: To delete objects via the AS3 Facebook API, use the deleteObject(method,callback) function of the Facebook object.


text:
Q: Link Multiple Gmails iOS Firebase How would I go about linking multiple gmail accounts to 1 auth account? I'm currently using Firebase and it seems like it only lets you link 1 account per provider. Is there any other way to do this without Firebase?

A: This cannot be achieved using Firebase Authentication.
Link Multiple Auth Providers to an Account on iOS
As the name suggests only multiple Auth providers (Email/Password, PhoneNumber, Facebook, Google, github) can be linked with one another but not with each other.
There can be no linking if the providers are the same.


text:
Q: interpolate a terrain surface from scattered data using heat equation This is my first question in this forum, so please bear with me and I hope I'm not violating any rules. I am looking at different ways to model scattered 3d data as a gridded function (over xy support, z=z(x,y)).
Answering another question, coryan was so nice as to mention the method using heat equation to interpolate (approximate) a terrain surface which I've heard about and been eager to learn, or even find a parallel implementation? Could please coryan or anybody else point me to such an implementation, if it's in public domain, or at least to explain a bit further how it is done.

A: Not sure about heat eqautions, but the way that I solve this problem is via TIN modelling.  Check out Herbert Edelsbrunners book on the topic, Geometry and Topology for Mesh Generation.  I would have it down as a must read.  Also well worthwhile is Joeseph O'Rourkes Computational Geometry in C which while more general does include worked examples and makes a useful cookbook.
In terms of open source, check the following Code Guru link and have a look at Paul Bourkes work.

A: Well, the Wikipedia article he pointed to is a good start.  Think about putting an ice cube in a glass of hot tea: the first instant, the gradient between them is steep:

     +-----
     |
-----+

but heat crosses the gradient in proportion to the gradient, so it starts changing quickly, and then changes more slowly over time.  (That's why it's a parabolic partial differential equation; the rate of change is changing, so you have ∂²t in there.)  So you evaluate the points, adjusting the terrain at each step, to smooth the process.  Doing it in parallel is simply that you can hand each grid point and its adjacent values to a separate process for each step; it doesn't depend on anything else.


text:
Q: How to use matchedGeometryEffect and view scaling I'm trying to make animation when I tap on view it becomes full screen and when I drag down view it scales down and returns to its previous state. I use matchedGeometryEffect with two views and change destination view frame with DragGesture, transition to source view works «unexpectedly». How to fix it or how to make this animation correct? If I don't change destination view frame it works as I expect (click button). GIF here: https://i.stack.imgur.com/yXsjF.gif
struct Test4: View {

    @Namespace var animation

    @State private var show = false
    @State private var scale: CGFloat = 1

    var body: some View {
        ZStack(alignment: .topTrailing) {
            if show {
                ScrollView {

                    Color.gray
                        .border(Color.black, width: 30)
                        .matchedGeometryEffect(id: "animation", in: animation)
                        .frame(
                            width: UIScreen.main.bounds.width * scale,
                            height: UIScreen.main.bounds.height * scale)
                        .gesture(
                            DragGesture(minimumDistance: 0)
                                .onChanged(onChanged)
                                .onEnded(onEnded)
                        )
                }
                 .ignoresSafeArea()

                Button("go back") {
                    withAnimation(Animation.easeInOut(duration: 1)) {
                        self.show.toggle()
                    }
                }
            } else {
                VStack {

                    Color.gray
                        .border(Color.black, width: 30)
                        .matchedGeometryEffect(id: "animation", in: animation)
                        .frame(width: 200, height: 200)
                        .onTapGesture {
                            withAnimation {
                                self.scale = 1
                                show.toggle()
                            }
                    }
                }
            }
        }
    }

    func onChanged(value: DragGesture.Value) {
        withAnimation(Animation.easeInOut(duration: 3)) {
            let currentScale = value.translation.height / UIScreen.main.bounds.height

            if currentScale <= 0 {
                return
            }

            let newScale = 1 - currentScale

            if newScale > 0.85 {
                self.scale = newScale

            } else if newScale < 0.85 {
                self.show = false
            }
        }
    }

    func onEnded(value: DragGesture.Value) {
        withAnimation(Animation.easeInOut(duration: 3)) {

            if self.scale < 0.85 {
                self.show = false
            }
        }
    }
}

struct Test4_Previews: PreviewProvider {
    static var previews: some View {
        Test4()
    }
}

A: The thing that you are trying get is possible without matchedGeometryEffect, here is a simple approach:

import SwiftUI

struct ContentView: View {
    var body: some View {

        ScaleView()

    }
}

struct ScaleView: View {

    @State private var translation: CGFloat = CGFloat()
    @State private var lastTranslation: CGFloat = CGFloat()

    var body: some View {

        GeometryReader { geometry in

            Color.black

            ZStack {

                Color
                    .gray

                Image(systemName: "arrow.triangle.2.circlepath.circle")
                    .font(Font.largeTitle)
                    .onTapGesture {

                        if lastTranslation == 400.0 {

                            lastTranslation = 0.0
                            translation = lastTranslation
                        }
                        else {

                            lastTranslation = 400.0
                            translation = lastTranslation
                        }
                    }

            }
            .position(x: geometry.size.width/2, y: geometry.size.height/2)
            .cornerRadius(30)
            .scaleEffect(1.0 - translation/(geometry.size.width > geometry.size.height ? geometry.size.width : geometry.size.height))
            .gesture(DragGesture(minimumDistance: 0.0).onChanged(onChanged).onEnded(onEnded))

        }
        .ignoresSafeArea()
        .animation(.easeInOut(duration: 0.35))
        .statusBar(hidden: true)

    }

    func onChanged(value: DragGesture.Value) { translation = lastTranslation + value.translation.height }

    func onEnded(value: DragGesture.Value) {

        if value.translation.height > 0.0 {

            lastTranslation = 400.0
            translation = lastTranslation
        }
        else {

            lastTranslation = 0.0
            translation = lastTranslation
        }

    }
}


text:
Q: Pass a file as an argument in Linux I have a python script which take's a file as an argument via sys.argv.
What is the best way for passing this file as an argument in Linux?
I have tried adding this line of code on the 1st line of my python script, thinking that this would enable me to drag and drop files onto it, but this does not seem to work.
#!/usr/bin/env python

Is there something I am missing? Cheers

A: This is a pretty basic example that takes the first argument (sys.argv[1]), which we will assume is a filename, opens it, and prints all of the lines.
import sys

f = open(sys.argv[1])
lines = f.readlines()

for line in lines:
    print line

f.close()

You would call this file by entering python
<source_file.py> <filename>

If my source file was called readMyFile.py and I wanted to read myFile.txt, I would type
python readMyFile.py myFile.txt

python system
As for accomplishing the drag and drop, you could always put the Python call into a bash script and then pass the argument from the bash script to the python script. Take a look at this stack overflow thread about this. Essentially, you would just make a bash script with this code in it.
#!/bin/bash
python <source_file.py> "$1"

or in my specific example...
#!/bin/bash
python readMyFile.py "$1"

It looks like you might have to accompany some of the above syntax with some code in a .desktop file. Check out this askubuntu link

A: Try using python script.py filename
The line #!/usr/bin/env python is the shebang line.
If you make your script an executable one (that is, change it's file permission to executable using chmod), the shebang helps identify the type of script.
An alternate shebang would be to use the path for python binary directly like #!/usr/bin/python, but the path may differ on different machines and hence we normally get the path for the bindary from the env.
The shebang is not normally required if you are ok running the script everytime with python script.py, but if the script is referenced elsewhere, it might cause issues. I add a shebang to all my scripts just to be sure what script it is from within my editor.
Note that the the extension .py is entirely optional, and for sake of generality, you might want to run ./script in bigger projects to achieve a task; this modularity ensures that the executable script can be in python, bash, or any other scripting language as long as it does what its supposed to do.
No, you can't drag and drop a file and pass it as a param to the python script even if it is an executable one.


text:
Q: how to return all the rows if I filter a column by a NULL value, instead of returning nothing Somebody knows how to return all the rows if I filter a column by a NULL value, instead of returning nothing?
ps. I'm using python
my code:
x = ''

conn = psycopg2.connect(dsn)
cur = conn.cursor()

cur.execute("SELECT column_1 FROM table_1 WHERE column_1 = '" + x + "'")

the code now return nothing..
Thanks

A: I don't use python but try something like this
...
 if (x==""): whereString=""
  else:
     whereString="where column_1='"+ x+"'"

     cur.execute("SELECT column_1 FROM table_1 "+whereString)
 ...


text:
Q: story id - werewolf biochemist vs alien invasion I am looking for the name of a science-fiction novel published no later than August 1992. The main character is a very long-lived (centuries) werewolf who is a biochemist. He conceals this by assuming a new identity every few decades. The aliens who conquered Earth are the only ones who can survive FTL without going into suspended animation.
The protagonist is found out by the aliens when he is being interrogated in a room. The aliens give him a list of the names he has used in previous lives and catch him out by slowly turning down the light to a level where normal humans couldn't read. The protagonist doesn't realize the lights are too low until after he denies knowing anything about the names on the list. The novel ends with him sneaking aboard an alien spacecraft and escaping to another world.

A: I was just looking for the same book, and then after reading your summary, it hit me.
I'm going to say The Madness Season by C.S. Friedman.

*

*Protagonist is a human shape shifter (albeit a vampire).

*Aliens are reptilian and share a single hive mind across the whole species. This is what allows them to endure FTL. They have conquered earth and taken humans to the stars as servants. Also many other alien races.

*Their one vulnerability is periodically one may become disconnected from the hIve consciousness and experience individualiy, temporarily. Such individuals are tolerated by the hive mind but are considered "mad", hence the title.

*The protagonist encounters one in this state and it goes from there, no spoilers please.


text:
Q: Starting my app as administrator while using the  Tag in the app.config file I need to use the <linkedConfiguration> element in my app.config, but at the same time I want to start my app as an administrator, what I could solve with the <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> element in the app.manifest.
The result of this is the following error:

Activation context generation failed for "C:\XYZ.exe".Error in
manifest or policy file "C:\XYZ.exe.Config" on line 3. The element
assemblyBinding appears as a child of element configuration which is
not supported by this version of Windows.

As it's stated here: https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/linkedconfiguration-element in the Note, it's not supported:

The <linkedConfiguration> element is not supported for applications
with Windows side-by-side manifests.

Is there any other way to force my app to start in elevated mode?
(All my search results refer to app.manifest)


text:
Q: Postgres incremental backups per db (not per cluster) According to the WAL Point-in-time recovery and incremental backup documentation, pg_basebackup and wals are used to take backups and incremental backups of a running PostgreSQL cluster.
Is there a way to take incremental backups per database instead of the whole cluster ?
Thanks !


text:
Q: How we use LTBouncytextfield library in iOS? Hello I am new on  Stack overflow. Can you tell me how to use LTBouncyTextField library for animating the right placeholder of the text field.
My code is
class SignUpViewController: UIViewController {

@IBOutlet weak var registrationView: UIView!
@IBOutlet weak var Username: LTBouncyTextField!
@IBOutlet weak var Email: LTBouncyTextField!
@IBOutlet weak var Password: LTBouncyTextField!
@IBOutlet weak var ConformPass: LTBouncyTextField!

override func viewDidLoad() {
    super.viewDidLoad()
    registrationView.layer.borderWidth = 1
    registrationView.layer.borderColor = UIColor.blackColor().CGColor
    Username.abbreviatedPlaceholder = " username"
    Username.alwaysBouncePlaceholder = true
    Email.abbreviatedPlaceholder = "email"
    Email.alwaysBouncePlaceholder = true
    Password.abbreviatedPlaceholder = "password"
    Password.alwaysBouncePlaceholder = true
    ConformPass.abbreviatedPlaceholder = "confirmpass"
    ConformPass.alwaysBouncePlaceholder = true
 }

A: It is simple. Just drag and drop the UITextField+LTBouncyPlaceholder.swift into your project. Select it as the class of textField. Add attributes and it should work.


text:
Q: How to Build New simple model in OpenERP7 I am new to OpenERP I want to start develop new model
But I am using OpenERP 7  the the documentation for it is less I find more examples for OpenERP 6
If anyone can help please , if the is like for this topic?

A: Following links will help you:

*

*OpenERP-7 Documentation

*How to Develop New Module


text:
Q: meld -- How to refresh display when you have changed one of the files I'm using Meld 1.8.5.
http://meldmerge.org/
I use gedit to change a file without meld's knowledge.  I like to re-do the comparison.  What is the easiest way of doing the refresh.  The refresh didn't do the re-comparison.
Robert

A: So for newer version of Meld, File/Revert does the requested refresh.

A: In Meld's View menu, you can try Refresh (Ctrl+R), but also Reload (Shift+Ctrl+R) to reload the files themselves. Depending on the changes, you may want to try the Reload option. Also, be sure to have gedit make a save to disk in order for Meld to see the change of file contents.


text:
Q: Processing dialog for SharePoint 2013 remote event receiver -Item Added event Is it possible to have a dialog, "Waiting for the Item to be added" for SharePoint 2013 custom list to which a remote event receiver is attached (Provider hosted app with App installed event), having an ItemAdded event. If an item is added, now the list add item page is seen as stuck, instead a user friendly dialog "Please wait for the item to be added" need to be displayed.
Any advice.

A: Try this one :)
// BEGIN long-running operation
SPLongOperation lop = new SPLongOperation(this.Page);
lop.LeadingHTML = "

Your enormous file is being uploaded...

";
lop.TrailingHTML = "

Please be patient

";
lop.Begin();

// your long operation code here

// END long-running operation
lop.End(spTargetListObject.DefaultViewUrl, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

Here'a a helpful blog about it http://howtosharepoint.blogspot.com/2010/04/how-to-programatically-show-processing.html


text:
Q: Validity of Ising model for mean field thoery The Heisenberg model for the Hamiltonian of a ferromagnet is given by:
$$H=-\frac{J}{2} \sum \vec{S}_i\cdot \vec{S}_j+\mu_B B \sum_i S^z_i$$
when performing mean field theory, to find $\chi$, we assume that the Ising model holds, i.e. take a Hamiltonian to be:
$$H=-\frac{J}{2} \sum S^z_i S^z_j+\mu_B B \sum_i S^z_i$$
My question is why when using mean field theory is it applicable to use the Ising model?


text: Q: making list of list of a row while parsing the file making list of list of a row while parsing the file  Apart from the first field, all the other fields are either numbers (so converted using float(), or empty, which can be translated to the Python object None


text:
Q: Create a url file with multiple links i need to edit the page number of multiple url links in the text file.
eg:
http://gk4success.com/questions.php?page=1&parent=0&lang=2&c-id=27&q_type=
...
http://gk4success.com/questions.php?page=162&parent=0&lang=2&c-id=27&q_type=
There are 162 links in the web site and i cannot edit links 162 times,even if i copy the lines 162 times,then how do i edit the page numbers easily ? is there any easy way with any text editor ?

A: sed 's/page=1\&/page=162\&' /path/to/lotsofurls.txt > /path/to/fixedurls.txt

A: You can generate the list
in pure shell:
for i in {1..162} ; do echo "http://gk4success.com/questions.php?page=$i&parent=0&lang=2&c-id=27&q_type=" ; done

in vim:
for i in range(1,162)| put ='http://gk4success.com/questions.php?page='.i.'parent=0lang=2c-id=27q_type=' | endfor


text:
Q: How to count the number of combinations of boolean data in R What is the best way to determine a factor or create a new category field based on a number of boolean fields? In this example, I need to count the number of unique combinations of medications.
   > MultPsychMeds
       ID OLANZAPINE HALOPERIDOL QUETIAPINE RISPERIDONE
    1   A          1           1          0           0
    2   B          1           0          1           0
    3   C          1           0          1           0
    4   D          1           0          1           0
    5   E          1           0          0           1
    6   F          1           0          0           1
    7   G          1           0          0           1
    8   H          1           0          0           1
    9   I          0           1          1           0
    10  J          0           1          1           0

Perhaps another way to state it is that I need to pivot or cross tabulate the pairs. The final results need to look something like:
Combination            Count
OLANZAPINE/HALOPERIDOL     1
OLANZAPINE/QUETIAPINE      3
OLANZAPINE/RISPERIDONE     4
HALOPERIDOL/QUETIAPINE     2

This data frame can be replicated in R with:
MultPsychMeds <- structure(list(ID = structure(1:10, .Label = c("A", "B", "C",
"D", "E", "F", "G", "H", "I", "J"), class = "factor"), OLANZAPINE = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L), HALOPERIDOL = c(1L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L), QUETIAPINE = c(0L, 1L, 1L, 1L,
0L, 0L, 0L, 0L, 1L, 1L), RISPERIDONE = c(0L, 0L, 0L, 0L, 1L,
1L, 1L, 1L, 0L, 0L)), .Names = c("ID", "OLANZAPINE", "HALOPERIDOL",
"QUETIAPINE", "RISPERIDONE"), class = "data.frame", row.names = c(NA,
-10L))

A: Here's one approach using the reshape and plyr packages:
library(reshape)
library(plyr)

#Melt into long format
dat.m <- melt(MultPsychMeds, id.vars = "ID")
#Group at the ID level and paste the drugs together with "/"
out <- ddply(dat.m, "ID", summarize, combos = paste(variable[value == 1], collapse = "/"))

#Calculate a table
with(out, count(combos))

                       x freq
1 HALOPERIDOL/QUETIAPINE    2
2 OLANZAPINE/HALOPERIDOL    1
3  OLANZAPINE/QUETIAPINE    3
4 OLANZAPINE/RISPERIDONE    4

A: Just for fun, a base R solution (that can be turned into a oneliner :-) ):
data.frame(table(apply(MultPsychMeds[,-1], 1, function(currow){
    wc<-which(currow==1)
    paste(colnames(MultPsychMeds)[wc+1], collapse="/")
})))

A: Another way could be:
subset(
    as.data.frame(
        with(MultPsychMeds, table(OLANZAPINE, HALOPERIDOL, QUETIAPINE, RISPERIDONE)),
        responseName="count"
    ),
    count>0
)

which gives
   OLANZAPINE HALOPERIDOL QUETIAPINE RISPERIDONE count
4           1           1          0           0     1
6           1           0          1           0     3
7           0           1          1           0     2
10          1           0          0           1     4

It's not an exact way you want it, but is fast and simple.

There is shorthand in plyr package:
require(plyr)
count(MultPsychMeds, c("OLANZAPINE", "HALOPERIDOL", "QUETIAPINE", "RISPERIDONE"))
#   OLANZAPINE HALOPERIDOL QUETIAPINE RISPERIDONE freq
# 1          0           1          1           0    2
# 2          1           0          0           1    4
# 3          1           0          1           0    3
# 4          1           1          0           0    1


text:
Q: Why is my MacBook getting hotter than usual since some time? Since some time my MacBook is constantly hotter than it used to be, even when not having much CPU load. What could the cause be?
Resetting the System Management Controller (SMC) didn't completely work, I think it has decreased since I reset it but not completely.

A: Sometimes is is good to reset the SMC.
SMC controls the devices on your computer including the fans.
Intel-based Macs: Resetting the System Management Controller (SMC)

A: Don't overlook purely software usage.   If you browse sites with flash content it is not unusual for it put more load on the machine.   you mention "not having much CPU load" which implies that the machine is not totally idle.  Is it while doing absolutely nothing with machine?   Switch to another browser for a while and see if it makes difference.

A: To kill a problem, you have to see it and then understand it.
For this hunt, I advise to start with the Activity Monitor which is here:
Applications/Utilities/Activity Monitor

Look at what is using the CPU when your MacBook is heating and when it is at a normal temperature. Try starting and stoping your actual programs one at a time and let the system take the time to free all the threads involved and the temperature decrease.
The delay between a hog kill and the fan slow down may be bigger than a minute.

A: Try disabling helpers on your browser (like Avast) which might be working too hard. I had this problem, but I disabled security as needed and it stopped right away.


text:
Q: Azure rest API (6.0-preview.1) Run Pipeline returns : "Value cannot be null.\r\nParameter name: runParameters" via postman I try to invoke rest API to azure via postman first, I invoke get pipelines API to get the pipeline id
and the result is: 2
the response :
{
    "count": 1,
    "value": [
        {
            "_links": {
                "self": {
                    "href": "https://dev.azure.com/xxx/5fcd81ac-534e-xxx/_apis/pipelines/2?revision=3"
                },
                "web": {
                    "href": "https://dev.azure.com/xxx/5fcd81ac-534e-xxx/_build/definition?definitionId=2"
                }
            },
            "url": "https://dev.azure.com/xxx/5fcd81ac-534e-xxx/_apis/pipelines/2?revision=3",
            "id": 2,
            "revision": 3,
            "name": "xxx.ios_build_on_azure",
            "folder": "\\"
        }
    ]
}

ok assuming the id is 2 as i have only 1 pipeline there i try to invoke the runs API to start this pipeline and I'm getting this :

{
    "$id": "1",
    "innerException": null,
    "message": "Value cannot be null.\r\nParameter name: runParameters",
    "typeName": "System.ArgumentNullException, mscorlib",
    "typeKey": "ArgumentNullException",
    "errorCode": 0,
    "eventId": 0
}

UPDATE
also if i try to add to the body :
as described in :
Azure REST API for running builds or pipelines
like this :
{
    "resources": {
        "repositories:" {
            "self": {
                "refName": "xxx/ios_build_on_azure"
            }
        }
    }
}

I'm getting :
{
    "$id": "1",
    "innerException": null,
    "message": "TF400898: An Internal Error Occurred. Activity Id: xxxxx-6ff6-4786-bb2e-f12dxxxx.",
    "typeName": "Newtonsoft.Json.JsonReaderException, Newtonsoft.Json",
    "typeKey": "JsonReaderException",
    "errorCode": 0,
    "eventId": 0
}

A: You may try the following content in the body:
{
    "resources": {
        "repositories": {
            "self": {
                "refName": "refs/heads/branchname"
            }
        }
    }
}


text:
Q: how to reinitialize the database I have downloaded a demo copy of Hybris for evaluation purposes, and it has been more than 30 days since I downloaded it, and recently I tried to restart it, but it would not, and instead gave me the following message:
"This licence is only for demo or develop usage and is valid for 30 days.
After this time you have to reinitialize database to continue your work."
I am/have been running it on a Mac, and the database is MySQL...
What (UNIX) commands do I use to re-initialise the database, so that I can start up the Hybris Server?

A: Using command line in the Terminal application - goto YOURPATH/hybris/bin/platform and run the ant clean all then ant initialize command then start hybris:
1) Goto your platform directory
cd $YOURPATH/hybris/bin/platform
2) Set ant's environment by runing "dot" "space" "dot-slash" setantenv.sh
. ./setantenv.sh
3) Then run ant clean all (to clean environment)
ant clean all
4) then run ant initialize (to re-initialize environment)
ant initialize
5) Re-start the hybris server process by running hybrisserver.sh
./hybrisserver.sh
6) have a nice rest of your day!  (if this helped you then please give an UP vote - thanks!)
:)

A: Ant initialize would removes tables that exists in Hybris items.xml files? If you want to reset your DB i have a script that i use across various projects (can be found here, on GitHub)
#!/bin/bash
MUSER="$1"
MPASS="$2"
MDB="$3"

# Detect paths
MYSQL=$(which mysql)
AWK=$(which awk)
GREP=$(which grep)

if [ $# -ne 3 ]
    then
    echo "Usage: $0 {MySQL-User-Name} {MySQL-User-Password} {MySQL-Database-Name}"
    echo "Drops all tables from a MySQL"
    exit 1
fi

TABLES=$($MYSQL -u $MUSER -p$MPASS $MDB -e 'show tables' | $AWK '{ print $1}' | $GREP -v '^Tables' )

for t in $TABLES
do
echo "Deleting $t table from $MDB database..."
$MYSQL -u $MUSER -p$MPASS $MDB -e "drop table $t"
done

A: you can use Ant command ant initialize and error will go away

A: You need to reinitialize, [ant all] and rebuild hybris as you have did in first time:
Reason : Evaluation copy works only for 30 days and after it will be expired.
When you start your server it will show in console like below image. Pls Check.

A: Yo can also use Hybris Administration Console to initialization
Platfrom -> Initialization


text:
Q: Dynamic indexed multidimensional array print in foreach loop and print in table I am having multiple indexed array,here the index changing dynamically.Actually the index of the arrays are id's of group.How can i pass these array in to foreach loop
 Array
(
    [0] => Array
        (
            [462] => Array
                (
                    [0] => Array
                        (
                            [group_name] => First
                            [invoice_no] =>

                        )

                    [1] => Array
                        (
                            [invoice_no] =>
                            [invoice_no] => 2Q

                        )

                )

            [525] => Array
                (
                    [0] => Array
                        (
                            [group_name] => Second
                            [invoice_no] =>

                        )

                    [1] => Array
                        (
                            [group_name] =>
                            [invoice_no] => 3QW

                        )

                )

        )

)

This is my array structure,Please help me to print results using foreach loop in php with out changing array structure
I am trying this code
foreach ($Sale_list_array as $key => $value) {
    echo ($key);

    echo $value[$key][group_name];
}

But,this won't fix my problem. I am hoping output like this in table structure

Group
Invoice

First

	2Q

Second

	3QW

A: try this
$newArray = array();
foreach ($Sale_list_array as $key => $value) {
   $newArray[$key] = $value[$key][group_name];
}
print_r($newArray)

A: Try this code below, $wholeArr is variable which holds your full array value
     foreach( $wholeArr as $group ){
        foreach( $group as $groupKey => $groupValues ){
           foreach( $groupValues as $groupVal ){
             echo $groupVal["group_name"]."
";
           }
         }
       }


text:
Q: How to fix [Error: While query - conversion error from string "pending" ] when trying to insert a new record into firebird database? I've created a table with the following schema:
CREATE TABLE orders (
    id INTEGER NOT NULL PRIMARY KEY,
    status VARCHAR(30) NOT NULL CHECK(status IN('ordered', 'paid', 'pending', 'complete')),
    order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    delivery_id INTEGER,
    client_id INTEGER,
    operator_id INTEGER,
    FOREIGN KEY(delivery_id)
    REFERENCES delivery_info(id) ON DELETE CASCADE,
    FOREIGN KEY(client_id) REFERENCES client(id) ON DELETE CASCADE,
    FOREIGN KEY(operator_id) REFERENCES operator(id)
);

However, when I'm trying to insert new data into the table using a node.js application, I get the following error:
Console output
Generated query looks okay to me:
INSERT INTO orders VALUES (793771, 'pending', '1612387572153', 590931, 3923, 0);

Application code:
class Order {
  static DEFAULT_OPERATOR_ID = 0;

  constructor(id, status, time, delivery, client,
              operatorId = Order.DEFAULT_OPERATOR_ID)
  {
    this.id = id;
    this.status = status;
    this.time = time;
    this.delivery = delivery;
    this.client = client;
    this.operatorId = operatorId
  }

  save() {
    console.log(this);
    const insertQuery = `
        INSERT INTO orders
        VALUES (${this.id}, '${this.status}', '${this.time}', ${this.delivery.id}, ${this.client.id}, ${this.operatorId});
    `;

    console.log(insertQuery);
    dbConnection.query(insertQuery, (error, result) => {
      if (error) throw error;
      console.log('Inserted new order');
    });
  }
}

A: Issue is fixed when I specify the column list during insertion. Thanks, @Mark Rotteveel.


text:
Q: Import compiled cyton file from child directory I am doing some object detection and I am trying to use the darkflow code of the yolo object detection which works correctly as outlined in the Readme. However, to make the programme folder cleaner, I am trying to group all the files and folders of the darkflow program into one parent folder.
When i do this i update all the import fuctions to darkflow.<sub folder> but i get an error when i run the program with the cyton files. Each file in the cython_utils folder has been updated to accommodate the extra parent directory and a recompile after the update as outlined in the Readme. The error is
File "/media/GIT/objdetect/darkflow/net/yolo/test.py", line 7, in <module>
from darkflow.cython_utils.cy_yolo_findboxes import yolo_box_constructor
File "cython_utils/cy_yolo_findboxes.pyx", line 1, in init cython_utils.cy_yolo_findboxes (cy_yolo_findboxes.c:18758)
ImportError: No module named 'cython_utils'

I have tried using relitive paths to find the files, as well as finding the parent directory automatically but neither has worked.
When i compile the cython_utils folder i get some warnings like, (full output posted further below)
Warning: Extension name 'nms' does not match fully qualified name 'cython_utils.nms' of 'nms.pyx'
Compiling nms.pyx because it changed.

How can one add parent folders with cython compiled folders?
This is the first time i have dealt with the cython module and i would have thought it would be just change each modules path location and then recompile.
NOTE: If i comment out the import line and where it is used the code, the programme completes without an error.
For example what i would like.
project/
   -> darkflow/
         -> cfg/
             -> other subfiles
         -> cython_utils/
             -> build/
                 -> temp.linux-x86_64-3.5/
                     -> cy_yolo2_findboxes.o
                     -> cy_yolo_findboxes.o
                     -> nms.o
             -> cy_yolo_findboxes.c
             -> cy_yolo_findboxes.pyx
             -> other files
         -> dark/
             -> other subfiles
             .
             .
             .
   -> main.py

What works.
project/
     -> cfg/
         -> other subfiles
     -> cython_utils/
         -> build/
             -> temp.linux-x86_64-3.5/
                 -> cy_yolo2_findboxes.o
                 -> cy_yolo_findboxes.o
                 -> nms.o
             -> cy_yolo_findboxes.c
             -> other files
         -> dark/
             .
             .
             .
     -> main.py

compiling cython
python3 setup.py build_ext --inplace
Warning: Extension name 'nms' does not match fully qualified name 'cython_utils.nms' of 'nms.pyx'
Compiling nms.pyx because it changed.
[1/1] Cythonizing nms.pyx
running build_ext
building 'nms' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c nms.c -o build/temp.linux-x86_64-3.5/nms.o
In file included from /usr/include/python3.5m/numpy/ndarraytypes.h:1777:0,
                 from /usr/include/python3.5m/numpy/ndarrayobject.h:18,
                 from /usr/include/python3.5m/numpy/arrayobject.h:4,
                 from nms.c:447:
/usr/include/python3.5m/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
 #warning "Using deprecated NumPy API, disable it by " \
  ^
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5/nms.o -lm -o /media/GIT/objdetect/darkflow/cython_utils/nms.cpython-35m-x86_64-linux-gnu.so
Warning: Extension name 'cy_yolo2_findboxes' does not match fully qualified name 'cython_utils.cy_yolo2_findboxes' of 'cy_yolo2_findboxes.pyx'
Compiling cy_yolo2_findboxes.pyx because it changed.
[1/1] Cythonizing cy_yolo2_findboxes.pyx
running build_ext
building 'cy_yolo2_findboxes' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c cy_yolo2_findboxes.c -o build/temp.linux-x86_64-3.5/cy_yolo2_findboxes.o
In file included from /usr/include/python3.5m/numpy/ndarraytypes.h:1777:0,
                 from /usr/include/python3.5m/numpy/ndarrayobject.h:18,
                 from /usr/include/python3.5m/numpy/arrayobject.h:4,
                 from cy_yolo2_findboxes.c:447:
/usr/include/python3.5m/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
 #warning "Using deprecated NumPy API, disable it by " \
  ^
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5/cy_yolo2_findboxes.o -lm -o /media/GIT/objdetect/darkflow/cython_utils/cy_yolo2_findboxes.cpython-35m-x86_64-linux-gnu.so
Warning: Extension name 'cy_yolo_findboxes' does not match fully qualified name 'cython_utils.cy_yolo_findboxes' of 'cy_yolo_findboxes.pyx'
Compiling cy_yolo_findboxes.pyx because it changed.
[1/1] Cythonizing cy_yolo_findboxes.pyx
running build_ext
building 'cy_yolo_findboxes' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c cy_yolo_findboxes.c -o build/temp.linux-x86_64-3.5/cy_yolo_findboxes.o
In file included from /usr/include/python3.5m/numpy/ndarraytypes.h:1777:0,
                 from /usr/include/python3.5m/numpy/ndarrayobject.h:18,
                 from /usr/include/python3.5m/numpy/arrayobject.h:4,
                 from cy_yolo_findboxes.c:447:
/usr/include/python3.5m/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
 #warning "Using deprecated NumPy API, disable it by " \
  ^
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5/cy_yolo_findboxes.o -lm -o /media/GIT/objdetect/darkflow/cython_utils/cy_yolo_findboxes.cpython-35m-x86_64-linux-gnu.so

Code
The original cython_utils folder contained
cy_yolo2_findboxes.pyx, cy_yolo2_findboxes.pyx, nms.pxd, nms.pyx, setup.py
darkflow/net/yolo/test.py
from darkflow.utils.im_transform import imcv2_recolor, imcv2_affine_trans
from darkflow.utils.box import BoundBox, box_iou, prob_compare
import numpy as np
import cv2
import os
from darkflow.cython_utils.cy_yolo_findboxes import yolo_box_constructor  # Error on this line

darkflow/cython_utils/cy_yolo_findboxes.pyx
import numpy as np
cimport numpy as np
cimport cython
ctypedef np.float_t DTYPE_t
from libc.math cimport exp
import os, sys
from darkflow.utils.box import BoundBox
from nms cimport NMS

@cython.cdivision(True)
@cython.boundscheck(False) # turn off bounds-checking for entire function
@cython.wraparound(False)  # turn off negative index wrapping for entire function
def yolo_box_constructor(meta,np.ndarray[float] net_out, float threshold):

    cdef:
        float sqrt
        int C,B,S
        int SS,prob_size,conf_size
        int grid, b
        int class_loop

    sqrt =  meta['sqrt'] + 1
    C, B, S = meta['classes'], meta['num'], meta['side']
    boxes = []
    SS        =  S * S # number of grid cells
    prob_size = SS * C # class probabilities
    conf_size = SS * B # confidences for each grid cell

    cdef:
        float [:,::1] probs =  np.ascontiguousarray(net_out[0 : prob_size]).reshape([SS,C])
        float [:,::1] confs =  np.ascontiguousarray(net_out[prob_size : (prob_size + conf_size)]).reshape([SS,B])
        float [: , : ,::1] coords =  np.ascontiguousarray(net_out[(prob_size + conf_size) : ]).reshape([SS, B, 4])
        float [:,:,::1] final_probs = np.zeros([SS,B,C],dtype=np.float32)

    for grid in range(SS):
        for b in range(B):
            coords[grid, b, 0] = (coords[grid, b, 0] + grid %  S) / S
            coords[grid, b, 1] = (coords[grid, b, 1] + grid // S) / S
            coords[grid, b, 2] =  coords[grid, b, 2] ** sqrt
            coords[grid, b, 3] =  coords[grid, b, 3] ** sqrt
            for class_loop in range(C):
                probs[grid, class_loop] = probs[grid, class_loop] * confs[grid, b]
                #print("PROBS",probs[grid,class_loop])
                if(probs[grid,class_loop] > threshold ):
                    final_probs[grid, b, class_loop] = probs[grid, class_loop]

    return NMS(np.ascontiguousarray(final_probs).reshape(SS*B, C) , np.ascontiguousarray(coords).reshape(SS*B, 4))

darkflow/cython_utils/nms.pxd
import numpy as np
cimport numpy as np
cimport cython
ctypedef np.float_t DTYPE_t
from libc.math cimport exp
from darkflow.utils.box import BoundBox

cdef NMS(float[:, ::1] , float[:, ::1] )

darkflow/cython_utils/nms.pyx
import numpy as np
cimport numpy as np
cimport cython
from libc.math cimport exp
from darkflow.utils.box import BoundBox

darkflow/cython_utils/setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
import os

if os.name =='nt' :

    ext_modules=[
        Extension("nms",
                sources=["nms.pyx"],
                #libraries=["m"] # Unix-like specific
                    include_dirs=[numpy.get_include()]
        )
    ]

    ext_modules_yolo2=[
        Extension("cy_yolo2_findboxes",
                  sources=["cy_yolo2_findboxes.pyx"],
                  #libraries=["m"] # Unix-like specific
                  include_dirs=[numpy.get_include()]
        )
    ]

    ext_modules_yolo=[
        Extension("cy_yolo_findboxes",
                  sources=["cy_yolo_findboxes.pyx"],
                  #libraries=["m"] # Unix-like specific
                  include_dirs=[numpy.get_include()]
        )
    ]

else :

    ext_modules=[
        Extension("nms",
                sources=["nms.pyx"],
                libraries=["m"] # Unix-like specific
        )
    ]

    ext_modules_yolo2=[
        Extension("cy_yolo2_findboxes",
                  sources=["cy_yolo2_findboxes.pyx"],
                  libraries=["m"] # Unix-like specific
        )
    ]

    ext_modules_yolo=[
        Extension("cy_yolo_findboxes",
                  sources=["cy_yolo_findboxes.pyx"],
                  libraries=["m"] # Unix-like specific
        )
    ]

setup(

    #name= 'cy_findboxes',
    ext_modules = cythonize(ext_modules),
)

setup(

    #name= 'cy_findboxes',
    ext_modules = cythonize(ext_modules_yolo2),
)

setup(

    #name= 'cy_findboxes',
    ext_modules = cythonize(ext_modules_yolo),


text:
Q: Stream run-time generated gzip file with proc_open I'm trying to stream a tar.gz without buffering anything in memory or saving data do disk. I need to gzip a bunch of PDF files (~100kb per file).
Everything seems to work fine if small 10-20 bytes text files are sent through the script and the user downloads a readable tar.gz file, but when sending real data (run-time generated PDF files) the script blocks and stops
Below is a snippet of the code. Why is the script blocking when writing to stdin after a couple of iterations of the loop? It stops at this point waiting for something
Every step is logged to a file to see the message before writing to stdin is the last logged message
$proc = proc_open('gzip - -c', [
    0   => ['pipe', 'r'],
    1   => ['pipe', 'w'],
    2   => ['pipe', 'w']
], $pipes);

stream_set_read_buffer($pipes[1], 0);
stream_set_read_buffer($pipes[2], 0);

stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);

while(true){
    log_step('file stream');
    // fetching data from database and generating PDF file as tar stream (string)

    log_step('stdin: '.strlen($tar_string));
    fwrite($pipes[0], $tar_string); // <--- in the second iteration the script blocks/stops here!
    log_step('stdin done!');

    if($output = stream_get_contents($pipes[1])){
        log_step('output: '.strlen($output));
        echo $output;
    }
}

Output log file
2021-01-26 10:28:29 file stream
2021-01-26 10:28:29 stdin: 116224
2021-01-26 10:28:29 stdin done!
2021-01-26 10:28:29 output: 32768
2021-01-26 10:28:29 file stream
2021-01-26 10:28:29 stdin: 116736

full code
$proc = proc_open('gzip - -c', [
    0   => ['pipe', 'r'],
    1   => ['pipe', 'w'],
    2   => ['pipe', 'w']
], $pipes);
stream_set_read_buffer($pipes[1], 0);
stream_set_read_buffer($pipes[2], 0);
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);

//  get data from database
while($row = $result->fetch()){
    //  generate PDF

    $filename = $pdf['name'];
    $filesize = strlen($pdf['data']);

    $header = pack(
        'a100a8a8a8a12A12a8a1a100a255',
        $filename,
        sprintf('%6s ',     ''),
        sprintf('%6s ',     ''),
        sprintf('%6s ',     ''),
        sprintf('%11s ',    $filesize),
        sprintf('%11s',     ''),
        sprintf('%8s ',     ' '),
        0,
        '',
        ''
    );

    $checksum = 0;
    for($i=0; $i<512; $i++){
        $checksum += ord($header{$i});
    }

    $checksum_data = pack(
        'a8',
        sprintf('%6s ',     decoct($checksum))
    );

    for($i=0, $j=148; $i<8; $i++, $j++){
        $header{$j} = $checksum_data{$i};
    }

    fwrite($pipes[0], $header.$pdf['data'].pack(
        'a'.(512 * ceil($filesize / 512) - $filesize),
        ''
    ));

    if($output = stream_get_contents($pipes[1])){
        echo $output;
    }
}

fwrite($pipes[0], pack('a512', ''));
fclose($pipes[0]);

while(true){
    if($output = stream_get_contents($pipes[1])){
        echo $output;
    }

    if(!proc_get_status($proc)['running']){
        foreach($pipes as $pipe){
            if(is_resource($pipe)){
                fclose($pipe);
            }
        }
        proc_close($proc);

        break;
    }
}

A: The reason your script doesn't progress is that it is attempting to write more data into the pipe than the gzip process is able to handle at once. The situation looks roughly like this:

*Your script writes 116736 bytes into the pipe.

*The gzip process reads some of it from its standard input, compresses it, and outputs compressed data on its standard output.

*The PHP process is blocked until the gzip process reads the rest of the input it wrote to the pipe.

*The gzip process is blocked until the PHP process reads the compressed output it wrote to standard output.

And so your script finds itself in a deadlock.
The root of the problem is that unlike its namesake in C, the PHP fwrite function in blocking mode will always attempt to write the entirety of the buffer to the stream until everything is written. This can be worked around by enabling non-blocking mode on the standard input pipe as well, and monitoring how much input has been actually written. For example like this:
$proc = proc_open('gzip -c -', [
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
], $pipes);

stream_set_read_buffer($pipes[1], 0);

stream_set_blocking($pipes[0], false);
stream_set_blocking($pipes[1], false);

$tar_string = '';
for (;;) {
    if ($tar_string === '') {
        if (/* more input available */)
            $tar_string = /* read more input */;
        else {
            $tar_string = null;
            \fclose($pipes[0]);
        }
    }

    if ($tar_string !== null) {
        $written = \fwrite($pipes[0], $tar_string);
        if ($written === false)
            throw new \Exception('write error');
        $tar_string = \substr($tar_string, $written);
    }

    /* THIS IS JUST SOME DUMB DEMONSTRATIVE CODE, DO NOT COPY-PASTE */

    for (;;) {
        $outbuf = \fread($pipes[1], 69420);
        if ($outbuf === false)
            throw new \Exception('read error');
        if ($outbuf === '')
            break;
        $outlen = \strlen($outbuf);
        echo $outbuf;
    }

    if (\feof($pipes[1]))
        break;
}

The above will superficially work. A big downside is that it is going to perform extremely poorly: when the gzip process is ready neither to read or write any data, the script is going to keep busy-looping uselessly and take away CPU time from the gzip process which actually needs it.
In a saner programming language, you would have access to:

*

*calls such as poll or select, which are able to signal when a stream is ready to be read from or written into, and otherwise give up CPU time to other processes which may need it;

*I/O primitives that can return immediately upon a successful partial read or write, instead of trying to process the entire size of the buffer.

But this is PHP, so we can't have nice things. At least not built in.
There is, however, a much better solution for this problem that avoids proc_open entirely, and instead implements gzip compression using the zlib extension, like this:
$zctx = \deflate_init(ZLIB_ENCODING_GZIP);
if ($zctx === false)
    throw new \Exception('deflate_init failed');

while (/* more data available */) {
    $input = /* get more data */;
    $data = \deflate_add($zctx, $input, ZLIB_NO_FLUSH);
    if ($data === false)
        throw new \Exception('deflate_add failed');
    echo $data;
}

$data = \deflate_add($zctx, '', ZLIB_FINISH);
if ($data === false)
    throw new \Exception('deflate_add failed');
echo $data;

unset($zctx); // free compressor resources

deflate_init and deflate_add are available since PHP 7, assuming that the zlib extension was enabled while building PHP. Calling a library is preferable to invoking a subprocess (in any language, in fact) as it is much more lightweight: putting everything in the same process avoids memory and context-switching overheads.


text:
Q: How to access a controller assigned through routeProvider outside of AngularJS I have a jquery/flash based microphone recording plugin and I want to be able to call a function inside an Angular controller to process the audio further.
Inside an ng-view I load a template and assign the controller I want to access via a routeProvider. In this template I have a top div element. I thought I could access the controller by doing:
e = document.getElementById("topElement");
scope = angular.element(e).scope();

And then in de microphone callback call:
scope.$apply(function() {
    scope.functionInController(micData);
});

But scope.functionInController is not defined.
By inspecting the scope element I can see that functionInController actually lives inside the $$childHead of the scope I retrieve, but I cannot seem to access it.

A: Change your callback to:
scope.$apply(function() {
    scope.$$childHead.functionInController(micData);
});


text:
Q: Hadoop tasks: "execvp: permission denied" In a small Hadoop cluster set up on a number of developer workstations (i.e., they have different local configurations), I have one TaskTracker of 6 that is being problematic. Whenever it receives a task, that task immediately fails with ChildError:
java.lang.Throwable: Child Error
    at org.apache.hardoop.mapred.TaskRunner.run(TaskRunner.java:242)
Caused by: java.io.IOException: Task process exit with nonzero status of 1.
    at org.apache.hardoop.mapred.TaskRunner.run(TaskRunner.java:229)

When I look at the stdout and stderr logs for the task, the stdout log is empty, and the stderr log only has:
execvp: Permission denied

My jobs complete because the tasktracker eventually gets blacklisted and runs on the other nodes that have no problem running a task. I am not able to get any tasks running on this one node, from any number of jobs, so this is a universal problem.
I have a DataNode running on this node with no issues.
I imagine there might some sort of Java issue here where it is having a hard time spawning a JVM or something...

A: We have same problem. we fix it by adding 'execute' to below file.
$JAVA_HOME/jre/bin/java

Because hadoop use $JAVA_HOME/jre/bin/java to spawn task program instead of $JAVA_HOME/bin/java.
If you still have this issue after change the file mode, suggest you use remote debug to find the shell cmd which spawning the task, see debugging hadoop task

A: Whatever it is trying to execvp does not have the executable bit set on it.  You can set the executable bit using chmod from the commandline.

A: I have encountered the same problem.
You can try changing the jdk version 32bit to 64bit or 64bit to 32bit.