text:
Q: How to display text in two columns on an iPad I want to display a certain text in two columns like this one:
================
line1  line4  ||
line2  line5  ||
line3  line6  ||
------------  ||
prev  next    ||

================
I do not want the text to have vertical or horizontal scroll just fit inside the area.
I do not know which View or layout to use - as I am new to IOS development-
thanks

A: If you have some skills in html, you can use UIWebView to show your text in any way that you can implement in mark-up.

A: The page http://www.cocoanetics.com/2011/01/befriending-core-text/ explains how to display two colums text by using the CoreText framework and NSAttributedString. I hope it helps you.

A: Displaying text in two columns using UITextview :
//Declare global variables.

    NSLayoutManager *_layoutManager;
    NSTextStorage *_textStorage;
    UIScrollView *scrollView;

//Create a scrollview and add it on the main view.

 scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(10, 10, screenWidth-20, screenHeight-20)];

        [self.view addSubview:scrollView];

//Get the file url path of .txt file.

 NSURL *contentURL = [[NSBundle mainBundle] URLForResource:@"introduction" withExtension:@"txt"];

//Create text storage :
_textStorage = [[NSTextStorage alloc] initWithFileURL:contentURL
                                                  options:nil
                                       documentAttributes:NULL
                                                    error:NULL];

//Create a layout manager and add it to textstorage
 _layoutManager = [[NSLayoutManager alloc] init];
    [_textStorage addLayoutManager:_layoutManager];

//then call the method

 [self layoutTextContainers];

method definition :
   -(void)layoutTextContainers{

        NSUInteger lastRenderedGlyph = 0;
        CGFloat currentXOffset = 0;

        while (lastRenderedGlyph < _layoutManager.numberOfGlyphs) {

         CGRect textViewFrame = CGRectMake(currentXOffset, 10,
                                           CGRectGetWidth(scrollView.bounds) / 2,
                                              CGRectGetHeight(scrollView.bounds) - 20);

            CGSize columnSize = CGSizeMake(CGRectGetWidth(textViewFrame) - 20,
                                           CGRectGetHeight(textViewFrame) - 10);

            NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:columnSize];
            [_layoutManager addTextContainer:textContainer];

            // And a text view to render it
            UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame
                                                    textContainer:textContainer];

            textView.scrollEnabled = NO;
            [introTextScrollView addSubview:textView];

            // Increase the current offset
            currentXOffset += CGRectGetWidth(textViewFrame);

            // And find the index of the glyph we've just rendered
            lastRenderedGlyph = NSMaxRange([_layoutManager glyphRangeForTextContainer:textContainer]);
        }

        // Need to update the scrollView size
        CGSize contentSize = CGSizeMake(currentXOffset, CGRectGetHeight(introTextScrollView.bounds));
        introTextScrollView.contentSize = contentSize;
    }

A: I think that you can add 2 uitextviews with the same size. In the left one, you can write lines 1, 2 and 3 and on the others 4, 5 and 6


text:
Q: How do I test receiving mail as not-logged-in user in GAE? I am using Django on GAE. On my local development server I have associated a django view function with email receiving address:
urlpatterns += patterns('',
    url(r'^_ah/mail/(.*)', 'core.views.handle_email')
)

As far as I understand, core.views.handle_email now receives all of the incoming emails for my application. That actually works. I am able to see that it works by sending emails to my application from application console http://localhost:8080/_ah/admin/inboundmail. But this works only if I am logged in to my application. If I am not looged in, I cannot send any email from http://localhost:8080/_ah/admin/inboundmail. But I still need to test behavior of my application in this case.
So the exact question is: how do I test receiving emails when application is not logged in?

A: On App Engine (live), when an inbound mail is sent to your application, an admin login will be used to send the request, so I don't think you need to worry about testing the "non-logged in" case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RemoveDuplicates; selecting the copy to keep I am using the RemoveDuplicates function to delete rows that have the same values in column 2-4-5-6-8 and 9, using the code shown below. The problem using this function is that it deletes the last instance. I have a column that may have some information in it, and I want to keep the row that have that information. I was wondering if there is a simple way to do that using this function.
        .Range("A1:M" & lastrow).RemoveDuplicates Columns:=Array(2, 4, 5, 6, 8, 9), _
        Header:=xlYes

A: After looking on various forums, I have come to the conclusion that I have no choice but to sort my table depending on the column with the information and then use RemoveDuplicates.


text:
Q: Monitoring a java request Is there a way to identify if the process is running currently and to define how long it has been running when it is triggered?
Say for instance, I make a web service/ web app call to a method named getFirstName() which has a call to the database to retrieve the names. Just before this I have a AOP advise methodinterceptor which will intercept the method getFirstName(). Now in the interceptor I will note the start time of this request and then proceed to the actual method, now i need to trigger a mail to the user if the request has been running for a long time.so How do I keep track of this request timing?
I don't want to use any thread to avoid the complexity, is there a simple way to do this?
Thanks!

A: You can organize it yourself. In getFirstName() you
have some sequence of operations/actions being done.
Either
1)
The getFirstName() has to somehow poll its own status (because
you said you don't want another process/thread to monitor it). But this
sounds weird and more difficult to do. Also, it has this problem that if
getFirstName() calls some long-running operation, then the polling will
not work (as getFirstName() is busy with something else currently).

or

2)
Another process/thread can check the status of the getFirstName() processes.
If the status is not DONE and some decent amount of time has elapsed,
it will send out an email. The responsibility of the getFirstName()
is to just set its status to DONE, once it is done and to STARTED
once it has started. Also, each getFirstName() call probably needs to have
some unique ID. That's basically it.

A: You can use Quartz to fire an evente every 10 seconds or so.
There you will have to check in a map or something your processes and when they started.
Make the calculation ( now() - startTime()) and send the mail if you have to.


text:
Q: How do I create a log-file for JNativeHook data? So I downloaded JNativeHook (https://github.com/kwhat/jnativehook) but it only captures data for a short period of time before overwriting itself.
I'm a complete beginner here, but what I'm trying to do is collect all my mouse and keyboard data, log it somewhere, then take that data and input it into a data visualizer so I can visually track my activity.
Would anyone be able to help me get started? Or a solid path to achieve this? I've got NativeHook working but having difficulties piecing everything else together.
If it matters, I'm working off of the newer model Macbook Pro.


text:
Q: When should Doctrine filters be disabled in the SonataAdmin workflow? I'm sure this is a common ask, I need softdeletable and similar filters off in SonataAdmin, until now I've been doing:
use Sonata\AdminBundle\Admin\Admin as BaseAdmin;

class Admin extends BaseAdmin
{
    /**
     * {@inheritdoc}
     */
    public function configure()
    {
        /**
         * This executes everywhere in the admin and disables softdelete for everything, if you need something cleverer this should be rethought.
         */
        $filters = $this->getModelManager()->getEntityManager($this->getClass())->getFilters();

        if (array_key_exists('approvable', $filters->getEnabledFilters())) {
            $filters->disable('approvable');
        }

        if (array_key_exists('softdeleteable', $filters->getEnabledFilters())) {
            $filters->disable('softdeleteable');
        }
    }
}

Which causes a number of problems, one, it needs the conditionals because the admin classes are configured twice, once to build the nav, and again to build interfaces, two, the admin classes are instantiated frontend on a cold (APC maybe?) cache, which is pretty uncool.
Where are you meant to put this logic?

A: You can use a Event Listener. For example:
Service:
filter.configurator:
class: AppBundle\Filter\Configurator
arguments: ["@doctrine.orm.entity_manager"]
tags:
    - { name: kernel.event_listener, event: kernel.controller }

Listener class:
namespace AppBundle\Filter;

use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\EntityManagerInterface;
use Sonata\AdminBundle\Controller\CoreController;
use Sonata\AdminBundle\Controller\CRUDController;
use Sonata\AdminBundle\Controller\HelperController;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

/**
 * Class Configurator
 *
 * @author Andrey Nilov <nilov@glavweb.ru>
 */
class Configurator
{
    /**
     * @var Registry
     */
    private $em;

    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * onKernelRequest
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();
        $controllerClass = $controller[0];

        $isAdminController =
            $controllerClass instanceof CRUDController ||
            $controllerClass instanceof CoreController ||
            $controllerClass instanceof HelperController
        ;

        if ($isAdminController) {
            $this->em->getFilters()->disable('softdeleteable');
        }
    }
}


text:
Q: Explanation for the meaning of the lowest value of $f'(x)$ in this task I see that when $f'(x)=0$ we have the value of $x$ where the value of $y$ is the largest or smallest. But in this task, what is the meaning of the lowest value of $f'(x)$? I don't understand how we can take the $x$ value from the derivative and the $y$ value from the function and get this information, and especially in this question I don't even know what the information is supposed to mean.

A: The derivative of a function $f$ describes the gradient of the function at that point. When $f'(x) = 0$, this corresponds to when the curve has zero gradient, or when the tangent line to $f$ at $x$ is horizontal. Note that this does not correspond with the largest or the smallest values of $y$ in general; for example, the function $f(x) = x^{3}$ has derivative $f'(x) = 3x^{2}$ so that $f$ has zero gradient at $x = 0$, but this has $y$-coordinate $y = 0$ so it is neither the largest nor the smallest value of $y$ on $f$ if $f$ is defined on the whole of the real line.
Note that a positive $f'(x)$ value corresponds to $f$ increasing in $y$ as $x$ increases, and a negative $f'(x)$ value corresponds to $f$ decreasing in $y$ as $x$ increases. Thus, when $f'(x)$ is a large negative number, this means that $f$ is decreasing quickly, so it will be going down steeply (as $x$ increases). Similarly, when $f'(x)$ has a large positive number, this means that $f$ is increasing quickly, so it will be going up steeply (as $x$ increases).
In terms of your example, a large positive $f'(x)$ value corresponds to a large rate of change of production, so rate of production is increasing as the days pass. A large negative $f'(x)$ value also corresponds to a large rate of change of production but in a negative way, so rate of production is decreasing as the days pass. If $f'(x)$ is zero, then the rate of production stays the same.


text:
Q: Deleting existing name ranges using Apache POI I am trying to delete all existing name ranges from a sheet when the workbook is closed.
I am using a template with Macros to generate my main workbook. The macro is preserved in the new sheet and works fine. I have to dynamically generate dropdowns in my sheet so I use org.apache.poi.ss.usermodel.Name. The problem is that, when the template is used to create another file, I am getting the exception: The workbook already contains this name
How can I clear all the named ranges to avoid this exception?


text:
Q: How to format the docstring for inherited methods in python? I have the following objects, in cars.py
import abc

class Car(abc.ABC):

  def drive(self):
    """This is the docstring for how to drive a {0}."""
    pass

class Van(Car):

  def shut_sliding_door(self):
    pass

class Hybrid(Car):

  def plug_in(self):
    pass

Van.drive.__doc__ = Car.drive.__doc__.format('van')
Hybrid.drive.__doc__ = Car.drive.__doc__.format('hybrid')

However, the docstring for Hybrid.drive is formatted with the "van" string rather than the "hybrid" string.
import cars as cars

cars.Hybrid.drive.__doc__
> "This is the docstring for how to drive a van."

cars.Van.drive.__doc__
> "This is the docstring for how to drive a van."

It appears that the line Van.drive.__doc__ = Car.drive.__doc__.format('van') is changing the string Car.drive.__doc__.format('van'). This is confirmed with,
cars.Car.drive.__doc__
> "This is the docstring for how to drive a van."

How do I format the string for Hybrid.drive.__doc__ so that it is "This is the docstring for how to drive a hybrid"?
Edit:
Although overriding the drive method in the children classes can work, what if drive is a long method and all I want to change about it in the children classes are the docstring?

A: That is because you did not override the method in the children class. So at the very first, if you call Hybrid.drive that is the exact same method as Car.drive, there is only one method existing no matter the class you access it from
If you override them, you'll get different method, each one has its own and so its own docstring
class Car(abc.ABC):
    def drive(self):
        """This is the docstring for how to drive a {0}."""
        pass

class Van(Car):
    def shut_sliding_door(self):
        pass
    def drive(self):
        pass

class Hybrid(Car):
    def plug_in(self):
        pass
    def drive(self):
        pass

if __name__ == '__main__':
    Van.drive.__doc__    = Car.drive.__doc__.format('van')
    Hybrid.drive.__doc__ = Car.drive.__doc__.format('hybrid')

    print(Van.drive.__doc__)     # This is the docstring for how to drive a van.
    print(Hybrid.drive.__doc__)  # This is the docstring for how to drive a hybrid.
    print(Car.drive.__doc__)     # This is the docstring for how to drive a {0}.


text:
Q: List of all possible SoapServer Exceptions Are any/all of the exceptions a PHP SoapServer might throw documented anywhere?  (meaning the built is native PHP implementation of a SoapServer, not a third part PHP based implementation)
If not, is it possible to extract the possible exceptions using some sort of reflection?  If so, where would one start with that?
Also, is it possible to examine the PHP source to determine what exceptions the built in object might throw?  If so, where would one start with that?

A: The only exception specific to the SOAP extension is SoapFault.
There are two exceptions built in to the language.
The other built in exceptions are in SPL.
As @Gordon mentioned, you can see the source at http://lxr.php.net/opengrok/xref/PHP_5_3/ext/soap/.  Search for exception in soap.c to start.


text:
Q: Symfony2 and Match Against, table InnoDB I had a problem to implement Match Against with symfony2, but I almost solve the problem thanks to stackoverflow :
MATCH AGAINST script is not working with Symfony2
I did what Picoss said, but now I have another problem :

SQLSTATE[HY000]: General error: 1214 The used table type doesn't
  support FULLTEXT indexes

After some search on google I suppose the reason is because of InnoDB table type, but I don't know how to change it in Symfony2 (and I have to search something on a table generated by an entity of fosuserbundle. Second solution can be to upgrade my mysql version (I am actually on the 5.1.66-0 version, but I am not sure if it will solve the problem or not).
Do you have any other ideas ?
Thanks

A: You can add the engine option in the @ORM/Table definition:
For annotions:
<?php

namespace My\Bundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MyEntity
 *
 * @ORM\Table(name="my_entity", options={"engine"="MyISAM"})
 * @ORM\Entity(repositoryClass="My\Bundle\Entity\Repository\MyEntityRepository")
 */
class MyEntity
{
    //...
}

Hope this helps

A: There is a way to do it with Doctrine:
/**
 * @ORM\Table(name="your_table_name", indexes={@ORM\Index(name="escape", columns={"name"}, flags={"fulltext"})})
 * @ORM\Entity(repositoryClass="...\YourRepository")
 */
class YourEntity extends SomeClass {

}


text:
Q: Android App is logged in even app is re-installed I have an Android app where I have at the start of the app.
There is one weird thing happening with my app.
Even I delete app and re-install, the app takes last logged in data and show me that I am already logged in.
Below are the steps.

*

*Login to app as testuser

*Delete app

*Install app again

*Actually it should ask me for login, however it shows that I am already logged in with testuser.

OS that I have on Android is 7.0 on S6 Edge phone.
Note : I check on S4 and all is fine. It ask me to login on each re-install.

A: Apps that target Android 6.0 (API level 23) or higher automatically participate in Auto Backup. This is because the android:allowBackup attribute, which enables/disables backup, defaults to true if omitted. To avoid confusion, we recommend you explicitly set the attribute in the <application> element of your AndroidManifest.xml.
<application ...
    android:allowBackup="false">
</application>

Files that are backed up
By default, Auto Backup includes files in most of the directories that are assigned to your app by the system:

*

*Shared preferences files.

*Files in the directory returned by getFilesDir().

*Files in the directory returned by getDatabasePath(String), which also includes files created with the SQLiteOpenHelper class.

*Files in directories created with getDir(String, int).

*Files on external storage in the directory returned by getExternalFilesDir(String).
for more information read Auto Backup for Apps
or when you logout Try to delete in manually like this
File preferenceFile = new File("/data/data/"+ getPackageName()+ "/shared_prefs/");
File[] listFiles = preferenceFile.listFiles();
for (File file : listFiles) {
    file.delete();
}


text:
Q: SQL Server 2008 varchar and char not working I get an error saying varchar or char is not a recognized in SQL Server. However I use the same software, SQL Server 2008 in college, so I do not want to go for a different version of SQL Server. Anyway I can fix this?

Major Error 0x80040E14, Minor Error 26302

create table abc
(
    id int,
    name  varchar(15)
)

Error is:

The specified data type is not valid. [ Data type (if known) = varchar
  ]

A: varchar(n) is not supported in SQL Server Compact. Here is the full list of types supported.
Following are the types that you can use.
nvarchar(n)
nchar(n)
ntext

So you might need to change to nvarchar(10), nvarchar(5) and nchar(1) etc..

A: Really ? , i tried it, also i tried in creating temp table, it seems both are ok.
    create table abc (id int, name varchar(15))

    create table #tmp (id int, name varchar(15))

http://sqlfiddle.com/#!3/66b44


text:
Q: Continuous Maps From $\Bbb R^n$ to $\Bbb R$ Is it possible to define a continuous 1-1 map from any open set $A \subset\mathbb{R}^n$ to $\mathbb{R}$?
I have trouble in giving a counter example here. I feel that it should not be possible but I may be wrong.

A: Not if $n > 1$.  Suppose such a function existed.  We may assume wlog $A$ is connected (else take a connected component).  Then $f(A)$ is an interval.  But removing a single interior point disconnects $f(A)$, while removing a single point of $A$ does not.  And the continuous image of a connected set is connected.


text:
Q: Set UITextFieldDelegate & release after UITextField dealloc, self contained I have created a class that implements UITextFieldDelegate so I only need to use [MyDelegateClass setDelegate:textField someConfigparams:...] in order to use it. Inside it will create an object and assign to the textFieldDelegate.
The problem appears when releasing: the setDelegate method in UITextField doesn't retain the object so I can't just autorelease it. I could keep a reference outside to release it but it is ugly and prone to error since I need to do an extra work outside the delegate class. Subclassing UITextField is a bad option since I would need to use always this subclass which could conflict with others.
Is there any way I could release the delegate object when UITextField object is destroyed without relying to code outside MyDelegateClass?

A: I assume [MyDelegateClass setDelegate:textField someConfigparams:...] creates and instance of MyDelegateClass and assigns that instance as the delegate on the provided textField.  What i would do is make the instance of MyDelegateClass a singleton, meaning there is only ever 1 instance.
Basically what will happen in this case is that MyDelegateClass will retain a strong reference to a single static instance of itself and that instance will stay alive for as long as your application stays alive or until you purposefully release it.  It is perfectly ok to have one instance of an object be the delegate for many textFields.  The memory impact of having a single instance of this class alive always is going to be constant, i.e. not growing, and very small.


text:
Q: Taking values from stdin and storing those in linked list nodes Yesterday after I did a stupid approach, I think I am on a good way right now. The thing I wanna program is that I am getting n values from the user and I am trying to store every value into a linked list node which has to be sorted after every input.
So it means:
Input:
5 1 9
Output:
1 5 9
Input:
2 3
Output:
1 2 3 5 9
My code so far:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct node {
    int val;
    struct node* next;
} node;

void printList(node* n) {
    while (n != NULL) {
        printf("%d ", n->val);
        n = n->next;
    }
}

void push(node * head, int val) {
    node * current = head;
    while (current->next != NULL) {
        current = current->next;
    }

/* now we can add a new variable */
    current->next = malloc(sizeof(node));
    current->next->val = val;
    current->next->next = NULL;
}

int main() {
    char input[20];
    char* ptr;
    node* head = NULL;
    head = (node*) malloc(sizeof(node));

    do {
        printf("Eingabe:");
        fgets(input,20,stdin);
        ptr = strtok(input," ");

        while(ptr!=NULL){
            int val = atoi(ptr);
            push(head,val);
            ptr = strtok(NULL, " ");
        }

        printList(head);
    }
    while(*input != '0');

    return 0;
}

Edited my code, node creation is working , but when I input 5 1 9 , it outputs 0 5 1 9 where is that 0 coming from?

A: The correct approach could be (pseudo-code):
[START]
Read new line from the STDIN;
While there are new values:
  Read new value;
      Add it on new node (easier adding on top of the list);
Sort the list;
Print the list;
Loop to [START]

In your code you are missing the "sort the list" phase.
Easier if you add a swap function and try one of sorting algorithm on your choice

A: The 0 is the value of your head.
When you create the first node you add it as the next of the head, this means that by having as input 5 1 9 your linked list will be:
head -> 5 -> 1 -> 9

When you print you don't just print the values of the nodes you have created but also the value of the head, since the value was never initialized and in the struct it's an int your compiler intializes it to 0 automatically (this depends on the compiler implementation so it's always better to initialize it).
If you don't want that 0 in the front you have a couple of options:

*

*assign to head->value the first number that you input

*call the printList as printList(head->node)

*change your linked list implementation to not have the head hold a value

*change printList to:
void printList(node* n) {
     n = n->next;
     while (n != NULL) {
         printf("%d ", n->val);
         n = n->next;
     }
 }


text:
Q: Using Launch4j, when should I Wrap the Jar? I'm new to Launch4j. By default, it "wraps" the jar, but there is a checkbox that reads "Dont't wrap the jar, launch only".
When should I check this box? When should I not check this box?

A: The only difference is that when you check this option, the jar file is not packaged inside the generated executable file, and it needs the jar file next to it.
So you should not check the box if you want to hide the jar to your users and have a single executable file, and you should check it if you are willing to keep the executable file and the jar file separated (if you want to update the jar file without re-generating the executable for instance).


text:
Q: How to update an element located multiple level deep inside an xml file I have an xml file structured like below:
<root>
      <DataFields>
        <DataField Id="FORM_HTML" IsArray="FALSE">
          <DataType>
            <DeclaredType Id="File">
            </DeclaredType>
          </DataType>
          <InitialValue>N/A</InitialValue>
          <Description>Form</Description>
          <ExtendedAttributes>
            <ExtendedAttribute Name="FormatString" Value="">
            </ExtendedAttribute>
            <ExtendedAttribute Name="FormatCulture" Value="">
            </ExtendedAttribute>
            <ExtendedAttribute Name="FormatPrecision" Value="0">
            </ExtendedAttribute>
            <ExtendedAttribute Name="FormatTimeZone" Value="0">
            </ExtendedAttribute>
            <ExtendedAttribute Name="Visible" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="DispSearch" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="DispList" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="DispHome" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="ReadOnly" Value="Y">
            </ExtendedAttribute>
            <ExtendedAttribute Name="File">
               <File>"What I want" </File>
            </ExtendedAttribute>
          </ExtendedAttributes>
        </DataField>
       ....
       </DataFields>

</root>

The above is just a sample, the DataField tag repeats multiple time with different ids, but with the same tags and names.
I tried below. It gets the datafield with the ID I want, but instead of replaces the content of just the File tag, it replace everything between the 'ExtendedAttributes' tag.
var getHTMLFORM = from data in xmlFile.Descendants(nameSpace + "DataField")
                       let customcheck = data.Attribute("Id").Value
                       where customcheck == "FORM_HTML" && customcheck != null
                        select data;
foreach (var i in getHTMLFORM)
 {
    i.Element(nameSpace + "ExtendedAttributes").Value = encodedstring;
 }

Its understandable that this does not do what I want because it gets the value of the 'ExtendedAttributes' tag and replaces it. Although i.Element(nameSpace + "ExtendedAttributes").Value does return only the the value in the file tag. I just can't figure out how to update the value in the 'File' tag and still be restricted to just the FORM_HTML datafield.
The result of that code is:
<root>
      <DataFields>
        <DataField Id="FORM_HTML" IsArray="FALSE">
          <DataType>
            <DeclaredType Id="File">
            </DeclaredType>
          </DataType>
          <InitialValue>N/A</InitialValue>
          <Description>Form</Description>
          <ExtendedAttributes>
                "inserted"
          </ExtendedAttributes>
        </DataField>
       ....
       </DataFields>

</root>

What I want is:
<root>
      <DataFields>
        <DataField Id="FORM_HTML" IsArray="FALSE">
          <DataType>
            <DeclaredType Id="File">
            </DeclaredType>
          </DataType>
          <InitialValue>N/A</InitialValue>
          <Description>Form</Description>
          <ExtendedAttributes>
            <ExtendedAttribute Name="FormatString" Value="">
            </ExtendedAttribute>
            <ExtendedAttribute Name="FormatCulture" Value="">
            </ExtendedAttribute>
            <ExtendedAttribute Name="FormatPrecision" Value="0">
            </ExtendedAttribute>
            <ExtendedAttribute Name="FormatTimeZone" Value="0">
            </ExtendedAttribute>
            <ExtendedAttribute Name="Visible" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="DispSearch" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="DispList" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="DispHome" Value="N">
            </ExtendedAttribute>
            <ExtendedAttribute Name="ReadOnly" Value="Y">
            </ExtendedAttribute>
            <ExtendedAttribute Name="File">
               <File>"Inserted" </File>
            </ExtendedAttribute>
          </ExtendedAttributes>
        </DataField>
       ....
       </DataFields>

</root>

The Question: How would I go about replacing the element in the 'File' tag?

A: All you need is to change the value of File Element instead of the ExtendedAttributes Element.
Change the code inside foreach loop to the following, it will update value of all the File Elements in the ExtendedAttributes Element:

i.Element(nameSpace + "ExtendedAttributes").Descendants(nameSpace +
  "File").ToList().ForEach(file => file.Value = "value for File");


text:
Q: Error while turning a string into a tuple This is for Jupyter Notebook/Google Colab/Pandas
the full number of my Latitude isn't showing up when I would run the code to convert a strong to a tuple.

Code I ran
#convert LATLNG from string to tuple
new_LNGLAT=[]
for i in range(len(df)):
    a=df['LATLNG'].iloc[i]
    new_LNGLAT.append((float(a[a.find(':')+2:a.find(',')]),float(a[a.find('-'):a.find('}')])))

df['LATLNG']=new_LNGLAT

Anyone know how to fix

A: Your code seems to be trying to extract from a string that't not formatted the same way that you show in the dataframe. The latitude and longitude are just separated by comma, there's no : or } characters. You can use the split() function to separate this.
for i in range(len(df)):
    a=df['LATLNG'].iloc[i]
    lat, lon = a.split(',')
    new_LNGLAT.append((float(lat),float(lon)))

A: You can try apply a lambda function:
df['LATLNG'] = df['LATLNG'].apply(lambda x: x.split(',')) #This return a list
df['LATLNG'] = df['LATLNG'].apply(lambda x: tuple(x)) #Transform the list to tuple

Also this will work:
df['LATLNG'] = df['LATLNG'].apply(lambda x: tuple(x.split(',')))

A: df['LATLNG'] = df['LATLNG'].str.split(',').apply(tuple)


text:
Q: Get single row when 2 column values are repeated Thanks in advance.
My customer gets a shippment of this particular item which has an ID based on their requirment. On this perticular requested item the ID is definied as follows.

*

*Barcode # - Machine generated

*Visible # - Manual serial number

On the item itself the barcode's actual value is not show instead they should the equivalent visibleid.
        Example
        -------

||||||||| <Barcode # - C007587>
 C000001  <Visible # - C000001>

The manufacturer of this item though generate and print the Barcode # and Visible # on, the number do get repeated. They provide my client with the final excel sheet and the excel data has to be imported to the DB which is done. But upon checking we found the data has duplicate id.
DB Schema with row sample

SRNO    BarcodeID    VisibleID
----    ---------    ---------
1       C007587      C000001
2       C000001      C011704

The operators use a barcode scanner to scan the ID present on the item most of the time but sometimes they also manually keyin the value.
SQL Query I am using is as follows
----------------------------------

select * from <table> where barcodeid='C000001' or VisibleID='C000001'

When execute the above SQL code we get 2 rows for obvious reason, where I need to get only 1 row. (As long there is no repeated values in either one of the columns we get single row result which works for us).
NOTE: I would not able able to differentiate if the operator key-in or scan the ID code NOR I would be able to modify the excel file we receive.
Hence request any suggestion on how to tackle this issue and get the actual result.

A: Without stating where the input comes from (barcode / manual input) there is no way detecting this.
Also: The number below a barcode is usually the barcode number itself, which is also part of the barcode specification (afaik).
But, this is not always possible. I have a customer who uses a human readable ID as well as an RFID-tag. The RFID-ID is a 36 hex digit code which is not suitable for human input. The solution to distuingish between the two is the length of the key (as well as the input source). The human readable ID is always 4 digits.
So I can offer 3 solutions:

*

*Take the input source into account when querying the database.

*Print the barcode # below the barcode

*Change the code length of either code.


text:
Q: How to enable Kubernetes api server instances to connect to external networks via a proxy The goal is to enable Kubernetes api server to connect to resources on the internet when it is on a private network on which internet resources can only be accessed through a proxy.
Background:
A kubernetes cluster is spun up using kubespray containing two apiserver instances that run on two VMs and are controlled via a manifest file. The Azure AD is being used as the identity provider for authentication. In order for this to work the API server needs to initialize its OIDC component by connecting to Microsoft and downloading some keys that are used to verify tokens issued by Azure AD.
Since the Kubernetes cluster is on a private network and needs to go through a proxy before reaching the internet, one approach was to set https_proxy and no_proxy in the kubernetes API server container environment by adding this to the manifest file. The problem with this approach is that when using Istio to manage access to APIs, no_proxy needs to be updated whenever a new service is added to the cluster. One solution could have been to add a suffix to every service name and set *.suffix in no proxy. However, it appears that using wildcards in the no_proxy configuration is not supported.
Is there any alternate way for the Kubernetes API server to reach Microsoft without interfering with other functionality?
Please let me know if any additional information or clarifications are needed.

A: I'm not sure how you would have Istio manage the egress traffic for your Kubernetes masters where your kube-apiservers run, so I wouldn't recommend it. As far as I understand, Istio is generally used to manage (ingress/egress/lb/metrics/etc) actual workloads in your cluster and these workloads generally run on your nodes, not masters. I mean the kube-apiserver actually manages the CRDs that Istio uses.
Most people use Docker on their masters, you can use the proxy environment variables for your containers like you mentioned.

A: We tried a couple of solutions to avoid having to set http(s)_proxy and no_proxy env variables in the kube-apiserver and constantly whitelist new services in the cluster...

*

*Introduce a self managed proxy server which would determine what traffic goes is forwarded to an internet connected proxy and what traffic is not proxied:

*

*squid proxy seemed to do the trick by defining some ACLs. One issue we had was that node names were not resolved by kube-dns so we had to add manual entries into the hosts files of containers (not sure how these were handled by default).

*we also tried writing a proxy using node but it had trouble with https in some scenarios.

*Introduce a self managed identity provider between azure and our k8s cluster which was configured to use the internet connected proxy this avoiding having to configure the proxy in the kube-apiserver
We landed up going with option 2 as it gave us more flexibility in the long term.


text:
Q: Swift Cross-actor references and Sendable types In proposal paper for the Swift language's actor model here, it's not allowed to call function returning non-Sendable type across actors.
However, I tried the example in the paper and it can compile and run while it suppose to emit errors.
class Person: CustomStringConvertible {
  var name: String = ""

  var description: String {
    return "Person name: \(name)"
  }
}

actor BankAccount {
  var owners: [Person] = [Person()]

  func primaryOwner() -> Person? {
    return owners.first
  }
}

@main
struct EntryPoint {
  static func main() async {
    let account = BankAccount()
    if let owner = await account.primaryOwner() {
      owner.name = "FooBar" // Change actor's mutable state outside of actor-isolated context
    }
    print(await account.owners)
  }
}

// Output: [Person name: FooBar]

My Swift version
$ swift --version
Swift version 5.5.1 (swift-5.5.1-RELEASE)
Target: x86_64-unknown-linux-gnu

Did I do something wrong in the code above? If I did it right, why the implementation does not conform with the proposal paper?
Thanks.


text:
Q: jQuery - De-selecting all items on drop I have two ListViews, one of items available to a user, and another of those already assigned to that user. I've followed a few articles and gotten to the point where I can select multiple entries in either list and drag them back and forth. I'm also to the point where, after releasing an individual item, it will automatically deselect itself. However, where I'm getting stuck is when I drag multiple items - the dragged item will deselect, but none of the siblings will do so, and instead they remain selected.
    $(function () {
    $("#AvailableCommGroups li, #AssignedCommGroups li").click(function () {
        $(this).toggleClass("selected");
    });
    $("#AvailableCommGroups, #AssignedCommGroups").sortable({
        connectWith: ".connectedSortable",
        start: function (e, info) {
            info.item.siblings(".selected").appendTo(info.item);
        },
        stop: function (e, info) {
            info.item.after(info.item.find("li"));
        },
        receive: function (e, info) {
            info.item.toggleClass("selected");
        }
    });
});

How I can modify the above so that all items with the "selected" class will deselect after being dropped into their new list?

A: It is because you only toggle the class of the item in the receive function. Try removing the class from its sibling elements as well
receive: function (e, info) {
    info.item.toggleClass("selected");
    info.item.siblings(".selected").toggleClass("selected");
}


text:
Q: CSS Loading on click of submit button I am building an advanced search form, and upon submit of criteria it brings back search results.
I wanted to implement a page loader for this, so on submit it then triggers the loading of the page
This tutorial works for the page itself
https://www.w3schools.com/howto/howto_css_loader.asp
Can anyone help me make this work when the submit button is clicked instead?

A: You can use JavaScript to show your loader when your submit button is clicked by adding at to the button directly
<input type="submit" onclick="document.getElementById(ID_OF_YOUR_LOADER).style.display='initial';">

or in a separate script-Tag:

Your loader would look like this:


text:
Q: Auto-correlation vs. number of observation periods I've just read an excellent post
mix model
I've a question connected to that. Can you recommend any reference to a comment that if one have not enough observation periods then it is difficult to model properly auto-correlation? Did I understand it properly, that four observation periods are probably not enough to successfully account on auto-correlation.

A: 4 time points is not necessarily a problem for handling autocorrelation. The lme function in the nlme package has several methods which may be appropriate such as corAR1 for fitting an AR(1) process
Edit to adddress @whuber's comment:
I can see why the question could seem a bit vague. I took it to mean that, in the context of a mixed effects model used for a longitudinal study, a number of participants say, $N$, are measured 4 times each. Of course there are many more than 4 observations in total ($4N$ obviously, if there are no missing data). I think that is where the OP was making a distinction. A single time series of length 4 would be hopelessly inadequate for estimating an AR(1) model, but with many participants, this is a common model to fit, either in a mixed model framework or an SEM (for example. latent growth curve models and extensions thereof) - at least it is common in lifecouse epidemiology where the previous measurement often has a large influence on the next measure, compared to the other covariates, even with just 4 time points. BMI is a good example of this. Perhaps the estimated AR(1) coefficient still does not have a desirable level of precision but I have seen such models where they offer an improved interpretation as well as a better fit. Without the AR(1) process in the model, the covariances between residuals at each time point can be unrealistic.
I prefaced my answer with "not necessarily" because, of course it might be too few time points particularly if the level of autocorrlation is small (and hence my example in lifecourse epidemiology where it can be quite large). I may be able to find a toy dataset to illustrate this, if interested.


text:
Q: Error: No FileSystem for scheme: hdfs (Docker) I am receiving the error: No FileSystem for scheme: hdfs in a Docker container when trying to run hadoop fs -ls
I am volume mounting my local machine's /etc/hadoop/conf directory so the configurations are the same.  I have no problems running the hadoop fs -ls command on my local machine.
Similar answers are not helpful because they do not address the host/docker issue.
I am running on CentOS 7.

A: I was able to fix.  The issue was because the directories:
/usr/lib/hadoop-0.20-mapreduce
/usr/lib/hadoop-hdfs
/usr/lib/hadoop-mapreduce
/usr/lib/hadoop-yarn were not present in the Docker container.  Once I volume mounted those directories into my container, it worked perfectly.


text:
Q: Why controller need a parameter of model if it's strongly bound to view ? I am new to MVC and was using web forms for the last 4 years but recently moved to MVC which I find quite different.
I created a repository named basicoperations.cs which just contains an InsertMethod with a return type of bool. Then a model which contains 2 properties name, password and then a controller which contains a single action result method and is strongly bound to a view.
When I fill the 2 textboxes on the front end then it submits it to the database. Fine. I understand but what I find confusing is this:
 public ActionResult AddStories2(Stories st)
       {

           Stories s2 = new Stories();
           basicoperations bo = new basicoperations();

           if (bo.insertImages(st))
           {
               ViewBag.Message = "Added";
           }
           else
           {
               ViewBag.Message = "Failed";
           }

           return View("AddStories");
       }

If the view is strongly bound to the model then
1. Why do I still need a Stories object as a parameter?
2. Why the object stories s2 contains null since it's bound?

A: I don't really understand your questions. To clarify it step by step:

*

*This is an action method called from the view at the submit of the form you mentioned. If your view had two fields name and password I guess your model Stories is something like that (I guess you are talking about two forms since your login model is not called Stories but with the information I have I am trying to clarify some things):
public class Stories
{
    public string name { get; set; }
    public string password { get; set; }
}

*If your post was submitted correctly then the object Stories st should have the input values of the user.

*The object Stories s2 is instantiated in your action and values are never given to the object. Something like that:
s2.name = "something";
s2.password = "somethingElse"

so it is should be clear why it is null. Else you could instantiate the object like that:
Stories s2 = new Stories(){ name = "something", password = "somethingElse"}

*Since for the View you return you don't need a model or any values and you only return a view with it's Viewbag values you don't have to use the object Stories as a parameter. If your View "AddStories" is using this model like this
@model Stories

in the beginning then you have to pass a model. However if you aren't actually using any values of the model like you imply then just delete this line from your view.


text:
Q: not understood Java syntax of defined Constructor I'm Implementing a type of table. To do this, I have used an AbstractTableModel, but I don't know what my code is doing (that's why I get a snippet that did his work, but obviously I want to understand). You can see the code
public class TablePanel extends JPanel
{
    private JTable table;
    public TablePanel()
    {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        table = new JTable(new MyTableModel());
        table.setFillsViewportHeight(true);
        table.setPreferredScrollableViewportSize(new Dimension(500, 100));
        JScrollPane jps = new JScrollPane(table);
        add(jps);
        add(new JScrollPane(table));
        table.setCellSelectionEnabled(true);
    }
    private class MyTableModel extends AbstractTableModel {
        private String[] columns = {"","Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        private String[][] data = {{"8:30 - 9:30","","","","","",""},
            {"9:30 - 10:30","","","","","",""},
            {"10:30 - 11:30","","","","","",""},
            {"11:30 - 12:30","","","","","",""},
            {"12:30 - 13:30","","","","","",""},
            {"13:30 - 14:30","","","","","",""},
            {"14:30 - 15:30","","","","","",""},
            {"15:30 - 16:30","","","","","",""},
            {"16:30 - 17:30","","","","","",""}};

        public int getColumnCount() {
            return columns.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columns[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }
        public Object myMethod (){
            //do something
        }
    }
}

Well, what does it mean table = new JTable(new MyTableModel());?
I thought that table would be a MyTableModel instance, but that is not true. In fact, if I pass table to another external class, this class won't see the method myMethod defined in the body of MyTableModel.

A: A MyTableModel is a TableModel, but a TableModel is not necessarily a MyTableModel.
As you know your table's model is an instance of MyTableModel, which has the desired myMethod(), you can use a cast:
JTable table = new JTable(new MyTableModel());
MyTableModel model = (MyTableModel) table.getModel();

It may be easier to create and use a reference to your model:
MyTableModel model = new MyTableModel();
JTable table = new JTable(model);

Don't neglect to include the implementation of setValueAt(), shown here.

A: a JTable constructor accepts any Object of a class that implements the TableModel interface
this will help you learn more.

A: its expected behaviour that other classes cant see the function myMethod because they "think" that your MyTableModel is just a AbstractTableModel (which in fact it isnt)
The code and everything else you put into MyTableModel is callen correctly but you just cant see the function myMethod
Thats because youre using a OOP language
So no youre wrong.
Youre creating a instance of MyTableModel so everything you do inside will be executed if you call
you should read this here which will explain more about the OOP part:
http://www.dummies.com/how-to/content/understanding-javas-objectoriented-programming-oop.html
just to say it quick
If you need to access your myMethod function just cast it like so:
     // Create the MyTableInstance (this is possible because AbstractTableModel is the parent and MyTableModel is the child)
     AbstractTableModel atmTestVariable = new MyTableModel();
 // Now to be able to call this:
 // atmTestVariable.myMethod();
 // we need to do this:

 if(atmTestVariable isntanceof MyTableModel) //make sure that atmTestVariable is REALY a MyTableModel
 {
    MyTableModel mtmTemp = (MyTableModel)atmTestVariable; //cast to MyTableModel
    mtmTemp.myMethod(); //Call the function
    // and now the short variant:
    ((MyTableModel)atmTestVariable).myMethod(); //cast to MyTableModel AND call the function
 }

Hopefully i was able to help
Ohhh and please move the define of your MyTabelModel class into a seperate file : /


text:
Q: Change button size while button is pressed My Question is how can i change the size of a button while the finger is hovering over it?
Sorry if this Question is already answered but i didn't found any results for me.
Please link the Thread as an answer if its already answered :)
I already tried it with a UIView and then listening with a CGRectIntersectsRect if it touches the button. But i think theres a simpler way of doing this.

A: You can add a method that observes that event. The one you're looking for, I think, is UIControlEventTouchDown
- (void)initOrSomething {
    UIButton *button = ...
    [button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchDown];
}

- (void)buttonPress:(UIButton *)button {
    button.frame = CGRectMake(0, 0, 100, 100);
}

If you add yourself as a target, you should be able to change the frame in the your selector.

A: - (IBAction)buttonPressed:(id)sender {
    CGRect f = self.button2.frame;
    f.origin.x += 10;
    f.size.width += 10;
    self.button2.frame = f;
}

Add this action with UIControlEventTouchDown.
Hope this helps...

A: - (void)viewDidLoad {
    ...
    UILongPressGestureRecognizer *pressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonPressed:)];
    pressGesture.minimumPressDuration = 0.0;
    pressGesture.delegate = self;
    [_button addGestureRecognizer: pressGesture];
    ...
}

- (void)buttonPressed:(UILongPressGestureRecognizer *)rec {
    switch (rec.state) {
        case UIGestureRecognizerStateBegan:
            [UIView animateWithDuration:0.1 animations: ^{
                 _button.transform = CGAffineTransformMakeScale(0.8, 0.8);
             }];
             break;
        case UIGestureRecognizerStateEnded:
            [UIView animateWithDuration:0.1 animations: ^{
                 _button.transform = CGAffineTransformIdentity;
             }];
             break;
        default:
             break;
    }

}

This basically animates the button to shrink while the user holds down onto the button. And when the finger's lifted, the button size go back to original size.


text:
Q: Which RAM is faster: 1333 MHz CL9 or 1600 MHz CL10? I'm looking to upgrade the RAM in my 2.4GHz i7 (2760QM) MacBook Pro, and I'm wondering which RAM is faster - 1333 MHz CL9 or 1600 MHz CL10?

A: The 1600Mhz CL10 RAM has a higher clock speed (800MHz versus 666MHz) and a lower latency (12.5 ns versus 13.5 ns), so it's the hands down winner.

A: A quick shortcut to determine which RAM is faster is to check this ratio:
1600/10 = 160
1333/9  = 148

So, even though CL10 is a higher divisor than CL9, the increase from 1333MHz to 1600MHz in the numerator is more than enough to compensate for that.


text:
Q: Scala: What does << mean? I am very new to Scala. I have been asked to implement a feature so I am reading the codebase.
I see the following:
def * = (id ~: columns) <>(Account.<<.<<.<<.<<, (Account.unapply _).<<.<<.<<.<<)

...but I don't know what <<.<<. means, and Google did not gave me any correct result since it is a symbol.
What is this called?

A: << is just a normal method name in Scala. It seems that in your code you have an Account object defined with a method name <<. And that method returns another object that also has method <<.
You need to look at the help or implementation of the Account.<< method to see what it does. There is nothing special in Scala regarding << that you should be concerned. It is all in your implementation.

A: Load the code in an IDE (e.g. Scala IDE, Ensime or IDEA) and ask the IDE to go to the definition of that <<.

A: I am not very familiar with Scala, but since it looks like an operator, a quick Google search on "Scala operators" gives the Scala Operator Cheat Sheet
This has the following on the << operator:

<< BigInt Leftshift of BigInt
      << Byte
      << Char
      << Int
      << Long
      << Short
      << Buffer Send a message to this scriptable object.
      << BufferProxy Send a message to this scriptable object.
      << Map Send a message to this scriptable object.
      << MapProxy Send a message to this scriptable object.
      << Scriptable Send a message to this scriptable object.
      << Set Send a message to this scriptable object.
      << SetProxy Send a message to this scriptable object.
      << SynchronizedBuffer Send a message to this scriptable object.
      << SynchronizedMap Send a message to this scriptable object.
      << SynchronizedSet Send a message to this scriptable object.

As for the ., I think that would be a way of chaining things.
Hence, one might be able to think of this as the << operator chained multiple times into Account etc.
However, << might actually be a method defined somewhere instead of one of the above operators.


text:
Q: How to limit framerate in a curses program? I've been trying to make a game using ncurses.
However, I am stumped with how to make the timing part of my main loop work.
Would someone be able to add some insight into how I could add framerate code to my main loop, while keeping portability and not compromising speed.
Thanks in advance!

A: The normal way to handle this type of problem I believe is to pass in the duration since the last loop (often called delta) as a parameter to the system. This allows you to update the progress of entities in the game based on the amount of real world time that has passed. For example:
new_position = old_position + delta*speed

This allows entities in your game to move at a constant speed independent of the frame rate of your program.

A: Assuming you have functionality to update your gamestate after a small period of time, next you need to be able to poll the user for input. If you do not specify otherwise, ncurses will block when you ask for input. To prevent this, look up the init functions here. In particular, the halfdelay() function may be of use of you (it implements a sort of framerate).
Just remember to check for ERR on the return value of getch() when using this mode.


text:
Q: How to iterate over vector of shared pointers to a Class I have a class:
class Company {
    public:
    int floors;
    std::set<std::string> managers;
};

And another class which has the following:
class Another {
    std::vector<std::shared_ptr<Company>> comp;
    }

If I have this function which needs to find if any of the managers have the name in any of the Company classes in comp, how I can I iterate over the comp vector, especially its managers set for each Company in comp?
bool Another::look_for(std::string name);

should return true if any of the managers in comp have 'name'
thanks for any help

A: bool Another::look_for(std::string name)
{
    for (auto &c : comp) {
        if (c->managers.find(name) != c->managers.end())
            return true;
    }
    return false;
}

Alternatively:
#include <algorithm>

bool Another::look_for(std::string name)
{
    return std::find_if(
        comp.begin(), comp.end(),
        [&](auto &c) { return c->managers.find(name) != c->managers.end(); }
    ) != comp.end();
}


text:
Q: Display repeated data in table from two different unrelated objects I'm trying to create a table that will show the data from two different unrelated objects.
There are two multiselect fields in page. Lets say one is A and other is B. So when user select 3 options - xy,ab,mn from A and 2 options - 123, 456 from B then in the table it should show all the 6 combination.
A          B
XY    123
XY    456
AB    123
AB    456
MN    123
MN    456
This is the sample code that I'm using to create the table in VF Page is:

  <apex:repeat value="{!A}" var="a">

      a
      <apex:repeat value="{!B"} var="b">
        b
      </apex:repeat>

  </apex:repeat>

It is showing output as but I need to show all 6 combination in table:
A B
XY 123
AB 456
MN

A: I think this is a job for our old friend the wrapper class.  If you create a wrapper class that contains two values, you can iterate the selections and create an instance of the wrapper class for each combination:
In the sample code below I've assumed you have access to the selected values via a pair of String arrays (i.e. that you are using an apex:selectlist component) - if these are input fields, you'll need to turn them into String arrays by splitting on the ';' separator from the field value:
public class MyController
{
   public List<String> selected1 {get; set;}
   public List<String> selected2 {get; set;}

   public List<Tuple> getCombinations()
   {
       List<Tuple> results=new List<Tuple>();
       for (String sel1 : selected1)
       {
          for (String sel2 : selected2)
          {
             Tuple tup=new Tuple(sel1, sel2);
             results.add(tup);
          }
       }
   }

   public class Tuple
   {
      public String value1 {get; set;}
      public String value2 {get; set;}

      public Tuple(String val1, String val2)
      {
          value1=val1;
          value2=val2;
      }
   }
}

and in the page:

     A
     B

  <apex:repeat value="{!combinations}" var="tuple">

      {!tuple.value1}
      {!tuple.value2}

  </apex:repeat>


text:
Q: C++ Prime Numbers program I'm working on a C++ program that determines and prints the prime numbers between 3 and an integer 'x' the user inputs.  I'm assuming that I need a double nested loop for this, one to iterate from 3 to x and the other to check if the number is prime.  I think it needs to do something like go from 2 to x-1?  I'm just really not sure how to do this syntax-wise. Thanks for any help! :)
EDIT:
 This is what I have:
#include <iostream>
#include <cmath>

using std::cout;
using std::endl;
using std::cin;

int main(){

   int x;
   int i;
   int j;

   cout << "Please enter an integer 'x' greater than 3: " << endl;

   cin >> x;

   if (x <= 3){

        cout << "Please enter new value 'x' greater than 3: " << endl;

        cin >> x;
   }
        for(int i=3; i<=x; i++){
                for(j=2; j<i; j++){
                   if(i%j == 0)
                        break;
                   else if(i == j+1);
                        cout << i << endl;
                   }
        }
        return 0;
}

And I when I enter 10 as 'x' I get the output:
3
5
5
5
7
7
7
7
7
9
Can anyone tell me how to fix this?

A: Provided your X is small enough, you can use the Sieve of Eratosthenes to do it more efficiently. This is ideal for the "primes up to X" case since it maintains a memory of previously discarded primes. It does so by keeping a set of flags for each candidate number, all initially set to true (except for 1, of course).
Then you take the first true value (2), output that as a prime, and then set the flags for all multiples of that to false.
Then carry on with:

*

*3;

*5 (since 4 was a multiple of 2);

*7 (since 6 was a multiple of 2 and 3);

*11 (since 8 and 10 were multiples of 2 and 9 was a multiple of 3);

*13 (since 12 was a multiple of 2);

*17 (since 14 and 16 were multiples of 2 and 15 was a multiple of 3 and 5);

*and so on.

Pseudo-code would be similar to:
def showPrimesUpTo (num):
    // create array of all true values

    array isPrime[2..num] = true

    // start with 2 and go until finished

    currNum = 2
    while currNum <= num:
        // if prime, output it

        if isPrime[currNum]:
            output currNum

            // also flag all multiples as nonprime

            clearNum = currNum * 2
            while clearNum <= num:
                isprime[clearNum] = false
                clearNum = clearNum + currNum

        // advance to next candidate

        currNum = currNum + 1

Otherwise, you can do trial division as per your suggestion. The basic idea is to check each number from 2 up to the square root of your target number to see if it's a multiple. In pseudo-code, that would be something like:
def isPrime (num):
    // val is the value to check for factor

    val = 2

    // only need to check so far

    while val * val <= num:
        // check if an exact multiple

        if int (num / val) * val == num:
            return false

        // no, carry on

        val = val + 1

    // if no factors found, it is a prime

    return true

The reason you only need to check up to the square root is because, if you find a factor above there, you would have already found the corresponding factor below the square root.
For example, 3 x 17 is 51. If you're checking the numbers from 2 through 50 to see if 51 is prime, you'll find 3 first, meaning you never need to check 17.

A: int main (char argv)
{
    int tempNum = atoi(argv);
    for (int i=3; i<=tempNum; i++)
        for (int j=2; j*j<=i; j++)
        {
            if (i % j == 0)
                break;
            else if (j+1 > sqrt(i)) {
                cout << i << " ";

            }

        }

    return 0;
}

Printing prime numbers from 1 through 100
Basically this, but modified

A: I find this one pretty fast and efficient
 int main(){
    for(int i=3; i<=X; i++)
            if(IsPrime(i)){
               cout<<i<<endl;
            }
    }

 bool IsPrime(int num){
    /* use commented part if want from 2
        if(num<=1)

            return false;

        if(num==2)

            return true;
    */
        if(num%2==0)

            return false;

        int sRoot = sqrt(num*1.0);

        for(int i=3; i<=sRoot; i+=2)

        {

            if(num%i==0)

                return false;

        }

        return true;
    }


text:
Q: 15-Puzzle BCS Python: unindent does not match any outer indentation level This code to solve 15-puzzle using various Breadth First Search method in Python. But when I run it, the output unindent does not match any outer indentation level
The entire traceback shown:
  File "main.py", line 58
    print "| %i | %i | %i | %i |" % (state[3], state[7], state[11], state[15])
                                                                             ^
IndentationError: unindent does not match any outer indentation level

I've try change the contraints state in every move (up, down, left and right), but it didn't working yet. Can every one help me to analyzed what the problem belong on my code?
#!/usr/bin/python
#
### Student Info
# Smith, Christopher, 02386569, 159.302
# Assignment 1: 8 Puzzle.
#
### Language
# This assignment was written in Python. An open source, interpreted language
# with a mix of imperative, OO and functional programming. Syntax is simple
# and easy to learn.
#
# Developed on Ubuntu Linux but this will run on the interpreter available
# from http://python.org. Documentation is also on that site but a good
# tutorial is available for free at http://diveintopython.org.
#
### Data Structures
#
# The state of the board is stored in a list. The list stores values for the
# board in the following positions:
#
# -------------
# | 0 | 3 | 6 |
# -------------
# | 1 | 4 | 7 |
# -------------
# | 2 | 5 | 8 |
# -------------
#
# The goal is defined as:
#
# -------------
# | 1 | 2 | 3 |
# -------------
# | 4 | 5 | 6 |
# -------------
# | 7 | 8 | 0 |
# -------------
#
# Where 0 denotes the blank tile or space.
goal_state = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]
starting_state = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 15]
#
# The code will read state from a file called "state.txt" where the format is
# as above but space seperated. i.e. the content for the goal state would be
# 1 8 7 2 0 6 3 4 5

### Code begins.
import sys

def display_board( state ):
    print "-------------"
    print "| %i | %i | %i |" % (state[0], state[1], state[2],  state[3])
    print "-------------"
    print "| %i | %i | %i |" % (state[4], state[5], state[6],  state[7])
    print "-------------"
    print "| %i | %i | %i |" % (state[8], state[9], state[10], state[11])
    print "-------------"
    print "| %i | %i | %i |" % (state[12], state[13], state[14], state[15])
    print "-------------"

def move_up( state ):
    """Moves the blank tile up on the board. Returns a new state as a list."""
    # Perform an object copy
    new_state = state[:]
    index = new_state.index( 0 )
    # Sanity check
    if index not in [0, 1, 2,3]:
        # Swap the values.
        temp = new_state[index - 1]
        new_state[index - 1] = new_state[index]
        new_state[index] = temp
        return new_state
    else:
        # Can't move, return None (Pythons NULL)
        return None

def move_down( state ):
    """Moves the blank tile down on the board. Returns a new state as a list."""
    # Perform object copy
    new_state = state[:]
    index = new_state.index( 0 )
    # Sanity check
    if index not in [12, 13, 14, 15]:
        # Swap the values.
        temp = new_state[index + 1]
        new_state[index + 1] = new_state[index]
        new_state[index] = temp
        return new_state
    else:
        # Can't move, return None.
        return None

def move_left( state ):
    """Moves the blank tile left on the board. Returns a new state as a list."""
    new_state = state[:]
    index = new_state.index( 0 )
    # Sanity check
    if index not in [0, 4, 8, 12]:
        # Swap the values.
        temp = new_state[index - 4]
        new_state[index - 4] = new_state[index]
        new_state[index] = temp
        return new_state
    else:
        # Can't move it, return None
        return None

def move_right( state ):
    """Moves the blank tile right on the board. Returns a new state as a list."""
    # Performs an object copy. Python passes by reference.
    new_state = state[:]
    index = new_state.index( 0 )
    # Sanity check
    if index not in [3, 7, 11, 15]:
        # Swap the values.
        temp = new_state[index + 4]
        new_state[index + 4] = new_state[index]
        new_state[index] = temp
        return new_state
    else:
        # Can't move, return None
        return None

def create_node( state, parent, operator, depth, cost ):
    return Node( state, parent, operator, depth, cost )

def expand_node( node, nodes ):
    """Returns a list of expanded nodes"""
    expanded_nodes = []
    expanded_nodes.append( create_node( move_up( node.state ), node, "u", node.depth + 1, 0 ) )
    expanded_nodes.append( create_node( move_down( node.state ), node, "d", node.depth + 1, 0 ) )
    expanded_nodes.append( create_node( move_left( node.state ), node, "l", node.depth + 1, 0 ) )
    expanded_nodes.append( create_node( move_right( node.state), node, "r", node.depth + 1, 0 ) )
    # Filter the list and remove the nodes that are impossible (move function returned None)
    expanded_nodes = [node for node in expanded_nodes if node.state != None] #list comprehension!
    return expanded_nodes

def bfs( start, goal ):
    """Performs a breadth first search from the start state to the goal"""
    # A list (can act as a queue) for the nodes.
    nodes = []
    # Create the queue with the root node in it.
    nodes.append( create_node( start, None, None, 0, 0 ) )
    while True:
        # We've run out of states, no solution.
        if len( nodes ) == 0: return None
        # take the node from the front of the queue
        node = nodes.pop(0)
        # Append the move we made to moves
        # if this node is the goal, return the moves it took to get here.
        if node.state == goal:
            moves = []
            temp = node
            while True:
                moves.insert(0, temp.operator)
                if temp.depth == 1: break
                temp = temp.parent
            return moves
        # Expand the node and add all the expansions to the front of the stack
        nodes.extend( expand_node( node, nodes ) )

def dfs( start, goal, depth=10 ):
    """Performs a depth first search from the start state to the goal. Depth param is optional."""
    # NOTE: This is a limited search or else it keeps repeating moves. This is an infinite search space.
    # I'm not sure if I implemented this right, but I implemented an iterative depth search below
    # too that uses this function and it works fine. Using this function itself will repeat moves until
    # the depth_limit is reached. Iterative depth search solves this problem, though.
    #
    # An attempt of cutting down on repeat moves was made in the expand_node() function.
    depth_limit = depth
    # A list (can act as a stack too) for the nodes.
    nodes = []
    # Create the queue with the root node in it.
    nodes.append( create_node( start, None, None, 0, 0 ) )
    while True:
        # We've run out of states, no solution.
        if len( nodes ) == 0: return None
        # take the node from the front of the queue
        node = nodes.pop(0)
        # if this node is the goal, return the moves it took to get here.
        if node.state == goal:
            moves = []
            temp = node
            while True:
                moves.insert(0, temp.operator)
                if temp.depth <= 1: break
                temp = temp.parent
            return moves
        # Add all the expansions to the beginning of the stack if we are under the depth limit
        if node.depth < depth_limit:
            expanded_nodes = expand_node( node, nodes )
            expanded_nodes.extend( nodes )
            nodes = expanded_nodes

def ids( start, goal, depth=50 ):
    """Perfoms an iterative depth first search from the start state to the goal. Depth is optional."""
    for i in range( depth ):
        result = dfs( start, goal, i )
        if result != None:
            return result

def a_star( start, goal ):
    """Perfoms an A* heuristic search"""
    # ATTEMPTED: does not work :(
    nodes = []
    nodes.append( create_node( start, None, None, 0, 0 ) )
    while True:
        # We've run out of states - no solution.
        if len( nodes ) == 0: return None
        # Sort the nodes with custom compare function.
        nodes.sort( cmp )
        # take the node from the front of the queue
        node = nodes.pop(0)
        # if this node is the goal, return the moves it took to get here.
        print "Trying state", node.state, " and move: ", node.operator
        if node.state == goal:
            moves = []
            temp = node
            while True:
                moves.insert( 0, temp.operator )
                if temp.depth <=1: break
                temp = temp.parent
            return moves
        #Expand the node and add all expansions to the end of the queue
        nodes.extend( expand_node( node, nodes ) )

def cmp( x, y ):
    # Compare function for A*. f(n) = g(n) + h(n). I use depth (number of moves) for g().
    return (x.depth + h( x.state, goal_state )) - (y.depth + h( x.state, goal_state ))

def h( state, goal ):
    """Heuristic for the A* search. Returns an integer based on out of place tiles"""
    score = 0
    for i in range( len( state ) ):
        if state[i] != goal[i]:
            score = score + 1
    return score

# Node data structure
class Node:
    def __init__( self, state, parent, operator, depth, cost ):
        # Contains the state of the node
        self.state = state
        # Contains the node that generated this node
        self.parent = parent
        # Contains the operation that generated this node from the parent
        self.operator = operator
        # Contains the depth of this node (parent.depth +1)
        self.depth = depth
        # Contains the path cost of this node from depth 0. Not used for depth/breadth first.
        self.cost = cost

def readfile( filename ):
    f = open( filename )
    data = f.read()
    # Get rid of the newlines
    data = data.strip( "\n" )
    #Break the string into a list using a space as a seperator.
    data = data.split( " " )
    state = []
    for element in data:
        state.append( int( element ) )
    return state

# Main method
def main():
    ### CHANGE THIS FUNCTION TO USE bfs, dfs, ids or a_star
    result = bfs( starting_state, goal_state )
    if result == None:
        print "No solution found"
    elif result == [None]:
        print "Start node was the goal!"
    else:
        print result
        print len(result), " moves"

# A python-isim. Basically if the file is being run execute the main() function.
if __name__ == "__main__":
    main()


text:
Q: hyperlink in label In a FrameLabel for Manipulate, I would like part of the string to be a hyperlink. Is this possible? I have tried various things (e.g. insert hyperlink, and the Hyperlink function) but nothing has worked.

A:  Manipulate[u, {u, 0, 1},
 FrameLabel -> {Hyperlink["Wolfram Research, Inc.", "http://www.wolfram.com"],
  Hyperlink["FrameLabel", "paclet:ref/FrameLabel"],
  Column[{Hyperlink[Style["this Q/A", "Section", 24],
      "http://mathematica.stackexchange.com/q/16224/125"],
  Hyperlink["Hyperlink", "paclet:ref/Hyperlink"]}],
  Hyperlink["Manipulate", "paclet:ref/Manipulate"]},
  RotateLabel -> True]

For lables that contain hyperlinks interspersed with strings:
 Manipulate[u, {u, 0, 1},  FrameLabel ->
 Row[{"Please see the doc pages \n ",
    Hyperlink["FrameLabel",
    "http://reference.wolfram.com/mathematica/ref/FrameLabel.html"],
     " and ", Hyperlink["Hyperlink", "paclet:ref/Hyperlink"]}]]


text:
Q: Can you dynamically assign variables inside a Python function? I have this code for a function to populate a connection string for sqlalchemy
def sql_path(yaml_path=None, login_key='login', user_key='username',
             pass_key='password', api_key=None, dialect=None,
             driver=None, host='localhost', port=None, database=None):

    with open(yaml_path, 'r') as file:
        sql_yaml = yaml.load(file, Loader=yaml.FullLoader)
    user = sql_yaml[login_key][user_key]
    password = sql_yaml[login_key][pass_key]
    pw_encoded = urllib.parse.quote_plus(password)
    if api_key is not None:
        if 'dialect' in sql_yaml[api_key].keys():
            dialect = sql_yaml[api_key]['dialect']
        if 'driver' in sql_yaml[api_key].keys():
            driver = sql_yaml[api_key]['driver']
        if 'host' in sql_yaml[api_key].keys():
            host = sql_yaml[api_key]['host']
        if 'port' in sql_yaml[api_key].keys():
            port = sql_yaml[api_key]['port']
        if 'database' in sql_yaml[api_key].keys():
            database = sql_yaml[api_key]['database']

    if port is None:
        sql_path = f'{dialect}+{driver}://{user}:{pw_encoded}@{host}/{database}'
    else:
        sql_path = f'{dialect}+{driver}://{user}:{pw_encoded}@{host}:{port}/{database}'

    return sql_path

Is there a way to dynamically assign the variables in the 'if api_key...' block without having to do an if statement for each of them?

A: Use get which will default to None if the key is not found
Replace
if api_key is not None:
    if 'dialect' in sql_yaml[api_key].keys():
        dialect = sql_yaml[api_key]['dialect']
    if 'driver' in sql_yaml[api_key].keys():
        driver = sql_yaml[api_key]['driver']
    if 'host' in sql_yaml[api_key].keys():
        host = sql_yaml[api_key]['host']
    if 'port' in sql_yaml[api_key].keys():
        port = sql_yaml[api_key]['port']
    if 'database' in sql_yaml[api_key].keys():
        database = sql_yaml[api_key]['database']

with
if api_key:
    dialect = sql_yaml[api_key].get('dialect')
    driver = sql_yaml[api_key].get('driver')
    host = sql_yaml[api_key].get('host')
    port = sql_yaml[api_key].get('port')
    database = sql_yaml[api_key].get('database')

OR with
if api_key:
    dialect,  driver,  host,  port,  database = map(sql_yaml[api_key].get, ['dialect', 'driver', 'host', 'port', 'database'])


text:
Q: ClassCastException using Class.cast using Generics I am writing a generic method which will validate a property by trying a class.cast on it but I keep getting a ClassCastException
... Class to Test
public <T> T get(Properties p, String propKey, Class<T> clazz) throws Exception {

    T val = null;

    Object propValue = p.get(propKey);

    if(propValue== null) {
        throw new Exception("Property (" + propKey + ") is null");
    }

    try {
        val = clazz.cast(propValue); // MARKER

    } catch(Exception e) {
        throw new Exception("Property (" + propKey + ") value is invalid value of type (" + clazz + ")", e);
    }

    return val;
}

... Test Class
@Before
public void setUp() {
    propUtil = new PropUtil();
    properties = new Properties();
    properties.setProperty("test.int.prop", "3");
}

@Test
public void testGet() {

    try {

        assertEquals(new Integer(3), propUtil.get(properties, "test.int.prop", Integer.class));
    } catch (Exception e) {
        System.out.println(e);
    }
}

The code at commented at MARKER is causing the ClassCastException.
Any ideas much appreciated.

A: The Properties class is a Hashtable stores String objects, especially when you call setProperty.  You have added the String "3", not the integer 3.  You are effectively attempting to cast "3" as an Integer, so that correctly throws a ClassCastException.  Try
assertEquals("3", propUtil.get(properties, "test.int.prop", String.class));

Or if you want to have get return an Integer, then just use a Hashtable<String, Integer>, or even better, use a HashMap<String, Integer>.

A: Assuming that Properties here is java.util.Properties, the values are always Strings.
You should use the getProperty() method, rather than the get() method that happens to be visible from HashTable because this class was written back when the Java folks were less careful about composition versus inheritance.

A: This Line
properties.setProperty("test.int.prop", "3");

puts a java.lang.String in properties
and You pass Integer.class to you generic method. So the ClassCastException is expected!
If you want to Test for Integer.class you have to put an Integer
properties.put("test.int.prop", 3);

Note in the above line the use of put since the Properties class is extending Hashtable
If your intention is to put a String  and test for an Integer then you have to somehow parse that String to an Integer value

A: Thanks for your replies.  I realise the basic act of casting from String to Integer wasn't possible.  I was just trying to make the method slicker and do the conversion check for me.  I've just worked out the solution I was lookin using Reflection which is :
    Object propValue = p.get(propKey);
    Constructor<T> constructor = clazz.getConstructor(String.class);
    val = constructor.newInstance(propValue);

i.e Using the public constructor that takes the String.class (i.e. the String property value)
Works a treat.


text:
Q: "Sort" an Array by Shifting Elements, with constraint My problem is the following:

Write an algorithm that takes as input an integer array $A$ and outputs $N$, the least nonnegative integer with the following property: $$\exists \text{ an integer array $X$, len($X$) = len($A$) such that }\forall i : |X[i]| \le N \text{ and } X + A \text{ is strictly sorted.}$$

Strictly sorted means $i < j \implies A[i]<A[j]$. Also, $X + A$ denotes component wise addition.
Here are a couple examples

$A = [3, 2, 1] \implies N = 2\,,\,X=[-2,0,2]$
$A = [5, 2, 5, -1] \implies N = 5\,,\,X=[-5,-1,-3,4]$

At first I thought I could just shift all entries towards the average of the largest inversion (-- to the left of middle ++ to the right), but this was just a heuristic estimate. I have not been able to actually prove anything substantial about $N$.
Not looking for the solution as much as some intuition / a hint.

A: Hint:

*

*$X$ is linear in its effect, i.e. you could shift the whole array by some number and it would still work.

*Because of the previous point you could try to search for an array $X'$ of non-negative numbers smaller than or equal some $N'$ and then $N = \left\lceil\frac{N'}{2}\right\rceil$.

*Given $N'$, can you check that there exists an array $X'$ such that $A+X'$ is strictly increasing?

*Using the above and binary search you can obtain $\mathcal{O}(n \log n)$ algorithm.

*Modify the algorithm so that it adjusts/calculates the $N'$ online to obtain $\mathcal{O}(n)$ algorithm.

I hope this helps $\ddot\smile$

A: Find an $X$ which satisfies the condition that $X + A$ is strictly sorted with $\max X - \min X$ minimal first (let e.g. $X[0] = 0$ and find the other values accordingly). Then find $k$ such that $X + k$ minimizes $N$, where by $X + k$ I mean the sequence obtained by adding $k$ to all the elements of $X$ (of course $k$ may be negative).


text:
Q: How to format an Index lookup number into minutes I have a Cell where i've used an Index lookup to pull a number from another sheet, (ie 5) this represent the number of minutes something takes to do, but for it to work in the current sheet, it needs to be formatted to time (ie 12:05) to work with another formula, however when i change the formatting, it just returns it to 12:00:00.
Is there a way to Change the formatting without loosing the Index formula?

A: Time is stored by Excel as numbers. 1 is a day and 0.00069444 is a minute.
It is likely the result of your formula displays as 12:00 since Excel interprets 5 as five days and zero minutes.
Dividing the result of your formula by 1440 should fix the problem


text:
Q: skip rotate of custom shareExtesion i have a shareExtension with custom viewController:
class ShareViewController: UITableViewController{

}

if i rotate phone it has been rotated, i would like to fix it to portrait orientation and i have used this code:
override func shouldAutorotate() -> Bool {
    return false
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait
}

But it does not work, any ideas? thanks!

A: Go to your project's general tab, look up 'deployment info', select your options for 'device orientation'


text:
Q: Python Class: Global/Local variable name not defined I have two sets of code, one which I use 'Class' (Second piece of code) to manage my code, and the other I just define functions, in my second piece of code I get a NameError: global name '...' is not defined.
Both pieces of code are are for the same purpose.
from Tkinter import *
import ttk
import csv

USER_LOGIN = "user_login.csv"

class Login:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        lment1 = StringVar()
        lment2 = StringVar()

        self.usernameLabel = Label(frame, text="Username:")
        self.usernameLabel.grid(row=0, sticky=E)
        self.passwordLabel = Label(frame, text="Password:")
        self.passwordLabel.grid(row=1, sticky=E)

        self.usernameEntry = Entry(frame, textvariable=lment1)
        self.usernameEntry.grid(row=0, column=1)
        self.passwordEntry = Entry(frame, textvariable=lment2)
        self.passwordEntry.grid(row=1, column=1)

        self.loginButton = ttk.Button(frame, text="Login",   command=self.login_try)
        self.loginButton.grid(row=2)

        self.cancelButton = ttk.Button(frame, text="Cancel", command=frame.quit)
        self.cancelButton.grid(row=2, column=1)

    def login_try(self):
        ltext1 = lment1.get()
        ltext2 = lment2.get()
        if in_csv(USER_LOGIN, [ltext1, ltext2]):
            login_success()
        else:
            login_failed()

    def in_csv(fname, row, **kwargs):
        with open(fname) as inf:
            incsv = csv.reader(inf, **kwargs)
            return any(r == row for r in incsv)

    def login_success():
        print 'Login successful'
        tkMessageBox.showwarning(title="Login successful", message="Welcome back")

    def login_failed():
        print 'Failed to login'
        tkMessageBox.showwarning(title="Failed login", message="You have entered an invalid Username or Password")

root = Tk()
root.geometry("200x70")
root.title("title")
app = Login(root)
root.mainloop()

That is the second piece of code ^^^
# **** Import modules ****

import csv
from Tkinter import *
import ttk
import tkMessageBox

# **** Declare Classes ****

lGUI = Tk()
lment1 = StringVar()
lment2 = StringVar()
USER_LOGIN = "user_login.csv"

def in_csv(fname, row, **kwargs):
     with open(fname) as inf:
         incsv = csv.reader(inf, **kwargs)
         return any(r==row for r in incsv)

def login_try():
     ltext1 = lment1.get()
     ltext2 = lment2.get()
     if in_csv(USER_LOGIN, [ltext1, ltext2]):
        login_success()
     else:
        login_failed()

def login_success():
    print 'Login successful'
    tkMessageBox.showwarning(title="Login successful", message="Welcome back")

def login_failed():
     print 'Failed to login'
     tkMessageBox.showwarning(title="Failed login", message="You have entered an invalid Username or Password")

lGUI.geometry('200x100+500+300')
lGUI.title('PVH')

lButton = Button(lGUI, text="Login", command=login_try)
lButton.grid(row=3)

label_1 = Label(lGUI, text="Username")
label_2 = Label(lGUI, text="Password")
entry_1 = Entry(lGUI, textvariable=lment1)
entry_2 = Entry(lGUI, textvariable=lment2)

label_1.grid(row=0)
label_2.grid(row=1)

entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)

lGUI.mainloop()

And that is the piece of code that works^
I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:/Users/User/Desktop/PVH_work/PVH_program/blu.py", line 33, in login_try
    ltext1 = lment1.get()
NameError: global name 'lment1' is not defined

Any help would be appreciated :D

A: In your first code piece, you define the variable 'lment1' in the __init __ method, making it local to that single method.
When you then try to access the same variable in the 'login_try', Python doesn't know what it is.
If you wish to access the variable form wherever in the class, you should define it on the class level, by setting it on 'self'
def __init__(self, master):
    [...]
    self.lment1 = StringVar()
    [...]

That way, you can access it later with:
def login_try(self):
    [...]
    ltext1 = self.lment1.get()
    [...]

The reason it works in your second code sample, is because you defined it outside of any class - Making it globally available


text:
Q: My program is showing many errors, "error: no matching function for call to 'getPercentScore'" I have a program that has to read two input files and sort some data from the two files. I have figured most of the things out but I keep trying to pass a stricter array into my function but it is not working.
int main()
{
    int labNumber=8;
    string labName = "MATH ANYONE";
    printHeader(labName, labNumber);

    ifstream    infile;             //INPUT input file stream

    struct test {
        string firstName;           //INPUT student first name
        string lastName;            //INPUT student last name
        string tempfirstName;       //INPUT temporary first name used to place into actual
        string templastName;        //INPUT temporary last name used to place into actual
        string tempId;              //INPUT temporary id used to compare with actual
        string studentId;           //INPUT student id
        double courseScore;         //OUTPUT student score %
        char courseGrade;           //OUTPUT student letter grade
        string answers;             //INPUT student answer
    };
    test *table[30];

this is just part of my code; I have one input file called functions.cpp
    for (int i=0;i<studentCount;i++)
    {
        double percent=0;
        getPercentScore(table[30], key);
    }

functions.cpp:
double getPercentScore(test *, string key)

{
    double tempscore=0;
    double percent;
    for (int i=0;i<20;i++)
    {
        if (table[i].answers[i] == key[i])
        {
            tempscore = tempscore + 2; //add two if answer is correct
        }
        else if (table[i].answers[i] == '_')
        {
            tempscore = tempscore + 0;//add zero if answer if unanswered
        }
        else
        {
            tempscore = tempscore - 1;//subtract one for wrong answer
        }
    }
    percent = tempscore/40;
    percent = percent*100;
    return percent;
}

my program has been giving me this error and I do not know how to solve it:
../lab8.cpp:112:3: error: no matching function for call to 'getPercentScore'
                getPercentScore(table[30], key);
                ^~~~~~~~~~~~~~~
../lab8.cpp:33:8: note: candidate function not viable: no known conversion from 'test *' to 'test *' for 1st argument
double getPercentScore(test *, string key);
Any help would be greatly apreciated.

A: First, try to create the test array:
test table[30];

At functions.cpp declare function getPercentScore() as:
double getPercentScore(test tbl[], string key)

also, replace any reference of table inside getPercentScore() body with tbl.
If you wish to know the size of the array, pass it as an extra parameter like:
size_t size = sizeof(table) / sizeof(test);
for (int i=0;i<studentCount;i++)
{
    double percent=0;
    getPercentScore(table, size, key);
}

Hope I helped you...


text:
Q: Convert a Java array into a Clojure list or sequence? How do I convert a Java array into a Clojure sequence data structure, such as a list, or other sequence?
This question shows how to do the inverse; The Clojure docs show how to create, mutate, and read arrays; but is there a built-in way to convert them to lists, or some other Clojure-native sequence?

A: Yes, there is a way to convert an array to a list! The code (seq java-array-here) will convert the array into an ArraySeq, which implements ISeq, and thus can be treated like any other Clojure sequence.


text:
Q: Grep a page in firefox using javascript Am writing an extension to provide grep'ing functionality in Firefox.  At my workplace we access all log files using a browser, and grep functionality would be ideal for filtering results, looking at only particular logging levels (INFO,WARN,ERROR) etc.
Have setup the extension boilerplate.
Was wondering if I could get some hints on the required javascript.  Am after a function:
function grepPage(regex){
...
}

which would apply the regex to each line in loaded text file in firefox, and change the loaded text file to only display lines that match.
This is the type of thing I could spend ages trying to work out, when I'm sure there would be simpler ways of doing this.
Any help would be highly appreciated.
Cheers,
Ben

A: Two ways to look at this.
One, you could avoid re-inventing the wheel:
http://api.jquery.com/jQuery.grep/
Two, you could whip up a quick function (this example doesn't require jQuery or other libraries).
function grepPage(regex) {

  var lines = document.getElementByTagName('body').innerHTML.split("\n");
  var matches = new Array();

  // Check if the regex is surrounded by slashes by checking for a leading slash
  if ( ! regex.match(/^\//) ) { regex = '/' + regex + '/'; }

  for (var i = 0; i < lines.length; i++) {
    if ( regex.test( lines[i] ) ) { matches.push(lines[i]); }
  }

  // Now the 'matches' array contains all your matches, do as you will with it.

}

Warning, untested, but it should work. :)


text:
Q: better way to test Css editor for manual tester There is an editor like cKEDITOR.
In which give content in ckeditor and design it same way there is an editor where user can put up their CSS in particular block which in return gives output .
How to test these CSS  editor??


text:
Q: What index types in hazelcast I'm using Hazelcast to save map Object Class which has many properties with difference types
Example
  public class Person() {
      public int id;
      public Syting name;
      public Date birthDay;
      public boolean isVip;
  }

So, how i can put map with object data and hazelconfig.xml as
  <indexes>
            <index ordered="true">id</index>
            <index ordered="true">name</index>
            <index ordered="false">birthDay</index>
            <index ordered="false">isVip</index>
  </indexes>

Thank you very much for any ideas.

A: You can just add your person to a map with the configured indexes.
Map personMap = hz.getMap("persons"):
personMap.put("1", new Person(.......))

Hazelcast will inspect the object and check if there are any fields/methods which match with the index definitions.
PS:
Why would you need ordered index on name of id? Unordered index is faster AFAIK.