GCP Kubernetes MongoDb statefulset connection string MongooseError getaddrinfo ENOTFOUND

Question: I am following the following tutorial to configure MongoDB as a stateful set within my Kubernetes cluster on GCP.
https://codelabs.developers.google.com/codelabs/cloud-mongodb-statefulset/index.html?index=..%2F..index#0
I am able to access the database using "kubectl exec -ti mongo-0 mongo" as shown in the tutorial.
However, my Node JS- Mongoose Application is unable to connect to it throwing the following error
MongoDB connection error: { MongooseError [MongooseServerSelectionError]: connect ECONNREFUSED 10.16.0.22:27017
    at new MongooseServerSelectionError (/usr/src/app/node_modules/mongoose/lib/error/serverSelection.js:24:11)
    at NativeConnection.Connection.openUri (/usr/src/app/node_modules/mongoose/lib/connection.js:823:32)
    at Mongoose.connect (/usr/src/app/node_modules/mongoose/lib/index.js:333:15)
    at Object.<anonymous> (/usr/src/app/app.js:6:10)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
    at internal/main/run_main_module.js:21:11
  message: 'connect ECONNREFUSED 10.16.0.22:27017',
  name: 'MongooseServerSelectionError',
  reason:
   TopologyDescription {
     type: 'ReplicaSetNoPrimary',
     setName: null,
     maxSetVersion: null,
     maxElectionId: null,
     servers:
      Map {
        'mongo-0.mongo:27017' => [ServerDescription],
        'mongo-1.mongo:27017' => [ServerDescription],
        'mongo-2.mongo:27017' => [ServerDescription] },
     stale: false,
     compatible: true,
     compatibilityError: null,
     logicalSessionTimeoutMinutes: null,
     heartbeatFrequencyMS: 10000,
     localThresholdMS: 15,
     commonWireVersion: null },
  [Symbol(mongoErrorContextSymbol)]: {} }
(node:29) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 10.16.0.22:27017
    at new MongooseServerSelectionError (/usr/src/app/node_modules/mongoose/lib/error/serverSelection.js:24:11)
    at NativeConnection.Connection.openUri (/usr/src/app/node_modules/mongoose/lib/connection.js:823:32)
    at Mongoose.connect (/usr/src/app/node_modules/mongoose/lib/index.js:333:15)
    at Object.<anonymous> (/usr/src/app/app.js:6:10)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
    at internal/main/run_main_module.js:21:11
(node:29) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:29) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

app.js connection code is as follows
mongoose.connect(
  process.env.MONGO_CONNECTION_STRING,
  {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  }
);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));

And Environment variable is as follows in deployment file.
env:
  - name: MONGO_CONNECTION_STRING
    value: "mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/test"

Mongo pods status
mongo-0                                         2/2     Running     0          8m35s
mongo-1                                         2/2     Running     0          7m49s
mongo-2                                         2/2     Running     0          6m54s

kubectl get statefulset
NAME     READY   AGE
mongo    3/3     9m31s

Service
NAME                                  TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)                      AGE
mongo                                 ClusterIP      None           <none>          27017/TCP                    27m

rs.config() output
{
    "_id" : "rs0",
    "version" : 1,
    "protocolVersion" : NumberLong(1),
    "members" : [
        {
            "_id" : 0,
            "host" : "mongo-0.mongo:27017",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 1,
            "tags" : {

            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        },
        {
            "_id" : 1,
            "host" : "mongo-1.mongo:27017",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 1,
            "tags" : {

            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        },
        {
            "_id" : 2,
            "host" : "mongo-2.mongo:27017",
            "arbiterOnly" : false,
            "buildIndexes" : true,
            "hidden" : false,
            "priority" : 1,
            "tags" : {

            },
            "slaveDelay" : NumberLong(0),
            "votes" : 1
        }
    ],
    "settings" : {
        "chainingAllowed" : true,
        "heartbeatIntervalMillis" : 2000,
        "heartbeatTimeoutSecs" : 10,
        "electionTimeoutMillis" : 10000,
        "catchUpTimeoutMillis" : 60000,
        "getLastErrorModes" : {

        },
        "getLastErrorDefaults" : {
            "w" : 1,
            "wtimeout" : 0
        },
        "replicaSetId" : ObjectId("5f16a0f3671c091fe183af72")
    }
}

Any help is appreciated.
Comment: can  you also share rs.conf() result after you do kubectl exec -ti mongo-0 mongo
Comment: sure I can. I'll add it to question
Answer: Figured it out
Tutorial has a step missing to initiate the set.
After connecting to set using the command
kubectl exec -ti mongo-0 mongo

Just Run following two commands
rs.initiate({_id: "rs0", version: 1, members: [
       { _id: 0, host : "mongo-0.mongo:27017" },
       { _id: 1, host : "mongo-1.mongo:27017" },
       { _id: 2, host : "mongo-2.mongo:27017" }
 ]});

rs.slaveOk()

Comment: I had to do it manually.
If anyone can help so that it could be done automatically it'd be great.


Determine if two objects have an identical structure with Jest

Question: I'm working on a React application which has multiple themes. Each theme should have the same structure, which can feature deeply-nested properties, but will have different values. It's the structure I'm wanting to add a test case for.
I'm wanting to use Jest to determine if the structure of each of my themes are identical to ensure that no properties have been missed.
All of my theme objects have an identical structure but with different properties. They're set up similar to this:
{
  brand: '...',
  navigation: {
    background: '...',
    link: {
      background: '...',
    },
    ...
  },
  ...
}

I'm aware of properties like toEqual and toMatchObject, but both of these fail if I directly try to compare two themes with one another:
expect(themeA).toMatchObject(themeB);

This fails because the values of each property are different. For example, themeA has a brand property set to '#ABC' whereas themeB has the same property set to  '#DEF'.
I'm also aware that a structure can be defined using Jest like this:
expect(themeA).toEqual({
  brand: expect.any(String),
  navigation: {
    background: expect.any(String),
    ...
  },
  ...
})

...but this would require updating the test case every time a new property is added or removed, which I feel complicates the purpose of the test.
Is there a simple way to test if two objects have the same structure but different values?
Comment: have you considered using snapshot testing instead?
Comment: @Peter I don't think that would work as I'm using JSS which only outputs class names and not the raw style values. I'm not really wanting a thorough test of my application, just a quick failsafe on the build step to point out that a theme has a missing property.
Comment: "Is there a simple way to test if two objects have the same structure but different values?"  this is usually accomplished with using `expect.any(String)` etc like you show at the bottom of your question or you ignore running unit tests and use a static types such as TS or Flow.
Comment: @Peter to achieve that I believe I'd have to define each property first? The theme files I'm working with each have several hundred properties and I don't have a need to perform type matching as the compiler would fail to apply the properties if they weren't strings (or objects containing child properties with strings) anyway.
Comment: Note that the objects in your question end with a semicolon and not with a comma (`background: '...';`). Is that a typo?
Comment: @mgarcia well spotted, yes that's just a typo. The theme files I'm dealing with are hundreds of lines long, so this post just contains an example of the sort of structure they contain, not the exact structure.
Answer: You can achieve what you want by implementing a custom matcher. The matchers jest has can be extended by using the extend method.
As a proof of concept, you can define a toMatchStructure matcher like this:
function hasEqualStructure(obj1, obj2) {
    return Object.keys(obj1).every(key => {
        const v = obj1[key];

        if (typeof v === 'object' && v !== null) {
            return hasEqualStructure(v, obj2[key]);
        }

        return obj2.hasOwnProperty(key);
    });
}

export default function toMatchStructure(actual, expected) {
    const pass = hasEqualStructure(actual, expected);

    return {
        message: () => `expected ${expected} to match structure ${actual}`,
        pass
    };
}

Note that this matcher does not take into account edge cases (does not check if the objects are null). Also, the matcher will pass if obj2 is a superset of obj1 (i.e. has the same properties plus some extra properties that are not present in obj1). Furthermore, it is only checking that the keys are present, but it could be extended to check that the type of the values in those properties are the same. You can also edit the returned message so that is more user friendly for the tests that fail.
Having that in mind, you can now extend jest matchers by calling:
expect.extend({
   toMatchStructure,
});

Ideally, you would do this in a file that would be executed through the setupFilesAfterEnv jest config option.
Once you have the setup done, you can call your matcher in the test:
expect(themeA).toMatchStructure(themeB);

Answer: You could remove all different values from your object and leave just a structure - then you could simply compare two structures using basic jest toEqual:

const obj1 = {
    brand: 'brand 1',
    navigation: { opacity: 0.2 },
};
const obj2 = {
    brand: 'brand 2',
    navigation: { opacity: 0.5 },
};

function normalizeObject(obj) {
    return JSON.parse(JSON.stringify(obj), (_key, value) => (
        typeof value !== 'object' ? '-' : value
    ));
}

// then you could compare structures of 2 objects:
// expect(normalizeObject(obj1)).toEqual(normalizeObject(obj2));

// or verify if every element from some array have the same structure:
const themeArray = [obj1, obj2, obj1];
themeArray.forEach((theme) => {
    // expect(normalizeObject(theme)).toEqual(normalizeObject(themeArray[0]));
});

// according to number of different types in your comparable objects you may want to modify normalizeObject function a little
function normalizeObject(obj) {
    return JSON.parse(JSON.stringify(obj), (_key, value) => {
        switch (typeof value) {
            case 'number': return 0;
            case 'string': return '-';
            case 'boolean': return true;
            // case ...: return ...;
            default: return value;
        }
    });
}

console.log({
    original: obj1,
    normalized: normalizeObject(obj1),
});
Answer: This is what Typescript will catch everywhere, automatically.  You won't really need to write tests for this type of thing.
type ThemeA = {
  brand: string,
  navigation: {
    background: string,
    link?: {
      background: string,
    },
    ...
  },
  ...
}

myStyle = { ... }

myStyle: ThemeA   // this will be highlighted by your IDE
                  // if it's not a match, even in tests.

Comment: In a typed environment, I don't see why you would need to write unit tests confirming the type.


Invalid value provided (invalid IRI?) Error testing api-platform endpoint

Question: I have a Product entity, related to another User entity with a relation manyToOne
class Product implements AuthoredEntityInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="products")
* @ORM\JoinColumn(nullable=false)
*/
private $user;

/**
* @ORM\Column(type="string", length=255)
*/
private $name;

/**
* @ORM\Column(type="double")
*/
private $price;

//various getters and setters

}

The AuthoredEntityInterface helps to set the user to the current logged in user. when I make an api call to /api/products (I use postman) passing a json like this:
{
    "name": "my product",
    "price": 10
}

This works and a new record is created. The problem is with unit tests. I make a call like this:
$headers = [
        'HTTP_AUTHORIZATION' => 'Bearer ' . $token,
        'CONTENT_TYPE' => 'application/ld+json',
        'HTTP_ACCEPT' => 'application/ld+json'
    ];
$postData = [
    'name' => 'my product',
    'price' => 10
];
$client = $this->makeClient();
    $client->request('POST', '/api/products', [], [], $headers, json_encode($postData));

I get this error:
    Invalid value provided (invalid IRI?)
Now the only IRI is referring to should be user, that as mentioned is auto-generated inside the class.
Any idea?
UPDATE:
To populate the user field
Method in Product
public function setUser(UserInterface $user): AuthoredEntityInterface
{
    $this->user = $user;
    return $this;
}

Then I use an event subscriber:
class AuthoredEntitySubscriber implements EventSubscriberInterface
{
/** @var TokenStorageInterface */
private $tokenStorage;

public function __construct(TokenStorageInterface $tokenStorage)
{
    $this->tokenStorage = $tokenStorage;
}

public static function getSubscribedEvents()
{
    return [
        KernelEvents::VIEW => ['getAuthenticatedUser', EventPriorities::PRE_WRITE]
    ];
}

public function getAuthenticatedUser(GetResponseForControllerResultEvent $event)
{
    $entity = $event->getControllerResult();
    $method = $event->getRequest()->getMethod();

    /** @var UserInterface $user */
    $user = $this->tokenStorage->getToken()->getUser();

    if((!$entity instanceof AuthoredEntityInterface) || Request::METHOD_POST != $method) {
        return;
    }

    $entity->setUser($user);
}
}

Comment: Do you have an ID attribute on User ? As well as getter/Setter on product and user ?
Comment: I have getters on both entities, setters aren't needed 'cause the field is auto increment (@ORM\GeneratedValue())
Answer: You must encode your $postData into content type you want, eg. JSON, and encoded data must be passed into $client->request()
Comment: Sorry I missed a bit, $postData is already json encoded. I updated the question.
Comment: How do you fill User into your Product? Can you show the part of code?
Comment: @user3174311 Well, it looks good, so what about token, are you sure its right? Is it `$user` variable filled in getAuthenticatedUser() call?
Comment: Have you tried logging `$user` in `AuthoredEntitySubscriber` or in `function setUser`. Are you running tests on other environments? If so, do they contains the same user data?
Comment: @ThomasVangelooven I can't log $user the AuthoredEntitySubscriber is not executed, the error is exactly when I run the request. I setup the application to run tests on an instance of sqlite, data is correctly set using fixtures.
Answer: I'm pretty sure you're encountering the same error I had awhile back, authentication credentials shouldn't be passed in the request head, it should be passed via the client.
Sample:
$credentials = array(
    'HTTP_AUTHORIZATION' => 'Bearer ' . $token,
);

$client = $this->makeClient($credentials);

Also make sure that HTTP_AUTHORIZATION is the correct name that you need to be using. Alot of times it's just Authorization.
To recap there's request headers and client headers. Make sure you're setting auth in client headers.
Comment: @user3174311 I concur, just confirmed on my stack, that you indeed need header `Authorization` to send the bearer token, as suggested by Lulceltech. It makes sense for no user to be loaded when no token is found.
Comment: makeClient is expected to receive an array with username and password, or nothing. Here I am authenticating using a bearer token. Anyway, the problem is not with authentication: for some reason I don't know yet my AuthoredEntitySubscriber is not triggered ONLY when i use phpunit/Liip.


Is it possible for a class to have a data member that only exists within an instance of that class if it isn't null?

Question: This code is in Java and utilizes Dropwizard and Lombok. I am wondering if there is an annotation I can use or some other way to make a data member of a class exist if it has some non-null value OR not exist if the value is null.
I'm not sure if this is something that is possible or not, but I'm trying to work within some restraints.
The relevant VerificationResponse class is this:
private SomeResponseContext context;

public static VerificationResponse response(String responseCode, String responseType,
        String explanationCode, String explanation, String optionalField) {

    SomeResponseContext context = VerificationResponseContext.builder().responseCode(responseCode).
            responseType(responseType).explanationCode(explanationCode).explanation(explanation).optionalField(optionalField).build();

    VerificationResponse verifyResponse = VerificationResponse.builder().context(context).build();

    return verifyResponse;

}

The someResponseContext class looks like this:
@Getter
@Setter
@Builder(builderClassName="SomeResponseContextBuilder")
@NoArgsConstructor
@AllArgsConstructor
@ToString
@ ? //Don't include optionalField if it is null
public class SomeResponseContext {
        private String responseCode;
        private String responseType;
        private String explanationCode;
        private String explanation;
        private String optionalField;
}

When I return the VerificationResponse verifyResponse I want its SomeResponseContext member to either have all the fields like the SomeResponseContext code posted above or, if when SomeResponseContext is built if the value of the Sting optionalField is null/does not exist then that data member is dropped and the class for all practical purposes would look like this:
public class SomeResponseContext {
        private String responseCode;
        private String responseType;
        private String explanationCode;
        private String explanation;
}

The issue is that certain situations expect verifyReponse to only have the four data members and it will crash if there are more. However, another situation has arose where we need a fifth data member in certain situations.
Comment: Abstract class with the minimum level of fields should work for you
Comment: Yeah I think that solution could work...I was just thinking there might be a magic lombok annotation or something like that.
Comment: I think it is not possible. It would require to have one type with 2 different class structures. I will post it as answer later.
Comment: Are you concerned about the JSON representation of the response? If so you could use @JsonInclude(JsonInclude.Include.NON_NULL)
Comment: Yes Matt, I just stumbled upon @JsonInclude(Include.NON_NULL). With this, the field wouldn't be included in the response when I'm building the response ... .entity(verifyResponse).build(); ?
Answer: I think it is not possible that would require the JVM to load a type/class
with two different structures:
class foo{
    String s1;
}

class foo{
    String s1;
    String s2;
}

Which one to use? It is ambiguous. Your best shot if the extra field becomes expensive over time is to use an abstract class
abstract class foo{
    protected String s1;
}

class foo1 extends foo{
}

class foo2 extends foo{
    String s2;
}

Lombok should be able to pick those up


How do I restore power to living room receptacles?

Question: I removed a data receptacle from my living room, and all the outlets to that room (the alarm system) and garage door are not working.  After trying to diagnose the problem I'm left very puzzled!

the receptacle has two different data cables and one Romex cable
Data cables are both white,green,blue,orange, white/green
Romex is green,black,red,yellow.
nothing is tripped in the box
testing 120v on every breaker with a Volt meter
the receptacles that aren't working are reading 0volts
all GFCI in the entire house have been reset and are working

Is it possible one of the GFCIs is defective even though the outlet itself works?

Does disconnected data cables have anything to do with loosing power to the entire room?
Comment: Why do you have a garage door in your living room?  Are your electric(120v) outlets working or not?  Is it only your low voltage(alarm, door bell,data) that stop working?
Comment: **ALL** the cables/wires you've shown us in this picture are low voltage. The one on the right with the white/cream sheath looks like POTS phone wire. The two on the left look to be newer (they have some cord in them to improve bend/break resistance, and the colors _look_ different), but they're still LV wiring. Probably for the alarm system.
Comment: what were those data cables for, did you just cut them off or disconected from what ?
Comment: "all the outlets to that room (the alarm system) and garage door are not working." All the _data_ outlets or all the 120v _power_ outlets are not working. You've shown us a picture of low-voltage wiring, not 120V household AC wiring.
Comment: Can you show us a picture of the "data receptacle" that you removed?  I'm not familiar with any one "receptacle" that would have all these wires connected to it.  Can you show us a picture of the receptacles that are no longer working also?   And explain why you "removed" it .... when you appear to have also disconnected a bunch of wires without knowing what they are.  The obvious answer would be to reconnect them.  Did you note how they were connected before?   A LOT more info is needed here.
Comment: @Ruskes They're for a landline I'm assuming.  I just sniped them off and didn't take a picture of the wiring before removing it.
Comment: @crip659. I have a garage door in my garage (which is the next room over).  All the 120v outlets and light switches in the garage and living room aren't working.
Comment: @FreeMan Thanks!  That's helpful to know the 4 cable black red green yellow cable is low voltage
Comment: Those data/low voltage cables and the house's electric system should be separated when put in.  It is possible if you pulled on those data cables, they caught a power cable and loosen/broke a connection or both just happen at the same time.  What were the data cables for?  Is it possible one or more controlled a relay/smart thingy?
Comment: Those are way too small to be Romex cable.  Romex starts at 14 AWG. Those like like #26 to #20 AWG.  (you can look up what that means). Also Romex has a **bare** ground and a white insulated wire.  Looks like ethernet and phone.  None of which are legal to be mixed with AC power in the same box. (unless there is a dividing wall in the box).
Answer: Romex is a brand name, but commonly used to refer to NM (non-metallic) sheathed multi-conductor cable for 120V/240V wiring.
What you have in the picture are 3 low voltage (i.e., telephone and/or networking) cables. Red/Green/Black/Yellow is extremely common for 2-pair telephone cable (Red/green for the first pair, black/yellow for the second pair, used for either two phone lines or a phone system with one pair for voice and one for control signals).
So none of that is what is commonly referred to as "Romex", and none of that should have anything to do with your 120V circuits. The insulation is almost certainly not rated for 120V, and the wires are way to small for even a basic 15A circuit. In addition, low voltage cables (phone, network, cable TV, burglar alarm, etc.) are never supposed to be in the same boxes, conduits, etc. as 120V circuits.
My best guess is that you have a loose connection somewhere near the data receptacle that you worked on, and now it has come apart, breaking the circuit. But it is also possible that it is a coincidence and totally unrelated.
GFCI is often a factor, but if a GFCI receptacle works then anything connected by the LOAD terminals should work as well. Possibilities (GFCI or not) include:

Loose screw connection
Bad backstab (and if you find one, replace the receptacle or at least move the wires to screw terminals)
Loose wire nut
Mouse chewed through a cable (evidence will include a dead toasted mouse)
Flipped switch - a switch can control a receptacle or a whole chain of receptacles. Not generally recommended, but stranger things have happened.

Keep hunting. And along the way, make a map of your circuits for the next time.
Comment: It ended up being a faulty GFCI in the garage - Thanks again for all the information.
Comment: Thanks!!  I thought the black,red,green,yellow was for delivering power.  (I was confused why all three were connected to one Ethernet receptacle). I'll start digging a little deeper, appreciate the thorough response!


How to take param values from Task Queue url.?

Question: Queue queue = QueueFactory.getDefaultQueue();
queue.add(("/worker").param("key", "ABC"));

how to take key value .? using below code or any other approach.
request.getParameter("key");

Answer: Absolutely. The /worker endpoint is configured in your web.xml as a Servlet. The request object will be passed to your Servlet method and you can use the standard methods like the one you have specified i.e. getParameter(...)


Complex form: Accordion + vertical navigation menu + back/next

Question: I have seen some wireframes from some colleagues asking the user to fill out some very complex forms.
They have seperated the forms in "sections" (which is a good idea). Further they introduced a vertical navigation area on the left which allows to switch between the "sections" of the forms. They also put every "section" in one accordion. And inside the accordion they've placed "back" and "next" button. With all those elements you can jump between the "sections" of the forms.
To me this feels a bit confusing and redundant. Are there any (documented) best practices which I can use to argument against this interaction design?
Comment: The model you described seems reasonable to me (just my *opinion*). Im not sure there are specific, documented best practices for this. The 'next' and 'back' buttons make sense because filling in the form is a process and the accordion is a nice way of keeping everything tidy. However, if this is such a complex form that it *needs* an accordion and 'next'/'back' controls, then I have to ask if there's a 'Save progress' function anywhere.
Comment: Next/back button seem like a good idea if some users might have a problem with the UI without those (user testing would probably be a great idea to decide). I asked a related question, and the accepted answer might give some clue to this question (https://ux.stackexchange.com/questions/100866/should-opening-a-modal-box-change-the-browser-history)
Comment: For sure "next"/"back" is a good idea, but it's primarily used to "open" the next accordion. I was confused about that. And they are placed inside the accordions.
Answer: I have designed exactly the same design for complex forms in a government agency. During the usability testing, user frustration was "They were filling out 10 sections and then hitting enter and finding 5 validation errors" so I introduced "next and back" buttons to validate each section separately before moving on to next one. The user found this idea to be quite helpful on mobile devices & tablets (I was designing these forms mobile first). In your case, if you are not putting validation on "next and back" buttons, then you don't need to use next and back buttons because users have enough choices to switch between sections.
Suggestion: Add validation on next button so user will see errors before they move on to the next section. This will help the form to run smoothly on smaller devices.
Answer: It sounds like the control you describe is a standard horizontally-based progress indicator with the "tabs" moved to a left-side navigation control. If this is the case, then using previous/next buttons is fairly common.
Comment: The "next" and "back" buttons are primarily used to open the next/previous accordion and they are placed inside the accordion.
Answer: Even complex forms are essentially made up of 'simple' parts combined together, so you really need to consider where the complexity comes from and how best to manage it within the constraints. These would generally fall under the category of information architecture and content design that is supported by the user interface design, rather than using UI to address underlying IA issues.
The two main things I can think of are the complexity of the process and the complexity of the content, which I will cover separately:
Process complexity

For linear processes (i.e. you can only move one step/section at a time) you can manage the complexity by keeping the user flow linear and helping them to skip to sections that they don't need to complete (if there is some conditional logic available). By the sounds of it this doesn't apply in your case. You can also provide a progress tracker if you feel like it will provide a good visual indicator.
For non-linear processes you should still try to organize the content into logical sections, but instead of a progress tracker you can use a checklist style menu that shows the number of sections completed. Instead of allowing users to navigate within each step/section, you should point them back to the checklist as a central and consistent point of navigation.

Content complexity

When the density and volume of content is greater than the optimal level that the user can process efficiently, the best option is to break things down into smaller 'chunks'. There are various guidelines on the amount of information (e.g. characters/words per line, lines per paragraph, etc.) but these can be language or content dependent and you have to adjust this for the audience.
When the type of content is very complex (e.g. complex charts or visualizations) you can also apply the same strategy to break the information down into simpler elements or provide additional content to support the explanation of the content.

So you should be able to see that in general complexity arises from combining smaller elements in ways that still maintain the logic and structure of the overall process/content. That way, even if you have to try and deal with something that is very complex, it still allows the designer and user a sensible way to manage it all.


java.net.Socket > InputStream > BufferedReader.read(char[]) blocks thread

Question: I'm trying to use BufferedReader.read(char[]) method instead of the easier, but less versatile BufferedReader.readLine() method for receiving an answer from a Server. BufferedReader is used in parallel with BufferedOutputStream and, in the code below, the read(char[]) method blocks everything, the last console output is "new buffer, waiting to read."
Client:
public class MessageSender extends Thread {
private String message;
MessageSender(String message) {
    this.message = message;
}

public void run() {
    try {
        Socket sk = new Socket("192.168.1.4", 3000);
        BufferedOutputStream bo = new BufferedOutputStream(sk.getOutputStream());
        bo.write(message.getBytes());
        bo.flush();

        char[] c = new char[100];

        BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
        StringBuffer sb = new StringBuffer();
        System.out.println("new buffer, waiting to read.");
        int ix = 0;

        while (ix != -1) {
            ix = br.read(c);
            sb.append(new String(c));
        }

        String message = sb.toString();

        System.out.println("reply: " + message);

        sk.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
Server:
public class MessageReceiver extends Thread {
    public void run() {
        try {
            ServerSocket ss = new ServerSocket(3000);
            System.out.println("server socket open");
            while (true) {
                Socket sk = ss.accept();
                System.out.println("new connection");
                BufferedReader br = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                String line = br.readLine();
                System.out.println("received line: " + line);
                BufferedOutputStream bo = new BufferedOutputStream(sk.getOutputStream());
                bo.write("ack".getBytes()); bo.flush(); //bo.close();
                sk.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Main:
public class Main {

    public static void main(String[] args) {
        MessageReceiver mr = new MessageReceiver();
        mr.start();
        while (true) {
            String msg = new Scanner(System.in).nextLine();
            MessageSender ms = new MessageSender(msg+"");
            ms.start();
        }
    }
}

Everything works fine as long as the BufferedReader.read is not called. But as the code is right now, the output doesn't seem to get sent to the server.
UPDATE
As answered by @JB Nizet, the problem lies in the server script that uses readLine() and waits for either EOL character or the connection end. Therefore, adding "\n" to the message sent from the client side solved the deadlock:
bo.write((message+"\n").getBytes());

Comment: `while (ix != -1)` the returned char is null i  think. try to rewrite:

`while( (ix = br.read() ) != null )`
Comment: Does it work with `readLine()`? If so, try to check if `InputStream.available() > 0` in your loop, so we don't indefinitely check for the next `char` in the stream (blocking a thread in the process).
Comment: @thekiwi5000, I wish I could downvote your comment, `int`s cannot be null. `Integer`s can, though.
Comment: @MeetTitan thaks, i'll keep this in mind.
Answer: When the server accepts a connection from the client, the first thing it does is:
String line = br.readLine();

So, it blocks until the client sends a complete line of text. The server only knows the line is complete if it reads an EOL character, or if the stream is closed by the client.
When the client starts, the first thing it does is
bo.write(message.getBytes());

And message is a line of text, without any EOL. Then the client does
ix = br.read(c);

so it waits for a response from the server, which is itself waiting for an EOL from the client.
You have implemented a networked deadlock.


Calling a function from a different class in Kotlin?

Question: I am trying to call a simple function in a separate class in Kotlin in Android:
public class TestOfAClass: AppCompatActivity()  {
      public fun ThisIsATest(thisTest: String) {
           print(thisTest)
    }
}

but in when I have:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            ThisIsATest("Hello World")
        }
    }
}

I get am Unresolved reference: ThisIsaTest
So how can I call a function from a different class?
Comment: "So how can I call a function from a different class?" -- your function is an instance function, and so you would need an instance of the other class first, then you call the function on that instance.
Comment: Seems that `ThisIsATest` is a class method, which you didn't specify in your question.
Comment: Are you really trying to call a method in another activity? Because that might be a much deeper understanding issue than just initializing an object on which you would call an instance method. Maybe you could elaborate on your thoughts - what you have and what you want to have.
Comment: You cannot directly invoke the method of a different activity. You need to use startActivityForResult, and more importantly you probably don't even need 2 Activities if that's what you need (unless you have an assignment at school that tells you to do this
Answer: The method you want to call is an instance method, the easiest answer is:
class MainActivity : AppCompatActivity() {

….
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            TestOfAClass().ThisIsATest("Hello World")
        }
    ))

the better answer is to rename your method to camel case:
     public fun thisIsATest(thisTest: String) {
           print(thisTest)
    }
}

That way you know its a method and not a class.

But if you are trying to communicate between two Activities, this is not how to do it. There are a few other options, one is using startActivityForResult:
https://developer.android.com/training/basics/intents/result
How to manage startActivityForResult on Android?
Comment: For sure. Sometimes though getting it working is what makes you realise its a mistake. Added a hint at that, thanks for the prompt @Michal
Comment: I think there is a much deeper question in the fact that the OP does not understand Android and wants to call a method of another activity.


Should I replace my mercury switch thermostat?

Question: We have an old mercury switch thermostat in our house, You know the type, gold ring, very common.
We are in new England on a gas/steam system. There is no central AC.
We have been told by more than one heating professional that there really aren't any decent alternatives. The problem is that the thermostat doesn't report the right temperature, so it basically functions as a switch. The other problem is that my wife hates it.
I think we are on a 2 rather than three wire system. The house was built in the late 1920's.
Does anyone have experience with alternative thermostats?
Comment: Why do the professionals say there aren't any good alternatives? There are countless other thermostats on the market now.
Comment: replacing mine like that for a moderately priced digital was the best thing I ever did. It seemed that for A/C, 60 degrees and 80 degrees were about 1 degree of rotation apart. :) Now I just need to get it recycled properly… It absolutely should not go into the trash.
Comment: see [Replace two-wire thermostat](http://diy.stackexchange.com/questions/6161/replace-two-wire-thermostat?rq=1)
Answer: Almost every thermostat on the market today is a better alternative than a mercury switch-type.
Even the cheapest digital thermostats have schedules, so that they can have different heating points during the morning, daytime, evening and overnight, and range from having weekend vs weekday to 7-day indepedent schedules. This allows you to save money by turning down the temperature while you're not home or sleeping.

On the more advanced side of things, there are internet-connected thermostats you can program/control from your PC/phone/etc, and ones that can self-learn based on manual adjustments and motion-sensing. There is a corresponding increase in price, and these typically do require a C-wire so since you only have two wires you'd have to pull a new wire for this.

To connect a basic digital thermostat to the 2-wires, the best thing is to follow the instructions that come with the thermostat. Typically you're going to connect the two wires between R (or Rh) and W.
Comment: Agree that the modern thermostats are a huge improvement, but consider: a bi-metallic strip and a glass bulb with two electrodes and a drop of mercury.  Functions for close to a century.  No firmware upgrades, no Blue Screen of Death, no re-booting...
Comment: I recently had the first mercury t stat failure I can remember at my house Built in 1930. Mine was probably a late 50' S early 60' S not original. There are modern looking ones out There and I could have gone with a programmable but went with the simple 9$ no batteries needed stat.
Answer: I agree with John (?) - simple, reliable, doesn't require batteries or power.  Indeed, if you have gas you can have normal heat during power outages.
If you are frustrated with the lack of temperature sensitivity, you might try messing with the bi - metallic strip and change its performance characteristics.
Answer: For 30 years we had an old round mercury thermostat. It worked great. Then we bought a new Trane furnace with a new digital honeywell stat like the one above. The new stat freezes. It's programed and constantly gets stuck on the previous setting and doesn't adjust when it's supposed to unless I press a button, any button, then it wakes up and almost like it says "oh, sorry, I was sleeping" and corrects it's self. Im tempted to reinstall the
mercury stat. And this isn't the 1st digital stat I've had problems with. It seems the digital stats I've encountered have a short lifespan, like smart phones. Perhaps they're designed not to last more than 2-3 years.
Comment: Congradulations, you are the one millionth customer to complain about a honeywell thermostat. Don't bother asking, the HVAC guy checked and couldn't find any problem.
Answer: I have a mercury thermostat and I have been told by more than one heating and cooling guy that it's the best.  It's simple and doesn't freeze up. Ours isn't the most accurate but it does the job.
Answer: Mercury thermostats are clearly the best for many reasons not the least of which is they will last forever and never need a battery.
They also have fully adjustable heat anticipators which NONE of the digital or Nest
thermostats have.
.......
Digital and Nest thermostats have dozens of components to fail and die without battery power.
So they simply turn what WAS a reliable furnace
into a Rube Goldberg machine that breaks down every heating season.
Comment: I can see that point. For the record I have not replaced the thermostat, mostly because I ask every plumber I know and they say don't do it, maybe for the reasons your state.
Answer: Interesting post. I have mercury switch thermostats. Had the first problem with it ever. It was at the beginning of the heating season. I had set the themostat all the way down for the summer. But the mercury got "stuck" at the end of the glass tube and I had an apparent no heat situation. I took the cover off the thermostat, saw the problem which was easily fixed by turning the thermostat all the way up to the highest heat setting. I watched the mercury roll out of the tip of the tube where it had been "stuck" and turn on the heat. After that it worked fine as it has for years. Requires no internet or battery.


How to get the exact return value of a Pig script and use it for further processing?

Question: I know that  Pig returns different code upon completion for these scenarios:
Return code 0: All jobs succeeded
Return code 1: Used for retrievable errors
Return code 2: All jobs have failed
Return code 3: Some jobs have failed
In my code, I want to take an appropriate action, based on the success of a MapReduce job. How to go about doing it?
Pig errors are saved in logs, however, what mechanism should I use to kknow about successfully executed pig scripts ?
Answer: If you are running your pig scripts using shell scripts, you can check the status of the last executed script and if that returns 0 then only you can proceed to second step, If the first step fails it can show an error message.
<code>./pig_script.sh

if [ $? -eq 0 ]; then
    echo "Succesfully finished"
else
    echo "Failed"
fi
</code>
If you are using any frame works or scheduling tools like Oozie or Autosys there are different ways of dealing it.
Comment: If you want to build a pipeline of pig jobs, I would advocate the use of Oozie (or a similar tool).


Rendering not being called after api request

Question: I am hoping someone can help me, I have been working on a side project for over a month and I can't figure this out.  Here is the code:
getNews() {
    var news_items = new Array();
    AsyncStorage.setItem('time', JSON.stringify({'last_cache': moment()}));
    var url = "http://api.podio.com/"
    fetch(url)
    .then(response => response.text())
    .then((responseText) => {
      const doc = new DOMParser().parseFromString(responseText, "text/xml");
      var items = doc.getElementsByTagName('item');
      for (var i = 0; i < items.length; i++) {
        var appType = new Object();
        appType.title = items[i].childNodes[1].childNodes[0].data;
        appType.link = items[i].childNodes[3].childNodes[0].data;
        news_items.push(appType);
      }
      var ds = this.state.dataSource.cloneWithRows(news_items);
      console.log("ds: ", ds)
      AsyncStorage.setItem('news_items', JSON.stringify(news_items));
      this.setState({
        'news': ds,
        'loaded': true
      })
      console.log("news: ", this.state.news)
    })
    .catch((error) => {
      console.log('Error fetching the feed: ', error);
    });
  }
}

render() {
  console.log("rendering....")
  console.log("loaded? ", this.state.loaded)
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <View style={styles.header_item}>
          <Text style={styles.header_text}>{this.state.title}</Text>
        </View>
        <View style={styles.header_item}>
          {  !this.state.loaded &&
            <ActivityIndicator />
          }
        </View>
      </View>
      <View style={styles.body}>
        <ScrollView ref="scrollView">
          {
            this.state.loaded && <ListView dataSource={this.state.dataSource} renderRow={this.renderNews} ></ListView>
          }
        </ScrollView>
      </View>
    </View>
  );
}

componentWillMount() {
  this.getNews();
}

renderNews() {
  console.log("loading....")
  return (
    <TouchableHighlight onPress={this.viewPage(news.link)} underlayColor={"#E8E8E8"} style={styles.button}>
    <View style={styles.news_item}>
    <Text style={styles.news_item_text}>{news.title}</Text>
      </View>
    </TouchableHighlight>
  );
}

As you can see I have quite a few console logs in the code.  Here is what it is telling me:
rendering....
loaded?  false
ds:  ListViewDataSource {_dataBlob: Object, _dirtyRows: Array[1],   _dirtySections: Array[1], _cachedRowCount: 142, rowIdentities: Array[1]…}
rendering....
loaded?  true
news:  ListViewDataSource {_dataBlob: Object, _dirtyRows: Array[1], _dirtySections: Array[1], _cachedRowCount: 142, rowIdentities: Array[1]…}

Here is the problem.  On the first render it displays "rendering....", but loaded is false, it then sets the ds variable here:
var ds = this.state.dataSource.cloneWithRows(news_items);
console.log("ds: ", ds)
The next time it renders it again displays "rendering...." and now loaded is true.  However, this line in render is never called:
this.state.loaded && <ListView dataSource={this.state.dataSource} renderRow={this.renderNews} ></ListView>

This line never calls "this.renderNews" and displays its' data.
Additionally, I don't see the console.log for "loading...."
One thing to mention is that this.renderNews is set in the constructor.  In other words: this.renderNews = this.renderNews.bind(this)(edited)
Answer: render is failed after mounting , means you are calling setState wrongly , let the call to be as following:
  this.setState({
    'news': ds || [],
    'loaded': true
  })

not
  this.setState({
    'news': ds,
    'loaded': true
  })

by that , you avoid this.state.news to not be null ,( assuming that news is an array.
Answer: Don't use conditional rendering on ListView. Always render it but initially the datasource is empty. My understanding is that the first rendering builds the component tree. Then subsequent renderings don't actually rebuild the tree, they simply update data on existing components. It's ok to set visible props on components and re-rendering will show/hide them properly.
BTW, you don't need the ScrollView. ListView already has a scroll bar. Nested scrollviews are bad on mobile devices.


Trying to sand class object between intents by parcelable

Question: I have a bit trouble implementing Parcelable. Here's how I did it:
public class Player implements Parcelable{
    String name;
    int score;
    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(score);
    }

    public Player(Parcel source){
        score = source.readInt();
        name = source.readString();
    }
}

public class MyCreator implements Parcelable.Creator<Player> {

    @Override
    public Player createFromParcel(Parcel source) {
        return new Player(source);
    }

    @Override
    public Player[] newArray(int size) {
        return new Player[size];
    }

}

This was the whole code implementing Parcelable. Now I'm trying to create a new class object:
Player newPlayer = new Player(null);
newPlayer.name = text;
newPlayer.score = 0;
playersParceledData.add(newPlayer);
zacniIgro.putParcelableArrayListExtra("parceledData", playersParceledData);

This is the line that is bothering me:
Player newPlayer = new Player(null);

Is the fact that I just insrted "null" okay? Or do I have to  insert something else between those ()? I was following this example and this isn't explained in it. It says that a new object should be created like this:
Player newPlayer = new Player();

But I am not allowed to do this since I made a constructor.
Answer: Create an additional constructor for use cases you're not using Parcel to construct your object, for example
public class Player implements Parcelable{
    /* ... */

    public Player(Parcel source){
        /* ... */
    }

    public Player(int score, String name){
        this.score = score;
        this.name = name;
    }
}

Then you can construct objects both from Parcel and using an int and an String:
final Player aPlayer = new Player(10000, "SomeRandomPlayerName");

Also, you read the int and the String in inverse order as you write them.
Comment: Thanks a lot! Could you just additionally explains your last sentence? What do you mean by reading them in reverse order?
Comment: It means when you write the parcel you're doing it in `String, int` order. When you read it, you're reading in `int, String` order.
Comment: This is related to your question but your code in general, you write to parcel using `dest.writeString(name)` followed by `dest.writeInt(score)`, while you read from parcel using `source.readInt()` followed by `source.readString()`. So your read it in a different order than you write it.


Joint Distribution of sum of Bernoulli stochastic processes

Question: Let $X_1, X_2, \ldots$ be independent and identically distributed (iid) Bernoulli random variables. For each $k,$
$$P\{X=k\} =  p, \text{       } 0 <p<1.$$
Set $N_0 = 0$ and $t=1,2, \ldots,$ set $$N=\sum_{k=1}^{t} X_k.$$
Find the joint distribution of $$P\{N_{t_1} = i_1, \ldots, N_{t_d} =i_d \}$$
Comment: Repost of https://math.stackexchange.com/q/3733385/321264.
Comment: @StubbornAtom. That one contained errors and it was closed for that reason. The one here is the updated version
Comment: You are supposed to edit the previous post to add context. It will then be reopened.
Comment: I'm sorry for that
Answer: Assuming $t_1<t_2<\ldots<t_d$, one can write $P(N_{t_1}=i_1,\ldots,N_{t_d}=i_d)=P(N_{t_1}=i_1,N_{t_2}-N_{t_1}=i_2-i_1,\ldots)$.
Each RV of the form $N_{t_k}-N_{t_{k-1}}$ is $Bin(t_k-t_{k-1},p)$ independent of the others.
To conclude, the probability is $\prod {t_k-t_{k-1} \choose i_k-i_{k-1}}p^{i_k-i_{k-1}}(1-p)^{t_k-t_{k-1}-(i_k-i_{k-1})}=p^{i_d}(1-p)^{t_d-i_d}\prod {t_k-t_{k-1} \choose i_k-i_{k-1}}$
Comment: Is it possible to also find $P\{ N_{t_1}-i_1, \ldots, N_{t_d} \}$?
Comment: I don't understand this notation.
Comment: I still don't follow. The last expression is exactly what is calculated in my answer.


Replacing Interlocking Ceiling Tiles From The "Wrong" Direction

Question: A section of ceiling above my front door has been damaged due to a leaky roof, so I need to replace around half of the 7' x 9'-ish entry area. The existing tiles are stapled to furring. However, based on the way the tiles intersect with each other, I can tell they were installed starting at the front door, and then inward into the house. I can't staple new tiles in because the lip where the staple would go needs to be inserted into the existing tile. The tiles in question are Armstrong 12" x 12" ceiling tiles:
My first thought was to install the new tiles the "wrong" way, and use adhesive instead of staples. However, the adhesive I bought (Henry 237 AcoustiGum) specifically says not to use on wood surfaces. After googling a bit, I can't find any mention of someone using adhesive on wood furring. Note that I haven't opened the AcoustiGum, so if another adhesive is required, I'm fine with returning it for something else.
Is there a way for me to avoid replacing the entire room? (One the one hand, I'd like to save myself unnecessary effort, as well as avoid replacing perfectly good tiles. However, I also don't want to do a shoddy job.)
I'm not particularly knowledgeable about home repair, so any input would be appreciated. If I haven't adequately described the problem, please let me know, and I'll try to be more clear.
Answer: Checking the Armstrong web site from the link you left they state that these particular tiles should NOT be stapled (for whatever reasons) and the warranty will be voided if done so.
There is also a question asked in their FAQ's asking this same problem :"can tiles be stapled?"  The rep answers with a curt yes and continues to reiterate the warranty void issue. That's all that's said.
I would try to remove the staples from the tiles that border the damaged area. Since that's what is preventing the new ones from being installed. Once the first new tiles are installed the remaining new ones will go in as per manufacturer's instruction.
As for method of securing them; the company states glue (like the Henry's you purchased) or their "ceiling track" (which doesn't work with your existing tiles). The "Accusto-Gum" adhesive is recommended for plaster and drywall surfaces. You may want to consider using an adhesive with more holding power. Any construction adhesive should hold. Staples or Henry's adhesive both are not advised for your repair. The staples have held for how long? Use both for increased holding power.
Comment: I should probably add that the area that needs to be replaced is basically the front half of the ceiling (the half closest to the outer wall). So it's not a hole, it's three walls and a row of good tiles.
Comment: The tiles have been there at least since I bought the house 14 years ago. I have no idea how long they were there before that.
Comment: I understood the tile layout SloppyNick. What I;m saying is since the company is sending contradictory answers I believe you will have to go by instinct. Do you feel confident with my suggestion to use construction adhesive and staples? This is basically the last resort for keeping tile in place securely. Let me know what you think.
Comment: Gotcha. Yeah, I feel confident enough to go with the construction adhesive and staples. Thanks for your help.


Zend Form file input set required false is not working

Question: I'm having the following code to render a zend form file input
<code>$pd_photo = new Zend_Form_Element_File('photo');
$pd_photo->setDestination(APPLICATION_PATH . '/../uploads');
$pd_photo->setRequired(false);
$pd_photo->setAllowEmpty(true);
$pd_photo->addValidator('Count', false, 1);
$pd_photo->addValidator('Size', false, 2097156672);
$pd_photo->addValidator('Extension', false, 'jpg,jpeg,png,gif,bmp');

$pd_photo->getValidator('Count')
         ->setMessage('You can upload only one file');
$pd_photo->getValidator('Size')
         ->setMessage('Your file size cannot upload file size limit of 1 MB');
$pd_photo->getValidator('Extension')
         ->setMessage('Invalid file extension, only valid image extensions are
                      (jpg, jpeg, png, gif, bmp) allowed.');
</code>
All is working fine but when I leave the file filed empty then, it does not work. The zend form validator returns an empty error string message.
What wrong am doing??
Comment: You form should normally work fine. Can you please show us how you validate your form? Also, providing the HTML code generated by your form will be helpful
Answer: This is my first answer, this might be right because,
I also once had the similar problem, I saw that you have used both
<code>$pd_photo->setRequired(false);
$pd_photo->setAllowEmpty(true);
</code>
In this case you should also define for <code>'NotEmpty' => 'false'</code>
Try defining the above property for file element this should solve your problem, mine was resolved by this.


Is there any way to increase the text size?

Question: Using a 55" TV, the size of most UI text is less than 1cm tall.  This is very hard to read sitting 6-7 feet away.
I looked through the options, but I didn't find any obvious way to increase the size of the HUD or text.  Is there any way to do this?
Comment: Agreed!  And according to http://www.rtings.com/tv/reviews/by-size/size-to-distance-relationship the optimal distance for 1080p viewing for that size TV is 8 feet away!  (At least it's 5.2ft if you're using a PS4 Pro with 4k viewing, but that font is still REALLY small)
Comment: Bigger text please!
Answer: In the Final Fantasy Update 1.09, the font size has been increased

Here's everything Square Enix says was added with update 1.09 today:
...
Enlarged font sizes for the subtitles and various menu screens
...

It does not mention exactly how much of an increase, but I am sure it allows a better readability of the text

I have read many reports and complaints on this same issue, however there is currently no way to adjust the font-size in Final Fantasy XV.
In the meantime, a user on Final Fantasy XV Forums suggests

Until they patch that, try using this: In the Settings menu of the PS4, go to Accessibility and turn on Zoom in. When you want to read the small text, press PS button+Square.

In recent discussion, the director states they are looking at tweaking the readability in upcoming updates
NA Square Enix

... We're also examining readability tweaks - increasing font size - for certain languages ...


Instability on Ubuntu 11.10 for wifi Intel Board 4965

Question: I'm a ubuntu user for a long time and always preferred to use LTS versions. But I decided to give a chance to 11.10 while 12.04 don't show up. But the wifi on 11.10 is not very stable which keeps me back on my 10.04 installation.
   Here is the deal i have the following card (lspci):
0c:00.0 Network controller: Intel Corporation PRO/Wireless 4965 AG or AGN [Kedron] Network Connection (rev 61)

I use my laptop (mainly) in three places. At home I use WPA and it works just fine. At work and the University they use WPA2 and it stays very unstable. It connects successfully but after a few minutes it drops. Only a new reconnection would bring it back online.
Tks
Answer: This (or a similar related issue to yours) was reported on UbuntuForums.
The recommendation was to try the following workaround - this disables wireless-N support:
gksu gedit /etc/modprobe.d/options.conf

Copy and paste the following text:
options iwl4965 11n_disable=1

Save and reboot.
Comment: This tweak makes wireless usable, however, only barely. The output of `iwconfig` shows lots of dropped packets under `Invalid misc:`. Are there other options to try?
Comment: not sure - but a small bounty on this question will probably elicit another answer.  Remember, wireless issues are kernel specific - so if you are using 12.04 then this answer probably doesnt apply to you - the OP is using 11.10.  Thus a new Q would be appropriate.


AMD ATi Radeon HD 6870 drivers not working

Question: Need some help with this. I've searched for a few hours and found no answer that worked for me.
When I try to install my drivers I get

One or more tools required for installation cannot be found on the system.
  Install the required tools before installing the fglrx driver. Optionally, run the installer with --force option to install without the tools. Forcing install will disable AMD hardware accelleration and may make your system unstable.
  Not recommended.
  See /usr/share/ati/fglrx-install.log for more details.

So I checked that log and it gave me

Supported adapter detected.
  Check if system has the tools required for installation.
  fglrx installation requires that the system have kernel headers.  /lib/modules/3.8.0-6-generic/build/include/linux/version.h cannot be found on this system.
  One or more tools required for installation cannot be found on the system. Install the required tools before installing the fglrx driver.
  Optionally, run the installer with --force option to install without the tools.
  Forcing install will disable AMD hardware acceleration and may make your system unstable. Not recommended.
Comment: Did you install the driver from AMDs site or from "Additional drivers" in Ubuntu? Also: which Ubuntu version are you running?
Comment: Using the proprietary ones from the AMD site, running Ubuntu 13.04. Thanks for the quick response. :)
Comment: that's not good. You should install drivers through ubuntu packages. Don't worry we'll fix it.
Comment: How do I do that?
Comment: Wait I think I've found it. Thanks for telling me and your quick responce! :)
Answer: Ok first we have to remove all your previous installations.
In the terminal run:
sudo sh /usr/share/ati/fglrx-uninstall.sh
sudo apt-get remove --purge fglrx fglrx_* fglrx-amdcccle* fglrx-dev*

then
sudo add-apt-repository ppa:xorg-edgers/ppa
sudo apt-get update
sudo apt-get install linux-headers-generic

now go to dash, open software sources, go to additional drivers tab. You should see the catalyst 13.2 beta 3 driver, activate it.
when you're done, in the term run:
sudo amdconfig --initial -f

reboot.
Comment: I have tried the steps and the additional drivers tab is still empty.
Answer: Download the driver from here : http://support.amd.com/us/kbarticles/Pages/AMDCatalyst13-3LINBetaDriver.aspx
To install refer to the second part of the answer on /questions/18747/.
I don't use fglrx drivers because they're not the same ones issued by AMD, and given this is all proprietary, then there's no point not going to the source instead of Xorg.


Concatenate an each loop inside another

Question: I want to to concatenate the results of a jquery each loop inside of another but am not getting the results I expect.
$.each(data, function () {
            counter++;
            var i = 0;
            var singlebar;
            var that = this;
            tableRow = '
' +
            '' + this.foo + '	' + //<---- should terminate this instead
            $.each(this.bar, function(){
                singlebar = '' + that.bar[i].baz + '	';
                tableRow += singlebar;
                console.log(singlebar); // outputs "the correct data	"
            });
            '
';

            $(tableRow).appendTo('#mainTable > tbody');
});

The portion inside the nested each does not get added to the string that is returned.
I can console.log(singlebar) and get the expected results in the console but I cannot concatenate those results inside the primary each loop.
I have also tried:
        $.each(this.bar, function(){
            tableRow += '' + that.bar[i].baz + '	';
        });

Which also does not add the desired content.
How do I iterate over this nested data and add it in the midst of the table that the primary each statement is building?

The solution (thanks to sushanth reddy)
I should not have continued trying to concatenate in such a way. I should have added each section of string to tableRow as I created it, not all at once. Something more like:
            tableRow = '
' +
            '' + this.foo + '	';

            $.each(this.bar, function(){
                singlebar = '' + that.bar[i].baz + '	';
                tableRow += singlebar;
            });

            tableRow += '
';

Comment: `that.bar[i].baz` ? what's the "desired content"? you should first do some `console.log` debugging
Comment: Can you post a real world example at jsfiddle of what you're trying to do? I don't get `this.bar` or `this.foo` it just doesn't make sense in this context. Where are those defined?
Comment: You have `tableRow + singlebar;` instead of `tableRow += singlebar;`
Comment: @Karoly Horvath - I do `console.log` it. I mentioned that above in my text but left it out of the code example. I'll add it in for clarity.
Comment: @elclanrs - the `this` object contains the correct data. I can console log everything and get what I expect.
Answer: You are returning at the wrong point.. Try this
var counter = 0;
var tableRow = '';
$.each(data, function () {
    counter++;
    var i = 0;
    var singlebar;
    var that = this;
    tableRow = '
' +
    '' + this.foo + '	' +
    $.each(this.bar, function(){
        singlebar = '' + that.bar[i].baz + '	';
        tableRow += singlebar;
    });
    tableRow +=  '
';

    $(tableRow).appendTo('#mainTable  tbody');
});

Check this example FIDDLE
Also make sure you have the table and tbody tags before you append..
Comment: Shoot, sorry. I typed that code in incorrectly. I am actually appending the results as I get through each iteration of the main loop, not returning. I've changed my example... sorry for that.
Comment: I have updated the code.. check the code..  The child selector > was messing it up
Comment: Bingo! Your fiddle helped. The problem was that I was trying to do too much inside the concatenation. By breaking each bit into sections and the `+=` to `tableRow` I was able to get it to work. Thanks so much, sushanth.
Answer: Try this
    $.each(data, function () {
                counter++;
                var i = 0;
                var singlebar;
                var that = this;
                tableRow = '
' +
                '' + this.foo + '	';
                $.each(this.bar, function(){
                    singlebar = '' + that.bar[i].baz + '	';
                    tableRow = tableRow + singlebar;
                });
                tableRow = tableRow + '
';

    });
return tableRow;

Answer: $.each(data, function () {
            counter++;
            var i = 0;
            var singlebar;
            var that = this;
            var tableRow = '
' +
            '' + this.foo + '	';
            $.each(this.bar, function(){
                singlebar = '' + that.bar[i].baz + '	';
                tableRow = tableRow + singlebar;
            });
            tableRow = tableRow + '
';

            return tableRow;
});

Comment: uncommented code-only answers are not encouraged, a simple "this should work:" can make an answer look much more professional (;

Concatenate an each loop inside another


Accidentally removed default gnome panel applications

Question: I accidentally removed the default Gnome panel menu on the top right (containing clock, mail, volume and shutdown options). After, I tried to get the menu back by adding some apps but that did not solve the problem. I then stumbled upon a reset via the terminal, however, the menu remains missing and the apps I added are still there.
sudo dconf reset -f /org/gnome/gnome-panel/
killall gnome-panel

and
gconftool-2 --recursive-unset /apps/panel
pkill gnome-panel

System: Ubuntu 12.04 with Gnome classic.
Any help is greatly appreciated!
Many thanks in advance.
Answer: I did this recently as well. Hold Super+Alt+Right Click to add to panel then search for 'Indicator applet complete'. Add that to the panel and everything should be back to normal. The Super is typically the one with  the Windows logo on it on most PCs (see What are the meta, super, and hyper keys?).
Answer: Hold Alt + Right-click an empty area of your panel (in Gnome 3), and choose "Add to Panel…", then scroll down till you find "Menu Bar", then drag and drop it on desired place or click Add.


Why there is an infinite recursion when function parameter is not defined as const reference?

Question: I am having troubles understanding what might be causing the infinite recursion. There are two points that play a role in my problem

Depending on the place of definition of the global functions
Whether we mark the parameter as const-ref of the second function (either global or class member)

Here is the code
#include <iostream>
#include <optional>
#include <vector>

using dataType = int;
using dataTypeReturn = float;
//#define ENABLE_AFTER  // For global fncs causes inf recursion
#define CONST_REF_FUNCTION  // Causes expected behavior when !ENABLED_AFTER
#define CONST_REF_CLASS     // Causes expected behavior

#ifndef ENABLE_AFTER
#ifdef CONST_REF_FUNCTION
// Causes expected behavior
std::vector<dataTypeReturn> foo(const dataType& bar){
#else
std::vector<dataTypeReturn> foo(dataType& bar){
#endif
    std::cout << "foo(const dataType& bar)" << std::endl;
    return std::vector<dataTypeReturn>(10, dataTypeReturn{});
}
#endif

std::vector<dataTypeReturn> foo(const std::optional<dataType>& bar){
    std::cout << "foo(const std::optional<dataType>& bar)" << std::endl;
    if(bar == std::nullopt)
        return {};
    return foo(*bar);
}

#ifdef ENABLE_AFTER
#ifdef CONST_REF_FUNCTION
// Causes infinite recursion
std::vector<dataTypeReturn> foo(const dataType& bar){
#else
std::vector<dataTypeReturn> foo(dataType& bar){
#endif
std::vector<dataTypeReturn> foo(const dataType& bar){
    std::cout << "foo(const dataType& bar)" << std::endl;
    return std::vector<dataTypeReturn>(10, dataTypeReturn{});
}
#endif

class Wrapper{
    public:
        std::vector<dataTypeReturn> foo(const std::optional<dataType>& bar){
            std::cout << "foo(const std::optional<dataType>& bar)" << std::endl;
            if(bar == std::nullopt)
                return {};
            return foo(*bar);
        }
    private:
#ifdef CONST_REF_CLASS
        // Causes expected behavior
        std::vector<dataTypeReturn> foo(const dataType& bar){
#else
        // Causes infinite recursion
        std::vector<dataTypeReturn> foo(dataType& bar){
#endif
            std::cout << "foo(const dataType& bar)" << std::endl;
            return std::vector<dataTypeReturn>(10, dataTypeReturn{});
        }
};

int main(int argc, char** argv){
    std::optional<dataType> myoptional(dataType{});
    foo(myoptional);

    Wrapper mywrapper;
    mywrapper.foo(myoptional);
    return 0;
}

In the case of the global functions, why depending on where I define the function the recursion happens or not? What would be the compile-process to decide what function to call?
In both cases, marking the parameter as const reference for the function that receives the underlying type of the optional does not incurr in the recursion, why? I was looking at the constructor implementations of std::optional and the only that could match I think is template < class U = value_type > constexpr optional( U&& value ); but I don't see how *bar ends up as a rvalue-ref.
Answer: You are dereferencing a const optional<datatype>, you are using const value_type & optional::operator*() const, not value_type & optional::operator*().
A free function definition only looks at names declared preceding it. This is one of the reasons for having declarations of functions in headers. In the case of a member function, definitions of members see all the declarations of members.
foo(dataType& bar) is not a viable overload. If you haven't declared foo(const dataType& bar) before the definition of foo(const optional<dataType>& bar), the only viable overload is foo(const optional<dataType>& bar), which constructs a temporary optional. It deduces U as const dataType &, and const dataType & && is collapsed to const dataType &
Comment: Got it, for free functions is all clear. The only thing that I didn't understand is, why in the member functions I have to declare `foo(const dataType& bar)` and not `foo(dataType& bar)`. The former has the expected behavior and the latter incurs infinite recursion.
Comment: in both `foo(*bar)`, you are using `const value_type & optional::operator*() const`, not `value_type & optional::operator*()`


How to fire JavaScript pixel on click

Question: I am trying to get a Javascript pixel

to fire after the click of a submit button similar to what you can find on this page. (I know this might require building a simple "thank you" page, which is okay, but the pixel can't fire onClick.
Additionally, I would need the text from the different fields passed in to the v1, v2, etc. variables to be captured by the pixel.

First Name *

<input type="text" name="first-name" value="" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" size="40" />

I am a bit new to this and am not a developer, but understand how it works conceptually so any help is greatly appreciated!
Comment: @user2288602 That still makes no sense...
Comment: @user2288602 What is a "JavaScript pixel"? This phrase is ambiguous, and needs further explanation.
Comment: `Oops! Google Chrome could not find pixel.tag.com`
Comment: JS pixel = javascript
Comment: What doesn't make sense?
Comment: @elevine JS "pixel" is a misnomer, but one which marketing departments come by honestly.  These used to be 1px x 1px .gif requests made to analytics solutions, which would use the image as an end-point, and collect the values of predefined query-parameters, to do stat-tracking (ie: `tag.com/img.gif?prod_id=1234&qty=2&profit=32.45`). These are CORS workarounds circa 1998, using GET requests for `` or `
Comment: @AndersonGreen to further extrapolate: this process can still be very primitive (``), or can be quite complex, such as Google Analytics, whose "snippet" is an inline script, which dynamically builds a script tag, whose `src` points at a Google-hosted JS application, which captures all sorts of client-machine information, business-defined metrics, captures values in cookies for persistance, and intelligently fires multiple .gif requests (without appending to DOM), based on URI-length. They are now also using POST requests, where CORS is supported in XHR2.
Answer: From working with pixels before, here's what I'd recommend as a broad solution. Start off with a JavaScript String variable that's collecting the appropriate information to go along with ?mt_id=123456789&mt_adid=123456&v1=&v2=&v3=&s1=&s2=&s3=. If you already have that built, great.

If it would be helpful to see another example of someone working through the same problem. Try reading through this forum post.
Comment: Sorry, still not quite following. Why can't I set the v1=&v2=&v3=&s1=&s2=&s3= variables equal to the variable name of what is collected in the form? i.e `v1="first-name"&v2="last-name"&v3=&s1=&s2=&s3`
Comment: You can. As you gather the variables, append them to the string. For example, when you set var firstName="John Doe" make sure to append it to the query string. So.. something like queryString = queryString + "&v1=" + firstName
Answer: The trick here isn't in the "tracking pixel", but rather, is in populating the values of the parameters.
The issue you're going to have here is that you're now going to have to build a string, which points to the .js file, and then build the parameters and values into strings, concatenate them all, build a script tag and point the url at your built values, so an ugly (by JS-purist standards) solution might look like this:
<form id="ContactForm">
    <input name="first-name">
    <input name="last-name">
    <button id="my-button" type="submit">sign up</button>
</form>

When the button is clicked, the values will be collected from the form, they'll be added to the URL, and the script will be added to the page.
Here's the next problem:
If this is a  and you're capturing a click which takes you to the next page, by default, then you have to cancel the form-submission, otherwise, the request for the JS file is going to be ignored (why load new stuff when you told the browser you want to go to the next page?).
So then you need to modify the button.onclick to be something like:
button.onclick = function (e) {
    // IE < 9 supports "window.event", instead of an event-object as a parameter
    e = e || window.event;

    if (e.preventDefault) {
        e.preventDefault();
        e.stopPropagation();
    } else {
        // IE < 9
        e.cancelBubble = true;
        e.returnValue  = false;
    }

    /*  DO ALL OF YOUR DATA-COLLECTION AND STRING-BUILDING HERE
        ie: most of the first version of this function (all before `script.src =...`)
     */

    // after the script loads, fire contact.submit
    script.onload = contact.submit;
    // if the script errors out (404/etc) fire contact.submit
    script.onerror = contact.submit;
    // GhettoIE fix, for when scripts don't support "onload"
    script.onreadystatechange = function () {
        if (script.readyState === 4) { contact.submit(); }
    };

    /* SET THE SCRIPT URL HERE */
    script.src = full_url;
    parent.appendChild(script);
};

Now when you click the button, it will prevent the form from submitting (taking you to the next page) until you collect all of the form values, stuff them into the URL for the script, putting the script on the page, and waiting for the server to get the request and respond.
This is done in a very, very ugly cross-browser (IE6+/Safari3+) compatible format.
If you've got a decent JS guy there, get him to do better than this, or I'll cry...
If you need to collect the data on the next page (say you need to calculate your actual profit on the sale, after the server processes payment), you're better off doing this in the server's language:
// php
"";

Hope that helps.
Comment: Thanks for the info! I feel like this is getting hairier than necessary. Why can't I just take the variables from the form, which I pulled from inspecting the page elements, and pass those into the pixel like so...`v1=&v2=&v3=&s1=&s2=&s3=` variables equal to the variable name of what is collected in the form? i.e `v1="first-name"&v2="last-name"&v3=&s1=&s2=&s3`
Comment: @user2288602 That's exactly what my code does. And you can't do it while leaving the `
Comment: @user2288602 HTML and JavaScript are two different languages, and one won't understand the other...  ...so if your HTML looks like: `` that's EXACTLY what you'll see in your report. If you write `v1=window.MyForm["first-name"]`, then the server that gets the response will see `$v1 = "window.MyForm[\"first-name\"]";` as an exact value. Because HTML doesn't run JavaScript...  So you have to wait for the button to be clicked, collect the values from the form, build the string like `"//www...?" + "v1=" + val_1 + "..."` and buid it yourself.
Comment: @user2288602 It gets extra-hairy because you want to fire a call when you're submitting data, where that submission causes the next page to load. When you ask the next page to load, it ignores ALL unfinished downloads and moves to the next page. So you have to stop the form, send the request, wait for it to come back, and then submit the form. If it wasn't a form, and you wanted to know how many people clicked "play", then the answer is easier. And like I said, for actual JS-devs, there are cleaner ways of doing this. My answer is just a quick'n'dirty library-free solution that will work.
Comment: PS: this has been my day-job for the past ~2 years. Custom-tracking for PPC/Analytics has been a very big deal at my company. I've even written code-recommendations/reviews for the product managers at Adobe, regarding their tracking-programs for PPC/Analytics. Fun times.
Comment: Thanks for all the info, and I think I'm starting to wrap my head around it a bit more. Assuming I can fire the pixel on button click instead of page load, how much easier would this be?
Comment: @user2288602 That depends on what the button *does* when it's clicked on. If the button submits the form, then it's all of the work seen above. If you have a "thank-you"/receipt page that loads after the current page, and you have a programmer who did the work for putting in the forms in the first place, then putting the pixel on the "thank-you" page, the way you have it, originally, but with all of the values filled in by the programmer (with values that would be going in the database, before loading the next page) would be more straightforward.  AND would be better for validation purposes.
Comment: @user2288602 the reason I say it would be better for validation purposes is: if you add it to the thank-you page, and the thank-you page ONLY shows up if the form was filled out properly, and the data was properly added to your database, then sending the affiliate data (which I'm assuming you pay for) on a successful booking/sign-up/etc would be the only time it fired.  Firing "onclick" means that first you have to make sure that the form is valid (so that you're sure it will be successful), otherwise, you might be paying for unsuccessful attempts. This is where being technical is important.

How to fire JavaScript pixel on click


Apex Batch class for the array for records from Inbound REST Service

Question: I have to upsert around 80 K records on daily nightly batch. I was thinking of using the REST service to get the records in an array, and create a batch apex to upsert them in Salesforce. I will not be getting the CSV and is out of question.
Will I able to iterate the record of array in batch apex start method to process them in batch?
Is this right approach?
Is there a better approach for getting the large amount of records and process them in bulk?
Comment: Please show us what you have tried so far. Please edit your Q.
Answer: The REST API upserts records to the database.  You cannot use it to pass data to a batch apex class.  You can use the REST API to save data and then later have a batch class perform additional operations on that data but why bother if you can just have that logic performed as part of your upsert.
Comment: Thanks Matt, for the response. I understand that we can use the REST API to upsert records. I want to upsert in bulk mode. How do I achieve that?  Any thoughts?
Comment: The Bulk API can be used to upsert large batches of data.  https://developer.salesforce.com/page/Loading_Large_Data_Sets_with_the_Force.com_Bulk_API


Is tangent vector on so(3) a matrix?

Question: I have read that the tangent vectors on manifolds are differential operators, looking at a particular example, the tangent space to $SO(3)$, ($SO(3)$ is the group of rotations in $\mathbb{R}^3$, which is a Lie group),  on the identity matrix, is the set of antisymmetrical matrices, and is called the Lie algebra $so(3)$. If $A\in so(3)$ we can talk about a curve on $SO(3)$ given by:
$$
\alpha (s)= e^{sA}, \quad \alpha(0) = e^{0} = \mathbb{I}, \quad \frac{d \alpha}{ds}\Big|_{s=0} = Ae^{sA}\Big|_{s=0} = A.
$$
Therefore in this case the matrix $A$ is a tangent vector right?, my conclusion is that differential operators are linear transformations, so they have an associated matrix, the matrix A would be that associated matrix, is that right?, if isn't, how can I see the tangent vector explicitly as a differential operator in this particular case?. If having any other examples on this would be great. Thanks in advance.
Answer: Differential operators are linear transformations, yes, but they're linear maps $C^{\infty}(M)\to\Bbb{R}$, the domain is an infinite-dimensional vector space. They don't have a matrix-representation (which is only for maps between finite-dimensional spaces, after choosing bases on the domain and target). The point is that if you have a submanifold $S$ of a vector space $V$ (in your case $S=\text{SO}(3)$ and $V=M_{3\times 3}(\Bbb{R})$), then there is a standard linear injection $T_pS\hookrightarrow V$, so we can identify $T_pS$ with its image under this linear injection.
In the case of $S=\text{SO}(3)$ and $V=M_{3\times 3}(\Bbb{R})$, if you think of $S$ as a manifold, then the tangent space at the identity $T_IS$ is an abstractly-defined vector space, which set-theoretically is very complicated. But, after injecting it into $V$, it is just $\mathfrak{so}(3)$, the space of skew-symmetric matrices $3\times 3$ real matrices, and this is where your $A$ lives.

I have several answers regarding similar issues:

Why is a vector field on the sphere equivalent to $f:S^n\to\Bbb{R}^{n+1}$ such that $f(x)\perp x$? Here I talk about how to relate the abstract definition to the more intuitive notion.
Calculating the derivative of a differentiable map between manifolds. Similar thing where I explain the theory, but also describe how to apply it for the specific computation for a map $f:S^2\to\Bbb{R}$.
How to show that $T_{(1,0)}S^1\cong \text{span}(\{e_2\})$? A similar thing, applied to the special case of the circle $S^1$.
What is meant by part (e) of MTW Exercise 9.13 involving the tangent to a curve on the manifold $\text{SO}(3)$? This is a PhySE answer where I explain similar stuff in the context of the manifold $\text{SO}(3)$. In that link, what I write $\Phi(T_I(SO(3)))$ is precisely equal to $\mathfrak{so}(3)$.

There may even be more answers along these lines, but this should be enough. I suggest reading them in order (though you're of course free to do it in whichever order you like).
Comment: @Sjang never heard of Ado's theorem lol, so I would guess not.
Comment: Thanks so much for your answer. Just for curiosity, does this have something to do with Ado's theorem?
Comment: @Sjang Maybe this is what you are looking for: https://mathoverflow.net/q/62234/40570
Comment: @Sjang not quite. Ado's theorem tells us that any Lie algebra has at least one faithful representation (and thus can be represented by matrices) but here we are using something simpler because you are starting from a Lie group which you have already assumed to be a matrix group. This makes things easier as it is natural to differentiate a curve in a matrix group and denote the answer by a matrix. Ado's theorem only assumes an abstract Lie algebra.

Is tangent vector on so(3) a matrix?


How do you handle Touch Events in a UITableView

Question: I'm trying to apply an event to a cell in order to specify the TouchesBegan method.
cell.TouchesBegan += OnTouchesBegan;

But TouchesBegan is a method group and not an event.
How do I add custom behavior to a Cells TouchesBegan() method in monotouch?
[Register("MenuView")]
public class MenuView : ViewControllerBase
{
    private new MenuViewModel ViewModel { get { return (MenuViewModel)base.ViewModel; } }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        // this ensures the sliding panel doesn't fill the entire view.
        var frame = View.Frame;
        frame.Width = 300;
        View.Frame = frame;

        var chapters = ViewModel.Chapters;

        //var listHeight = (chapters.Count*40);
        var navigationList = new UITableView(new RectangleF(0, 50, 300, 300))
            {
                Source = new NavigationTableSource(chapters)
            };
        Add(navigationList);
    }
}

public class NavigationTableSource : UITableViewSource
{
    private readonly IList<ChapterViewModel> _chapters;
    private const string CellIdentifier = "NavigationCell";

    public NavigationTableSource(IList<ChapterViewModel> chapters)
    {
        _chapters = chapters;
    }

    public override int RowsInSection(UITableView tableview, int section)
    {
        return _chapters.Count;
    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        var cell = tableView.DequeueReusableCell(CellIdentifier) ??
                   new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier);
        // if there are no cells to reuse, create a new one
        cell.TextLabel.Text = _chapters[indexPath.Row].Title;
        cell.TouchesBegan += OnTouchesBegan;
        return cell;
    }
}

Answer: TouchesBegan is a method that you can override by subclassing UITableViewCell:
public class CustomCell : UITableViewCell
{
    public CustomCell(UITableViewCellStyle style, NSString reuseIdentifier) : base(style, reuseIdentifier)
    {
    }

    public override void TouchesBegan(NSSet touches, UIEvent evt)
    {
        // do something

        base.TouchesBegan(touches, evt);
    }
}

Then use your subclass when creating a cell:
var cell = tableView.DequeueReusableCell(CellIdentifier) ??
               new CustomCell(UITableViewCellStyle.Default, CellIdentifier);

Comment: wow, so as I'm discovering in my noobness to iOS is that there aren't really any Event listeners that you can set, and beyond that there aren't really any Properties you can set either. Everything is Method Groups and require full Custom classes for anything you want to do...
Answer: So the way I was able to manage this was to SubClass my UITableViewSource. In there I overrode RowSelected(UITableView tableView, NSIndexPath indexPath)
public class NavigationTableSource : UITableViewSource
{
    private readonly IList<ChapterViewModel> _chapters;
    private const string CellIdentifier = "NavigationCell";

    public NavigationTableSource(IList<ChapterViewModel> chapters)
    {
        _chapters = chapters;
    }

    public override int RowsInSection(UITableView tableview, int section)
    {
        return _chapters.Count;
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        // todo: This is where we're going to load up the appropriate chapter.
        new UIAlertView("Row Selected", _chapters[indexPath.Row].Title, null, "OK", null).Show();
    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        var cell = tableView.DequeueReusableCell(CellIdentifier) ??
                   new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier);
        // if there are no cells to reuse, create a new one
        cell.TextLabel.Text = _chapters[indexPath.Row].Title;
        return cell;
    }
}


Why is my furnace limit tripping?

Question: My furnace is tripping the high limit.  It is a Downflow Payne 90+ have replaced the limit switch. I pulled the blower door off and checked all vents to ensure they are open and it still short cycles.  I also changed the speed on the blower and checked gas pressure.  I'm stumped!  Does anyone have any ideas as to what's going on?
Comment: Have you changed the filter, and checked for inflow restrictions? Are you sure it's the high limit?
Comment: You checked the exhaust vent for blockages?
Comment: Yes like i said had blower door off. if exhaust vent was blocked would b press switch right
Comment: 99.9% of the time high limit trips are airflow problems. Check for dirty filter, clogged/dirty blower wheel, closed dampers, blocked vents (supply and return), etc. If you have an inducer motor, exhaust flow should trip the pressure sensor not the limit. However, in the unlikely event that the pressure switch has failed closed, that would be a problem.
Comment: What is the model number of your furnace?  Do you have the owners manual?
Comment: Did you replace the limit switch with an approved replacement part? Was the replacement an adjustable model, that you did not adjust?
Comment: Have u by chance changed out your thermostat recently?
Comment: I have seen this problem when the blower motor is not doing its job from loose belts and or bearings that need lubrication. Usually a few drops of oil at the blower motor oil points can free up the bearings and give a few more years of life, other than that closed vents and dirty filters are the problems I have found or crushed flex lines.
Answer: The only way the plenum can get hot enough to hit the high limit is lack of air flow.
Open all registers and dampers and take the filter out.
If it still gets too hot your central air "A"
coil may be plugged with dirt.
Comment: Yeah -- if the A coil is clean and your furnace is still cycling on the high-limit, then I'd check for a blower failure or excess duct static.

Why is my furnace limit tripping?