Django foreign key model is not saving reference

Question: I am having an issue on saving my model, my UserProfile reference on a foreign key to a Customer, and I have gotten sure that my form in sending the needed info and the customer object is being loaded, however when I save my model, this lost the reference to customer
My code is
models.py
from django.db import models
from customers.models import Customer
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from anfitrion.models import ModelBase
from django.db.models.signals import post_save

class UserProfile(ModelBase):
    user = models.OneToOneField(User)
    customer = models.ForeignKey(Customer)
    address = models.CharField(max_length = 255)
    phone_home = models.CharField(max_length = 16)
    phone_office = models.CharField(max_length = 16)
    expiration = models.DateTimeField(null=True, blank=True)
    picture = models.ImageField(upload_to='profiles/%Y/%m/%d')
    observations = models.TextField(null=True, blank=True)
    status = models.BooleanField()

    def __str__(self):
        return "%s's profile" % self.user

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(create_user_profile, sender=User)

class SiteProfile(ModelBase):
    site = models.OneToOneField(Site)

    def __str__(self):
        return "%s's profile" % self.user

def create_site_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = SiteProfile.objects.get_or_create(site=instance)

post_save.connect(create_site_profile, sender=Site)

function running the saveing
def users_save (request):
    #try:
        if request.is_ajax() and request.POST:
            user_id = request.POST['user_id']
            s = get_current_site(request)
            u = User (
                      username = request.POST['username'],
                      first_name = request.POST['first_name'],
                      last_name = request.POST['last_name'],
                      email = request.POST['email']
                      )
            u.set_password(request.POST['password'])
            c = None
            if int( request.POST['customer_id'] ) > 0:
                c = Customer.objects.get(id=request.POST['customer_id'])
            up = UserProfile(
                      customer = c,
                      address = request.POST['address'],
                      phone_home = request.POST['phone_home'],
                      phone_office = request.POST['phone_office']
                      )
            up.user = u
            u.save()
            if int( request.POST['group_id'] ) > 0:
                g = Group.objects.get( id = request.POST['group_id'] )
                g.user_set.add(u)
            return HttpResponse(1, mimetype='application/json')

Answer: Here
up.user = u
u.save()

You are not saving the up anywhere.
So u.save() should be up.save()
u.save()
up.user = u
up.save()

Comment: yes, as you could see my model file, I am working on the user framework extension. I have also do that after saving my User model, however a new error appear that said me that "user_id field" could not be null
Comment: I assumed you were saving the user object elsewhere. edited the answer
Comment: Yes, but as you propose it will try to save the object two times cause  I am using " post_save.connect(create_user_profile, sender=User) ", then doing that generated a double saving try
Comment: you are not doing anything useful in the post_save signal. Just get rid of it. You are already creating it in the view.
Comment: Actually, the second time (in post_save), you are only doing a database query - the get returns userprofile type. It is __not__ saving twice
Comment: You are right, I just trying be as close as possible django way docs, but at this case is not useful. thanks a lot


asking advice for the schduled task

Question: I am about to implement the schduled kind of task, not sure whether should implement in window sevice or window schduler.
The use case is, there will be one executable deployed on the mechine, which is attached to the scanner.  For every five minutes, the exe will be reading the scanned files from the specified folder and upload the files to the server.
What would be the best solution for this use case.
Thanks
Answer: Use a scheduled task. A windows service would have to be specially written, and this is perfectly suited for a simple job which runs at 5 minute intervals.
Answer: You'll find some good comparisons here:
windows service vs scheduled task
Personally, I would use the Windows Service because it is easier to troubleshoot, locate the logs and restart if necessary.

asking advice for the schduled task


Finding the effective annual rate of interest (no constant)

Question: A deposit of 10,000 is done. During first year, the bank credits an annual effective interest rate of $\text {i}$. During the second year, the bank credits an annual effective interest rate of $\text {i-5%}$. After two years, he has 12,093.75
What would be the amount earned by an annual effective interest rate of $\text {i+9%}$ for each of the three years?
So, we need to solve for $\text {i}$ from $A(2)=10,000[1+(i-0.05)]^2=12,093.75$
$$i=\Bigg(\frac{12,093.75}{10,000}\Bigg)^{1/2}-0.95, \text {for t=2}$$
But when substituted in $A(2)$, $A(2)\ne 12,093.75$
I'm new at this. How it is supposed to be done?
Answer: If the first year's effective interest rate is $i$, then at the end of the first year, the deposit will be $10000(1+i)$.  Then, if the second year's rate is $i - 0.05$, then at the end of the second year, the deposit will be
$$10000(1+i)(1 + i - 0.05).$$
This is the amount that must equal $12093.75$.  Then the question asks, if the interest rate had been $i+0.09$ for all three years, then I would interpret that to mean the accumulated value $$10000(1 + i + 0.09)^3,$$
where $i$ was the rate calculated earlier.
Comment: Thanks! I just solved it


Search and delete in double linked list

Question: I want to search something in a double linked list and delete it.
My problem is that I lose both previous and the node of the node I want to delete.
Here is my code:
    int delnode(string moviename)
        {
            node *temp,*del;
            //check empty
            if(!head)
                {
                    cout<<"empty";
                }
            else
                {
                    temp=head;
                while (temp->next!=NULL)
                    {

                        if (temp->title==moviename)
                            {
                                del=temp;
                                temp=temp->previous;
                                temp->next=del->next;
                                delete del;
                            }
                        temp=temp->next;
                    }
                }
        }

For example if I have 5 movies, movie1,movie2,movie3,movie4,movie5 and want to delete movie3 my list will be movie1,movie4,movie5 :S
Comment: Consider separating the two operations into separate functions.  Make a find that takes a movie name and returns a pointer to the node.  Make a separate function that takes a pointer to the node and deletes it.
Answer: You're making this incredibly hard on yourself. Your code has a number of problems, including:

failure to properly wire the previous pointers
failure to account for a last-node deletion.
failure to advance the head pointer if it was the prospect node.

Considering that, I think this does what you want, and I strongly advise you to examine it carefully, even stepping through it in a debugger to see how it works.
void delnode(const std::string& moviename)
{
    // pp holds the address of the pointer that will
    //  eventually point to our node being deleted.
    node **pp = &head;

    // skip nodes until we find a match
    while (*pp && (*pp)->title.compare(moviename))
        pp = &(*pp)->next;

    if (*pp)
    {
        node *tmp = *pp;
        if ((*pp = tmp->next)) // assignment-eval intentional
            (*pp)->previous = tmp->previous;
        delete tmp;
    }
}

This solves a number of issues, including

properly updating the head pointer if it was the node matching your string.
properly wiring next and previous to all proper pointers
properly removing the last node in the list if that is your suspect node.
doing absolutely nothing if the head pointer is null.
Comment: This is working perfect, i just need some time to understand it :D
Thanks!
Comment: @DeviLFisH you need to *seriously* understand how pointers work. Above all remember this: a pointer is nothing more than a variable that *holds* the address of someplace that contains the data type of the pointer. *And this is true for pointers-to-pointers as well.*. Ex: Given `int a, *p=&a` `p` holds the address of `a`, an `int` variable. Now consider this: `int a, *p=&a, **pp=&p` As before, `p` holds the address of `a`. And  in *exactly* the same way, `pp` holds the address of `p`. Getting a grip on that will really help you understand this code.
Answer: You're not updating the previous link on what is temp->next at the end of it all.
You need to add in temp->next->previous = temp just before the delete del line, since you're using a double linked list.
Comment: I add "temp->next->previous = temp" before delete, but i have the same result
Answer: You have several problems.
If your list only has one item, you'll never test it because of
if ( temp->next != NULL )

If your item is at the head of the list that you want to delete, you don't update head and you're code will crash anyways because you don't test that temp->previous is valid.
And if you delete an item, you don't update the back pointer as @Leigh mentioned.
Here is my unlink an item code from my list template:
void    untie_pointer( _Tp * aptr )
{
    if ( aptr )
    {
        if ( aptr-> prior() ) { aptr-> prev_-> next_= aptr-> next_ ; }
            else { if ( first_ == aptr ) { first_= aptr-> next_ ;  if (first_) { first_-> pr
ev_= nullptr ; } } }
        aptr -> prev_= nullptr ;
        if ( aptr-> next() ) { aptr-> next_-> prev_= aptr-> prev_ ; }
            else { if ( last_ == aptr ) { last_= aptr-> prev_ ;  if ( last_ ) { last_-> next
_= nullptr ; } } }
        aptr-> next_= nullptr ;
    }
}

Its because of all these cases that the gcc stl list uses a sentinel object.
Comment: what i noticed when looking at your code snippet is that how ugly it looks when you make your variables with underscore `_` and use it with object pointer dereferencing with `->`
Comment: It is, but since its internal private implementation code, hopefully nobody will ever have to look at it.
Comment: yes, same as stl source code. But providing it in an answer should not be done.
Answer: Here is a code I wrote to check if the node
1.is in the front and no nodes after it.
2.is in the front and have nodes after it.
3.the node is the last node
4.a node is in the nth position
void deleteRear()
{
if(n == NULL)
{
cout <<"No People Found" << endl;
}
else
{
node *temp1;
if(n == NULL)
{
cout<<"No People Found"<<endl;
}
else
{
temp1 = start_ptr;
if(temp1->prev == NULL && temp1->nxt == NULL)
{
start_ptr = NULL;
delete temp1;
n = NULL;
}
else
{
while (temp1->nxt != NULL)
{
temp1 = temp1->nxt;
end_ptr= temp1->prev;
}
end_ptr->nxt = NULL;
delete temp1;
cout<<end_ptr->name<<endl;
}
}
}
}
void deleteAPerson()
{
if(n == NULL)
{
cout <<"No People Found" << endl;
}
else
{
node *temp1;
temp1 = start_ptr;
while(temp1 != NULL)
{
cout << "Name : " << temp1->name << endl;

temp1 = temp1 ->nxt;
}
node *temp, *temp2, *temp3, *temp4;
temp = start_ptr;
string names;
cout << "Please Enter Person's Name: >>";
cin >> names;
while(temp->nxt != NULL && temp->name != names)
{
temp = temp->nxt;
}
if (temp->name == names)
{
if(temp->prev == NULL && temp->nxt == NULL)
{
cout<<"Deleting Front"<<endl;
cout<<"Only one person on the list"<<endl;
temp = start_ptr;
start_ptr = NULL;
delete temp;
n = NULL;
}
else if (temp->prev == NULL && temp->nxt != NULL)
{
cout<<"Deleting Front"<<endl;
cout<<"There are other people on the list"<<endl;
temp2 = start_ptr;
start_ptr = start_ptr->nxt;
start_ptr->prev = NULL;
delete temp2;
}
else if(temp->prev != NULL && temp->nxt == NULL)
{
cout<<"Deleting End"<<endl;
deleteRear();
}
else
{
current = temp;
current->prev->nxt = current->nxt;
current->nxt->prev = current->prev;
delete current;
}
}
else
{
cout<<"No such person exists"<<endl;
}
}
}

Search and delete in double linked list


Translate message from tabledrag.js

Question: I try to translate the message that is used in the following JavaScript code.
<code>Drupal.t('Changes made in this table will not be saved until the form is submitted.')
</code>
I use the String Overrides module; I tried also translation using settings.php. None of the methods work.
Does anybody have an idea on how to translate the sentence? I do not want to use big modules like localize.
Answer: Drupal loaded only the needed strings on every page which we are included.
Those strings are added in javascript itself.
I think this is fixed by across the script files before they are actually added to the page.
So, you should be able to translate that string into the translate interface.
For more help, You can see this link,
https://www.drupal.org/node/323109
Hope it will be helpful.
Comment: I think you need to use localize module without this you can not do translation.
Comment: Hi, I am not able to translate the string without localize module. Is there any workaround?
Comment: Unless you use localize or internationalization modules you can not translate any string, though it is included in the t() function.

Translate message from tabledrag.js


Excel VB Button

Question: In the "ActiveSheet.Buttons" I get the size of the buttons but not the text that I want, it only shows "Button 1" (whatever number shows up).  Can anyone tell me how to get a custom text in the button?
Sub AT()
    Sheets("134B").Select
    Sheets("New Tab").Visible = True
    Sheets("New Tab").Select
    ActiveSheet.Buttons.Add(0.75, 0.75, 36, 28.5).Select
    ActiveSheet.Buttons.Add(37.5, 0.75, 17.25, 28.5).Select
    ActiveSheet.Buttons.Add(55.5, 0.75, 17.25, 28.5).Select
    ActiveSheet.Buttons.Add(73.5, 0.75, 36, 28.5).Select
    Sheets("New Tab").Copy Before:=Sheets(3)
    Sheets("New Tab").Select
    ActiveWindow.SelectedSheets.Visible = False
    Sheets("New Tab (2)").Select
    ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
    Sheets("DB").Select
    Range("J23").Select
End Sub

Answer: ActiveSheet.Buttons.Add(0.75, 0.75, 36, 28.5).Caption= "Hi!"

Comment: @tigeravatar: He is recently known for that... Just pray he doesn't have his coffee :p

Excel VB Button


Weird Spaces After PHP Generated HTML

Question: I have a weird issue. I have a dynamic website www.lamanscanada.com it appears fine in firefox and safari and almost perfect in IE7. But it appears that on certain php generated html. There is a bunch of space added after the function output. I also user mod_rewrite for nice SEO urls just a note.
The function sorts an array of data into columns with bullets
<?php
//breaks array values into two columns
function groupBullets($array){
   //count the array items
   $bulletcount = count($array);
   //divides that in two and round the result
   $roundhalf = round(($bulletcount/2));
   //initailize a counting variable
   $i=1;
   //loop throught the array
   foreach($array as $bullet){
       //if it is the first item
       if($i==1){
           echo "";//open the main container div
       }
       echo "• $bullet";//then create bullet
       //if the counter is at the half mark
       if($i==$roundhalf){
           echo "";//close the container
           $i=1;//and start the counter over
       }else{
           $i++;//if not at half keep counting
       }
   }
}
//end

//I am implementing it like this:
//this is my array it actually has a second level
$array = array(
        columngroup01("bullet 1","bullet 2","bullet 3","bullet 4"),
        columngroup02("bullet 1","bullet 2","bullet 3","bullet 4")
);

//I loop through this array
foreach($array as $column=>$arrayofbullets){
    echo "
".//open the div contains the columns
    "
$column
";//print the title of the column
    //use the groupBullets function on each array of bullets
    groupBullets($arrayofbullets);
    echo "
";//close the column container
}
?>

Comment: Do you get this problem fixed or do you still want help regarding this question?
Answer: The  is not being closed at the end of the generated list of  tags.
Current generated output:

features

        • 10'X6'X8' Aluminum Extrusion Structure
        • R18 Insulated Panels
        ...

Needs to be:

features

        • 10'X6'X8' Aluminum Extrusion Structure
        • R18 Insulated Panels
        ...

Comment: Wow one of those things.... Sometimes all you need is a fresh set of eyes, Greatly appreciated.

Weird Spaces After PHP Generated HTML


How can I input password to manage-bde -pw option via windows powershell

Question: I am trying to encrypt Data volume (for example E:) with the following command:
manage-bde -protectors -add E: -pw

When I execute the above command, it will ask for the password, so I entered it. It is successfully encrypting my data volume. Now, I want to make a script to encrypt a data volume, so I need to pass the password as an argument to the above powershell command.
How can I do that? Is there any option of passing the password for manage-bde command?
Comment: Be aware that `manage-bde` is a command line executable and not a PowerShell cmdlet (although it tries to emulate PowerShell's parameter syntax) - and according to the documentation, `manage-bde` does not seem to support scripted password inputs, even the `-changepassword` context prompts for the password interactively :(
Comment: There is no option of achieving this? :(
Answer: If you're working on Windows Server 2012 or newer, you can use the BitLocker cmdlets:
Add-BitLockerKeyProtector -MountPoint "E:" -Password ("Password" | ConvertTo-SecureString -AsPlainText -Force) -PasswordProtector

The Add-BitLockerKeyProtector cmdlet accepts the password in the form of a SecureString object, which is why we pipe the plaintext "Password" to ConvertTo-SecureString
Comment: I am using Windows 7, is there any option of achieving the same on windows 7?
Comment: @SureshKota Sorry, the PowerShell module is not available on Windows 7 according to this [RSAT support matrix](http://social.technet.microsoft.com/wiki/contents/articles/2202.remote-server-administration-tools-rsat-for-windows-client-and-windows-server-dsforum2wiki.aspx#RSAT_Platform_and_Tools_Support_Matrix)


Exists point c such that property

Question:
Let $f : \mathbb{R} \to (0, \infty)$. Show if $f$ is continous, exists $\alpha \in \mathbb{R}$ such that $f(\alpha) = \frac{\alpha}{1-\alpha}$.

I tried with Bonzano Weierstrass but not kinda work..
Comment: Bonzano, made me chuckle
Comment: Do you have any ideea?
Comment: You already tagged the question with [continuity], so perhaps you should add that assumption to the problem statement.
Comment: Try looking at function $H(x)=f(x)-x/(1-x)$.Then try Bolzano
Answer: This is trivially false without any assumption on $f$ except that it is a positive function on $\mathbb R$. (Can you write down a counter-example?).
I will give a proof assuming that $f$ is continuous. Let $g(x)=(1-x)f(x)-x$. Then $g(1)=-1$ and $g(0)=f(0) \geq 0$. By IVP there exists $\alpha $ such that
$g(\alpha)=0$. Since $\alpha \neq 1$ we can write this as $f(\alpha)=\frac {\alpha} {1-\alpha}$.
Answer: Let $f(x) = {x \over 1-x}+1$ for $ x \in (0,1)$ and $f(x) = 1$ for $x\ge 1$.
Then there is no $\alpha$ such that $f(\alpha) = {\alpha \over 1-\alpha}$.
Comment: Given that the question is tagged with [continuity] I would assume that this assumption is just missing in the problem statement.
Comment: @MartinR: Me too, but I am tired of dealing with questions with missing information.
Comment: f is continous, sorry.

Exists point c such that property


Exchange admin center forward and prepend body

Question: I want to forward all incoming E-mails to my HubSpot CRM System. To achieve this I want to configure my Exchange Server to forward them.
Exchange Server seems to provide only a redirect rule and no forward rule. Unfortunately redirect does not work, as Hubspot only recognize forwarded emails.
I've found this in the Hubspot Docs.

I assume that my exchange server redirects the email to Hubspot, but Hubspot can't find the forwarded text block and so it can't match the email to a contact.
Is there any way to forward all emails and append a text block with the sender to the original message ?
Comment: The `---Forwarded---` Block originates from Outlook Client, not from Exchange. Have you tried to create an Outlook rule on the client?
Answer: Do you want to forward all incoming emails include a forwarded text block to Hubspot? If so, you could create a new mailbox which is specified to get all incoming emails, then create a transport rule which is used to Cc these emails to the new mailbox, after that, you could create an Outlook rule for this "Cc" mailbox to forward these incoming emails to Hubspot.
The following snapshots which show the transport/Outlook rule:
1.1 Exchange 2010(Transport Rule):

1.2 Exchange 2013/2016/2019(Transport Rule):

Outlook Rule:

After creating the above transport/outlook rules, all incoming emails will be Cc to the new mailbox, at the same time, they will be forwarded to another external email address :
Comment: Does it work even if my outlook is closed ?
Comment: @SimonLudwig You could check if the rule only applies for Outlook, or both of Outlook and OWA by viewing if there is a status "Client-Only" behind the rule. If the rule shows "Client-Only" status, the rule won't work until you start Outlook. For the rule I post above, it will work even Outlook is closed
Comment: This looks good. But does this work for a accounts for the whole company ?
Comment: Yep, the step 1.1 and 1.2 are to copy all incoming or outgoing emails in your organization  to a specific mailbox, and then we could use this mailbox to forward emails to Hubspot(The forwarded emails also include the forwarded text block).


How to make absolute positioned DIV push content below it with slideDown()?

Question: I have a page that houses all of the body content within an old-school 960x wrapper. I need to add a banner into the middle of the page, but this banner needs to span the full width of the page. Not only that, but it has a show/hide accordion that uses slideUp() and slideDown(). So it needs to push the content below it down as it slides.
Full example here: http://jsfiddle.net/dvawzg8g/1/
The only way I can think of getting a child element of a wrapper to be full width of the page, where the wrapper has a set pixel width, is to use absolute positioning. When I do that, it ends up above or below the other page content and doesn't push it with slideUp() and slideDown().
Comment: position it absolutely, add a "filler" in it's place, a div of the same height and when you toggle the accordion toggle the height of the filler div as well
Comment: I'm confused.  Doesn't your JSfiddle already do what you're describing?  Some sketches of your desired states might help.  Also, I'm not sure I see what your question is.
Comment: @SurrealDreams He wants the banner to span 100% of the window, yet it has to be located in the 960px container.
Comment: @PatsyIssa is correct. It is housed within the 960px wrapper, but itself has to be 100% page width. When it expands down, it should push the content below it down accordingly, not cover it up.
Comment: Told ya add a filler div, sec i ll make a demo
Comment: @user1729506 - thanks for clarifying about pushing content while animating the transition.
Answer: So basically the concept behind this is to fake the effect by having the banner positioned absolute and have an empty div right behind it that simulates it's place:
The html

potatopotatopotatopotatopotatopotatopotatopotato

potatopotatopotatopotatopotatopotatopotatopotatopotatopotato

banner

filler

potatopotatopotatopotatopotatopotato

potatopotatopotatopotatopotato

The Css
.container{
    width:960px;
    height:1000px;
    margin:0 auto;
}
.content{
    height:200px;
    border:1px solid #000;
}
.banner{
    position:absolute;
    width:100%;
    height:20px;
    border:1px solid red;
    left:0;
    -webkit-transition:all 0.2s linear;
}
.filler{
    height:20px;
    -webkit-transition:all 0.2s linear;
}
.toggled{
    height:100px;
}

And the js:
$('.banner').on('click', function(){

    $('.filler, .banner').toggleClass('toggled');
});

Fiddle
Comment: I was easily able to adapt it to my code. Simple enough concept, and worked well on the final page. Thanks.


Linked Server inconsistent metadata

Question: Set up a linked server between SQL 2005 and Azure.  Downloaded Native Client 10 since it is apparently needed.
Says the Connection is successful.
Receive the following in trying to retrieve or upload data:
The OLE DB provider "SQLNCLI10" for linked server "EBPCloud" supplied inconsistent metadata for a column. The column "CustomerId" (compile-time ordinal 1) of object ""my table"" was reported to have a "Incomplete schema-error logic." of 0 at compile time and 0 at run time.
The column in question is a uniqueidentifier
Comment: server options:  collation compatible-true
lazy schema validation - true
Answer: Not possible to link server from 2005 to Azure. Minimum requirement is server 2008 R2

Linked Server inconsistent metadata


Rodapé cobrindo outros widgets do Scaffold

Question: Estou tentando fazer um aplicativo bem simples, de listagem de filmes, mas quando fiz um rodapé, ele ficou por cima dos widgets do Scaffold, cobrindo alguns deles, desse jeito:

Segue o código:
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  bool mudado = false;
  final amountGet = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Isso é uma appBar'),
        backgroundColor: Colors.orange,
        centerTitle: true,
      ),
      body: Padding(
        padding: EdgeInsets.all(30),
        child: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                child: TextField(
                  controller: amountGet,
                  textAlign: TextAlign.left,
                  decoration: InputDecoration(
                    hintText: 'Digite aqui sua busca',
                    hintStyle: TextStyle(color: Colors.grey),
                  ),
                ),
              ),
              body(),body(),body(),body(),body(),body(),body(),body(),body(),
            ],
          ),
        ),
      ),
      bottomSheet: Expanded(
        flex: 2,
        child: Container(
          color: Colors.grey[200],
          height: 230,
          width: 700,
          child: Padding(
            padding: EdgeInsets.all(30),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "nome do filme",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.grey[700],
                      ),
                    ),
                    Text(
                      "R\$ 55,00",
                      style: TextStyle(
                          color: Colors.orange,
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                  ],
                ),
                Padding(
                  padding: EdgeInsets.only(top: 20),
                  child: Row(
                    children: [
                      Text(
                        "VALOR TOTAL SELECIONADO: R\$ 65,40",
                        style: TextStyle(
                          color: Colors.grey[700],
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 20),
                  child: FlatButton(
                    onPressed: () {
                      return showDialog(
                        context: context,
                        builder: (context) {
                          return AlertDialog(
                            content: Text(amountGet.text),
                          );
                        },
                      );
                    },
                    color: Colors.indigo[800],
                    child: Text(
                      'Comprar',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  body() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.only(left: 15),
          child: Row(
            children: [
              Checkbox(
                focusColor: Colors.grey,
                activeColor: Colors.grey[400],
                value: true,
                onChanged: (value) => value,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "Total:",
                    textScaleFactor: 1,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[700],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(30, 0, 20, 0),
                    child: Text(
                      "R\$ 55,00",
                      style: TextStyle(
                          color: Colors.grey[700],
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 30, right: 30),
          child: Container(
            decoration: BoxDecoration(
              border: Border(
                left: BorderSide(
                  width: 2,
                  color: Colors.grey[400],
                ),
              ),
            ),
            child: Padding(
              padding: EdgeInsets.fromLTRB(20, 0, 20, 5),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Text(
                        "Duração: 120 minutos",
                        textScaleFactor: 1.2,
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        "Data Lançamento: 00/00/0000",
                        textScaleFactor: 1.2,
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        "Direção: fulano",
                        textScaleFactor: 1.2,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}

Answer: Como você quer exibir uma lista, pelo que entendi, com a sua estrutura atual você pode utilizar o Widget SingleChildScrollView, para que você possa rolar entre os itens.
Como você vai trabalhar com uma bottomSheet fixa, uma saída é você redimencionr o seu body para caber dentro da tela.
Segue abaixo o exemplo:
class MyWidget extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyWidget> {
  bool mudado = false;
  final amountGet = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Isso é uma appBar'),
        backgroundColor: Colors.orange,
        centerTitle: true,
      ),
      body: Container(
        color: Colors.red,
        padding: EdgeInsets.all(30),
        height: MediaQuery.of(context).size.height - kToolbarHeight - 230,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                child: TextField(
                  controller: amountGet,
                  textAlign: TextAlign.left,
                  decoration: InputDecoration(
                    hintText: 'Digite aqui sua busca',
                    hintStyle: TextStyle(color: Colors.grey),
                  ),
                ),
              ),
              body(),body(),body(),body(),body(),body(),body(),body(),body(),body(),
            ],
          ),
        ),
      ),
      bottomSheet:
        Container(
          color: Colors.grey[200],
          height: 230,
          width: double.infinity,
          child: Padding(
            padding: EdgeInsets.all(30),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "nome do filme",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.grey[700],
                      ),
                    ),
                    Text(
                      "R\$ 55,00",
                      style: TextStyle(
                          color: Colors.orange,
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                  ],
                ),
                Padding(
                  padding: EdgeInsets.only(top: 20),
                  child: Row(
                    children: [
                      Text(
                        "VALOR TOTAL SELECIONADO: R\$ 65,40",
                        style: TextStyle(
                          color: Colors.grey[700],
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 20),
                  child: FlatButton(
                    onPressed: () {
                      return showDialog(
                        context: context,
                        builder: (context) {
                          return AlertDialog(
                            content: Text(amountGet.text),
                          );
                        },
                      );
                    },
                    color: Colors.indigo[800],
                    child: Text(
                      'Comprar',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
    );
  }

  body() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.only(left: 15),
          child: Row(
            children: [
              Checkbox(
                focusColor: Colors.grey,
                activeColor: Colors.grey[400],
                value: true,
                onChanged: (value) => value,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "Total:",
                    textScaleFactor: 1,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[700],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(30, 0, 20, 0),
                    child: Text(
                      "R\$ 55,00",
                      style: TextStyle(
                          color: Colors.grey[700],
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 30, right: 30),
          child: Container(
            decoration: BoxDecoration(
              border: Border(
                left: BorderSide(
                  width: 2,
                  color: Colors.grey[400],
                ),
              ),
            ),
            child: Padding(
              padding: EdgeInsets.fromLTRB(20, 0, 20, 5),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Text(
                        "Duração: 120 minutos",
                        textScaleFactor: 1.2,
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        "Data Lançamento: 00/00/0000",
                        textScaleFactor: 1.2,
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        "Direção: fulano",
                        textScaleFactor: 1.2,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}

Observação
Você também pode fazer uso da ListView, que ao meu ver é o mais aconselhado para você, ao invés de utilizar um SingleChildScrollView junto com uma Column.
Editado
Você pode redimensionar a tua área de visualização, pegando o tamanho máximo da sua tela e subtraindo o tamanho do teu rodapé e também o tamanho da sua appbar

height: MediaQuery.of(context).size.height - kToolbarHeight - 230

kToolbarHeight: É uma constante do próprio SDK que retorna o tamanho padrão da appbar.
Comment: muito obrigado, eu nao conhecia essa função MediaQuery! Vai ser de grande ajuda no futuro! :D
Comment: Mesmo com o SingleChildScrollView(), o rodapé ainda está tampando a listinha.
Comment: @KayaRyuuna me desculpe, não percebia que o checkbox era o primeiro Widget de cada item... Você precisa realmente usar o _bottomSheet_?
Comment: Eu queria ter um rodapé nessa página, o bottomSheet foi uma das opções que eu encontrei, que deram certo, porém ele tampa os widgets. Ate tentei colocar junto do column, mas não deu certo.
Comment: @KayaRyuuna atualizei minha resposta


what is the use of Backup Folder?

Question: I'm going to migrate my site to another server. so, i need to backup my database if i dump my database using mysqldump command into backup folder. does database manage it by updating the changes done into database to the sql file.
Answer: No, the database does not update your dump-file afterwards. You should prepare your new site with a database dump.
Then when you are ready to move the site finally you should put your original site in maintenance mode, and dump and import your database with the latest content. In this way you ensure that you will get the most recent content from your old live site.

what is the use of Backup Folder?


Problem with jquery or jquery ui (animating color)

Question: I have found a jquery code which animates colors. I made a fiddle from it (after minor change), and it's working perfectly on jsfiddle:
http://jsfiddle.net/kFuzp/
Unfortunately, it's not working on my Drupal site. I have JQuery Update module and updated to 1.8, using jQuery CDN. The code (as in jsfiddle) is inserted using drupal_add_js ($script1, 'inline') in mytheme_preprocess_page(). When I debug the code in Chrome, it just runs (I can observe how the color_index changes etc using breakpoints). But the
 background color is always white.
By the way, when I change the animation property to { opacity: color_index/7 } then the opacity animation is working (slowly) both in jsfiddle and in Drupal.
Why it's not working in Drupal and how to fix it?
Answer: It sounds like you're having a problem with your jQuery selector.
Are you using changing the properties for all paragraphs? Or just a particular one? Or a class?
Below are the selectors for each option respectively:
$("p")...

$("p#theIdofTheParagraph")...

$("p.theClassofTheParagraphs")...

Answer: I was also having the same problem once, I was doing an animation in color change. It was not working for me in Drupal, however for some reason I do not know the color change animation was working when I was logged in as administrator(with admin_menu installed), while as authenticated and anonymous user it was not working.
I used jQuery.Color() plugin and it worked for me. Its written in jQuery.animate() documentation:

All animated properties should be animated to a single numeric value,
  except as noted below; most properties that are non-numeric cannot be
  animated using basic jQuery functionality (For example, width, height,
  or left can be animated but background-color cannot be, unless the
  jQuery.Color() plugin is used). Property values are treated as a
  number of pixels unless otherwise specified. The units em and % can be
  specified where applicable.

Hope that helps!


I need your help to solve this problem, it seems very easy but i still get errors every time

Question: My goal is: "The user should be able to abandon the game by answering 0 when the program waits for its
response. The program should clearly state that the user has quit the game". But even though I tried, I couldn't write the right code.
    print("I guessed a number, try to find it")
    my_number = int(input("Guess the number:"))
    number_to_guess = random.randint(1,9999)
    number_of_tries = 1
    while number_to_guess !=  my_number:
        if number_to_guess > my_number:
            print("Your number must be higher")
            number_of_tries = number_of_tries+1
            my_number = int(input("Guess the number:"))
        if number_to_guess < my_number:
            print("Your number must be lower")
            number_of_tries = number_of_tries + 1
            my_number = int(input("Guess the number:"))
        if number_to_guess == my_number:
            print("Congrats, you guessed the number")
            print("Number of guesses is:", number_of_tries)
            break

Answer: Write another if statement and put it before all the other ones:
while number_to_guess !=  my_number:
    if my_number == 0:
        print('Quitting the game')
        exit()
    if number_to_guess > my_number:
        print("Your number must be higher")
        number_of_tries = number_of_tries+1
        my_number = int(input("Guess the number:"))
    ...

Comment: yes, I did it earlier but it gives TabError. "TabError: inconsistent use of tabs and spaces in indentation"
Comment: The code runs ok on my end, sounds like you might have some of the code not aligned properly, as in, something is tabbed out too far or too little.
Answer: You don't need to get input in multiple places rather take input at the bottom for once until while condition getting true.
import random

print("I guessed a number, try to find it")
my_number = int(input("Guess the number:"))
number_to_guess = random.randint(1, 9999)
number_of_tries = 1
while number_to_guess != my_number:
    if my_number == 0:
        print('Quitting the game')
        break
    if number_to_guess > my_number:
        print("Your number must be higher")
        number_of_tries = number_of_tries+1
    if number_to_guess < my_number:
        print("Your number must be lower")
        number_of_tries = number_of_tries + 1
    if number_to_guess == my_number:
        print("Congrats, you guessed the number")
        print("Number of guesses is:", number_of_tries)
        break
    my_number = int(input("Guess the number:"))

Answer: just revise your code:
import random
print("I guessed a number, try to find it, quite the game input 0")
my_number = int(input("Guess the number:"))
number_to_guess = random.randint(1,9999)
number_of_tries = 1
while number_to_guess !=  my_number:
    if number_to_guess > my_number:
        print("Your number must be higher")
        number_of_tries = number_of_tries+1
        my_number = int(input("Guess the number:"))
    if number_to_guess < my_number:
        print("Your number must be lower")
        number_of_tries = number_of_tries + 1
        my_number = int(input("Guess the number:"))
    if number_to_guess == my_number:
        print("Congrats, you guessed the number")
        print("Number of guesses is:", number_of_tries)
    if my_number == 0:
        break


How to "catch" highlighted text with script?

Question: I'd like to write a script that sits idle and executes upon some keypress. This script would "catch" the user's highlighted text and do something with it (write it to an excel file, pass it to a dictionary, etc.)
My initial thought was to put the code in catch.sh file, highlight a word, and run the script. But I don't know how to pass the highlighted word as a parameter.
How could I write a script that takes the highlighted word as an argument?
Answer: The best approach for this is to use /Applications/Automator.app to create a Service. The Service can be implemented in terms of a shell script by using the Run Shell Script action, or it can use a multitude of other available actions that may be even simpler.
Services are available in the application menu and right-click/Control-click contextual menu. The user can assign a key combination to invoke a Service, in System Preferences > Keyboard > Shortcuts tab > Services list element.
In addition to just receiving text, a Service can return text, if you want, which will replace the selection in the app from which it was invoked. That allows a Service to transform the selected text.


using sstream header file in C++

Question: so I was trying to utilise the istringstream to parse through a text file. The idea is to break down each line by space and based on the substring do stuff. The code works fine except for two things, it double counts last substring for each line and it seg faults when its done reading through the file. I have not used sstream before so any insight would be helpful.
file.getline(str,80);

    while(!file.eof())

    {

        cout<<str<<endl;
        istringstream iss(str);
        while (iss)
            {
                iss >> sstr;
                cout << "Substring: " <<sstr << endl;
         }
        file.getline(str,80);
    }

Comment: I would also highly encourage changing from `while(!file.eof())` to `while(file)` which will also stop on stream errors.
Comment: I would highly encourage changing from `file.getline(str, 80);` to `std::getline(file, str);` ( http://www.cplusplus.com/reference/string/getline/ ), assuming `str` is a `std::string`.  At the very least, you don't have to worry about lines that are "too long."
Comment: Thanks a ton guys....works like a charm. I used the getline as the first while loop condition and iss>>sstr as the second while loop condition.
Answer: The while loops should go like this:
std::string line;

while (std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;

    while (iss >> token)
    {
        cout << "Substring: " << token << endl;
    }
}

The getline and input operations return the stream object, which itself has a specialized conversion to bool that indicates whether the operation succeeded, and it will fail precisely when you've reached the end of the respective stream.
Answer: while !eof is almost always wrong.
Switch to a different C++ book, and tell us which one you're using now so that we may mock and warn accordingly.
while (file.getline(str,80)) {
    cout<<str<<endl;
    istringstream iss(str);
    while (iss >> sstr) {
       cout << "Substring: " <<sstr << endl;
    }
}

Comment: Hm, the member-`getline` is a bit clunky for my taste... as is the magic `80`.
Comment: @Kerrek: Indeed, global `getline` would be better. But I'm just fixing _one_ error here. :)
Comment: I have seen !eof() in a ton of books. Could you point me to as to why its a bd idea?

nvm found it...thanks!!
Comment: @Tomalak: Yeah, usually one error at a time is the Right Way. But this time I tried to measure carefully what the OP wanted and what I thought he needed and took a shot... it's thin ice, though -- other times that sort of liberty gets you downvoted :-)

using sstream header file in C++


React.js files syntax in sublime text 3

Question: i am using sublime text 3 as my code editor,i have written a basic hello world example in React.but the coloring is improper on the code ,i have tried installing Babel plugin but even after that also the coloring doesn't seem to work ,as you can see the image below

Comment: You may want to try this new syntax https://github.com/borela/naomi as it supports ES2017+ features.
Answer: Just installing it isn't enough, you have to also tell SublimeText to use it.
Either do
a) Ctrl-Shift-P, type "Babel" and select Set Syntax: Javascript(Babel)
or
b) Go to the menu and do View->Syntax->Open all with current extension as...->Babel->Javascript(Babel).
Answer: You could follow the below mentioned steps:-
Setting babel as the default syntax
To set it as the default syntax for a particular extension:

Open a file with that extension,
Select View from the menu,
Then Syntax -> Open all with current extension as... -> Babel -> JavaScript (Babel).
Repeat this for each extension (e.g.: .js and .jsx).

Setting a Color Scheme
Babel comes bundled with Next and Monokai from Benvie/JavaScriptNext.tmLanguage. Select one from Preferences -> Color Scheme -> Babel
Courtesy: https://github.com/babel/babel-sublime
Answer: This might possibly help you out...follow below steps

press Ctrl + Shift + P
Doing so, Command Palette pops up and there type : Package control . And then
select the option Package Control: install package
Now typein and select 'Babel'
Now open 'View' menu and Navigate to Syntax, Open all with current extension
as…, Babel, Javascript (Babel).

React.js files syntax in sublime text 3


Checkbox com jQuery Habilitar e Desabilitar campo

Question: Tenho a seguinte estrutura:

    Modalidade
    <input type="checkbox" name="check_adulto" id="check_adulto"> Adulto(s) <?php echo $detalhes->ati_faixa_adulto_inicio; ?> - ∞
    <input type="checkbox" name="check_crianca"> Criança(s) <?php echo $detalhes->ati_faixa_crianca_inicio; ?> - <?php echo $detalhes->ati_faixa_crianca_final; ?>
    <input type="checkbox" name="check_infante"> Infante(s) <?php echo $detalhes->ati_faixa_infantes_inicio; ?> - <?php echo $detalhes->ati_faixa_infantes_final; ?>

<?php foreach($modalidades as $valor){ ?>

    <?php echo $valor->titulo; ?>

            BRL
            <input type="text" class="form-control adulto" disabled="disabled">

            BRL
            <input type="text" class="form-control" disabled="disabled">

            BRL
            <input type="text" class="form-control" disabled="disabled">

E o seguinte jQuery

Porém, na hora de clicar em habilitar ou desabilitar... não funciona, ele habilita, porém, não desabilita. Como posso resolver?
Answer: Forma bem simples de fazer isso:

$("#check_adulto").click(function(){
   var adulto = $(".adulto");
   adulto.prop("disabled", !adulto.prop("disabled"));
});

    Modalidade
    <input type="checkbox" name="check_adulto" id="check_adulto"> Adulto(s) <?php echo $detalhes->ati_faixa_adulto_inicio; ?> - ∞
    <input type="checkbox" name="check_crianca"> Criança(s) <?php echo $detalhes->ati_faixa_crianca_inicio; ?> - <?php echo $detalhes->ati_faixa_crianca_final; ?>
    <input type="checkbox" name="check_infante"> Infante(s) <?php echo $detalhes->ati_faixa_infantes_inicio; ?> - <?php echo $detalhes->ati_faixa_infantes_final; ?>

<?php foreach($modalidades as $valor){ ?>

    <?php echo $valor->titulo; ?>

            BRL
            <input type="text" class="form-control adulto" disabled="disabled">

            BRL
            <input type="text" class="form-control" disabled="disabled">

            BRL
            <input type="text" class="form-control" disabled="disabled">

Answer: Será que isso te ajuda ?
$("#check_adulto").on("click", function (){
    var isDisabled = $(".adulto").is(':disabled');
    if (isDisabled) {
        $(".adulto").prop('disabled', false);
    } else {
        $(".adulto").prop('disabled', true);
    }
});

Forte abraço.


python hangs after computer sleep/hibernate [Mac OS X]

Question: when running a python script, if my computer goes to sleep/hibernate (ie. screen gets turned off) and is turned back on the script hangs (freezes) and does not continue.
I believe this happens specifically when the script uses the network but I'm not certain.
I ended up using caffeine to prevent my computer from sleeping but I wonder if there is a better workaround for this issue?
I would love to be able to run a background script that doesn't hang when the computer comes back from hibernate.
Comment: Possibly when your computer sleeps, the network and/or disk is suspended. Check your power management settings.
Answer: This is not a python issue.
take a look at nohup command
and at &
for example:
nohup python -u my_script.py  &

Comment: Do you have reason to believe this would fix the problem? I would expect the kernel to send SIGSTOP, not SIGHUP, when hibernating, and SIGCONT when waking up.


If I purchase AWS reserve instance in mid of month, will it cost for full month?

Question: If I purchase AWS reserve instance (EC2 and / or RDS) in mid of month, will it cost for full month or it will be on pro rata basis ?

I have searched on there docs I was not able to find, may be I have missed.

EDIT

I have requested cancel current AWS EC2 RI and AWS RDS RI in US, AWS support team told me first I need to purchase in different region.
Payment option is No Upfront
Comment: I'm voting to close this question as off-topic because the questioner should ask the vendor.
Answer: There aren't any monthly costs for reserved instances, so the question doesn't arise. You pay an up-front payment for a one or three year period, and then a payment calculated hourly for instance usage. It's billed monthly, but it's charged per hour.
Comment: In which case there's only an hourly cost, which you pay whether or not the instance is running.
Comment: Thank you very much @mike-scott , I have also analyzed last year bill if AWS RI is purchased in mid month(`No Upfront`), they will cost for remaining hour for the month.
Comment: I need to purchase with `No Upfront`.
Answer: Given answer from Mike Scott is correct. I would like to add:
Think about Reserved Instance (RI) like a discount and not like a running EC2 instance. If you purchase a RI for 1 year, the respective discount is available for 365 days.

When you purchase a Reserved Instance, you are billed for every hour or second during the entire Reserved Instance term that you select, regardless of whether the instance is running or not.
For example, if you own three Reserved Instances with the same instance attributes and region (or Availability Zone if applicable), the billing system checks each hour to see how many total instances you have running that match those parameters. If it is three or less, you will be charged the Reserved Instance rate for each matching instance running that hour. If more than three are running, you will be charged the On-Demand rate for the additional instances.
Purchases of Reserved Instances are non-refundable.

How Billing Works


Autosave form fields example

Question: I have a form with 3 textareas and some other fields. I would like to put in an autosave functionality and found the Autosave module. But that seems to be specifically for editing nodes and is also too advanced for what I need. I just need to save the contents every 3 seconds or so, no revision support or anything fancy like that.
I'm thinking about a silent form submit that the user doesn't notice or a specific page that receives the contents of the form posted with JavaScript.
But something like this must have been done before, so is there an example or some pointers on how to implement this? I'm using Drupal 7.
Answer: Try the Save Form State module. Here is a quote about it (from the module's project page):

... provides a way to autosave data entered in any Drupal form without actually submitting the form, which helps if the user is writing an article or a comment and the browser crashed or the power went down, or even if the window was closed accidently.
It works using the jQuery Sisyphus plugin, which is a lightweight jQuery plugin that uses Local Storage to save form fields every specific time span that is configurable from the module settings page.

Autosave form fields example


Best practice for node expiration with email notification

Question: I have a page where users can create meetings which have a specific start date and time, other users can join this meetings until up to an hour before it starts.
One hour before the meeting starts i would like to send an e-mail to the participants to tell them that the meeting will take place, or that it is canceled because not enough participants have been found. So i need to filter all the existing and not yet closed/started meetings and see if any of them are less than one hour away from starting.
Question:
Whats the best practice to do this kind of data evaluation in Drupal. Is there a recommended way of doing this?
My idea:
Just create an external PHP file including all the drupal shebang, call it every x minutes with a cron job and access the DB from inside this script.
Comment: Have you looked into using rules and rules scheduler to send off the emails? [Node one](http://nodeone.se/en/learn-the-rules-framework) has a lot of tutorials on using rules to do the type of thing you're looking to do with [video 15](http://nodeone.se/en/using-fields-for-setting-evaluation-time) going over how to use fields and rules scheduler to evaluate at what time to send an email
Comment: Thanx pokermoneyclips, that is a great video, explaining exactly what i want to do and how to do it with modules instead of custom php code ! Can you put this into an answer so that i can accept it please?
Answer: Drupal has a custom module available called Rules with a submodule Rules Scheduler that will allow you to set up custom scenarios for when you want a certain action to take place.
In your specific scenario you would use Rules and Rules Scheduler to set up custom emails to be sent out at your specified time based off of your time field.
Node one has several tutorial videos available to watch with a specific video available about how to use content fields and rules scheduler to set up time specific actions.
Comment: Thanks, this solution is not only with less programming and more 'drupal conform' as my "just use a php script and query the db" but it is also more efficient, as the evaluation of a specific node is scheduled and no complex db query to find the nodes that will expire in x hours is necessary!!


What is "Service extensions" in Flutter?

Question: https://flutter.dev/docs/testing/build-modes
The above page has the following explanation.
In debug mode,Service extensions are enabled.
in release mode,Service extensions are disabled.
what is "Service extensions" in Flutter?
Comment: if the answer below helped you, consider marking it as the accepted answer. We can help others with the same question.
Answer: Service Extension are a set of tools that provide additional debugging capabilities, For example debugAllowBanner, debugDumpApp, debugDumpRenderTree,debugPaint etc.
You can find the full list of these service extension at the source link below.
Source


Remotely accessing Sharepoint 2013 using REST on Office 365 from JavaScript

Question: I want to integrate with SkyDrive Pro for file storage from a browser page directly, so I don't want to do this from our web server.
Almost every example I've seen of doing this involves either running code hosted inside Sharepoint itself or remotely over using C# in ASPX hosted on another site.
Can anyone point me to a pure JavaScript example that would run solely in an HTML page (NO server side code).
From what I can tell, this is possible, but nearly every authentication example uses C# libraries again. It doesn't look like they provide a client-side JavaScript library similar to the Windows Live SDK and it probably means constructing json/xml for the auth request.
Ideally, I want to simply popup the Office365 logon screen to authenticate and then be able to make API calls from my page using the browser session cookie.
Answer: This does not seem to be possible:

Note that you cannot obtain an access token from code that is running
  on a browser client. You must obtain the access token from code that
  is running on a server and make it available to the client-side code
  (by using a cookie, URL parameter, etc.).

Source: http://msdn.microsoft.com/en-us/library/jj164022%28v=office.15%29.aspx
Your server side code needs to be in a sort of trust relationship with the identity server (Azure Access Control Services) in that they share a client ID and client secret (generated when your app is installed in Sharepoint as an app principal). See steps 6 and 7 of the process here: http://msdn.microsoft.com/en-us/library/fp142382


How do I initially show 3 blank fields on a form when cardinality is unlimited?

Question: I have created a field programmatically that has 'cardinality' => FIELD_CARDINALITY_UNLIMITED. This is the functionality that I want. I want users to be able to add as many items as they need to. However, when the form first shows, I'd like to have 3 blank fields ready to be filled out before having to click the "Add another item" button. Is this possible?
Lots of answers on the web about how to set the cardinality, but that's not what I'm looking to do. I just want to show 3 blank ones to get started while still keeping my cardinality as unlimited. I hope this question makes sense.
Answer: You can alter your form to add your proposed blank fields , to do that you need to implement hook_form_alter in your module and inside you would have :
if (empty($form_state['field_counter'])) {
  $form_state['field_counter'] = 3;
}
else if($form_state['field_counter'] < 3)
{
  $form_state['field_counter'] = 3;
}
for ($i = 0; $i < $form_state['field_counter']; $i++) {
  $form['YOUR FIELD NAME'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Your Lable'),
  );
}

Comment: Thank you so much! I got it to work using this. It was difficult because I had a pretty complicated custom field inside a field collection, but I finally got it to work.
Comment: I am having one problem though. Now when I click the "Add another" button, I don't get a new field until the third time I click the button.


What is the proper way to organize two different views of the same model?

Question: ROR newbie. I have read a lot, but I think I'm slow to absorb. I'm trying to create a web app with two different views of the same content:

A page full of artworks for visitors to browse by image (at the root of the site).
A page with a table listing out those same artworks and showing all the relevant attributes I've defined for them (medium, etc.) so I can review data associated with each artwork. This is supposed to be my super-lightweight admin page.

My questions are:

Since I generated this site from a scaffold, I'm currently using views/artworks/index.html.erb as the admin table view (supposed to be private), and I created a 'home' page and added some code to the 'home' view (and pages_controller) to make the artworks show up there (for the public). Am I doing this right? Is this a good method of organization?
I've installed devise and successfully hidden links for editing artworks on the page behind a sign in, but I don't know the proper way to cordon off portions of the app (e.g. the admin table page, edit pages, etc.) from the rest of the world. Should I be putting these pages in a different folder? How do I make these pages private?

Here are some snippets:
home.html.erb

    <% @artworks.each do |artwork| %>

                <%= link_to image_tag(artwork.image.url(:medium)), artwork %>

    <% end %>

artworks/index.html.erb:

Listing artworks

      <%= link_to 'New Artwork', new_artwork_path, class:"btn btn-default" %>

          Image
          Title
          Genre
          Category
          Medium
          Date
          Dimensions
          Availability
          Rating
          Edit

        <% @artworks.each do |artwork| %>

            <%= link_to image_tag(artwork.image.url(:thumb)), artwork %>
            <%= artwork.title %>
            <%= artwork.genre %>
            <%= artwork.category %>
            <%= artwork.medium %>
            <%= artwork.date %>
            <%= artwork.height %> x <%= artwork.width %>
            <%= artwork.availability %>
            <%= artwork.rating %>
            <%= link_to 'Edit', edit_artwork_path(artwork) %>

        <% end %>

both pages_controller.rb and artworks_controller.rb have code like this:
def index
    if params[:tag]
      @artworks = Artwork.tagged_with(params[:tag])
    else
      @artworks = Artwork.all
    end
  end

pages_controller.rb:
def home
    @artworks = Artwork.all
  end

and the routes.rb:
get 'tagged' => 'artworks#index', :as => 'tagged'

  devise_for :users
  # get "artworks" => "artworks#index"
  # post "artworks" => "artworks#index"

  root "pages#home"
  get "about" => "pages#about"
  #get "users" => "users#index"

  resources :artworks

Thanks in advance for your patience and help!
Answer: This can be the right way. But you have installed devise and hidden the links. But someone can directly hit the url. You need to add some authorization code which will take care that only admin user can edit the artworks. This can be done in many ways. If you have a simple application you can just add a before filter in which you can check if the user is admin then only he can access the page and call that on edit and update action. Either you can also use any authorization gem like Authority or so if it needs many roles. Hope this helps.
For making the code DRY:
before_filter :set_artworks, :only => [:home, :index]

private

 def set_artworks
  @artworks = Artworks.all
 end

Comment: Definitely helpful. Thanks!
Comment: Seems like my '@artworks = Artwork.all' being written in two places isn't very DRY. How should I arrange things to avoid this?
Comment: You can add this in a before_filter too. I have updated the answer for same
Answer: artworks/index.html.erb

You want this page to be private until the user is logged in. Then you can try this :
<% if current_user.present? %>

<% end %>

This div will be visible only if the user is logged in. for not yet signed in users this page will be private.
In order to make the edit option private :
<% if current_user.present? %>

    <% @artworks.each do |artwork| %>

          <%= link_to image_tag(artwork.image.url(:medium)), artwork %>

    <% end %>

<% end %>

In any case if you want to public/private few sections then just wrap it inside the conditional if statements for views.
Still if anyone wishes then he can hit the url and enter into your action directly, in that case you can put condition in the controller.
 before_action :authenticate_user!, only: [:action_1, :action_2]

Further if you need to keep things private on basis of user role, you can
always chose for cancan gem.
Comment: thanks for this. It helped me sort through the first part of my problem (how to arrange the pages within the app), and consequently solved some other problems I was having with routes, etc.
Comment: Most welcome @PeterBentley. Consider accepting answer if this has fixed your issue :)
Comment: For posterity: as to overall site organization I found it much easier to follow this advice and create a separate admin.html.erb page, cut/paste the table into the admin page, and cut/paste the home page to artworks/index, which helped me then cleanup my routes. I also followed advice [from here](https://github.com/plataformatec/devise/wiki/How-To:-Set-up-devise-as-a-single-user-system), and designated one user as the admin through the rails console (both in dev and prod).
Answer: The simplest way of maintaining privileges is using cancancan gem.
Install it via bundler and generate model via rails generate cancan:ability. Then you have to distinguish admin users from others (e.g you can add integer "role" to User model) and write something like this in models/ability.rb#initialize
if user.admin?
    can :manage, :all
else
    can :read, Artwork
end

and modify controllers like this:
def index
authorize! :edit, Artwork
if params[:tag]
  @artworks = Artwork.tagged_with(params[:tag])
else
  @artworks = Artwork.all
end

end
This will throw an exception if not admin user will want to go to index. You can use redirect_to to inform user about that error. Add this to ApplicationController:
rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
end


How to convert soapMessage object to Java Object

Question: I have this soap response below and I need to parse it to a java object ...But all the fields are returning null when I print it. Below the classes that I am using to interpret the response.
I have been trying to use jaxb to unmarshall the content but none of my tries went right.
<code> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
       <SOAP-ENV:Header/>
       <SOAP-ENV:Body>
          <ns2:consultarPosicaoCotistaOnOfflineFundoResponse>
             <ns2:listCotistaFundo>
                <ns2:cotistaFundo>
                   <ns2:cdFundo>014588</ns2:cdFundo>
                   <ns2:nmCliente>BRADESCO FIC FIM GAVEA MACRO</ns2:nmCliente>
                   <ns2:dtPosicao>2021-02-18</ns2:dtPosicao>
                   <ns2:vlCota>1.3121393</ns2:vlCota>
                   <ns2:qtdCotas>43650.7211055</ns2:qtdCotas>
                   <ns2:vlCorrigido>57275.83</ns2:vlCorrigido>
                   <ns2:vlIr>221.1</ns2:vlIr>
                   <ns2:vlIof>0</ns2:vlIof>
                   <ns2:vlLiquidoResg>57054.73</ns2:vlLiquidoResg>
                   <ns2:vlContaCorrente>57054.73</ns2:vlContaCorrente>
                   <ns2:vlContaInvestimento>57054.73</ns2:vlContaInvestimento>
                   <ns2:noCnpjFundo>28428211000149</ns2:noCnpjFundo>
                   <ns2:icAfPosicao>F</ns2:icAfPosicao>
                   <ns2:vlAplicacao>49069.11</ns2:vlAplicacao>
                   <ns2:qtCotasBloqueadas>0</ns2:qtCotasBloqueadas>
                   <ns2:vlBrutoBloqueado>0</ns2:vlBrutoBloqueado>
                   <ns2:vlLiquidoBloqueado>0</ns2:vlLiquidoBloqueado>
                   <ns2:vlAplicacaoNaoCotizada>0</ns2:vlAplicacaoNaoCotizada>
                   <ns2:vlResgateNaoCotizado>0</ns2:vlResgateNaoCotizado>
                </ns2:cotistaFundo>
             </ns2:listCotistaFundo>
             <ns3:responseMessages>
                <ns3:message>
                   <ns3:code>EJCOT-0000</ns3:code>
                   <ns3:desc>Operação Concluída</ns3:desc>
                </ns3:message>
             </ns3:responseMessages>
          </ns2:consultarPosicaoCotistaOnOfflineFundoResponse>
       </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

 Unmarshaller unmarshaller = JAXBContext.newInstance(ConsultarPosicaoCotistaOnOfflineFundoResponse.class).createUnmarshaller();
            response = (ConsultarPosicaoCotistaOnOfflineFundoResponse) unmarshaller.unmarshal(soapMessage.getSOAPBody().extractContentAsDocument());

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "consultarPosicaoCotistaOnOfflineFundoResponse",
                    namespace = "http://totvs.cot.webservices")
public class ConsultarPosicaoCotistaOnOfflineFundoResponse implements Serializable {

    private ListCotistaFundo[] listCotistaFundo;

    public ListCotistaFundo[] getCotistaFundo() {
        return listCotistaFundo;
    }
    @XmlElement(name ="listCotistaFundo",
            namespace = "http://totvs.cot.webservices")
    public void setCotistaFundos(ListCotistaFundo[] listCotistaFundo) {
        this.listCotistaFundo = listCotistaFundo;
    }
}

@XmlAccessorType(XmlAccessType.FIELD)
public class ListCotistaFundo {

    @XmlElement(name = "cdFundo")
    private String cdFundo;
    @XmlElement(name = "nmCliente")
    private String nmCliente;
    @XmlElement(name = "dtPosicao")
    private Date dtPosicao;
    @XmlElement(name = "vlCota")
    private BigDecimal vlCota;
    @XmlElement(name = "qtdCotas")
    private BigDecimal qtdCotas;
    @XmlElement(name = "vlCorrigido")
    private BigDecimal vlCorrigido;
    @XmlElement(name = "vlIr")
    private BigDecimal vlIr;
    @XmlElement(name = "vlIof")
    private BigDecimal vlIof;
    @XmlElement(name = "vlLiquidoResg")
    private BigDecimal vlLiquidoResg;
    @XmlElement(name = "vlContaCorrente")
    private BigDecimal vlContaCorrente;
    @XmlElement(name = "vlContaInvestimento")
    private BigDecimal vlContaInvestimento;
    @XmlElement(name = "noCnpjFundo")
    private double noCnpjFundo;
    @XmlElement(name = "icAfPosicao")
    private String icAfPosicao;
    @XmlElement(name = "vlAplicacao")
    private BigDecimal vlAplicacao;
    @XmlElement(name = "qtCotasBloqueadas")
    private BigDecimal qtCotasBloqueadas;
    @XmlElement(name = "vlBrutoBloqueado")
    private BigDecimal vlBrutoBloqueado;
    @XmlElement(name = "vlLiquidoBloqueado")
    private BigDecimal vlLiquidoBloqueado;
    @XmlElement(name = "vlAplicacaoNaoCotizada")
    private BigDecimal vlAplicacaoNaoCotizada;
    @XmlElement(name = "vlResgateNaoCotizado")
    private BigDecimal vlResgateNaoCotizado;

    Getters and Setters ...
</code>
Does anyone have a tip in how to convert the response in Java object?
Answer: It could be an issue with namespace since I dont see namespaces declared in the XML. You could try setting the namespace as empty in both @XmlRootElement and @XmlElement as follows :
<code>@XmlRootElement(name = "consultarPosicaoCotistaOnOfflineFundoResponse",
                namespace = "")

@XmlElement(name ="listCotistaFundo", namespace = "")
</code>


What kind of piano exercise books has notes and chords mixed together?

Question: I have seen piano exercises with only notes, with their fingerings, like Hanon.
And I have seen piano exercises with only chords, and their fingerings.
I was wondering if there are any books containing exercises with notes and chords mixed together, like in a real song, with fingerings underneath as guide of course.
Would love any suggestions
Comment: @AlbrechtHügli In general, it's best to avoid asking users to google stuff. See https://meta.stackexchange.com/q/5280/247309  and   https://meta.stackexchange.com/q/8724/247309
Comment: I don't think what you are asking for would be very useful so I doubt they exist.
Comment: Did you google for what you're asking here and looking up under: images? There are lots of easy piano arrangements with chord names and fingerings. e.g. Sikorski or musescore ...
Answer: Have you tried Schumann's Album für die Jugend?  They are not exercises as such, but are multiple short pieces written for educational purposes.  There are plenty of pieces in there that combine melody with chords.  The edition that I have includes fingering suggestions.
Answer: I'm confused about what kind of exercises you want, because you mix Hanon and real songs into the same questions. Most classical piano methods don't contain songs, but little dance-like or short two-part pieces.
Anyway, things like

https://imslp.org/wiki/Vorschule_im_Klavierspiel%2C_Op.101_(Beyer%2C_Ferdinand)
https://imslp.org/wiki/100_Progressive_Studies%2C_Op.139_(Czerny%2C_Carl)
https://imslp.org/wiki/M%C3%A9thode_compl%C3%A8te_et_progressive_de_piano_(Bertini%2C_Henri)

...will give you lots of material mixing scales, chords, arpeggios, broken chords, etc.
At imslp.org try search for words like "method, study, etude, etc" combined with "easy, beginner, facile, etc."
You can also look for folk dance type material:
  - https://imslp.org/wiki/120_Country_Dances,_Jigs,_Reels,_Hornpipes,etc.(Westrop,_Thomas)
  - https://imslp.org/wiki/Harding's_All-Round_Collection_of_Jigs%2C_Reels_and_Country_Dances_(Various)


Django filter using two conditions

Question: I am developing a web app using django. Among with other tables, I have a table called GeneralContract, which has issueDate and Expiration Date as date fields.
I want to find out the profit of an insurance agent in my case would get from these contracts between a period. For example, if the date range is 15 January 2015 - 25 February 2015 I would like to filter all GeneralContract objects who are issued ANY year between this period.
(i.e. issueDate__month = Date1.month AND IssueDate.day_gte= Date1.day) AND (IssueDate__month = Date2.month AND IssueDate.day_lte = Date2.day) ??
I tried the following but it is not giving me the results I wanted and I am not sure if I am writing this in the correct syntax or if my logic is wrong.
criterion1 = Q(issuedate__month=date1.month)
criterion2 = Q(issuedate__day__gte=date1.day)
criterion3 = Q(issuedate__month=date2.month)
criterion4 = Q(issuedate__day__lte=date2.day)
criterionA = criterion1 & criterion2
criterionB = criterion3 & criterion4
criterionC = criterionA & criterionB
currentGenProfits = GeneralContract.objects.filter(criterionC, cancelled=False)

Is this the right way of doing this filtering logic?
Comment: check the query generated by the django orm. You can get some hints.
`print(currentGenProfits.query)`
Comment: Thank you I'll check that out. Do you think this the right way of querying to get entries between a range of dates of any years though?
Comment: What do you mean by any year between this period, it is unclear. Could you put in relevant data example cases in. Also note this written code has no much sense :).
Comment: @Iklinac Here are some examples:Let's say the period is 25/2/16 - 25/3/16, I would want: entries between 25/2/16-25/3/16  and 25/2/15-25/3/15 and 25/2/14-25/3/14 and so on and so forth...
Answer: You can't do that because if date1.day = 5 and date2.day = 4 you will have no result, you must check the month and the date together, syntax is right but logic is wrong.
I may suggest to start by taking the biggest set and then apply filtering on it
Start with filtering between the two month and then remove from the queryset objects which are on the first month but before the min day and remove from the queryset objects which are on the last month but after the max day, i think that can do the job.
Comment: This is what I was trying to write. If you read my written example I am trying to check the month together with the date, but I don't know how to syntax to make this logic.
Comment: No problem ! Please accept the answer if this solved your problem.

Django filter using two conditions


Intro to building scalable public web services (ref)

Question: I have experience building small, internal web applications.
I'm looking for a good beginners introduction to the subjects of

Scalable web architectures (ex. what are the basic pieces?)
Managing public-facing web systems (ex. statistics, monitoring, alerting)

Most of the material I can find assumes knowledge of either (1) or (2) - I know neither.
Edit: Looking for an introduction to the underlying concepts and principles as opposed to "use [company]'s [product] for [problem]"
Answer: Microsoft published a book on this look here:
http://www.microsoft.com/en-us/download/details.aspx?id=16236


Showing a subgroup contains the identity element

Question:
Let $G$ be the set of all functions from $\mathbb{R}$ to $\mathbb{R}$ along with $+$. Show that $H$ defined by $H=\{f:f(x)=0 \text{ for all } x \in [0,1]\}$ is a subgroup.

I am able to show $H$ has inverses and that $H$ is closed. But how do I show $H$ is nonempty? Any argument I use would begin with "let $x\in H$..." and isn't this begging the question of emptiness?
Comment: Just provide an explicit example of a function in $H$ (hint: You know the neutral element needs to be there).
Comment: Ok thanks, will it always be the case to choose to find the neutral element?
Comment: @Moz In many cases it's the obvious choice to begin with.
Answer: You could just use a concrete example
$$
f(x)=0\;\forall\;x\in\mathbb R
$$
to show it's non-empty (which is in fact the identity element).


Setting ImageView source to an image from SQLite

Question: I have a small SQLite DB in my project, where I have table "Products". One of the columns of this table is String "image". In the activity I receive a product id in the Intent extras, and create a Product object from the DB. In the layout of this activity I have an ImageView. Each time a Product object is created, I want to set the ImageView image to the one that is stored in the object. I tried to do the following:
ImageView product_image = (ImageView) findViewById(R.id.product_image);
product_image.setImageDrawable(Integer.parseInt("R.drawable."+productToPresent.getImage());

productToPresent is my Product object and getImage returns the image string name.
However at this point my app crashes and I'm getting the following error message in the logcat:
RuntimeException: Unable to start activity ComponentInfo{com.myapp.appname/com.myapp.appname.ActivityProductDetails}: java.lang.NumberFormatException: Invalid int: "R.drawable.cat02_prod02"
where cat02_prod02 is the string stored stored in my DB and the filename of the image.
So how can it be done?
Answer: You can do it in this manner:
int id = getResources()
       .getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following
imageview.setImageResource(id);

Comment: Yes, it worked great! Learned something new today. Thank you very much!


How to determine if an array has consecutive integers and if so, how many?

Question: I am still pretty new at Scala, but I am trying to determine if an array has any consecutive integers, and if it does then how many does it have. Here is what I have so far, but I haven't got it working yet.
def isConsecutive(seq: Array[Int]): (Boolean, Int) = {
    var arr: Array[Int] = Array[Int]()
    for((v, i) <- seq.zipWithIndex) {
      if (i < seq.length()) {
        if (v + 1 == seq(i + 1)) {
          arr = arr :+ v
        }
      }
    }
    var res = if (arr.length() < 1) true else false
    return (res, arr.length())
  }

I just want to return a Boolean for whether or not the array has consecutive integers, i.e. 1,2,3, and the number of consecutive integers or zero.
Comment: How many consecutive integers would you say are contained in `Array(1, 2, 3, 5, 6, 7, 9, 10)` ?
Comment: @m-z good question. The use case for this function will only have 5 numbers in it. Really with a situation like that I'd want to get the larger set of consecutive numbers. So the output would be `true, 3`. Maybe this isn't the way to go about what I am aiming to accomplish
Answer: def isConsecutive(seq: Array[Int]): (Boolean, Int) = {
  val count = seq.sliding(2).count(a => a(0)+1 == a(1))
  (count > 0, count)
}

And to test it:
scala> isConsecutive(Array(3,5,8,99))
res0: (Boolean, Int) = (false,0)

scala> isConsecutive(Array(3,4,5,8,99))
res1: (Boolean, Int) = (true,2)

scala> isConsecutive(Array(3,4,5,98,99))
res2: (Boolean, Int) = (true,3)

Answer: If you need to check for integers that always start with 1, and always from the first element:
scala> List(1,2,3,4,5,8,9).zipWithIndex.takeWhile(x => x._1 == x._2 + 1).size
res45: Int = 5

*you can use res45 == 0 to check your condition, no need for additional Boolean
Or if you want all counts of elements in any subsequences that has consecutive integers:
case class Counter(v: Int, counters: List[Int], prevElem: Int)

def conseq(l: List[Int]) = {
   val r = l.tail.foldLeft(Counter(0,List.empty,l.head)){(acc, el) =>
      if (el - acc.prevElem == 1) Counter(acc.v + 1, acc.counters, el)
      else if (acc.v == 0) acc.copy(prevElem = el)
      else Counter(0, acc.v + 1 :: acc.counters, el)
   }
   r.counters.reverse ++ List(r.v).filter(0!=)//linear time; you might consider Vector or something instead of List
}

scala> conseq(List(1,2,3,4,100,105,106,107))
res44: List[Int] = List(4, 3)

You can also collect intitial values (like 1 and 105 in prev example) and their indicies (like 0 and  5 in prev example) per subsequence - you can do it inside Counter as well.
Comment: Perhaps you could include definition of `Counter`?
Answer: Measure length of the longest stretch of consecutive integers, similar to current answers, but as simple tail recursive implementation:
  def countConsecutive(s: Seq[Int]) = {
    @tailrec
    def countConsecutiveRecurse(maxLen: Int, s: Seq[Int], currLen: Int, currVal: Int): Int = s match {
      case Seq() => maxLen max currLen
      case head +: tail =>
        if (head == currVal + 1) countConsecutiveRecurse(maxLen, tail, currLen + 1, head)
        else countConsecutiveRecurse(maxLen max currLen, tail, 1, head)
    }

    countConsecutiveRecurse(0, s, 0, 0)
  }

Answer: The following solution will try to identify the longest stretch of consecutive integers not just how many consecutive pairs exists. For the latter problem, the solution from @jwvh is awesome.
The idea is to have a Result type which you foldLeft and update accordingly:
case class Result(prev: Int, curMax: Int = 0, max: Int = 0) {
   /* process takes the next int and updates the result up to that point */
   def process(n: Int) = {
      val newRunningMax = if(n==(prev+1)) curMax + 1 else 0
      Result(n, newRunningMax, Math.max(max, newRunningMax))
   }
}

def findLongestConsecutiveSeq(data: Array[Int]): (Boolean, Int) = {
   require(data.nonEmpty, "Only works with non empty arrays")
   val res = data.tail.foldLeft(Result(data.head))( (p,n) => p.process(n) )
   if(res.max > 0) (true, res.max + 1) // max = consecutive pairs (+1 for length)
   else (false, 0)
}

Testing in the REPL:
findLongestConsecutiveSeq(Array(1,2,3,4,5,8,9))
res1: (Boolean, Int) = (true, 5)

findLongestConsecutiveSeq(Array(1,3,3,4,5,8,9))
res2: (Boolean, Int) = (true, 3)

findLongestConsecutiveSeq(Array(3,2,2,2))
res3: (Boolean, Int) = (false, 0)

findLongestConsecutiveSeq(Array(0,1,2,3,4,5,6,6,6,6,7,8,9,10,11,12,13))
res4: (Boolean, Int) = (true, 8)


Application-wide globals in vue.js

Question: Does Vue.js have an idiomatic way of declaring application-wide globals like baseUrl and then referencing them throughout the app (for API calls etc)?
If so, what is the best way to configure such globals at build-time to create development, test and prod instances? For example, I imagine doing export BASEURL='http://dev.myapp.com', running a build and getting an app with this baseUrl configured. This would in turn allow me to create automated builds for Continuous Delivery certain branches are updated (develop -> dev.myapp.com, master -> www.myapp.com etc).
Thanks!
Answer: What I do: use some state management tool, like Vuex.
If you don't want to add complexity to your app, I use a parent Vue instance, let say App.vue and define global data in that instance, then when I need that data from the parent I call this.$root.baseUrl in case you want the baseUrl. Notice that you can also call this.$parent.baseUrl but this will only work for direct childs, if you are inside a child of a child, you wont get the global data, that's why is better the $root object.

Application-wide globals in vue.js


Deleting Set of Indexs from NSMutableArray Efficiently

Question: i have a set of Index  setOFIndex = {0,1,3,4}.
 now i want to remove this set of index from an NSMutableArray ?
what is the efficient method to do that ?
i have checked for any library method , but not able to find any.
 i cant use removeObjectAtIndex directly as at each deletion array will be shifted by one.
Comment: @Anurag : what i was looking was generic code. Index can be in any order , and i think accepted answer will solve this problem.
Comment: do you care about the order of the indexes?
Answer: NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"a", @"two", @"b", @"three", @"four", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array removeObjectsAtIndexes:indexes];
NSLog(@"array: %@", array);

// Output: array: (one, two, three, four)

read the documentation
Comment: @Ramshad: "if the setOFIndex array comes as {0,1,4,5} , The above all logic will fail" - This is *not correct*, see the documentation of `NSMutableIndexSet`: "The values in a mutable index set are always sorted, so the order in which values are added is irrelevant.".
Comment: +1 For pointing out that an exact example of what OP wants exists *in the documentation*  Please, everyone...read the docs -__-
Comment: if the setOFIndex array comes as {0,1,4,5} , The above all logic will fail
Comment: Yes @MartinR , you are absolutely right .the above example will work fine . , thanks for correction .
Answer: You should use NSMUTABleArray's method removeObjectsAtIndexes:
This is the code from documentation
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"a", @"two", @"b", @"three", @"four", nil];

NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];

[indexes addIndex:3];

[array removeObjectsAtIndexes:indexes];

NSLog(@"array: %@", array);

I simply don't understand why people don't read documentation.
Answer: Why don't you use
– removeObjectsInArray:

Convert your Indexset to array and then use above method.
EDIT:
 Very straight forward example from documentation.
NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"a", @"two", @"b", @"three", @"four", nil];

NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];

[indexes addIndex:3];

[array removeObjectsAtIndexes:indexes];

NSLog(@"array: %@", array);

Comment: What I meant is: If you convert the index set to an array like e.g. `@[ @1, @4, @5 ]` then `removeObjectsInArray:` will remove the *objects* `@1, @4, @5` from the array, and not the elements with *index numbers* 1, 4, 5. - But if I understood your answer wrong then I beg your pardon and you can just ignore my comment.
Comment: The argument of `removeObjectsInArray:` is an array of objects that are to be removed, not an array of indexes.
Comment: Yes, that is why next line is there :)
Comment: @MartinR : i think you are right . this will not solve given problem
Comment: communication gap :(   I said to convert indexset to array means the value that the index set stores in the array, not the value itself. anyways he got a lot of anwers now. Its my fault that i only suggested the way, i should have coded then i would have got vote up and accepted. :(


Proving limits involving floor function.

Question:
Let $\theta $ be real, and $0<\theta<1$, define $g_n = 0$ if $\lfloor n\theta\rfloor=\lfloor(n-1)\theta \rfloor$ and $g_n=1$ otherwise. For example, take $\theta = \frac{3}{4}$, then $g_2 =1$, since $\left\lfloor \frac{3}{2}\right\rfloor = 1 \ne 0 =\left\lfloor \frac{3}{4} \right\rfloor$. Prove that $$
\lim_{n \to \infty} \dfrac{g_1+g_2+\cdots + g_n}{n} = \theta$$ Note $\lfloor x \rfloor$ denotes the greatest integer function/ floor function.

This is what I did: $g_1$ is always $0$, since $\lfloor\theta\rfloor=0$, and $g_2 = 0$ if $\theta \in \left(0,\frac{1}{2}\right)$. Now consier $g_4$, $$
\begin{array}{cccc}
& \left( 0 ,\frac{1}{4}\right) & \left[ \frac{1}{4} , \frac{1}{3} \right) & \left[ \frac{1}{3} , \frac{1}{2} \right) & \left[ \frac{1}{2} , \frac{2}{3} \right) & \left[ \frac{2}{3} , \frac{3}{4} \right) & \left[ \frac{3}{4} , 1 \right) \\ \hline
\lfloor 4\theta \rfloor & 0 & 1 & 1 & 2 & 2 & 3\\
\lfloor 3\theta \rfloor & 0 & 0 & 1 & 1 & 2 & 2\\
\end{array}$$
Hence $g_4 = 0$ when $\theta \in\left( 0 ,\frac{1}{4}\right) \cup \left[ \frac{1}{3} , \frac{1}{2} \right) \cup \left[ \frac{2}{3} , \frac{3}{4} \right) $ and $g_4 = 1$ otherwise. Similarly, $g_n = 0$ when $\theta \in \left( 0 ,\frac{1}{n}\right) \cup \left[ \frac{1}{n-1} , \frac{2}{n} \right) \cup \left[ \frac{2}{n-1} , \frac{3}{n} \right) \cup \cdots \cup \left[\frac{n-2}{n-1}, \frac{n-1}{n} \right)$ and $g_n=1$ otherwise. Consider the case when $\theta = \frac{p}{q}$ is a rational number with $ p,q>0 \in \mathbb{Z}$ and $p,q$ are copime. Then we see a periodic behaviour, $g_1 = g_{mq+1} = 0$ where $m \in \mathbb{Z_{\ge 0}}$ and $g_i = g_{mq+i}$ for $i \in \{ 1,2,\cdots,q-1\}$. But for irrational $\theta$ I don't even know how to start. Any hints on how to further progess in this problem ?
Answer: Hint: Show that $g_n=\lfloor n\theta \rfloor-\lfloor (n-1)\theta \rfloor$, so that $\sum_{i=1}^n g_n=\lfloor n\theta\rfloor$ by a telescoping sum argument.  So what you need to do is show that
$$\lim_{n\to\infty}\frac{\lfloor n\theta\rfloor}{n}=\theta$$
which shouldn't be too difficult for you since that is a series of rational approximations that you can show that $|\theta-a_n|<\frac1n$ for all $n$
Comment: Thank you so much. After this, we can write the limit as :  $\lim_{n \to \infty} \frac{n\theta - \{ n \theta \} }{n} = \theta - 0$, where $ \{ x \}$ represents the fractional part of $x$, and $\{ x \} \in [0,1)$


Rendering a nested Paragraph's field using Twig

Question: We are using the Drupal 8 Paragraphs module and are have a Paragraph which contains a Paragraph type field, called "Steps" (machine name fs_steps), allowing editors to add a number of "Step" Paragraphs (machine name fss_steps) to the parent paragraph for rendering.
Within the twig file, we loop through the entities of the parent's Steps fields, but when we try to render a field of the nested Step paragraph field "Heading" using either (this code is within the context of a for loop):
{{ content.field_fs_step[key]['#paragraph'].field_fss_heading }}

or
{% set step = content.field_fs_steps[key]['#paragraph'] %}
{{ step.field_fss_heading }}

It fails with the following error:
Exception: Object of type Drupal\Core\Field\FieldItemList cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 476 of core/lib/Drupal/Core/Template/TwigExtension.php).
Here is our current code that successfully retrieving the "values" of the bested paragraphs' fields, but does not end up using the renderer (which would respect the field's formatting types) as we need (this is a rudimentary example retrieving text values, but in other cases we want to render more complex data such as links and images):
        {% for key, item in content.field_fs_steps if key|first != '#'%}
                    {% set step = content.field_fs_steps[key]['#paragraph'] %}

{{ step.field_fss_step_marker.0.value|raw }}

{{ step.field_fss_heading.0.value|raw }}

                            {{ step.field_fss_description.0.value|raw }}

                {% endfor %}

We're looking for help in understanding the following:

Why is it that the renderer triggers when calling a top level field against our parent Paragraph, such as {{ content.field_fs_heading }}, but attempting to render a subproperty of the "content" object or rendering a field of a referenced entity, generates an error?
If we are taking the wrong approach to "nested paragraphs", and/or how to render sub-entity fields properly from within the context of a Twig file? Do we need to (as a guess) create a separate template for the nested paragraph template? If so, how would we then pass in the contextual content data to that "partial" and have it properly render there?
Answer: For nested / referenced paragraph rendering, it's probably best to use a separate template as you theorized above by stating "Do we need to (as a guess) create a separate template for the nested paragraph template?"
A general rule of thumb for Twig rendering is, if you are starting to dig that far down in a render array in a given template, best to use the next template inline in the chain.
in addition, In Drupal 8 Paragraphs, there is a nice API function for referenced paragraphs called getParentEntity().
/**
 * Gets the parent entity of the paragraph.
 *
 * Preserves language context with translated entities.
 *
 * @return ContentEntityInterface
 *   The parent entity.
 */
public function getParentEntity();

I wrote a blog post dedicated to that here: https://www.dannyenglander.com/blog/drupal-8-architecture-how-to-get-a-value-from-a-paragraphs-parent-entity/
The bottom line is, you will look at Twig template debugging and see the referenced paragraph template suggestion in the output. Then you can use that template with some preprocessing to pull any data you need from the parent paragraph entity. A common use case for this might be some kind of setting like a boolean in the parent entity that you need to pass to the referenced paragraph entity / template.
Answer: You can use the twig_tweak module, which provides the drupal_field() fucntion in twig to do this.
{% block content %}
  {% for key, field_fs_steps_item in content.field_fs_steps %}
    {% if key|first != '#' %}
      {% set paragraph_id = content.field_fs_steps[key]['#paragraph'].id.value %}
      {% set field_fs_steps = drupal_field('field_fs_steps', 'paragraph', paragraph_id) %}