text:
Q: GPA calculator/ adding outside a loop Greetings,
I'm just looking for a bit of help here. Here's the prompt:
For research purposes the admissions officers of your local university wants to know how well female and male students perform in certain courses. The user enters the number of courses to be considered. The student's data for each course is provided as a GPA followed by a letter code representing the gender of the student in this format: each line of input consists of a real number representing the student's GPA followed by the letter code f (for female students); m (for male students).
The number of entries (students) for each course is not known and the number 0.0 followed by the letter O indicates the end of data for specific course.
That being said, this is an introduction to c++ and as such; arrays, strings, and anything else outside of int, floats, doubles, and char is basically not allowed. In the code there needs to be the ability to type in various entries in any order (male entry followed by female and as well as the opposite.)
the issue i'm having is this, at the end of the program it is required to give an output of "General School Averages" which are sorted by female and male.  I understand how to get the total in which to divide the problem, i just can't seem to get the sum.  Anytime I try to get the sum, the value for the first course (first time through loop) is not kept so I can't figure out for the life of me how to do it. Any hints or assistance would be greatly appreciated. I know the code is long and kinda "brutish" so bear with me on that part. here's the code
//GPA calculator for Ghemri
//dealing with gpa range 0.0-4.0, set cap?
//try a do while loop

#include <iostream>

using namespace std;

int main(void)
{

 int size, counter;
 //int studentTotal= 0;
 char gender;
 double studentInfo,total,sum, avg;
 double minRange = 0.0, maxRange = 4.0;
 double maxGpa=0,gpaAvg,gpaSum;
 double femaleSum, femaleAvg, femaleTotal;
 double maleSum, maleAvg, maleTotal;
 int femaleNumber,maleNumber, gpaNumber;
 double sumFemaleAvg;// femaleGeneralAvg;//sumMaleAvg, maleGeneralAvg;

 cout << "\nPlease enter the number of courses you want considered: ";

 cin >> size;

 while(size <=0)
 {
  cout << "\nInvalid entry, number of course must be greater than zero\n";

  cin >> size;

 }

 //sumFemaleAvg+=femaleAvg;

 for(int course =1; course <= size; course++)
 {
  maleTotal = 0;
  femaleTotal=0;
  total = 0;
  femaleNumber = 0;
  maleNumber = 0;
  gpaNumber = 0;
  maxGpa= 0;
  gpaSum = 0;

  //double  doubleArray[course] = {femaleAvg};
   cout << "\nEnter student information(0.0 O to end):\t";

   cin >> studentInfo >> gender;

  while(studentInfo < minRange || studentInfo > maxRange)
  {
   cout << "\nInvalid entry, try again...\n";

   cout << "Enter student's information(0.0 O to end): \t";

   cin >> studentInfo >> gender;
  }
  if(studentInfo > maxGpa)
  {
   maxGpa=studentInfo;
  }
  if(studentInfo > 3.00)
  {
   gpaSum=studentInfo;
   gpaNumber=1;
  }

  if(gender == 'f' && studentInfo > minRange && studentInfo < maxRange)
  {
   femaleNumber=1;
   femaleSum = studentInfo;
   maleSum=0;

  }
  if(gender == 'm' && studentInfo > minRange && studentInfo < maxRange)
  {
   maleNumber=1;
   maleSum = studentInfo;
   femaleSum=0;
  }

  sum =studentInfo;
  counter = 0;
  counter++;

  while(studentInfo != 0.0 && gender != 'O')
  {

   cout << "Enter student information(0.0 O to end):\t";

   cin >> studentInfo >> gender;

   if(studentInfo > maxGpa)
   {
    maxGpa=studentInfo;
   }

   if(studentInfo < minRange || studentInfo > maxRange)
    {
     cout << "\nInvalid entry, try again...\n";

     cout << "Enter student's information(0.0 O to end): \t";

     cin >> studentInfo >> gender;
    }

   if(gender != 'm' && gender !='f'&& gender != 'O')
    {
     cout << "Invalid entry, enter m for male or f for female\n";

     cout << "Enter student's information(0.0 O to end): \t";

     cin >> studentInfo >> gender;
    }

    sum +=studentInfo;
    total+=counter;
    avg = sum/total;

    if(studentInfo > 3.00)
    {
     gpaSum+=studentInfo;
     gpaNumber++;
     gpaAvg= gpaSum/gpaNumber;
    }

    if(gender == 'f' || gender =='F')
    {
     femaleSum+=studentInfo;
     femaleNumber++;
     //femaleTotal+=femaleNumber;
     femaleAvg = femaleSum/femaleNumber;
     //sumFemaleAvg = femaleAvg;
    }

    if(gender == 'm' || gender == 'M')
    {
     maleSum+=studentInfo;
     maleNumber++;
     //maleTotal+=maleNumber;
     maleAvg = maleSum/maleNumber;
    }

   if(studentInfo == 0 && gender == 'O')
   {
    cout << "\nResults for course "<< course<<":\n";
    cout << "Female Student Average\t Male Student Average\n";
    cout << "\t";
    if(femaleNumber==0)
    {
     cout<< "N/A" << "\t\t\t";
    }
    else
    {
     cout<< femaleAvg <<"\t\t\t";//femaleAvg

    }
    if(maleNumber==0)
    {
     cout << "N/A\n";
    }
    else
    {
     cout<<maleAvg << endl;
     //sumMaleAvg = maleAvg;
    }

    cout << "\nHighest GPA: " << maxGpa<<endl;
    cout <<  "Highest average GPA for course "<< course << ": "<< gpaAvg<< endl;
   }
  }
  sumFemaleAvg = femaleAvg;

 }

 /*double genAvg[]={femaleAvg};

 result+=genAvg[course];*/

 sumFemaleAvg+=femaleAvg;

 cout<< "this is a test for the value sum " << sumFemaleAvg<<endl;
 //cout<< "this is another test " << result <<endl;

    //maleGeneralAvg = sumMaleAvg/course;
  /*cout << "the sum is " << sumFemaleAvg<<endl;
  cout << "the other sum is "<< sumFemaleAvg2<<endl;
  cout << "the other other sum is " << femaleAvg;*/

 return 0;
}

A: Try to avoid extreme repetition and factor common operations into functions. I'll "bear with you" for now, but really there's no reason I should. This is the first thing you need to learn as a programmer.
It looks like the variable sumFemaleAvg is supposed to be summed over loop iterations. However the line   sumFemaleAvg = femaleAvg; overwrites the variable every time. Do
  sumFemaleAvg += femaleAvg;

and likewise for other variables you wish to add up over multiple iterations.


text:
Q: understanding salesforce licensing for development and deployment I am trying to understand the licensing issues on I would come across on Force.com for developing an application that will have its own data source and will also be pulling data from SalesForce.com via api/service. I have spent over a day researching this from various sites but most of them keep throwing up new things which don't really answer my questions and have got me more confused. IF anyone here has any insight into this that can help me understand the cost of development and maintaining a site using Force.com, so I can compare it with building an application ground up on say .Net or Java and hosting it on a different cloud provider, then please help me out. My questions are:

*

*If I have 5 developers working on an application called XYZ using the Force.com platform, how many Force.Com licenses would I need to purchase for such development work and of what type should those licenses be?

*Would I also need to buy separate SalesForce licenses if those developers need to fetch data from the SalesForce database through code written on Force.com?

*If I already have a SalesForce license then will my access to SalesForce be suspended if I convert that license to access Force.com for doing development work?

*Can I reuse those same licenses for the testing phase later or should I buy separate licenses for testing?

*Once development is complete and people create accounts for themselves on my XYZ web application, will they need a salesforce login to access the salesforce related data from their company network or can they still access it without?

*If my XYZ web application doesn't access SalesForce's data then will my XYZ web application's users still need a salesforce or Force.com license to login into XYZ?

*If I dont use Force.com as my development platform, and I still need to access SalesForce data, how many licenses would I need to have? One per login created on my XYZ application or just one will do?

Thanks.

A: You might be better off asking this at salesforce.stackexchange.com (beta). Seems like quite a lot of experts there have done some cool integrations, managed packages etc or even are ISVs. so they might have more experience in the matter. They'll maybe even point you to database.com.
Or just go and talk to SF sales rep.
Also I think you don't understand that you don't simply "buy a Salesforce license". You buy licenses bound to particular production organisation (an instance if you prefer). You can't transfer them between organisations and the fact that your web app will talk to specific Salesforce instance doesn't mean you can use same license too connect to different instance. So if this is what you mean by

I have spent over a day researching this from various sites but most
  of them keep throwing up new things which don't really answer my
  questions and have got me more confused.

then you'll have hard time...
I think for such question you'll need to eventually ask your lawyer, don't trust people on the internet :) Safe harbor, blah blah, don't sue me...

*

*To kick off the development you don't have to pay anything. Sign up for Developer Edition and hack away. (each developer can do it, you can synchronize between them using SVN etc - it's definitely enough for quick start). If you already have a "production" (for example Enterprise Edition") then I think up to 4 simultaneous logins are allowed for each active user. This counts for different channels (so for example developer who would both click through app's UI and work in Eclipse IDE counts as 2) so you can try to do some cost cutting here... But I'd recommend 5 full Salesforce licenses.

*No, will be sufficient.

*I don't think you can convert licenses ;) You'd simply buy licenses of different type and contact them to reduce the count of licenses of type you don't need. You can kind of convert users by assigning them license of different type (and this might lead to change of Profile). As a result you for example downgrade a full System Administrator (on Salesforce license) to say user who can see only Chatter and loses access to Accounts etc.

*You can use same licenses. Even to say deactivate developer user accounts and use the freed licenses to create some test users.

*Depends how many features of SF you'd want to use (in terms of data ownership, visibility etc.). You will have to provide "some" credentials of an active user in your Salesforce. So you might be fine with having just 1 "integration user" account that would see all data and then do all filtering etc on your webapp.

*I don't understand that one so I'm going to say "no" ;) If you don't need to connect to SF and get the data - don't? Unless you have some kind of Single Sign On solution there.

*If you need to access Salesforce from external app you need to authenticate. Username + password, Oauth,sessionId, single-sign-on... whatever the means - SF needs something to say that this user is active, he can see this data. So it kind of goes back to answer #5.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why I'm getting "error expected an expression" while compile cilk program I'm using Linux, Eclipse and Intel compiler V14.
I'm trying to compile the basic fibonacci example:
#include <iostream>
#include <cilk/cilk.h>

using namespace std;

int fib(int n) {

    if (n < 2) return 1;
    else {

        int rst = 0;
        rst += cilk_spawn fib(n-1);
        rst += cilk_spawn fib(n-2);
        cilk_sync;
        return rst;
    }
}

int main() {

    int res = fib(9);
    return 0;
}

And getting compile error:
error expected an expression

I tried to use:
cilk_spawn
Cilk_spawn
_cilk_spawn
_Cilk_spawn

but same error..

A: Not sure if you can use cilk_spawn with the += operator.
Does the following code work?
        int rst = 0;
        int temp = 0;
        temp = cilk_spawn fib(n-1);
        rst += temp;
        temp = cilk_spawn fib(n-2);
        rst += temp;
        cilk_sync;
        return rst;

A: The Intel compiler automatically enables Cilk Plus. The message "symbol _Cilk_spawn could not be resolved" indicates that you're not using the Intel compiler. Check your compilation command and make sure that it's invoking icc instead of gcc.
Also, your original example contains a race. The correct implementation of the classic fibonacci in Cilk Plus is:
int fib(int n) {
    if (n < 2)
        return n;
    int x = cilk_spawn fib(n-1);
    int y = fib(n-2);
    cilk_sync;
    return x+y;
}

You need to use two independent variables to which are only summed after the sync to avoid the race.
You should also avoid the cilk_spawn on the second recursive call to fib(). Remember that the Cilk runtime implements stealing of the continuation. So what would be stolen if you used a second cilk_spawn is the code from the ; of the second fib() call until the sync. It will just slow your program down. MIT Cilk required that all calls to Cilk functions be spawned. Intel Cilk Plus removed that requirement.


text:
Q: Daily Coding Problem, 1.4: Running time given in the solution incorrect?
PREAMBLE:
I am working on a particular puzzle in a book named Daily Coding Problem. It is the fourth problem in the first chapter.
The problem statement is:
Given an array of integers, return a new array where each element
in the new array list is the number of smaller elements to the
right of that element in the original input array.

They propose the naive solution, which is to iterate through the elements right of each element in the array and count appropriately. This, of course, is O(n^2) time.
They claim, however, that there is a solution that runs in O(nlogn) time. So for a few days now I have been scratching my head over it. Finally, out of impatience and and frustration, having come up with a few different solutions, none of which improve on O(n^2), I looked at their solution.

MY QUESTION:
Their solution was exactly one of the solutions I had come up with. But, when I consider the runtime of this solution, I find that is O(n^2) time and not O(long) time, as they claim it to be.
I would like your input :)
The algorithm:

*

*Iterate backwards over the input list

*Maintain a sorted list of the elements so far seen

*Look at the current element to see where it would fit into the sorted array that is under construction as we proceed from back to front.

The "analysis:"
For every element in an n-element array,

*

*The algorithm searches the sorted array under construction not find the place of that element, O(logn)

*That element is inserted into the array, O(n) (the entire sorted array that is being constructed may have to be shifted).

So, for every element in an n-element array, the operations of searching for the proper place of that element and inserting that element into sorted array under construction would be O(logn + n) = O(n), and, hence, the entire algorithm would be O(n * n).
For example, if we are given the array
 1 2 3 4 5 6 7 8 9 10

the insertion of every element into the sorted array we are maintaining (constructing) would require a shift.
Am I incorrect?
Thanks for your time and feedback :)

A: You're right but not if you use a binary heap for inserting. Essentially doing a sort of heap-sort along the way.
https://en.wikipedia.org/wiki/Binary_heap
The insert operation is O(logn) at worst and after that your last inserted element becomes the root of a subtree which has the property that all the elements from the subtree are smaller than the root.
The binary heap is usually used to implement a priority queue.
A more straightforward solution is to use an indirect index to sort the array. The index will give you the number of elements smaller at the right of the current element because those are the elements that keep the current element out of position in the unsorted array with exactly count positions.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int arr[6] = {8, 1, 3, 10, 5, 6};
//int arr[6] = {1, 2, 3, 4, 5, 6};
vector<int> a(begin(arr), end(arr));
 // sort using a custom function object
struct {
    bool operator()(int idx1, int idx2) const
    {
        return a[idx1] < a[idx2];
    }
} custom_compare;

int main(int argc, char** argv) {
    vector<int> idx(a.size(), 0);
    vector<int> result(a.size(), 0);
    for (int i = 0; i < a.size(); i++) {
        idx[i] = i;
    }
    sort(idx.begin(), idx.end(), custom_compare);
    for (int i = a.size() - 1; i >= 0; i--) {
        result[idx[i]] = i - idx[i];
        result[idx[i]] = result[idx[i]] < 0 ? 0 : result[idx[i]];
    }

    for (int i = 0; i < a.size(); i++) {
        cout << result[i] << " ";
    }
    cout << endl;
    return 0;
}

For the simple example the idx will look like the following:
1 2 4 5 0 3

So element a[1] = 1 should be in position 0, element a[2] = 3 should be in position 1 and so on. If we look at element 0, that is in position 4 in the sorted array and in position 0 in the unsorted array, so there are four elements smaller than 8, keeping 8, 4 positions apart from its place in the sorted array. Of course we get negative numbers for numbers that are out of position but because bigger numbers are in front, but we just set these to 0.
And the result will look like the following after running the program:
4 0 0 2 0 0

So 8 has 4 elements smaller than him at the right, and 10 has 2.


text:
Q: Delayed for some heavy users of a billing details page I've developed a billing summary page use mysql + php.

*

*there are many users :  (1M)

*light user :each has less than 10K record :0.99M users

*heavy user :each has about 1M record

SQL is the following :
SELECT SUM(value_a) A, SUM(value_b) B, SUM(value_c) C
FROM  daily_data_sep_2010
WHERE  user_id='<user_id>'
AND type
IN (
  'type_a',  'typeb'
 )
AND publish_date
BETWEEN  '<start_date>'
AND  '<end_date>'
GROUP BY publish_date
ORDER BY publish_date DESC

daily_data_sep_2010 table type is MyISAM
There are several types of same Queries,but
 SUM(value_a) A, SUM(value_b) B, SUM(value_c) C are realy same (equal)
"WHERE", "GROUP BY" conditions are not same
This screen is very slow for heavy users.
Do you have any good solutions?
explain is here
|table  |type   |possible_keys  |key    |key_len    |ref    |rows   |Extra|
|daily_data_sep_2010|   ALL|    PRIMARY,user_id_key,type,publish_date||||               1059756 |Using where; Using temporary; Using filesort|
I think row size is too large for sum.
so I look forward to onother solutions (Hadoop?)

A: Any difference if you create a composite index on (userid, type) and do this:
       where userid = ? and type in (a,b)
       and publish_date between...
       group by publish_date

A: You may try running your query through the explain command.
However, I'd guess that adding one of these indexes would help out (depending on how frequent rows with matching types are found):

*

*user_id, type, publish_date, value_a, value_b, value_c

*user_id, publish_date, type, value_a, value_b, value_c

That should allow it to consult only the index for your query (reducing the number of pages read), as well as allow an index range scan (or whatever MySQL calls it) to build up the actual data.
Another option is running a scheduled (maybe nightly?) process to build up the data for your 'heavy' users, and use that data when showing them reports.

A: MySQL 5.1.3 Server supports partitioning.
you can reference mysql partitioning,the url is http://dev.mysql.com/doc/refman/5.1/en/partitioning.html


text:
Q: Using Neural Networks For Time Series Predictions In PHP I'm currently building a website which will aggregate news articles and then categorise them based on their content. However, I would like to analyse the times in which the articles are published so that I can determine if their is some sort of trend occuring, thus allowing me to predict the time when the next article is likely to be published and also eliminating the need to for frequent / unnecessary crawling attempts.
I've had a look on the internet and it seems that neural networks can be used for analysing time series', however I haven't found any examples / code snippets that are benefical or easy for a beginner to understand and then adapt.
These articles also seem to suggest that the inputs to a neural network should either be a 0 or a 1, therefore how would you go about creating a neural network in PHP that has the following inputs i.e. unix timestamps and the capabilitiess to output a single value?

*

*1332193520

*1342194916

*1342196716

*1342197376

*1352197856

*1362198756

Any help would be greatly appreciated.

A: It would be hard to train a NN in PHP. This should be done offline using some fast non-scripting language. Oh, implementation, training and especially tuning of NNs parameters is not a trivial task.
If I were you I would go for Linear SVMs that outperform other methods for text classification and are quite simple in deployment (and elegant theoretically - Btw, NNs are old fashion). There are excellent implementation of SVMs like
SVM Light and LIBSVM written in multiple languages.


text:
Q: Log in using Scrapy not working I am trying to log in to site using scrapy. I took an example site and checked. It is working for that site. Then i took another site and checked. Its not working. I just changed the urls and ran the code. But not working. What would be the problem?
    # -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class QuoteSpider(scrapy.Spider):
    name = 'Quote'
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = (
        'http://quotes.toscrape.com/login',
    )

    def parse(self, response):
        token=response.xpath('//input[@name="csrf_token"]/@value').extract_first()

        return FormRequest.from_response(response,formdata={'csrf_token':token,'password':'foo','username':'foo'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)

This is working fine. THe other one is not.
    # -*- coding: utf-8 -*-
import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class BucketsSpider(scrapy.Spider):
    name = 'buckets'
    allowed_domains = ['http://collegekart.in/login']
    start_urls = ['http://collegekart.in/login/']

    def parse(self, response):
        token=response.xpath('//meta[@name="csrf-token"]/@content').extract_first()
        print(token)
        return FormRequest.from_response(response,formdata={'csrf-token':token,'password':'*********','username':'**************'},callback=self.scape_home_page)

    def scape_home_page(self, response):
        open_in_browser(response)
        print("yes")

This is not working. The response is not opening in browser. Please suggest me some ways to solve this.

A: I think the problem is with your allowed_domains = ['http://collegekart.in/login'] please try changing it to allowed_domains = ['collegekart.in'] the other response is probably getting filtered.


text:
Q: Selenium Chromedriver "Failed to Load Extension" Can anyone point me in the right direction?
I'm running Chrome using the following Python code:
opts = Options()
opts.add_argument("--disable-extensions")
self.browser = webdriver.Chrome(chrome_options=opts)

I am receiving the following error:

I've tried disabling extensions through code... as well as actually removing all extensions from Chrome before running the code. Neither solution has worked.
I'm running code using the following:

*

*ChromeDriver 2.28

*Chrome V57.0.2987.110

*Selenium 3.3.1

*Python 2.7

A: I run into the same kind of problem and I solved it following the answer to this other question:
What is python's equivalent of useAutomationExtension for selenium?
For me, the necessary part of this answer is to set the chromeOptions capability 'useAutomationExtension' to false. My code looks like:
from selenium import webdriver
capabilities = { 'chromeOptions':  { 'useAutomationExtension': False}}
driver = webdriver.Chrome(desired_capabilities = capabilities)
driver.get('https://www.python.org/')

I'm not sure if the "--disable-extensions" you add as argument is still necessary, but I think you can keep it by changing capabilities in the code above such as:
capabilities = { 'chromeOptions':  { 'useAutomationExtension': False,
                                     'args': ['--disable-extensions'] }
               }

Both works for me and I don't get the error anymore. My settings are a bit different (Chrome v63, ChromeDriver 2.35, Selenium 3.9 and Python 2.7) but I hope it will help you.

A: I had the same issue as above. Referencing the below link, the use of ".add_experimental_option('useAutomationExtension', False)" worked for me.
What is python's equivalent of useAutomationExtension for selenium?
Sample Code:
options = webdriver.ChromeOptions()
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=driverPath)

A: Here's the solution to your Question:
Add the following ChromeOptions to overcome the error:
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);`

Apologies as the code is in Java, you have to convert it into Python format.
Let me know if this helps you.


text:
Q: Correctly loading admin scripts in Wordpress 5.0.0 I am trying to load some scripts to the editor page of my Wordpress admin, and although I can see that the scripts have loaded correctly, and with no console errors, the functionality they should provide is not working.
More specifically, I am trying to load flickity.js, to enable a slideshow to function when viewing the element in the new Guternberg editor.
The code being used with functions.php to load the scripts is as follows, where 'flickity' is the library, and 'single' contains the init script.:
function my_enqueue($hook) {

    wp_register_script('flickity', get_template_directory_uri() .'/js/vendor/min/flickity.pkgd-min.js', false, '2.1.0', true);
    wp_register_script('single', get_template_directory_uri() .'/js/min/single-min.js', false, '1.0', true);

    wp_enqueue_script('flickity');
    wp_enqueue_script('single');
}

add_action('admin_enqueue_scripts', 'my_enqueue');


text:
Q: NoReverseMatch Django Postman Why does this return a NoReverseMatch?
From django-postman:
url(r'^write/(?:(?P<recipients>[\w.@+-:]+)/)?$', 'write', name='postman_write'),

Template:
Send Message

This does not work either..
Send Message

Returns: Reverse for 'postman_write' with arguments '(<User: admin>,)' and keyword arguments '{}' not found. What am I missing to construct this url properly? Thanks!

A: you are passing a user object in url tag. You need to pass the username.
{% url postman_write recipients=object.user.username %}

Also make sure you have included the postman urls in your main urls.py file.

A: Try:
{% url postman_write object.user.username %}


text:
Q: Como atualizar com AJAX uma lista após a ação de um formulário remoto? Estou com um problema que nunca tive em Java mas estou quase ficando louco em Rails.
Eu estou desenvolvendo um projeto onde existem usuários e grupos. Então criei um model separado para relacionamento N:N entre usuários e grupos.
Na página show de grupos eu criei a descrição do grupo, logo abaixo aparece a partial de formulário _groupsuser para permitir que o criador do grupo adicione usuários aquele grupo. Abaixo de tudo isso eu renderizei a partial para exibir a listagem de usuários pertencentes ao grupo.
O projeto ficou com uma estrutura um pouco diferente porque estou usando partials para evitar ficar replicando a mesma lógica no controle e na view portanto gostaria de evitar ficar mexendo na estrutura e focar apenas em atualizar a listagem assim que tiver a resposta 'ajax:complete'. No caso criei no controle o metodo create:
def create
    if group.user == current_user
        @groupsuser = Groupsuser.new(groupsuser_params)
        @groupsuser.group = group
        if @groupsuser.save
            flash[:notice] = 'User was successfully add.'
        else
            flash[:alert] = 'User cannot be add.'
        end
    else
        flash[:notice] = "You didn't have permition."
    end
    head :ok
end

Gostaria de fazer a atualização usando apenas ajax semelhante ao metodo update do java com facelets tipo:
    <p:commandButton value="All" id="btnAll" process="@all" update="grid"
                actionListener="#{personBean.savePerson}"/>

Por exemplo:
$('create_button').onClick('ajax:complete', render(@group));

para atualizar a página inteira ou
$('create_button').onClick('ajax:complete', "Comando mágico para atualizar apenas a div");

A: Antes de tudo, estude a gem Cancan para implementar as permissões.
Com a Cancan, o código do seu método ficaria assim:
def create
    @groupsuser = Groupsuser.new(groupsuser_params)
    @groupsuser.group = group
    if @groupsuser.save
        flash[:notice] = 'User was successfully add.'
    else
        flash[:alert] = 'User cannot be add.'
    end
end

Agora para fazer o cadastro de usuário por Ajax, primeiro adicione a opção remote: true ao seu form de cadastro. Com isso, você não precisa adicionar código JS para o form fazer POST com Ajax.
Depois, adicione o código no fim da action create. Esse código indica que a requisição será do tipo javascript.
respond_to do |format|
    format.js
end

Por último, crie a view create.js.erb, que contém o código JS que deve ser executado na resposta da requisição. Deve ser algo do tipo:
$('div#users-container').html('<%= j render(@group.users) %>');

Com esse código, não é necessário adicionar listener JS "na mão".
A opção remote: true está disponível pela biblioteca jquery_ujs.


text:
Q: How to deal with iteracy in Python I have this code:
def PCP(seq, feature):
  l = []
  mean = st.mean(list(feature.values()))
  std = np.std(list(feature.values()))
  for elem in seq:
      for aa in elem:
          if aa in feature:
              l.append((feature[aa]-mean)/std)
          else:
              l.append(0)
  return l

seq is a list of strings with sequences, and feature is a dict with aminoacids as keys and certain values as values. I want the function to get throught every aa in a string in the list (seq) and take the values that corresponds in the dict and make calculation.
Here is a piece of of data I put as seq, and feature dict:
['KISKDLSIAVQMMKRIHSLLERYPEIL', 'SGRVEKSPHEQEIKFFAKILLPLINQY', 'IDQLIVFGEQLIQKSEPLDAVLIEDEL', ..], pI= {"K":9.47, "P":6.3, "R":10.76, "T":5.6, "A":6.11, "C":5.02, "D":2.98, "E":3.08, "F":5.91, "G":6.06, "H":7.64......}
Maybe there is something wrong with them.
When I run the function I get this error:
Traceback (most recent call last)
<ipython-input-13-89a7be7ecda7> in <module>
----> 1 test_hydrofobowosc= PCP(test_data_neg, hydrofobowosc)

<ipython-input-12-2f318f9cb908> in PCP(seq, feature)
     14   mean = st.mean(list(feature.values()))
     15   std = np.std(list(feature.values()))
---> 16   for elem in seq:
     17       for aa in elem:
     18           if aa in feature:

TypeError: 'NoneType' object is not iterable

What's wrong?

A: 'range' returns a list of numbers.
therefore 'elem' is a number.
therefore it is not iterable.
do you mean 'for elem in seq' ?

A: Here's a modified version of your code that should work:
def PCP(seq, feature):
  l = []
  mean = st.mean(list(feature.values()))
  std = np.std(list(feature.values()))
  for elem in seq:
      for aa in elem:
          if aa in feature:
              l.append((feature[aa]-mean)/std)
          else:
              l.append(0)
  return l

The main changes I made were:

*

*Instead of using "range(len(seq))" to iterate through the list of sequences, I used "seq" directly. This way, "elem" will be the actual string in the list, instead of the index of the string.

*Inside the nested loop, I used "aa" as the variable to iterate through the characters in the string.

*When checking if the current character is "in" the feature dictionary, I used the in keyword instead of "keys[s]". This is because "keys()" is a method that returns a list-like object of the dictionary's keys, and you need to use "[]" to access an item in the list. Since "aa" is a string and not an index, you can just check if it's in the dictionary directly.

*I moved the "return l" statement outside of the nested loop, so that it only happens once after all the calculations are done.

With these changes, the code should work as expected and append the calculated values to the l list for each amino acid in the sequences that has a corresponding value in the feature dictionary.


text:
Q: How can i setup remote project with PhpStorm with Google Compute Engine running LEMP? I was working on a web cloud app and setup Google compute Engine with micro instance (Ubuntu 14.4) with nginx, Laravel, MySQL and PHP.
Now I want to setup my PhpStorm IDE with this setup to make development fast.
Kindly help me with this thing.

A: To make development faster with PHPStorm follow the steps below:

*

*Make sure you generate a SSH key-pair(public+private) with PuttyGen.

*Paste the contents of your public key in GCE in the SSH Key section.

You can find that section when you go to Edit menu of your GCE instance.

*Go to PHPStorm and enter data for your remote host in Tools/Deployment/Configuration

*Choose SFTP and browse and enter the path to your private key in "Private Key File" field.

Now test your connection and enjoy rapid deployment with PHPStorm and GCP


text:
Q: TableView Inside of Xib File I want to add table view inside my xib file but i got error. My controller is
class ViewController: UIViewControllerUITextViewDelegate,UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "Cell"

        var cell:UITableViewCell? = yerImleriView.tableView.dequeueReusableCell(withIdentifier: identifier)

        if cell == nil {
            _ =  YerImleri().loadNib() as UIView
            tableView.register(UINib(nibName: "YerImleri", bundle: nil), forCellReuseIdentifier: identifier)
            cell = yerImleriView.tableView.dequeueReusableCell(withIdentifier: identifier)
            cell?.textLabel?.textColor = UIColorFromRGB(rgbValue: 0xEFEFEF)
            cell?.textLabel?.text = items[indexPath.row]
            cell?.backgroundColor = UIColorFromRGB(rgbValue: 0x3A4858)
            cell?.textLabel?.font = UIFont (name: "Proxima Nova", size: 16)
        }
        return cell!
    }
    var items: [String] = ["Katmanlar", "Yer Imleri", "GPS Cihazlari", "Kategorik Arama","Cevrimdisi Haritalar"]

    override func viewDidLoad() {
        super.viewDidLoad()

        yerImleriView.tableView.delegate = self
        yerImleriView.tableView.dataSource = self
}
}

and my Xib file is
class YerImleri: UIView{

    @IBOutlet var contentView: UIView!
    @IBOutlet weak var tableView: UITableView!

    override init(frame: CGRect){
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit(){
        Bundle.main.loadNibNamed("YerImleri", owner:self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
        contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}

and the error is
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key contentView.'

A: As per the understanding : You are assigning wrong class as file owner to xib check whether correct classes are assigned and all outlets are connected and circle of ib outlet is filled and it will work fine


text:
Q: With Argonaut, how can I convert a list of Map(String->Any) to json? import scalaz._, Scalaz._
import argonaut._, Argonaut._

object Minimal {
  val list = List(Map("id" -> 1), Map("name" -> "Mr. Name"))
  println(list.asJson)
}

gives me
Error:(8, 16) diverging implicit expansion for type argonaut.EncodeJson[A0]
starting with method IMapEncodeJson in trait EncodeJsons
  println(list.asJson)
               ^
Error:(8, 16) diverging implicit expansion for type argonaut.EncodeJson[V]
starting with method IMapEncodeJson in trait EncodeJsons
  println(list.asJson)
               ^
Error:(8, 16) not enough arguments for method asJson: (implicit e: argonaut.EncodeJson[List[scala.collection.immutable.Map[String,Any]]])argonaut.Json.
Unspecified value parameter e.
  println(list.asJson)
           ^

However, if I redefine list to be
  val list = List(Map("id" -> "1"), Map("name" -> "Mr. Name"))

it works.


text:
Q: Issue Running Monogame in F# I am experimenting a bit with F# and I am wanted to see if I could do some simple stuff with Monogame in F#. I figured the translation from C# to f# would be straightforward but it has not been so far. The code I have so far is just a simple empty project which should run. Or at least it would in C#. However running this in F# yields a
Unhandled exception. System.InvalidOperationException: No Graphics Device Service

The code I have is this, which really does not do anything crazy. I was forced to use a mutable val for the spritebatch as you must instantiate it in LoadContent for whatever reason. Anyone have any pointers to what I am doing wrong? I would be most grateful.
type GameState =
    inherit Game
    new() =  { inherit Game(); Sb = null;  }
    member this.Gfx : GraphicsDeviceManager = new GraphicsDeviceManager(this)
    val mutable Sb : SpriteBatch

    override this.Initialize() =
        this.Content.RootDirectory <- "Content"
        this.IsMouseVisible <- false
        base.Initialize ()

    override this.LoadContent () =
        this.Sb <- new SpriteBatch(this.Gfx.GraphicsDevice)
        base.LoadContent ()

    override this.UnloadContent () =
        base.UnloadContent ()

    override this.Update (gameTime : GameTime) =
        base.Update (gameTime)

    override this.Draw (gameTime : GameTime) =
        this.Gfx.GraphicsDevice.Clear (Color.CornflowerBlue)
        this.Sb.Begin()
        //draw here
        this.Sb.End()
        base.Draw (gameTime)

[<EntryPoint>]
let main argv =
    let gs = new GameState()
    gs.Run()
    0 // return an integer exit code

A: Asti is correct, you don't want to create a new GraphicsDeviceManager repeatedly.
Here is some working code with minimal changes to yours.  Note that to define values at constructor-time you need the () after the type name.  Using mutable for the SpriteBatch is ugly but common in this case, and you don't need to make it a member:
open Microsoft.Xna.Framework
open Microsoft.Xna.Framework.Graphics

type GameState() as this =
    inherit Game()
    let gfx = new GraphicsDeviceManager(this)
    let mutable sb = Unchecked.defaultof<SpriteBatch>

    override this.Initialize() =
        this.Content.RootDirectory <- "Content"
        this.IsMouseVisible <- false
        base.Initialize ()

    override this.LoadContent () =
        sb <- new SpriteBatch(gfx.GraphicsDevice)
        base.LoadContent ()

    override this.UnloadContent () =
        base.UnloadContent ()

    override this.Update (gameTime : GameTime) =
        base.Update (gameTime)

    override this.Draw (gameTime : GameTime) =
        gfx.GraphicsDevice.Clear (Color.CornflowerBlue)
        sb.Begin()
        //draw here
        sb.End()
        base.Draw (gameTime)

[<EntryPoint>]
let main argv =
    let gs = new GameState()
    gs.Run()
    0 //

Feel free to take a look at this repo of mine which gives a working example of using MonoGame with F# (although it's probably a bit out-of-date now), including basic content pipelines.


text:
Q: calculus order for (li-qij) o (qij-c).||oj-qij|| I have to compute a formula, this one:

However I don't know the calculus order between the big circle and the small one and I am also not quite sur about what these symbols mean. each vaiable are 3d points in a plane. could you tell me what is the order and what the symbols mean ?

A: The thick dot is the inner product or dot product of two vectors, defined by
$$
\begin{pmatrix} v_1 \\ v_2 \\ v_3 \end{pmatrix} \bullet \begin{pmatrix} w_1 \\ w_2 \\ w_3 \end{pmatrix} = v_1w_1 + v_2w_2 + v_3w_3.
$$
Note that the outcome is a number, not another vector. The double bars give the norm, which is defined by
$$
\|v\| = \sqrt{v \bullet v}.
$$
Finally, the small dot $\cdot$ is just the multiplication of two numbers.
If you know what vectors of the letters in your expression stand for, you should now be able to compute the formula.


text:
Q: OnbackPrees to return home always in react stack navigation I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init   Screen in stack navigations
What is happening
On home:
go details then go A
back arrow press in A, it  return  back to  details
Need actions
On home:
go details then go A
back arrow press in A  return  back to home instead of details
The code I try
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to A"
        onPress={() => navigation.navigate('A')}
      />

    </View>
  );
}
function A({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>AAAAAAAAAAAAAAAAAAA Screen</Text>

    </View>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
        detachPreviousScreen={true}>
        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Group screenOptions={{ presentation: 'modal' }}>
          <Stack.Screen name="Details" component={DetailsScreen}
            options={{ presentation: 'transparentModal' }}
          />
          <Stack.Screen name="A" component={A} />
        </Stack.Group>
      </Stack.Navigator>

    </NavigationContainer>
  );
}

export default App;

A: u can do it by passing "key" to "navigate"
more info (source):
https://reactnavigation.org/docs/navigation-prop/
https://reactnavigation.org/docs/navigation-prop/#going-back-from-a-specific-screen
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_A });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_B });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_C });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_D });

navigation.navigate({ key: SCREEN_KEY_A }); // will go to screen A FROM screen D

A: I think you can use BackHandler on Screen A.
So you should listen for BackHandler in Screen A and the navigate to Home screen when it's triggered.
Your Screen A should look like this:
  import { BackHandler } from 'react-native';

  function handleBackPressHandler() {
    navigation.navigate('HomeScreen');
    return true;
  }

  useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', handleBackPressHandler);

    return () => {
      BackHandler.removeEventListener('hardwareBackPress', handleBackPressHandler);
    };
  }, []);

A: The default behaviour of React Navigation is this only, it takes you to the last visited stack on pressing back but if you want to update it, you can you this line of code:
useFocusEffect( //imported from @react-navigation/native-stack
React.useCallback(() => {
  const onBackPress = () => {
    navigation.navigate('InitialRouteName');
  };

  BackHandler.addEventListener('hardwareBackPress', onBackPress);

  return () =>
    BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [])

);
For reference, you can check this out - https://reactnavigation.org/docs/custom-android-back-button-handling/

A: please try this,
import { BackHandler } from 'react-native';
<!- -->
  useEffect(() => {
    const backAction = () => {
      navigation.navigate('intialRouteName');
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );

    return () => backHandler.remove();
  }, []);


text:
Q: Cocos2d Android Lock Screen or Leaving Game Forces Restart I am in the final stages of a Cocos2d - Android game and I am having a problem that I can't figure out.
When I lock my tablet (Nexus 7) or when I hit the home button to leave the game, it restarts. It goes right back to the splash screen like the game is opening all over again. For your reference, here is my Main Activity and my Android Manifest:
public class MainActivity extends Activity {

//To get a static reference to context for shared preferences
private static Context context;

protected CCGLSurfaceView _glSurfaceView;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    //To get a static reference to context for shared preferences
    MainActivity.context = getApplicationContext();
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    _glSurfaceView = new CCGLSurfaceView(this);

    setContentView(_glSurfaceView);
}

//To get a static reference to context for shared preferences
public static Context getAppContext(){
    return MainActivity.context;
}

@Override
public void onStart()
{
    super.onStart();

    CCDirector.sharedDirector().attachInView(_glSurfaceView);

    CCDirector.sharedDirector().setDeviceOrientation(CCDirector.kCCDeviceOrientationPortrait);

    CCDirector.sharedDirector().setDisplayFPS(true);

    CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);

    CCScene scene = Splash.scene();

    CCDirector.sharedDirector().runWithScene(scene);
}

@Override
public void onPause()
{
    super.onPause();

    CCDirector.sharedDirector().pause();
    SoundEngine.sharedEngine().pauseSound();
}

@Override
public void onResume()
{
    super.onResume();

    CCDirector.sharedDirector().resume();
    SoundEngine.sharedEngine().resumeSound();
}

@Override
public void onStop()
{
    super.onStop();

    SoundEngine.sharedEngine().pauseSound();

}

and
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="bigfiresoftware.alphadefender"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />

<application
    android:allowBackup="true"
    android:icon="@drawable/adicon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name="bigfiresoftware.alphadefender.MainActivity"
        android:screenOrientation="portrait"
        android:label="@string/app_name"
        android:hardwareAccelerated="false">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
android:configChanges="keyboard|keyboardHidden|orientation"
</manifest>

Any/all help is very much appreciated. Thanks.

A: add  below line in your manifest file to your activity.
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"

when you locked the screen the orientation of your screen changes.So that your activity destroys and again it creates.If you ad this line your orientation will not change.

A: The answers above didn't fix it but I finally found the answer. This was a tough one.
If anyone else finds this problem:
Remove the targetSdkVersion in AdnroidManifest.xml. Or change to some others, I haven't tried others but removal worked.
android:minSdkVersion="9"
android:targetSdkVersion="17" /> //git rid of this guy

A: add this line in your onstop() method
CCDirector.sharedDirector().end();

and you need to write an onDestroy() method to remove all the instances when you close the game.


text:
Q: voice acting of numbers in English in pyttsx3 I am writing a pastry shop with voice acting.
Voice - installed in windows.
Windows in Russian.
Library - pyttsx3
I have a dictionary:
{cake: description, cost, quantity}
pastry = {'napoleon': [['butter', 'flour', 'sugar'], 7, 1000],
          'honey cake': [['flour', 'butter', 'sugar'], 4, 1025],
          'kiev': [['sugar', 'flour', 'butter'], 5, 985]}

faced with the fact that everything is spoken in English, except for numbers
For example, this code sounds like this:
engine.say(f'The cake {cake} {v [2]} grams left')

The cake honey одна тысяча двадцать пять grams left'
Please tell me how to make the numbers sound in English too
Maybe you know another library that accurately sound the numbers or  can set this up in this


text:
Q: Requisition method PUT angular enter image description hereI have the following problem, when I try to put to an api the server returns the error 405.
can you help me?
Below is the code so you can check if you see any error in my code that may be generating this error...
I believe there may be something wrong with the Component's Typescript.
I believe there may be something wrong with the Component's Typescript

Service Typescript

  getUser(id: any): Observable<ResponseUse> {
    const _url = `${this.apiClient}/${id}`
    return this.http.get<ResponseUse>(_url);
  }

  updateUser(id: any, request: ResponseUpdate): Observable<ResponseUpdate> {
    const _url = `${this.apiClient}/${id}`
    return this.http.put<ResponseUpdate>(_url, request);
  }
COMPONENT UPDATE

Update user

        ID:
        <input placeholder="ID" [(ngModel)]="request.id" />

        Name:
        <input placeholder="Name" [(ngModel)]="request.name" />

        Email:
        <input placeholder="Email" [(ngModel)]="request.email" />

        Telephone:
        <input placeholder="Telephone" [(ngModel)]="request.telephone" />

      <button mat-raised-button color="primary"  (click)="update()">
      Update
      </button>
      <button mat-stroked-button routerLink="/">Cancel</button>

  TYPESCRIPT COMPONENT

  import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { RequestUpdate } from 'src/app/model/live.model';
import { apiService } from 'src/app/services/api.service';

@Component({
  selector: 'app-client-update',
  templateUrl: './client-update.component.html',
  styleUrls: ['./client-update.component.css']
})
export class ClientUpdateComponent implements OnInit {

  id: any;
  request!: RequestUpdate;

  constructor(
    private clientService: apiService,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get('id');
    this.clientService.getUser(this.id).subscribe(res =>{
      this.request = {
        id: res.id,
        name: res.name,
        email: res.email,
        telephone: res.telephone
      }
    })
  }

  update(){
    this.clientService.updateUser(this.id, this.request).subscribe(res => {
      console.log(`${this.request}`)
    })
  }
}

A: a response code of 405 indicates that the method (PUT) is not allowed for the endpoint you are requesting.
Double check that a PUT method is accepted and that the url you are sending the request to is accurate (no typo's and such). Also worth checking the developer console on your browser to make sure the full endpoint is compiled correctly
[edit] 405 status code MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
http status codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status


text:
Q: User validation in Blackberry We have BES set up in the server. And we don't have any web service for user validation.
With these in mind, what all are the different types of authentication that can be performed from Blackberry application like certificate authentication  or pass key authentication ?

A: Did some research on this item and finally decided to go with LDAP based authentication. This has been implemented using the LDAP class provided in blackberry.
Other possible options are certificate based authentication, pass key based authentication etc..


text:
Q: How to create HFS partition on Windows 7 machine I've got Windows 7 running on my computer and I would like to partition my D: volume, make it HFS+ but I cannot find any tool that will accomplish this.
Anyone had done this before? Is it possible? I have EaseUS partition tool but it does not support HFS/HFS+.

A: I only know of two commercial tools: MacDrive and TransMac. They both have limited time trials to evaluate before you buy.
You could also try a Live CD of GParted, it has HFS support.
Update: a colleague of mine told me you can create a HFS partition with diskpart. Just make sure it's primary and use partition id af (create partition primary id=af).

A: You can use Paragon HFS + for Windows, for example. With him will be an opportunity and to read and write.

A: There is Paragon Partition Manager Free with which you can do this, to format Windows partitions to Apple HFS+.

A: This did the trick for me.
Paragon Hfs-Ntfs converter.


text:
Q: How do I get an s3 select query to return individual rows With data structured like so
{
    "rows": [
        {
            "rowId": "IDP_2z8dfj9KbB1hrPI_1554508960_1_1",
            "version": "1554508960",
            "lastUpdatedDate": 1554508960604,
            "createdAt": 1554508960604,
            "payload": ""
        },
        {
            "rowId": "IDP_2z8dfj9KbB1hrPI_1554508960_1_2",
            "version": "1554508960",
            "lastUpdatedDate": 1554508960604,
            "createdAt": 1554508960604,
            "payload": ""
        },
        {
            "rowId": "IDP_2z8dfj9KbB1hrPI_1554508960_1_3",
            "version": "1554508960",
            "lastUpdatedDate": 1554508960604,
            "createdAt": 1554508960604,
            "payload": ""
        }
    ]
}

The following select query
select * from S3Object s where 'IDP_2z8dfj9KbB1hrPI_1554508960_1_2' in s[*]."rows"[*]."rowId"

returns the entire JSON document, where I would expect it to return only a single row, i.e.
[{
            "rowId": "IDP_2z8dfj9KbB1hrPI_1554508960_1_2",
            "version": "1554508960",
            "lastUpdatedDate": 1554508960604,
            "createdAt": 1554508960604,
            "payload": ""
}]

I have tried several variations of the query
select s.rows[0] from S3Object s where 'IDP_2z8dfj9KbB1hrPI_1554508960_1_2' in s[*]."rows"[*]."rowId"

which returns only 1 record, but it is the wrong record.
select * from S3Object s where  s[*]."rows"[*]."rowId"='IDP_2z8dfj9KbB1hrPI_1554508960_1_2'

returns nothing.
Any ideas on what I'm doing wrong?

A: After several more modifications of the query, I was able to get my expected result with
select * from S3Object[*]."rows"[*] as r  where ('IDP_2z8dfj9KbB1hrPI_1554508960_1_1') in r[*]."rowId"


text:
Q: Options for packaging a RIA app using html and javascript I'm working on a RIA app based on html and javascript, jquery to be more specific.  I would like to package and run it in on desktops as a standalone application.  I'm looking at mongoose as an option for a simple webserver. What are the front-end options to create such a package.

*

*The native browser - Need to determine in each os what the default browser is and launch it.  Besides the app would end up as one of the tabs in a window and would be affected by a misbehaving script on an unrelated page.

*Packaging with Mozilla Prism -  Seems to be inactive

*Google Chrome Apps - First, Google Chrome needs to installed by the user.  Next it seems like the app can be installed only through the marketplace and even then the user has to go to the tools section and specify  "Create Application Shortcut". Seems like asking too much from the user.  Is there an option where I can package chrome itself with my app?

*Titanium Appcelerator -  Seems promising but I'm not sure of the license for desktop apps and I have issues setting up Titanium in my 64 bit machine (ubuntu 10.10) which questions my dependence on Titanium for cross-platform development.

Is there any other option that I can approach?
Has anyone encountered this before?

A: Adobe Air lets you package an app using the web stack to run as a standalone on a desktop:
http://www.adobe.com/products/air/


text:
Q: What systems are there to manage backend and front end logic/validation? I'm just wondering how people working in teams manage the relationship between the logic and validation in the backend, say in php, and the exact same logic and validation in the front end, for example in JavaScript?
Ideally, the final say should be given by the backend, but in order to make the application more accesible, it would be good to mimic as much as possible in the front end using JavaScript. I'm obviously trying to minimise duplication of code, and as projects get bigger, I'm finding it harder to manage how the front end stuff gets 'copied' from the backend stuff. The danger is that, as they're not tightly coupled, sometimes the front-end validation can get 'out of sync' with the backend - especially when there's a rogue JavaScript developer who thinks they've got a better way of doing some validation!
Does anyone have any insight?
EDIT
To be more concise, my question is really about how teams of people manage the 'papertrail' when it comes to duplication of logic (or how the front end access the backend as suggested by Fanis below), rather than the actual implementation. For example, do you leave comments in the backend code saying "front end copies/accesses this bit" or is there a more 'professional' way to keep track of what's doing what?

A: Whichever part actually uses the data should be the one with the final say, ie the backend, and it should have the strictest validation rules. For me validation in the front end is there to improve user experience, so that the user gets faster feedback on what's wrong with his input without waiting for a page reload. I would be ok with the front end having a small subset of the most generic validation rules (ie fields empty, malformed email addresses etc) and let the back end do any heavy lifting (eg duplicate entries detection).
However, if you need to bring full validation to the front end, consider this:

*

*make the backend's validation decoupled from any form submission logic

*setup a separate endpoint (API) that will receive data, perform validation, and echo out any errors or "ok"

*have the front end pass via ajax the form data into that endpoint and return any errors to display

*if all ok then let the form submission go ahead

This way you only have 1 copy of the validation rules, in your backend.
Note that you would be doing the validation twice, and if it's expensive (ie duplicates detection with heuristics over a large data set) perhaps that's not desireable. You could solve that by storing the form data in the user's session during the first validation if no error was found. Then when the form is actually submitted the backend won't re-validate it.
This should degrade nicely if javascript is not enabled.

A: have you looked at nodejs lately? with a bit of work and the appropriate framework (like, mootools) you can run literally the same validation classes both client and server side.


text:
Q: Can i open svg syntax string into default android web browser as svg file on haxeflixel without server request/response manipulation? Haxeflixel android targeting.
I need open text string with SVG syntax (XML) in default android browser, without server request/response actions. Something like just pushes text variable to the browser and display it as SVG file, like in the case when I do request and server response me SVG, but without internet and without creating the SVG file in the system storage (need additional permissions... in time of install apk...).
Is it possible?Any help will be good.

A: An actual browser window does not allow that, so I think what you want is a WebView.  It uses the default Android browser engine and is what you see in most apps.
Since you are using HaxeFlixel and it, in turn, is based on OpenFL, you can use its extension-webview native extension:
var htmlString = <...>;
extension.webview.WebView.openHtml(htmlString);

You can also specify a onClose callback.
Note: it might be necessary to wrap the SVG in some HTML.


text:
Q: Differentiability of the composition of a Lipschitz, convex function and a power function $f:\mathbb{R}^n\rightarrow \mathbb{R}$ is a positive, convex and Lipschitz function.
Is the fuction $|f|^{2+\alpha}$, $\alpha>0$, twice continuously differentiable?
How to prove it, or there is some counterexample?

A: Counterexample: Let $f(x) = |x| + 1.$ Then $f:\mathbb {R} \to \mathbb {R}$ is convex and Lipschitz. But $|f(x)|^3 = f(x)^3 = |x|^3 + 3x^2 + 3|x| +1,$ which implies $|f|^3$ is not differentiable at $0.$


text:
Q: Getting Error while trying to load DLL using DllImport in windows 10 universal app I am creating windows app. which is targeting windows 10 platform and it is Universal Windows App and I am using https://github.com/phatware/WritePadSDK for creating writing lad in windows app. Now what i have done is in the solution that i downloaded from github i added a project that targeted the windows universal app. I have added all the needed references that needed to run the project but every time i run the windows 10 universal project i get error Unable to load DLL 'WinRT_CPPLayer.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E).
Please help
Thank you.


text:
Q: How to solve $\ddot{x} + \epsilon \dot{x} +\sin x = 0$? I have tried as follows
$$\ddot{x} + \epsilon \dot{x} +\sin x = 0$$
$$\therefore  \frac{d}{dt}[(\dot{x})^2e^{2\epsilon t}] = 2\frac{d}{dt}{(\cos x)}e^{2\epsilon t}$$
$$\therefore \frac{d}{dt}\bigg\{\big[(\dot{x})^2 - 2\cos x\big]e^{2\epsilon t}\bigg\} = -4 e^{2\epsilon t} \cos x $$
The last step was a leap of faith...
I can integrate both sides, but I can not see that getting me further.
The exact solution is:
$$x(t) = \frac{1}{\sqrt{1-\frac{\epsilon^2}{4}}} e^{\frac{-\epsilon t}{2}}\sin(t\sqrt{1-\frac{\epsilon^2}{4}})$$
I would like to get to it.
EDIT :
I am convinced the first inferences are correct.
$$\ddot{x} + \epsilon \dot{x} +\sin x = 0$$
$$2\ddot{x}\dot{x} + 2\epsilon (\dot{x})^2 +2\dot{x}\sin x = 0$$
$$2\ddot{x}\dot{x}e^{2\epsilon t} + 2\epsilon (\dot{x})^2e^{2\epsilon t}+2\dot{x}e^{2\epsilon t}\sin x = 0$$
$$\frac{d}{dt}\{(\dot{x})^2\}e^{2\epsilon t} + (\dot{x})^2\frac{d}{dt}\{e^{2\epsilon t}\}+2\dot{x}e^{2\epsilon t}\sin x = 0$$
$$\therefore  \frac{d}{dt}[(\dot{x})^2e^{2\epsilon t}] = 2\frac{d}{dt}{(\cos x)}e^{2\epsilon t}$$
What part of the above is incorrect?
$$\frac{d}{dt}\{(\dot{x})^2\} = \frac{d}{d\dot{x}}\{\dot{x}^2\}\frac{d \dot{x}}{dt}$$
and using the chain rule on the $\sin x$ term we get the right hand side. A gentleman mentioned elliptic integrals in the comments, I have had a look on wikipedia and I am not entirely sure how to apply.


text:
Q: PHP explode string only if line does not end with '!' I'm writing a parser for a scripting programming language in PHP. The syntax of that scripting language looks like this:
ZOMFG
&This is a comment
(show "Hello, World\!");

This is a page written in that language, that displays Hello, World! in the browser. But I could also have code like this:
ZOMFG
&This is a comment !
on multiple !
lines.
(show !
"Hello, !
World\!!
");

For now I use explode("\n", $content) to explode the page's content to an array which has each line of code in a separate index.
So
ZOMFG
&This is a comment
(show "Hello, World\!");

becomes:
array('ZOMFG', '&This is a comment', '(show "Hello, World\!");');

When a line ends with a ! (except when the ! is escaped as \!), it should add that line, including the following line to the array as one single element. So
&This is a comment !
on multiple !
lines.

becomes
&This is a comment on multiple lines.

Does anyone know how to do this?

A: you should be able to use preg_split with a negative lookbehind.
(i'm finding an example)
$lines = preg_split('|(?<!\!)\n|', $code);

As per comments, aware that this causes both the newline characters and the ! to remain. Can't see an easier solution to this than str_replace at the moment - but imagine there is one ... !


text:
Q: How can I text-align the very last line of my div when there is a  present? I am trying to make so that only the very last line of text is set to text-align: justify;
My html looks like this:

Some Text goes here

My CSS:
#textbox {
    text-align: center;
    text-align-last: justify;
}

The
 is causing the second-to-last line to be justified, and the link which is the last line is also justified. The problem is that I do not want the second-to-last line to be justified. I only want the very last line be justified.
I have tried to add the following to my CSS:
a {
   text-align: justify;
}

and removing text-align-last: justify; from #textbox but I did not have any luck.
Any recommendations on how I can go about achieving this?

A: Because a tag is an inline tag,so you should wrap a tag into a block tag,say p tag,and then apply justify css style.
If you have to use a tag alone,following is an example:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore sed magni nesciunt pariatur recusandae quam. Suscipit dolorum, labore exercitationem natus!

                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis nulla autem perferendis enim deleniti magnam incidunt, maxime praesentium amet officiis.

PS:Instead of using br tag,you should use html semantically,you can use such block tags as p tag to wrap line.
About text-align-last,see css-tricks text-align-last
Hope it can help you.

A: You can assign this CSS to the the a tag:
#textbox > a {
  display: block;
  text-align-last: justify;
}

Whatever the contents of your link will be (which you didn't specify), in order to justify it, you first need to make it a block element. Then you can justify its contents.

#textbox > a {
  display: block;
  text-align-last: justify;
}

Some Text goes here
What is supposed to be here?


text:
Q: SQL Server Order first by ParentID, then Child I'm currently dealing with a database my company is phasing out, and we're trying to build a quick and dirty interface so that people can easily extract some data. A major problem with this database however, is that the primary assets are all recorded in one large table in order of when they were created, not how they relate to one another.
The gist of the database is shown below:
ParentAssetID ChildAssetID AssetName
------------------------------------
84            2            abc
35            1            cdf
956           35           PARENT35
84            1            ghi
956           3            PARENT3
35            3            jkl
956           84           PARENT84
3             5            mno

I would like to, using a select statement, output this ordered in such a way so that it appears as below:
ParentAssetID ChildAssetID AssetName
------------------------------------
956           3            PARENT3
3             5            mno
956           35           PARENT35
35            1            cdf
35            3            jkl
956           84           PARENT84
84            1            ghi
84            2            abc

As you can see, the data is first sorted by the ChildAssetID, and then each child of that asset is sorted below it. It's a pain to deal with, and that's one of the reasons why we're trying to get rid of it.
Currently, all I've got is the following:
select ParentAssetID, ChildAssetID, AssetName from dbo.Assets order by ParentAssetID

however this only groups the child assets all together without their parent headings at the start - they're all the way down the bottom at 956, grouped with their parent's children. Is there any way to sort the table like this so it's easily human readable, or will this job have to be done by hand?

A: For your example this could work:
SELECT t1.*
       FROM elbat t1
       ORDER BY CASE
                  WHEN NOT EXISTS (SELECT *
                                          FROM elbat t2
                                          WHERE t2.childassetid = t1.parentassetid) THEN
                    t1.childassetid
                  ELSE
                    t1.parentassetid
                END,
                CASE
                  WHEN NOT EXISTS (SELECT *
                                          FROM elbat t2
                                          WHERE t2.childassetid = t1.parentassetid) THEN
                    0
                  ELSE
                    1
                END,
                t1.childassetid;

db<>fiddle
The first CASE gets all children and their parent together, the second makes sure the parent is atop and then the children are sorted. If the levels in your real table are any deeper than in the example though, this might no longer work. But maybe you can make something out of it anyways.

A: you can achieve this using CTE
;with cte as
(
select
    ParentAssetID,
    ChildAssetID,
    AssetName,
    cast(row_number()over(partition by ParentAssetID order by AssetName) as varchar(max)) as [path],
    0 as level,
    row_number()over(partition by ParentAssetID order by AssetName) / power(10.0,0) as x
from Assets
where ParentAssetID =956
union all
select
    t.ParentAssetID,
    t.ChildAssetID,
    t.AssetName,
    [path] +'-'+ cast(row_number()over(partition by t.ParentAssetID order by t.AssetName) as varchar(max)),
    level+1,
    x + row_number()over(partition by t.ParentAssetID order by t.AssetName) / power(10.0,level+1)
from
    cte
join Assets t on cte.ChildAssetID = t.ParentAssetID
)

select
    ParentAssetID,
    ChildAssetID,
    AssetName,
    [path],
    x
from cte
order by x

A: Your data is a bit awkward, because "mno" has a parent of "3" and "3" is associated with two parent ids.
Other than this, you appear to want to order by the path to the top.  You can do this with a recursive CTE:
with cte as (
      select a.parentassetid, a.childassetid, a.assetname,
             convert(varchar(max), concat(format(a.parentassetid, '0000'), format(a.childassetid, '0000'))) as path, 1 as lev
      from assets a
      where not exists (select 1 from assets ap where a.parentassetid = ap.childassetid)
      union all
      select a.parentassetid, a.childassetid, a.assetname,
             convert(varchar(max), concat(cte.path, '/', format(a.childassetid, '0000'))), lev + 1
      from cte join
           assets a
           on cte.childassetid = a.parentassetid
      where lev < 10
     )
select *
from cte
order by path;

This doesn't produce exactly what you want, because "mno" is duplicated.  I would assume that is a transcription error.
If this is not a transcription error and you want the first time that a row occurs, you can use:
select cte.*
from (select cte.*,
             row_number() over (partition by parentassetid, childassetid order by lev asc) as seqnum
      from cte
     ) cte
where seqnum = 1
order by path

Here is a db<>fiddle.

A: Is this what you are looking for?
select
    ParentAssetID,
    ChildAssetID,
    AssetName
from dbo.Assets
order by ParentAssetID desc, ChildAssetID asc;

A: Testing answer from @Krishna Muppalla (https://stackoverflow.com/a/59174634/956364)
Is there a way to not use the power(10) functions? I've never seen them used to sort like this!
drop table if exists #Assets;

create table #Assets( [ParentAssetID] int, [ChildAssetID] int, [AssetName] varchar(30) );

insert into #Assets( [ParentAssetID], [ChildAssetID], [AssetName] )
select 84,  2,  'abc' union all
select 35,  1,  'cdf' union all
select 956, 35, 'PARENT35' union all
select 84,  1,  'ghi' union all
select 956, 3,  'PARENT3' union all
select 35,  3,  'jkl' union all
select 956, 84, 'PARENT84' union all
select 3,   5,  'mno';

declare @one float = 1; --I don't know if power(10.0,0) was being recomputed each call.

with [cte] as (
        select
            [ParentAssetID],
            [ChildAssetID],
            [AssetName],
            0 [level],
            row_number() over( partition by [ParentAssetID] order by [AssetName] ) / @one [x]
        from #Assets
        where [ParentAssetID] = 956 --this is bad. How do we get around this?
    union all
        select
            t.[ParentAssetID],
            t.[ChildAssetID],
            t.[AssetName],
            [level] + 1,
            [x] + row_number() over( partition by t.[ParentAssetID] order by t.[AssetName] ) / power(10.0, [level] + 1) [x]
        from [cte]
        join #Assets t on cte.[ChildAssetID] = t.[ParentAssetID]
)
select
    [ParentAssetID],
    [ChildAssetID],
    [AssetName]
    ,[x]
from [cte]
order by [x];


text:
Q: How can I use ggplot() to create this plot? This is my data frame:
library(ggplot2)
Year <- c(2019,2018,2017,2016,2015)
googlerev <- c(161857,136819,110855,90272,74989)
ibmrev <- c(77147,79591,79139,79919,81741)
df <- data.frame(Year, googlerev, ibmrev)
df
#>   Year googlerev ibmrev
#> 1 2019    161857  77147
#> 2 2018    136819  79591
#> 3 2017    110855  79139
#> 4 2016     90272  79919
#> 5 2015     74989  81741

How can I make a plot as shown in the picture below:

(Revenue represents the value of google rev and ibmrev).

A: We can use pivot_longer from the tidyr package to change your data, then use geom_col:
library(tidyr)

df %>%
    pivot_longer(cols = -Year, names_to = "company", values_to = "revenue") %>%
    ggplot(aes(Year, revenue, fill = company))+
    geom_col(position = 'dodge')

A: This will be easier with long formatted data to control ggplot behavior. You can use reshape2 package for that.
library(ggplot2)
df <- reshape2::melt(df, id.vars = "Year")

ggplot(df, aes(x = Year, y = value, fill = variable)) +
   geom_bar(stat = "identity", position = "dodge") +
   labs(x = "Year", y = "Revenue")


text:
Q: How can I eliminate wxListCtrl flicker while scrolling? I'm using wxListCtrl within a wxWidgets application, and can't seem to eliminate the flickering that occurs while scrolling through a large list of items quickly (e.g. holding the 'page down' key.)  The list control is created as a virtual/report list, and I'm testing under Win7 at the moment.
It appears the background clear is causing the flickering, though I can't simply override it because it's required for the text/borders to appear correctly.
I believe what I need is a way to do double buffering, where the list isn't updated visually until after both the background is cleared and the items are drawn (offscreen.)  Does anyone know how to do this in wxWidgets?  Or is there a better way?
Many thanks...

A: Using the VCL version of TListView I call pListView->DoubleBuffered = true; If there is a property under wxWidgets that like you might try it.


text:
Q: Using application.ini for configuring Zend_Application Bootstrap I have written custom resources for my Zend_Application bootstrap.
In the manual the following code is given for loading them:
$application = new Zend_Application(APPLICATION_ENV, array(
    'pluginPaths' => array(
        'My_Resource' => APPLICATION_PATH . '/resources/',
    ),
    'resources' => array(
        'FrontController' => array(
            'controllerDirectory' => APPLICATION_PATH . '/controllers',
        ),
    ),
));

This however does not make use of the application.ini which I want to use. Is there a possibility to configure this completely from my application.ini?
My final solution: (with help of Will's answer):

*

*create an empty project with zf.sh create project (version 1.9.6)

*make the following class in application/resources/Ftp.php
class My_Resource_Ftp extends Zend_Application_Resource_ResourceAbstract
{
    protected $_params = array();
    public function init() {
        echo "init invoked";
        return array("hey");
    }
}

*The following application.ini
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"

pluginPaths.My_Resource = APPLICATION_PATH "/resources/"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"

resources.ftp.username = "me"

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

A: Yes, you just have to use the path to your application.ini as the second argument to the constructor, e.g:
$application = new Zend_Application(
  APPLICATION_ENV,
  APPLICATION_PATH . '/config/application.ini'
);

This is the approach the quick start guide takes: http://framework.zend.com/manual/en/zend.application.quick-start.html
In your .ini file you would then add resource paths like:
pluginPaths.My_Resource = APPLICATION_PATH "/resources/"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"


text:
Q: Difficulties with total cost of graph in Dijkstra algorithm in python I'm currently trying to make an algorithm that gives me the total cost of a graph when all nodes have been visited but am failing miserably and honestly out of ideas. My goal is to get the total costs of the graphs below, using the Dijkstra algorithm.
Here's what I have so far:
from collections import defaultdict
import heapq

def build_graph():
    # Create the graph with the all given nodes and costs
    edges = aeroDistances
    graph = defaultdict(dict)

    for edge in edges.items():
        tuple1 = edge[0][0]
        tuple2 = edge[0][1]
        cost = edge[1]

        connection1 = {tuple2 : cost}
        connection2 = {tuple1 : cost}

        graph[tuple1].update(connection1)
        graph[tuple2].update(connection2)

    return dict(graph)

def dijkstra(graph, starting_vertex):
    # All the distances set to infinity
    distances = {vertex: float('infinity') for vertex in graph}
    # Distance from the starting vertex
    distances[starting_vertex] = 0
    # Priority queue
    pq = [(0, starting_vertex)]

    while len(pq) > 0:
        current_distance, current_vertex = heapq.heappop(pq)

        # Nodes can get added to the priority queue multiple times. We only
        # process a vertex the first time we remove it from the priority queue
        if current_distance > distances[current_vertex]:
            continue

        for neighbor, weight in graph[current_vertex].items():
            distance = current_distance + weight
            # Only consider this new path if it's better than any path we've
            # already found
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, neighbor))

    return distances, distance

numCidades = 0
numAeroportos = 0
numEstradas = 0
#custoAeroportos = {}
#custoEstradas = {}

#custoAeroportos = {(1, 2): 2, (1, 3): 4}
#custoEstradas = {(3, 1, 'E'): 2}

#custoAeroportos = {(1, 2): 1, (2, 3): 2, (3, 4): 1, (4, 1): 1}
custoAeroportos = {(1, 2): 1, (1, 3): 6, (2, 4): 2, (3, 4): 2}
custoEstradas = {(2, 3): 3}

listCidades = [1,2,3]
distances = []
indexValue = 0
indexKey = 0
currentIndex = 0

# Deconstruct the dict into a list of keys (tuples)
# Deconstruct the dict into a list of values
# Make it easier to sort the connections by creating a list of tuples and
# their respective weights and zip them toghether
distancesAeroKeys = list(custoAeroportos.keys())
distancesAeroValues = list(custoAeroportos.values())
aeroDistances = dict(map(list, zip(*[distancesAeroKeys, distancesAeroValues])))

print()
print("AeroDistances: " + str(aeroDistances))

graph = build_graph()
print()
print("Graph: " + str(graph))
print()
print("Dijkstra: " + str(dijkstra(graph, 1)))

The two graphs, dicts, I'm currently trying this with are named custoAeroportos and I can't seem to get the total minimum cost when all nodes are visited.
Here're the graphs, they are fairly simple:
This one has a total cost of 5
This one has a total cost of 3
The total cost I'm getting is wrong and I can't figure it out.
For the first graph:
AeroDistances: {(1, 2): 1, (1, 3): 6, (2, 4): 2, (3, 4): 2}

Graph: {1: {2: 1, 3: 6}, 2: {1: 1, 4: 2}, 3: {1: 6, 4: 2}, 4: {2: 2, 3: 2}}

Dijkstra: ({1: 0, 2: 1, 3: 5, 4: 3}, 7)

For the second graph, which somehow is correct:
AeroDistances: {(1, 2): 1, (2, 3): 2, (3, 4): 1, (4, 1): 1}

Graph: {1: {2: 1, 4: 1}, 2: {1: 1, 3: 2}, 3: {2: 2, 4: 1}, 4: {3: 1, 1: 1}}

Dijkstra: ({1: 0, 2: 1, 3: 2, 4: 1}, 3)

I really appreciate your help, thank you.

A: Your function returns the distance of the path from the starting vertex to whichever was the last node that was added to the heap. This is not really what you want to return. Certainly when the BFS-tree has multiple outgoing edges from some vertices, this path has little to do with the total distance.
Instead you need to accumulate the weights of the edges that are "accepted", i.e. those that are (implicitly) popped from the heap and improve the distance for that node.
So I would suggest extending the tuples on the heap with one more information: the weight of the last edge that brought us to that node. When the node is accepted, then this edge becomes part of the spanning tree, and its weight should then be added to an accumulating total.
Here is the adapted code. The changes have accompanying comments:
def dijkstra(graph, starting_vertex):
    distances = {vertex: float('infinity') for vertex in graph}
    distances[starting_vertex] = 0
    graph_distance = 0  # this will be returned
    pq = [(0, 0, starting_vertex)]  # middle value is edge weight

    while len(pq) > 0:
        current_distance, edge_weight, current_vertex = heapq.heappop(pq)
        if current_distance > distances[current_vertex]:
            continue

        graph_distance += edge_weight  # accumulate

        for neighbor, weight in graph[current_vertex].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, weight, neighbor))  # include weight

    return distances, graph_distance  # ...return it


text:
Q: Getting IdentityManager to make changes on two different databases We have two databases with User tables like below:

*

*MasterDB.AspNetUsers

*Customer1DB.AspNetUsers

We use MasterDb to log-in the users and then we connect them to a customer database, for example Customer1DB (or some other customer db depending on the user). Both user tables have identical schemas based on ASP.NET Identity Framework and we can use IdentityManager to manage users on MasterDb.
Now what I want is any changes performed on a MasterDb user record, mirror that to the users table on the customer's database (with same user Id). I was wondering what is the best way to do this? Do I need to modify all operations on UserStore, RoleStore, UserManager, RoleManager? I have a function that gets a UserId and adds or updates it from the first db to the second db, but I'm not sure how exactly I should integrate it in the Identity Framework implementations.
Thanks!

A: I think you have 2 options:

*

*Create adapters for the stores and functions you need. The adapters will call the same method on both databases.

*In the Master DbContext, when you SaveChanges, you look at the ChangeTracker and duplicate the changes to the other DbContext.
Each method has is advantages and inconveniences.
1
Sample adapter:
class MultiDatabaseUserStore<T> : IUserStore<T>
    where T : IdentityUser
{
    private readonly UserStore<T>[] stores;

    public MultiDatabaseUserStore(params IdentityDbContext[] dbContexts)
    {
        if (dbContexts == null || dbContexts.Length <= 0)
        {
            throw new ArgumentException("At least one db context is required.", "dbContexts");
        }

        this.stores = dbContexts.Select(x => new UserStore<T>(x)).ToArray();
    }

    public void Dispose()
    {
        foreach (var store in this.stores)
        {
            store.Dispose();
        }
    }

    public Task CreateAsync(T user)
    {
        return this.ExecuteOnAll(x => x.CreateAsync(user));
    }

    public Task UpdateAsync(T user)
    {
        return this.ExecuteOnAll(x => x.UpdateAsync(user));
    }

    public Task DeleteAsync(T user)
    {
        return this.ExecuteOnAll(x => x.DeleteAsync(user));
    }

    public Task<T> FindByIdAsync(string userId)
    {
        return this.stores.First().FindByIdAsync(userId);
    }

    public Task<T> FindByNameAsync(string userName)
    {
        return this.stores.First().FindByNameAsync(userName);
    }

    private Task ExecuteOnAll(Func<UserStore<T>, Task> function)
    {
        return Task.WhenAll(this.stores.Select(function));
    }
}

And it integrates like this:
var store = new MultiDatabaseUserStore<IdentityUser>(new MasterDb(), new Customer1DB());
var userManager = new UserManager<IdentityUser>(store);

This works but depending on your needs you will have a lot more interfaces to implement:

*

*IUserLoginStore

*IUserClaimStore

*IUserRoleStore

*IUserPasswordStore

*IUserSecurityStampStore

*IQueryableUserStore

*IUserEmailStore

*IUserPhoneNumberStore

*IUserTwoFactorStore

*IUserLockoutStore

2
Sample Master DbContext:
class MasterDb : IdentityDbContext
{
    public MasterDb()
    {
    }

    public override int SaveChanges()
    {
        var changes = this.GetChangesToReplicate();

        var i = base.SaveChanges();

        this.SaveReplicatedChanges(changes);

        return i;
    }

    public override Task<int> SaveChangesAsync()
    {
        return Task.Run(async () =>
        {
            var changes = this.GetChangesToReplicate();

            var i = await base.SaveChangesAsync();

            this.SaveReplicatedChanges(changes);

            return i;
        });
    }

    private void SaveReplicatedChanges(IEnumerable<Action<IdentityDbContext>> changes)
    {
        if (changes != null)
        {
            using (var db = new Customer1DB())
            {
                foreach (var change in changes)
                {
                    change(db);
                }

                db.SaveChanges();
            }
        }
    }

    private IEnumerable<Action<IdentityDbContext>> GetChangesToReplicate()
    {
        var actions = new List<Action<IdentityDbContext>>();
        var userTye = typeof(IdentityUser);
        var changedEntries = this.ChangeTracker.Entries();
        var users = changedEntries.Where(x => x.Entity.GetType() == userTye).ToList();

        foreach (var u in users)
        {
            switch (u.State)
            {
                case EntityState.Added:
                    var userToAdd = (IdentityUser)u.Entity;
                    actions.Add(db => db.Users.Add(userToAdd));
                    break;

                case EntityState.Modified:
                    var userToUpdate = (IdentityUser)u.Entity; ;
                    actions.Add(db =>
                    {
                        db.Users.Attach(userToUpdate);
                        db.Entry(userToUpdate).State = EntityState.Modified;
                    });
                    break;

                case EntityState.Deleted:
                    var userToDelete = (IdentityUser)u.Entity; ;
                    actions.Add(db =>
                    {
                        db.Users.Attach(userToDelete);
                        db.Entry(userToDelete).State = EntityState.Deleted;
                    });
                    break;
            }
        }

        return actions;
    }
}

This also works but it's limited to the user entity. You will have to add replication of roles, claims,... depending on your needs.
2 Improved
Thinking about it, you can skip the type check and just replicated all changes to the other DbContext. This simplifies a lot the code and it will work for roles/claims. You would also need to add a bool property IsReplicatingChanges to enable the replication only when necessary.
You will have to create an instance only for the identity Stores and set the flag to true:
var dbContext = new MasterDb { IsReplicatingChanges = true };
var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(dbContext));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(dbContext));

And GetChangesToReplicate() becomes:
private IEnumerable<Action<IdentityDbContext>> GetChangesToReplicate()
{
    if (!this.IsReplicatingChanges) // Flag
    {
        // Return null when not activated
        return null;
    }

    var actions = new List<Action<IdentityDbContext>>();
    var changedEntries = this.ChangeTracker.Entries().Where(x => x.State != EntityState.Unchanged);

    foreach (var u in changedEntries)
    {
        var entity = u.Entity;
        var state = u.State;

        actions.Add(db =>
        {
            db.Set(entity.GetType()).Attach(entity);
            db.Entry(entity).State = state;
        });
    }

    return actions;
}

And don't forget to add the null check to SaveReplicatedChanges().


text:
Q: Pyqt4 accessing objects when creating a dynamic form I have created a layout which adds labels and lineedits automatically, once i assigned it into the list, but for me to create a user I need the values from the line edits and comboxes but as you can see I have set each object names, how could i access all the values in my tryCreateUser() function? as you can see i checked by printing edit but that only gives me the last object!! Thanks for help in advance!
def addNewUser(self):
    def tryCreateUser():
        print(edit)

    self.deleteLayout(self.dynamicFrame.layout())

    grid = QtGui.QGridLayout()
    grid.setSpacing(10)
    row = 1
    column = 1
    edit = ['First Name', 1, 'Last Name', 1, 'Date of Birth', 2, '', 'Gender', 3, 'Access Level', 4, 'Password', 5, 'Verify Password', 5]

    for item in edit:
        if item == '':
            self.dob = QtGui.QLabel()
            grid.addWidget(self.dob, 3, 3)
            column -= 1
        else:
            if item == 1:
                edit = QtGui.QLineEdit()
            elif item == 2:
                edit = QtGui.QPushButton('Choose')
                edit.clicked.connect(self.openCal)
            elif item == 3:
                edit = QtGui.QComboBox()
                edit.addItem('Male')
                edit.addItem('Female')
            elif item == 4:
                edit = QtGui.QComboBox()
                edit.addItem('General Staff')
                edit.addItem('Stock Admin')
                edit.addItem('Manager')
            elif item == 5:
                edit = QtGui.QLineEdit()
                edit.setEchoMode(QtGui.QLineEdit.Password)
            else:
                edit = QtGui.QLabel(item)

        edit.setObjectName(str(item))
        grid.addWidget(edit, row, column)
        if column >= 2:
            column = 1
            row += 1
        else:
            column += 1

    createButton = QtGui.QPushButton("Create User")
    createButton.clicked.connect(tryCreateUser)
    cancelButton = QtGui.QPushButton("Cancel")
    cancelButton.clicked.connect(self.populateUser)
    grid.addWidget(createButton, row , column)
    grid.addWidget(cancelButton, row, (column+1))

    self.dynamicFrame.setLayout(grid)

A: You should have each button register itself with a dictionary somewhere. Try this instead:
from collections import namedtuple

Button = namedtuple('Button', ["title", "to_do"])

buttons_to_make = [Button("First Name", [1]),
                   Button("Last Name", [1]),
                   Button("Date of Birth", [2, '']),
                   ...]

self.buttons = {}
for button in buttons_to_make:
    for action in button.to_do:
        # your big long if/elif structure here, e.g.:
        if action == 1:
            b = QtGui.QLineEdit()
        elif action == 2:
            b = QtGui.QPushButton('Choose')
            b.clicked.connect(self.openCal)
        # etc
    self.buttons[button.title] = b

Then you have a central repository of all your stuff there in buttons, and can iterate on that.
def tryCreateUser():
    for title, button in self.buttons.items():
        print("Title is {}, button obj is {}".format(title, button))

Note that this isn't exactly the way I'd do it, but it IS the closest to your original example. Honestly each of those if blocks should be its own function, such that you'd have something like:
def __create_QLineEdit(self):
    b = QtGui.QLineEdit()
    return b

def __create_QPushButton(self):
    b = QtGui.QPushButton("Choose")
    b.clicked.connect(self.openCal)
    self.dob = QtGui.QLabel()
    grid.addWidget(self.dob, 3, 3)
    column -= 1
    return b

...

Then you'd define your namedtuple as:
Button = namedtuple("Button", ['name','action'])

And define buttons_to_make as
buttons_to_make = [Button("First Name", self.__create_QLineEdit),
                   Button("Last Name", self.__create_QLineEdit),
                   Button("Date of Birth", self.__create_QPushButton),
                   ...]

and execute with:
buttons = {}
for button in buttons_to_make:
    name, action = button
    buttons[name] = action()


text:
Q: Disable mobile Chrome 43's "Touch to Search" feature programmatically When I select text in Chrome 43 on my Android device I get the "Touch to Search" popup. We're currently using text selection for a feature on our site and this new Chrome feature interferes with some of our UI.
In the long run, we'll be working out new UI/UX to work side-by-side with this feature, but in the interim, we want to disable it on our web app.
Is there some sort of meta tag or JavaScript we can add to turn this off? Does anyone know if this is currently possible?

A: Possible workaround could be to wrap text in <button> tag. This obviously wouldn't work if talking about big blocks of text, but for other elements like titles, icons and other small stuff this works fine.

A: This can be manipulated in a number of ways.  The user can turn it off in flags as PaulI suggested, and you can control it.
Developer control, right now there are a couple of options but the basic summary is if we think it is an user interactable element then it won't be enabled:

*

*CSS: -webkit-user-select: none;

*HTML:

*

*Anything with an aria-role will not have the touch to search enbabled

*Anything with a tabindex of -1 or > 0

A: As of 2021, it isn't possible to disable touch-to-search (when this is triggered by a long-press for text selection) in chrome mobile. The article that Kinlan is referencing is apparently concerned only with touch-to-search triggered through a tap gesture.
Quoting donnd, from bugs.chromium.org:

Regarding #2 -- developer control: The 2015 article that you mentioned (https://developers.google.com/web/updates/2015/10/tap-to-search) focuses on triggering through the tap gesture. As you correctly point out, it does not address the long-press gesture triggering. Touch to Search responds to both tap and long-press but treats them differently. As I'm sure you know, the long-press gesture activates a whole set of features which can include copy, translation, smart text selection, and Web Search. A site developer can markup their page text as non-selectable in order to disable the long-press gesture entirely, but currently there's no way to disable only the Touch to Search response to long pressing. If you'd like to work with us to add such a feature, let us know and we'll file a separate feature request.

A: If you want disabled "touch to search" in a menu that has an action open / close (toggle), it is necessary to javascript :
event.preventDefault();

A: Navigate to about:flags or chrome:flags and look for Enable Contextual Search
Then toggle to Disabled and hit restart at the bottom.