text:
Q: how to get TimeStamp Certificate? In order to add docuemnt the timestamp, using itext, we have com.itextpdf.text.pdf.security.TSAClient abstract interface.
but how to get TimeStamp Certificate from the  PDF file?

A: You can call the AcroFields method verifySignature for signature fields containing document timestamps, too, and query its result for the certificates.
PdfReader reader = ...;
AcroFields fields = reader.getAcroFields();
List<String> names = fields.getSignatureNames();
String signatureName = names.get(names.size() - 1);
PdfPKCS7 pkcs7 = fields.verifySignature(signatureName);
System.out.println(String.format("Checking %ssignature %s", pkcs7.isTsp() ? "document-level timestamp " : "", signatureName));
Certificate[] chain = pkcs7.getSignCertificateChain();

This code inspects the outermost signature or document time stamp of a document and returns that signature's or time stamp's certificate chain as far as it is known.
You might want to look at the LtvVerifier class (from which I extracted the code above) for verification of all signatures and document timestamps and read section 5.4.4 Validating an LTV document in Digital Signatures for PDF documents for the use in context.


text:
Q: Azure Data Flow Getting Error on Update and Insert When i am joining Two tables and allowing Alter Update and Insert getting this Error
Allowing delete, insert, or update requires an Alter Row transformation to set row policies.

Then i created the Alter Rows Now i am getting this Error When i am running trigger

{"error":{"code":"BadRequest","message":"ErrorCode=InvalidTemplate,
  ErrorMessage=Unable to parse expression 'Order
  ID'","target":"pipeline/SaleDB/runid/1cf1e695-dff8-4330-8401-b4ebb86d573f","details":null}}

A: Error regarding 'Order ID', this column is a duplicate mostly coming from the Distinct (Aggregate) and Select1 (duplicate stream for OriginalData). So you can put a select before sink drop the duplicate column. That will solve this problem.
Regarding AlterRow. Only alter row is the transformation which can mark rows to update, delete, upserts. In case you intention is to update some rows, then you need Alter Row, in case intention is not to update then you can remove Allow Update from sink.

redpajama_set_name: RedPajamaStackExchange


text:
Q: typecast structure member in C during assignment Is there a way to type cast structure member during its initiation, for instance:
struct abc {
    char k;
};

int main()
{
  struct abc data[] = {.k= 'TI'};
}

Above wouldn't work since k is of type char, is there way to type caste this member k (to int) during its assignment to 'TI' ?

A: You don't need a cast here.
struct abc {
    char k;
};

int main()
{
  struct abc data[] = {.k= 'TI'};
}

Your object data is an array of struct abc. The initializer is for a single object of type struct abc.
If you want data to be a 1-element array, you can do this:
  struct abc data[] = {{.k= 'TI'}};

or, if you want to be more explicit:
   struct abc data[] = {[0] = {.k = 'TI'}};

That's valid code, but it's likely to trigger a warning. 'TI' is a multi-character constant, an odd feature of C that in my experience is used by accident more often than it's used deliberately. Its value is implementation-defined, and it's of type int.
Using gcc on my system, its value is 21577, or 0x5449, which happens to be ('T' << 8) + 'I'.  Since data[0].k is a single byte, it can't hold that value. There's an implicit conversion from int to char that determines the value that will be stored (in this case, on my system, 73, which happens to be 'I').
A cast (not a "type cast") converts a value from one type to another. It doesn't change the type of an object. k is of type char, and that's not going to change unless you modify its declaration. Maybe you want to have struct abc { int k; };?
I can't help more without knowing what you're trying to do. Why are you using a multi-character constant? Why is k of type char?

A: No matter what you do to the value, it doesn't change the fact that the field cannot store that much information. You will need to change the type of k.

A:
"...I was thinking if member K which of type char can be type caste to int ..."

As mentioned in comments, struct members are static and cannot be cast.
But given your willingness to cast (even though that will not work) why not start with a type that naturally accommodates multi-byte characters, i.e. wchar_t ?
If this is acceptable for your work, then when working with multi-byte char in C, you can do the following:
#include <wchar.h>

struct abc {
    wchar_t k[2];//or k[3] depending on k will be used as a C string.
};
...
//inside function somewhere:
//assignment can be done as follows:
struct abc buf = {.k[0] = L'T', .k[1] = L'I'};
// Or:
struct abc buf = {.k = L"TI"};//Note, no null terminator, so not C string

Note: regarding 2nd method, by definition, L"TI" contains three characters, T, I and \0.  If k is to be used as a string, k must be defined with space for the null terminator: wchar_t k[3];.
(See examples here.)
This results in the following:

(where 84 and 73 are the ASCII values for T and I respectively.)
Note: compiled using GNU GCC, set to follow C99 rules

A: *

*'TI' is wrong you probably mean string "TI"

*If typecast mean see the sting "TI" as integer you need to use union - it is called type punning.

typedef union
{
    char k[2]; //I do not want to store null terminating character
    short int x;
}union_t;

int main(void)
{
    union_t u = {.k = "TI"};

    printf("u.k[0]=%c (0x%x), u.k[1]=%c (0x%x) u.x = %hd (0x%hx)\n", u.k[0], u.k[0], u.k[1], u.k[1], u.x, u.x);
}

https://godbolt.org/z/EhbKG5qnW


text:
Q: Array of objects in swagger 2.0 I am trying to define the swagger for below JSON response.
[
        {
            "STATE": [
                {
                    "CODE_NM": "A&B",
                    "CODE_DSC": "Argyll & Bute",
                    "CODE_ID": 123
                },
                {
                    "CODE_NM": "AA",
                    "CODE_DSC": "sd",
                    "CODE_ID": 12345
                }
            ]
        },
        {
            "COUNTRY": [
                {
                    "CODE_NM": "sd",
                    "CODE_DSC": "CAN",
                    "CODE_ID": 12
                },
                {
                    "CODE_NM": "AA",
                    "CODE_DSC": "USA",
                    "CODE_ID": 12345
                }
            ]
        }
    ]

My swagger definition is something like below.
`responses:
        '200':
          description: ''
          schema:
            type: array
            items:
              $ref: '#/definitions/searchTypeResp'
definitions:
  codeTable:
    title: codeTable
    type: object
    properties:
      CODE_NM:
        type: string
      CODE_DSC:
        type: string
      CODE_ID:
        type: string
    required:
    - CODE_NM
    - CODE_ID
  searchTypeResp:
    title: searchTypeResp
    type: object
    properties:
      COUNTRY:
        type: array
        items:
          $ref: '#/definitions/codeTable'
        example:
        - CODE_NM: 1
          CODE_DSC: Sherlock
          CODE_ID: 1
        - CODE_NM: 1
          CODE_DSC: Sherlock
          CODE_ID: 2
      STATE:
        type: array
        items:
          $ref: '#/definitions/codeTable'
`

Above definition is yielding the response like below which is wrong for my requirement.
  [
      {
        "COUNTRY": [
          {
            "CODE_NM": 1,
            "CODE_DSC": "Sherlock",
            "CODE_ID": 1
          },
          {
            "CODE_NM": 1,
            "CODE_DSC": "Sherlock",
            "CODE_ID": 2
          }
        ],
        "STATE": [
          {
            "CODE_NM": "string",
            "CODE_DSC": "string",
            "CODE_ID": "string"
          }
        ]
      }
    ]

Can anyone please help to get to the correct definition? I need the swagger definition that suits the json I posted above.


text:
Q: GKE deployment ReactJS app CrashLoopBackoff I have built my Docker image for my ReactJS app. I run the image locally and tested it, which works fine.
I'm using Google Cloud Build which automatically puts my container image to gcr.io container repo.
Then I try to create a deployment from my container image which resides in gcr.io
But the deployment is not successfully finishing. It gives me

Pod errors: CrashLoopBackOff
Does not have minimum availability

Here is my Docker image.
FROM node:latest
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ "npm", "start" ]

When I look at the pod -> container logs, I see my app has been restarting without any error log.
I 2020-04-27T15:07:57.505370601Z > react-scripts start

I 2020-04-27T15:07:57.505375001Z

I 2020-04-27T15:07:59.392880949Z [34mℹ[39m [90m「wds」[39m: Project is running at http://10.48.0.14/

I 2020-04-27T15:07:59.393329591Z [34mℹ[39m [90m「wds」[39m: webpack output is served from

I 2020-04-27T15:07:59.393494921Z [34mℹ[39m [90m「wds」[39m: Content not from webpack is served from /usr/src/app/public

I 2020-04-27T15:07:59.393641770Z [34mℹ[39m [90m「wds」[39m: 404s will fallback to /

I 2020-04-27T15:07:59.393881277Z Starting the development server...

I suspect what happens is, kubernetes does not wait enough and try to restart application.
I'm not using a deployment.yaml but simply using the GCP console.
There is no health endpoint in my ReactJS app.
This is the output for kubectl describe pod ...
Name:           helloworld-gke-7fd977fd94-kvrcj
Namespace:      default
Priority:       0
Node:           gke-helloworld-gke-default-pool-a23be758-g8q7/10.182.0.2
Start Time:     Mon, 27 Apr 2020 17:15:18 +0200
Labels:         app=hello
                pod-template-hash=7fd977fd94
Annotations:    kubernetes.io/limit-ranger: LimitRanger plugin set: cpu request for container hello-app
Status:         Running
IP:             10.48.0.15
IPs:            <none>
Controlled By:  ReplicaSet/helloworld-gke-7fd977fd94
Containers:
  hello-app:
    Container ID:   docker://389151ed6...
    Image:          gcr.io/tuition-h...
    Image ID:       docker-pullable://gcr.io/...
    Port:           3000/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Mon, 27 Apr 2020 18:28:00 +0200
      Finished:     Mon, 27 Apr 2020 18:28:02 +0200
    Ready:          False
    Restart Count:  19
    Requests:
      cpu:  100m
    Environment:
      PORT:  8080
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-sqpm7 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  default-token-sqpm7:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-sqpm7
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason   Age                    From                                                    Message
  ----     ------   ----                   ----                                                    -------
  Warning  BackOff  4m17s (x320 over 74m)  kubelet, gke-helloworld-gke-default-pool-...  Back-off restarting failed container


text:
Q: Get number of days in a specific month that are in a date range Haven't been able to find an answer to this problem. Basically what I'm trying to do is this:
Take a daterange, for example October 10th to November 25th. What is the best algorithm for determining how many of the days in the daterange are in October and how many are in November.
Something like this:
def daysInMonthFromDaterange(daterange, month):
    # do stuff
    return days

I know that this is pretty easy to implement, I'm just wondering if there's a very good or efficient algorithm.
Thanks

A: Borrowing the algorithm from this answer How do I divide a date range into months in Python?
, this might work. The inputs are in date format, but can be changed to date strings if preferred:
import datetime
begin = '2018-10-10'
end = '2018-11-25'

dt_start = datetime.datetime.strptime(begin, '%Y-%m-%d')
dt_end = datetime.datetime.strptime(end, '%Y-%m-%d')
one_day = datetime.timedelta(1)
start_dates = [dt_start]
end_dates = []
today = dt_start
while today <= dt_end:
    #print(today)
    tomorrow = today + one_day
    if tomorrow.month != today.month:
        start_dates.append(tomorrow)
        end_dates.append(today)
    today = tomorrow

end_dates.append(dt_end)

out_fmt = '%d %B %Y'
for start, end in zip(start_dates,end_dates):
    diff = (end - start).days
    print('{} to {}: {} days'.format(start.strftime(out_fmt), end.strftime(out_fmt), diff))

result:
10 October 2018 to 31 October 2018: 21 days
01 November 2018 to 25 November 2018: 24 days

A: The problem as stated may not have a unique answer.  For example what should you get from daysInMonthFromDaterange('Feb 15 - Mar 15', 'February')?  That will depend on the year!
But if you substitute actual days, I would suggest converting from dates to integer days, using the first of the month to the first of the next month as your definition of a month.  This is now reduced to intersecting intervals of integers, which is much easier.
The assumption that the first of the month always happened deals with months of different lengths, variable length months, and even correctly handles the traditional placement of the switch from the Julian calendar to the Gregorian.  See cal 1752 for that.  (It will not handle that switch for all locations though.  Should you be dealing with a library that does Romanian dates in 1919, you could have a problem...)

A: You can use the datetime module:
from datetime import datetime

start = datetime(2018,10,10)
end = datetime(2018,11,25)
print((end - start).days)

A: Something like this would work:
def daysInMonthFromDaterange(date1, date2, month):
    return [x for x in range(date1.toordinal(), date2.toordinal()) if datetime.date.fromordinal(x).year == month.year and datetime.date.fromordinal(x).month == month.month]

print(len(days_in_month(date(2018,10,10), date(2018,11,25), date(2018,10,01))))

This just loops through all the days between date1 and date2, and returns it as part of a list if it matches the year and month of the third argument.


text:
Q: Running a PHP script inside a Python WSGI enviroment I have a simple PHP script that outputs a dir listing in XML format. I use it to let a flash slideshow know what files are available to show.
I've just added the flash to a website that's powered by Django and the PHP file is now served up as it is, not parsed.
It's in the directory with the images under my media directory.
The server I use runs plesk so I do my config for each domain in a vhost.conf file (which gets included into the main appache conf I think)
It looks like this:
WSGIScriptAlias / /var/www/vhosts/<domain>/conf/django.wsgi
Alias /media/ /var/www/vhosts/<domain>/httpdocs/media/

I thought this meant that requests for anything under / are passed django to handle.
Except when they are for /media/... then they are served by apache as normal from the specified dir.
That works for the images, but does not parse the PHP file.
What should I do?

A: Maybe read this thread, and port your PHP script to Python:
os.walk() python: xml representation of a directory structure, recursion

A: So it turns out the problem was two things, making it hard to find.
Thanks Ignacio Vazquez-Abrams, I had my lines the wrong way around.
Once that was solved, PHP would not serve my file because it was in a dir that was symlinked from outside the allowed path(s). I resolved this by turning off open_basedir restrictions for this vhost. My new vhost.conf is below.
<Directory /var/www/vhosts/<domain>/httpdocs>
    php_admin_flag engine on
    php_admin_value open_basedir none
</Directory>

Alias /media/ /var/www/vhosts/<domain>/httpdocs/media/

WSGIScriptAlias / /var/www/vhosts/<domain>/conf/django.wsgi

A: If you have not configured Apache so that it knows that .php files under the '/media' directory should be processed by PHP somehow, they will not be. So, the mod_wsgi configuration is fine, the problem is likely your PHP configuration.
How are you configuring PHP? Are you using mod_php, or PHP via fastcgi? How is Apache configured so that it knows to treat .php files as PHP and for what directories has that configuration been applied to?

A: The WSGIScriptAlias directive there swallows up URLs meant for Alias. Swap the order.


text:
Q: "waver one's determination"

*

*She never wavers in her determination to shoot for the moon

*She never wavers her determination to shoot for the moon.

My question is whether waver can be used as a transitive verb that can modify something.

A: "Waver" is an intransitive verb. "Wavers her determination" is wrong.


text:
Q: How can I get Windows 7 to turn off lights? Since I installed Windows 7, the lights on thumb drives don't turn off when the option to eject them is selected.  Also, the lights on the power button and hard drive indicator lights on my case never go out when Windows is shut down.

A: This is the default behavior since Vista. But you can fix it:

*

*run regedit.exe, go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\usbhub,

*create a key with the name HubG

*create a DWORD32 with the name DisableOnSoftRemove

*change the Value data field to 1 and click OK

(picture-)Source:
http://www.howtogeek.com/120914/how-to-make-your-usb-devices-power-down-on-safe-removal-in-windows/


text:
Q: Delete objects (similar objects/duplicates) in coreData I have in my entity an property named cardId.
Sometimes this cardId is more then once in my entity. I want to delete these duplicates.
How can I find these duplicates and delete them?
allObjects = [__fetchedResultsController fetchedObjects];
for (Entity *inbox in allObjects) {

    [managedObjectContext deleteObject:**objectToDelete**];
}

How can I find these similar objects?

A: The following is just an idea, you have to elaborate it yourself.
You can specify to return only distinct results from your fetch with setReturnsDistinctResults of NSFetchRequest after specifying your key (cardId) as propertiesToFetch. So you make a first fetch of all distinct object and copy the result to a mutable array what I'll call distinctArray. Then you make a second fetch where you query ALL objects, thus with setReturnsDistinctResults disabled into completeArray. You iterate through the elements of distinctArray and remove each element from completeArray. What remains in completeArray will be the objects to delete.
The more low level implementation of this (probably more efficient as well) would be a double for cycle. You fetch only all objects in completeArray and do the old good double cycle:
NSMutableArray* objectsToDelete = [[NSMutableArray alloc] initWithCapacity:how_many_duplicates_you_expect];
for (int i = 0; i < [completeArray count]; i++) {
   for (j = i + 1; j < [completeArray count]; j++) {
      MOObject* objecti = [completeArray objectAtIndex:i];
      MOObject* objectj = [completeArray objectAtIndex:j];
      if (objecti.cardId == objectj.cardId) {
          [objectsToDelete addObject:objectj];
      }
   }
 }

At the end there will be all objects to be deleted in objectsToDelete. Pay attention, if you have more than two occurrences of the same object in your db, there might be duplicates even in objectsToDelete so check it before deleting.


text:
Q: How to handle delete in Google App Engine (Python) I'm a newbie programmer and new to Google App Engine and webapp2 etc. So this may be a very basic question.
I am creating an application to store images into BlobStore. My model stores description, blob_key, image url and date.
I am able to save everything, so that bit is okay.
But now I want to create a delete button which will not only delete an item from the datastore, but also delete the image saved in the blobstore.
I have created a DeleteHandler, and in the html I have a form, passing the key for the item I want to delete. In the DeleteHandler, I am using the posted key to delete the item from the datastore. I am also trying to use the key to use it delete the image saved in the blobstore.
So far I'm getting a 404 on the delete form post, and even if I get past that, I'm not sure if my DeleteHandler is correct to handle the functionality I am looking for.
Any help would be much appreciated..
Main.py:
import os
import urllib
import webapp2
from google.appengine.ext.webapp import template
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import images
#Models
from google.appengine.ext import db

class ImageItem(db.Model):
    description = db.StringProperty(required=True)
    img_url = db.StringProperty()
    blob_key = blobstore.BlobReferenceProperty()
    when = db.DateTimeProperty(auto_now_add=True)

#Handlers (Views)
class MainHandler(webapp2.RequestHandler):
  def get(self):
    upload_url = blobstore.create_upload_url('/upload')
    imgs = db.GqlQuery(
        'SELECT * FROM ImageItem '
        'ORDER BY when DESC')
    imgs_dict = {'imgs': imgs}
    self.response.out.write( template.render( 'main.html',locals() ) )

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    f = self.get_uploads('file')[0]  # 'file' is file upload field in the form
    img =ImageItem(description=self.request.get('description'))
    img.blob_key = f.key()
    img.img_url = images.get_serving_url( f.key() )
    img.put()
    self.redirect('/')

class DeleteHandler(webapp2.RequestHandler):
    def post(self):
        key = self.request.get('k')
        item = db.get(key)
        images.delete( item.blob_key )
        item.delete()
        self.response.out.write(key)

#URL Routing happens here
app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/upload', UploadHandler),
                               ('/delete', DeleteHandler)],
                              debug=True)

Main.html:
<form action="{{upload_url}}" method="POST" enctype="multipart/form-data">

                Upload File
                <input type="file" name="file" id="file">

                Description
                <input type="text" id="description" name="description">

            <input type="submit" name="submit" value="Submit">
    </form>

        {% for i in imgs %}

            {{i.description }}

{{i.when }}

            <form action="/delete" method="POST"  enctype="multipart/form-data">
                <input type="text" name="k" value="{{i.key}}" />
                <input type="submit" value="delete">
            </form>

        {% endfor %}

A: The deletes are close.  Once you have a key, you can delete entities by calling db.delete(key).

For your example, this would be something like this:
class DeleteHandler(webapp2.RequestHandler):
    def post(self):
        key = self.request.get('k')
        item = db.get(key)
        blobstore.delete([item.blob_key])
        db.delete(item)
        self.response.out.write(key)

Your url handling in main.py is good, so it's not obvious to me why you're getting a 404.  You could double-check your app.yaml file to make sure all urls are passed to main.py.
Here's a sample app.yaml handlers url section:
handlers
- url: /.*
    script: main.app

A: Got it to work. Thanks Eric, yours was real close. I needed to use blob_key.key().
Final code is following:

class DelHandler(webapp2.RequestHandler):
  def post(self):
    key = self.request.get('k')
    item = db.get(key)
    n = item.blob_key.key()
    blobstore.delete(n)
    item.delete()
    self.redirect('/')


text:
Q: Resolve  in std::async call Can't resolve this instance of calling std::lower_bound from std::async. Example:
#include <vector>
#include <algorithm>
#include <future>
#include <iostream>

int main() {
  std::vector<int> v = {1,3,4,6,7};
  auto res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 4);
  std::cout << *res.get() << std::endl;
  return 0;
}

Compiler output makes it look like it doesn't realize std::launch::async is a launch policy and it should use the async call with the launch policy but I could be wrong.
test.cpp:8:84: error: no matching function for call to 'async(std::launch, <unresolved overloaded function type>, std::vector<int>::iterator, std::vector<int>::iterator, int)'
res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 3);
                                                                            ^
In file included from test.cpp:3:0:
/usr/include/c++/6/future:1709:5: note: candidate: template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...)
 async(launch __policy, _Fn&& __fn, _Args&&... __args)
 ^~~~~
/usr/include/c++/6/future:1709:5: note:   template argument deduction/substitution failed:
test.cpp:8:84: note:   couldn't deduce template parameter '_Fn'
res = std::async(std::launch::async, std::lower_bound, v.begin(), v.end(), 3);
                                                                          ^
In file included from test.cpp:3:0:
/usr/include/c++/6/future:1739:5: note: candidate: template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(_Fn&&, _Args&& ...)
 async(_Fn&& __fn, _Args&&... __args)
 ^~~~~
/usr/include/c++/6/future:1739:5: note:   template argument deduction/substitution failed:
/usr/include/c++/6/future: In substitution of 'template<class _Fn, class ... _Args> std::future<typename std::result_of<typename std::decay<_Tp>::type(typename std::decay<_BoundArgs>::type ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = std::launch; _Args = {}]':
test.cpp:8:84:   required from here
/usr/include/c++/6/future:1739:5: error: no type named 'type' in 'class std::result_of<std::launch()>'

A: std::lower_bound is a function template, you have to explicitly specify its arguments to be able to pass it around:
int main() {
  using V = std::vector<int>;
  V v = {1,3,4,6,7};
  auto res = std::async(std::launch::async, std::lower_bound<V::iterator, int>, v.begin(), v.end(), 4);
  std::cout << *res.get() << std::endl;
  return 0;
}


text:
Q: Handling bash system variables and slurm environmental variables in a wrapper script Problem: Inspired by this thread, I'm trying to write a wrapper script that submits SLURM array jobs with bash variables. However, I'm running into issues with SLURM environment variables like $SLURM_ARRAY_TASK_ID as it acts as an empty variable.
I suspect it has something to do with how the test_wrapper.sh is parsing the yet undefined SLURM variable, but I can't seem to find a solution.
Below I provide a working example with a simple python script that should take an array ID as an input variable, but when it is called by the bash wrapper script, the python script crashes as it receives an empty variable.
test_wrapper.sh :
#!/bin/bash
for argument in "$@"
do
  key=$(echo $argument | cut -f 1 -d'=')
  value=$(echo $argument | cut -f 2 -d'=')
  case "$key" in
    "job_name")     job_name="$value" ;;
    "cpus")         cpus="$value" ;;
    "memory")       memory="$value" ;;
    "time")         time="$value" ;;
    "array")        array="$value" ;;
    *)
  esac
done

sbatch <<EOT
#!/bin/bash
#SBATCH --account=foobar
#SBATCH --cpus-per-task=${cpus:-1}
#SBATCH --mem-per-cpu=${memory:-1}GB
#SBATCH --time=${time:-00:01:00}
#SBATCH --array=${array:-1-2}
#SBATCH --job-name=${job_name:-Default_Job_Name}

if [ -z "$SLURM_ARRAY_TASK_ID" ]
then
      echo "The array ID \$SLURM_ARRAY_TASK_ID is empty"
else
      echo "The array ID \$SLURM_ARRAY_TASK_ID is NOT empty"
fi

srun python foo.py -a $SLURM_ARRAY_TASK_ID

echo "Job finished with exit code $?"

EOT

where foo.py is:
import argparse

def main(args):
  print('array number is : {}'.format(args.array_number))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--array_number",
        help="the value passed from SLURM_ARRAY_TASK_ID"
        )
    args = parser.parse_args()
    main(args)

$cat slurm-123456789_1.out yields :
The array ID 1 is empty
usage: foo.py [-h] [-a ARRAY_NUMBER]
foo.py: error: argument -a/--array_number: expected one argument
srun: error: nc10931: task 0: Exited with exit code 2
Job finished with exit code 0

I find it strange, that "The array ID 1 is empty" is correctly printing the $SLURM_ARRAY_TASK_ID (??)

A: Thanks to the feedback posted in the comments I was able to fix the issue. Posting a "fixed" version of the wrapper script below.
In short, the solution is to escape $SLURM_ARRAY_TASK_ID.
#!/bin/bash
for argument in "$@"
do
  key=$(echo $argument | cut -f 1 -d'=')
  value=$(echo $argument | cut -f 2 -d'=')
  case "$key" in
    "job_name")     job_name="$value" ;;
    "cpus")         cpus="$value" ;;
    "memory")       memory="$value" ;;
    "time")         time="$value" ;;
    "array")        array="$value" ;;
    *)
  esac
done

{ tee /dev/stderr | sbatch; } <<EOT
#!/bin/bash
#SBATCH --account=foobar
#SBATCH --cpus-per-task=${cpus:-1}
#SBATCH --mem-per-cpu=${memory:-1}GB
#SBATCH --time=${time:-00:01:00}
#SBATCH --array=${array:-1-2}
#SBATCH --job-name=${job_name:-Default_Job_Name}

if [ -z "\$SLURM_ARRAY_TASK_ID" ]
then
      echo "The array ID \$SLURM_ARRAY_TASK_ID is empty"
else
      echo "The array ID \$SLURM_ARRAY_TASK_ID is NOT empty"
fi

python foo.py -a \$SLURM_ARRAY_TASK_ID

EOT

cat slurm-123456789_1.out yields :
The array ID 1 is NOT empty
array number is : 1

Note: the { tee /dev/stderr | sbatch; } is not necessary, but is very useful for debugging (thanks Charles Duffy)

A: So according to this page:

Job arrays will have two additional environment variable set. SLURM_ARRAY_JOB_ID will be set to the first job ID of the array. SLURM_ARRAY_TASK_ID will be set to the job array index value.

That suggests to me that sbatch is supposed to set these for you. In that case, you need to escape all instances of $SLURM_ARRAY_TASK_ID in the script you pass via the heredoc so that they don't get prematurely substituted before sbatch can set the relevant environment variable.
The two options for this are:

*

*If you don't want any expansions to occur at all, quote the heredoc delimiter.

sbatch <<"EOT"
<your script here>
EOT

*If you need some expansions to occur but want to disable others, then escape the ones that should not be expanded by putting a \ in front of them like you have done in your existing script.


text:
Q: Is there two different definition of covariance? I see two different expressions of covariance and wonder whether they are different:

$$Cov(X,Y)=\sum_i p(X=X_i,Y=Y_i)(X_i-E(X))(Y_i-E(Y))$$

and

$$Cov(X,Y)=\sum_{(i,j)} p(X=X_i,Y=Y_j)(X_i-E(X))(Y_j-E(Y))$$

Are the two expressions for different situations? I find it confused.


text:
Q: php working with array in single column in mysql mysql database on phpmyadmin
table_1: id, link

table_2: user_id, c_id

i have to store multiple values in c_id column in table_2 which
    refer to id column in table_1
how to write UPDATE queries to add new values to c_id column
and also SELECT queries to access each c_id value and get link from table_1
also i need to write php APIs for the same

A: You shouldn't try to add multiple values to your c_id field, simply because thats not how relational databases are meant to be used. If you want to link multiple rows from table2 to one row of table1 add rows for that.
e.g. to link two rows of 'table2' to one row of table1
table1:
id | link
-----------
1  | something
2  | some other

table2:
user_id | c_id
----------------
100     | 1
100     | 2

And please elaborate on

also i need to write php APIs for the same

I don't believe anyone here can understand what you're trying to do.


text:
Q: How to make option tag in HTML display rows of one column but save values of another from the same table I am trying to make a calorie counter app using flask/python-anywhere, and part of it is making a drop down menu of foods to choose from. I want the user to be able to see the food name, but when they submit the food, it's the food's calories that I want to be added to the database.
This is the python code for the relevant tables:
class Post(db.Model):
    __tablename__ = "posts"
    id = db.Column(db.Integer, primary_key=True)
    calories = db.Column(db.Integer)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.now)
    consumer_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    consumer = db.relationship('User', foreign_keys=consumer_id)

class Food(db.Model):
    __tablename__ = "foods"
    id = db.Column(db.Integer, primary_key=True)
    food_name = db.Column(db.String(200))
    food_cal = db.Column(db.Integer)

This is the python code for the page:
@app.route("/", methods=["GET", "POST"])
@login_required
def index():
    if request.method == "GET":
        return render_template("main_page.html", foods=Food.query.all(), posts=Post.query.all(), timestamp=datetime.now())
    if not current_user.is_authenticated:
        return redirect(url_for('index'))

    add_food = Post(calories=request.form["calories"], consumer=current_user)
    db.session.add(add_food)
    db.session.commit()
    return redirect(url_for('index'))

and this is my html code:

            {% for post in posts %}

                        You added {{ post.calories }} calories

                            at
                            {% if post.timestamp %}
                                {{ post.timestamp.strftime("%A, %d %B %Y at %H:%M") }}
                            {% else %}
                                at an unknown time
                            {% endif %}

            {% endfor %}

            {% if current_user.is_authenticated %}

                    <form action="." method="POST">

                            Food:
                            <select class="form control" name="food_name">
                                {% for food in foods %}
                                    <option value = "{{ food.food_name }}" selected>{{ food.food_name }}</option>
                                {% endfor %}
                            </select>
                            <input type="submit" class="btn btn-success" value="Add calories">

                    </form>

            {% endif %}

Just to clarify, the foods in the Food table have been added on my end, but I want the foods that users select to be saved as 'calories' in my Post table. Thanks in advance :)

A: <option value = "{{ food.food_name }}" selected>{{ food.food_name }}</option>

should be
<option value = {{ food.food_cal }} selected>{{ food.food_name }}</option>


text:
Q: How can I figure out if my hardware specs are adequate for Ubuntu 13.10? How can I figure out if my hardware specs are adequate for Ubuntu 13.10?
My Lenovo G505 is a modern laptop which seems to fulfill the official minimums, but  GUI interaction is  slow, even with Lubuntu or Xubuntu. I'd like to understand if something is misconfigured or if the  hardware is really too limited.
I'm not asking for a specific assessment of my specs, but I'd like to know-- how do I figure this out?
(Specs: AMD E1-2100 Dual Core, with 2 GB RAM and an AMD Radeon HD 8210M graphics accelerator)

A: When it comes to graphic card management, you may want to install your card's proprietary drivers. On Ubuntu, this can be done in Systems settings > Additional drivers.
Then, remember that your laptop has only 2GB of RAM, which was extraordinary a few years ago, but not today anymore. Ubuntu is basically running Unity, Compiz and GNOME, three components that are quite heavy, and for some, experimental.
Linux is very light by nature, however, some distributions such as Ubuntu make it quite heavier...


text:
Q: Find a Pouchdb document by date i created the db and inserted the records below is my doc
 var doc = {
      _id: Sno,
      Date:date,
      time:Time,
      trip : Trip,
      triptype:TripType,
      vechicleNo: VechicleNo,
      customer: Customer,
      vechicletType: VechicleType,

   };

now i want to get the values based on date selection

on selecting date i want to get all values based on date
i used the find plugin but it display doc as 0 even if there is data in particular date
here is my find plugin code
\\getting the date value on select
var saledate = document.getElementById('startdate').value;
   console.log(saledate);

   db.createIndex({
      index: {
        fields: ['Date']
      }
   });

   db.find({
        selector: {
          Date: saledate,  // assigning date value to the selector
        },
      });
   }).then(function (response) {
      console.log(response);
   }).catch(function (err) {
      console.log(err);
   });

can any any one help me with code


text:
Q: Can't put button on bottom with layout_gravity in LinearLayout I have just started android programming and I want to build a registration page, but I can't put bottom on bottom with layout_gravity. I have set orientation:vertical, but it doesn't work. anyone have any ideas? I will really appreciate if someone helps me to correct it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical"

>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Your Username"
            android:textColor="@android:color/darker_gray"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"

    />
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Your Email"
            android:textColor="@android:color/darker_gray"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"

    />

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:textColor="@android:color/darker_gray"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"

    />
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Confirm Password"
            android:textColor="@android:color/darker_gray"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"

    />

    <Button
            android:text="Register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"

    />

</LinearLayout>

A: A RelativeLayout is the easy solution in these cases, because it only takes this attribute to achieve what you want:
android:layout_alignParentBottom="true"

as for the other EditTexts, I gave them each an id and aligned each below the other:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Your Username"
        android:textColor="@android:color/darker_gray"
        android:layout_alignParentTop="true"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Your Email"
        android:layout_below="@id/editText1"
        android:textColor="@android:color/darker_gray"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:layout_below="@id/editText2"
        android:textColor="@android:color/darker_gray"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Confirm Password"
        android:layout_below="@id/editText3"
        android:textColor="@android:color/darker_gray"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"/>

    <Button
        android:text="Register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>


text:
Q: why I can't use tkinter module with batch file Batch code:
TITLE %~nx0
python "c:\users\aaa\desktop\coding\python\first project with tkinter\buttomtest.py"
pause

and python code is:
from tkinter import *
window = Label(text="gg")
print("tt")

and this is what I get:
It shows the cmd prompt window but it doesn't show the window of tkinter

A: Tkinter is a python module meant ONLY for python.
Now I see what you tried to do but learning python may be the way there is an OS module import OS which could allow you to run command prompt commands. os.system("command here") will allow you to run commands from the system DOS.
Hope this helps and enjoy the community!

A: You may also run a start command
start File.py
Exit

A: way to fix that: window.mainloop()
and there is no need for import OS


text:
Q: Solving a System of Linear Equations Step-by-Step, What is the solution for this system of linear equations?

$7x + 2y -5z = -18$
$x + 5y - 3z = -40$
$2x -y -9z = -26$

The correctly answer is (x = 2, y = -6, z = 4).

A: Well,use Gauss-Jordan...(use fractions ,if you think it´s better)

*

*Divide row 1 by 7

*Subtract row 1 from row 2

*Subtract (2 × row 1) from row 3

*Divide row 2 by 4.714

*Subtract (-1.571 × row 2) from row 3

*Divide row 3 by -8.333

*Subtract (-0.714 × row 3) from row 1

*Subtract (-0.485 × row 3) from row 2

*Subtract (0.286 × row 2) from row

Ten you will get in your matrix,that in this point is in a reduced row echelon form,the answer you already had:first line is (1 0   0   2),second line(0    1   0   -6), third line (0  0   1   4).The one´s correnspond to x , y and z.

A: Without resorting to matrices as Austin does in his answer, you can first multiply the last equation ($2x-y-9z=-26$) by an appropriate constant so that when you add it to the first equation ($7x+2y-5z=-18$), the $y$ variable is canceled. Repeat the process but this time add the last equation to the second equation ($x+5y-3z=-40$). Now you're left with 2 equations in two variables. Use this same process to multiply one of the equations by a constant so that when you add then two together, you eliminate the $x$ variable. Finally you have a single linear equation to solve for $z$. Once you have a value for $z$, plug that into your original equations and look for a way to multiply one equation by a constant to make a variable disappear.
I do recommend using matrices over this method. This takes longer, looks messier,and the process isn't as algorithmic as using Gaussian elimination.
EDIT I thought it might be useful to show you how to set this up using Gaussian elimination. At each step the indicated operation will use $R_1$ for row 1, $R_2$ for row 2, and $R_3$ for row 3.
$$
\begin{bmatrix}
1&5&-3&-40\\2&-1&-9&-26\\7&2&-5&-18
\end{bmatrix} \xrightarrow{-2R_1+R_2} \begin{bmatrix}
1&5&-3&-40\\0&-11&-3&54\\7&2&-5&-18
\end{bmatrix} \xrightarrow{-7R_1+R_3} \begin{bmatrix}
1&5&-3&-40\\0&-11&-3&54\\0&-33&16&262
\end{bmatrix} \xrightarrow{-3R_2+R_3} \begin{bmatrix}
1&5&-3&-40\\0&-11&-3&54\\0&0&25&100
\end{bmatrix} \xrightarrow{\frac{1}{25}R_3} \begin{bmatrix}
1&5&-3&-40\\0&-11&-3&54\\0&0&1&4
\end{bmatrix} \xrightarrow{\text{skipping steps}} \begin{bmatrix}
1&0&0&2\\0&1&0&-2\\0&0&1&4
\end{bmatrix}
$$

A: One way is to write a corresponding matrix equation. Let
$$
A =
\left[
\begin{array}{ccc}
7 & 2 & -5\\
1 &5 & -3\\
2 & -1 & -9
\end{array}
\right],
$$
$$
X = \left[
\begin{array}{c}
x\\
y\\
z
\end{array}
\right],
$$
and
$$
B = \left[
\begin{array}{c}
-18\\
-40\\
-26
\end{array}
\right].
$$
You should convince yourself that the system of linear equations is exactly the same as the matrix equation
$$
AX = B.
$$
Multiplying both sides on the left by $A^{-1}$ (matrix multiplication does not commute) gives
$$
A^{-1}AX = A^{-1}B
$$
which simplifies to
$$
X = A^{-1}B.
$$
You can use a calculator to evaluate this last line.
Note $A^{-1}$ may not always exist (you will know this is the case if your calculator gives a message like "singular matrix"). In this situation, you have either an inconsistent system (no solutions) or a dependent system (infinitely-many solutions). To handle these kinds of systems, you should resort to Gauss-Jordan elimination.

A: We tag the equations for convenience:
$$\tag 1 7x + 2y -5z = -18$$
$$\tag 2 x + 5y - 3z = -40$$
$$\tag 3 2x -y -9z = -26$$
We first perform $(1)-7\times(2)$ which gives
$$\tag 4-33y+16z=262$$
Now we perform $2\times(1)-7\times (3)$, which gives
$$\tag 5 11  y+ {53}  z=146 $$
Now we make $11\times(4)+33\times (5)$, which gives
$$1925z=7700$$
so $z=7700/1925=4$. And now it's just a "chain reaction".
Note we chose the constants so that the first term cancelled out. This method is called Gaussian elimination, or Gauss-Jordan method.


text:
Q: Vue performance issue with input type color and v-model I'm setting the v-model on input type color. The issue is when I change the color, frame drop occurs and application FPS surges from 60 FPS to 3 FPS. Here is the screenshot of the Vue performance graph.

How do I tackle down this performance issue? I'm not using the Vue single-file components. I just have a Vue on the solo page and using v-model to handle input changes. Here is the color input code,

    <input type="color" v-model="conf.default">

What the thing leads to sudden drop of FPS? Is there any solution for this? I'm facing this on chrome version 83.0, didn't test in other browsers yet.
Note: I tried using @change, and it's performing well without performance issues. Here is the code

    <input type="color" @change="setStyle($event)">

Seems that it's only the issue with using v-model. I would have used it but I want the color to be updated in realtime. Here, @change listener updates the value after the color input loses focus.

A: I'm guessing you are using the color to update parts of your DOM. The color picker can update the v-model value a lot especially if the user is dragging to pick a color. This can be expensive on performance depending on what you are doing with the color. One thing you could try is to throttle how often your color gets updated.
<input type="color" v-model="color">

Here I am using lodashes throttle method to throttle the color changing every 500 milliseconds.
import throttle from 'lodash/throttle'

{
    watch: {
         color: function () {
             this.throttledColor()
         }
    },
    methods: {
        // update color every 500 milliseconds
        throttledColor: throttle(function () {
            this.conf.default = this.color
        }, 500)
    }

}

See this stackblitz to see a comparison of how many times the color is getting updated standard vs throttle.


text:
Q: Matlab - modify class attributes i'm trying to simulate a car's position with Matlab.
So far I have created a class representing the car with public attributes position (obj.position), speed (obj.vIst) and delta (obj.delat). Delta represents the time steps.
When I let my car drive I want to change it's position by adding the actual speed. Unfortunately it isn't working...
The code
fprintf(' \n Position: %4.0f',  obj.position );
obj.position = obj.position + obj.vIst*obj.delta;
fprintf(' \n Position: %4.0f',  obj.position );

creates the following output:
Position: 1000
Position:

What am I doing wrong? Has this anything to do with a handle or value class? I'm pretty sure my question is stupid but im just starting to work with Matlab so i'm needing some help here...
Thanks very much in advance.
The class definition:
classdef myCar < handle
    %UNTITLED Summary of this class goes here
    %   Detailed explanation goes here

properties
    id;
    typ;
    startzeit;
    vStart;
    posStart;

    position;
    vIst;
    vSoll;
    vMax;
    laenge;
    aktiv = false;
    vMaxStrecke;

    POI;
    vPOI;
    POIaktiv = false;

    bremswegZumPOI;
    bremsverzoegerung = 0.8;

    aGeg = [];
    vGeg = [];
    delta;

    zeitLinie = [];
    vIstLinie = [];
    posLinie= [];
    vSollLinie = [];
end

methods
    function drive(obj, time)
            fprintf(' \n in fahre: %4.0f',  obj.position );
            obj.position = obj.position + obj.vIst*obj.delta;
            fprintf(' \n in fahre: %4.0f',  obj.position );

            obj.zeitLinie = [obj.zeitLinie, time];
            obj.vIstLinie = [obj.vIstLinie, obj.vIst];
    end
end
end

The Method drive is called from another script managing several cars.


text:
Q: properly accessing images within a
* I currently have:

in my HTML
and I am attempting to add button like functionality to the thumbnails with this javascript
var isMousedOver = [
false,
false,
false,
false
];

function init()
{
   DoStuffWithThumbs();
}

this.onload = init();

function DoStuffWithThumbs()
{
   var thumbs = document.getElementById("thumbImages");
   var itemsUL = thumbs.getElementsByTagName("ul");
   var itemsLI = itemsUL.item(0).getElementsByTagName("li");
   for (var i = 0; i < itemsLI.length; ++i)
   {
      var curThumb = itemsLI[i];
      curThumb.onclick = DoStuff(i);
      curThumb.onmouseover = MouseOver(i);
      curThumb.onmouseout = MouseOut(i);
   }
}

function MouseOver(val)
{
   isMousedOver[val] = true;
}

function MouseOut(val)
{
   isMousedOver[val] = false;
}

function DoStuff(val)
{
   if(isMousedOver[val] == true)
   {
       //stuff is done here ( I know the stuff in question is working)
   }
}

However currently I am getting no visible response from this at all on the page when I have separately tested the result itself ( simply flipping an image and changing some text on the page based on another array). Which leads me to believe I am accessing the elements incorrectly. I am new to using Javascript alongside html so forgive me if I have made some grave error. Am I accessing my elements properly? or is this entirely the wrong way to go about accessing them/using onmouseover/onmouseout?

A: You are invoking functions instead of assigning them as handlers. So you need to fix that first. To fix it according to your current approach, each function you invoke would need to return a function that references the current i value.
But instead of tracking the mouseover state in an Array, it would be simpler to track it on the DOM element itself by adding a property.
function DoStuffWithThumbs() {
   var thumbs = document.getElementById("thumbImages"),
       itemsUL = thumbs.getElementsByTagName("ul"),
       itemsLI = itemsUL.item(0).getElementsByTagName("li");

   for (var i = 0; i < itemsLI.length; ++i) {
      itemsLI[i].onclick = DoStuff;
      itemsLI[i].onmouseover = MouseOver;
      itemsLI[i].onmouseout = MouseOut;
   }
}

function MouseOver(val) {
   this._over = true;
}

function MouseOut(val) {
   this._over = false;
}

function DoStuff(val) {
   if(this._over === true) {
       // do your stuff
   }
}


text:
Q: How to disable the Home tap gesture on home page but not on other pages in Xamarin.Forms? Xamarin.Forms implementation.
I have home button on all pages and have implemented it in one file and render it on all pages.
Now, my requirement is if the user is on home page and if he taps home icon nothing should happen i.e should not navigate to home page by flicking the page(this is the current implementation).
I tried if else to my logic but may be that is not how it has to be. (i.e)
if
{
  //user on home page. Do nothing.
}
else
{
  //navigate to Home.
}

Here is my image with tap gesture command
<Image Grid.Row="0" Grid.Column="0" Source="OneD_Icon_Small.png" HorizontalOptions="StartAndExpand" Margin="5,5,0,0">
    <Image.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding HomeCommand}" NumberOfTapsRequired="1" />
    </Image.GestureRecognizers>
</Image>

A:
in each contentPage.xaml

set the name of contentPage and pass it as Parameter of CommandParameter
For example in MainPage
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App12"
             x:Name="myPage"
             x:Class="App12.MainPage">
    <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" >

        <Image Source="OneD_Icon_Small.png" HorizontalOptions="StartAndExpand" Margin="5,5,0,0">
            <Image.GestureRecognizers>
                <TapGestureRecognizer Command="{Binding HomeCommand}"  CommandParameter="{Binding .,Source={x:Reference myPage}}" NumberOfTapsRequired="1" />
            </Image.GestureRecognizers>
        </Image>
    </StackLayout>

</ContentPage>

And in the ViewModel
public class TapViewModel : INotifyPropertyChanged
 {
   ICommand homeCommand;
   public TapViewModel()
   {
      // configure the TapCommand with a method
      homeCommand = new Command(OnTapped);
   }
   public ICommand HomeCommand
   {
     get { return homeCommand; }
   }

   public event PropertyChangedEventHandler PropertyChanged;

   void OnTapped(object s)
   {
     var page = s as ContentPage;

     if (page.GetType() == typeof(MainPage))
     {
        //user on home page. Do nothing.
     }

     else
     {
        //navigate to Home.
     }

    }

}

Note:  object s is the contentPage ,and you can do something you want.


text:
Q: Listing the files in a directory of the current JAR file I am making a game in JAVA where I want to come up with a list of files in a certain directory in my jar so I can make sure to have a list of those classes to be used in the game.
For example say in my jar I have a directory
mtd/entity/creep/

I want to get a list of all the .class files in that directory using java code from another class in the jar.
What is the best code to do so?

A: Old java1.4 code, but that would give you the idea:
private static List getClassesFromJARFile(String jar, String packageName) throws Error
{
    final List classes = new ArrayList();
    JarInputStream jarFile = null;
    try
    {
        jarFile = new JarInputStream(new FileInputStream(jar));
        JarEntry jarEntry;
        do
        {
            try
            {
                jarEntry = jarFile.getNextJarEntry();
            }
            catch(IOException ioe)
            {
                throw new CCException.Error("Unable to get next jar entry from jar file '"+jar+"'", ioe);
            }
            if (jarEntry != null)
            {
                extractClassFromJar(jar, packageName, classes, jarEntry);
            }
        } while (jarEntry != null);
        closeJarFile(jarFile);
    }
    catch(IOException ioe)
    {
        throw new CCException.Error("Unable to get Jar input stream from '"+jar+"'", ioe);
    }
    finally
    {
        closeJarFile(jarFile);
    }
   return classes;
}
private static void extractClassFromJar(final String jar, final String packageName, final List classes, JarEntry jarEntry) throws Error
{
    String className = jarEntry.getName();
    if (className.endsWith(".class"))
    {
        className = className.substring(0, className.length() - ".class".length());
        if (className.startsWith(packageName))
        {
            try
            {
                classes.add(Class.forName(className.replace('/', '.')));
            } catch (ClassNotFoundException cnfe)
            {
                throw new CCException.Error("unable to find class named " + className.replace('/', '.') + "' within jar '" + jar + "'", cnfe);
            }
        }
    }
}
private static void closeJarFile(final JarInputStream jarFile)
{
    if(jarFile != null)
    {
        try
        {
            jarFile.close();
        }
        catch(IOException ioe)
        {
            mockAction();
        }
    }
}

A: Probably the best approach is to list the classes at compile time.
There is a fragile runtime approach. Take you Class (MyClass.class of this.getClass()). Call getProtectionDomain. Call getCodeSource. Call getLocation. Call openConnection. (Alternatively open a resource.) Cast to JarURLConnection. Call getJarFile. Call entries. Iterate through checking getName. I really do not recommend this approach.

A: 10 years after the question, I propose an another way to do the job:
private static void listFilesFromDirectoryInsideAJar(String pathToJar,String directory,String extension) {
        try {
            JarFile jarFile = new JarFile(pathToJar);
            Enumeration<JarEntry> e = jarFile.entries();
            while (e.hasMoreElements()) {
                JarEntry candidat = e.nextElement();
                if (candidat.getName().startsWith(directory) &&
                    candidat.getName().endsWith(extension))
                    LOG.info(candidat.getName());
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(),e);
        }
    }

A: It's not possible, as Java doesn't provide direct access to the jar file the classes are loaded from. You could try to parse the java.class.path system property to find it, but that wouldn't work under all circumstances. Or you could restrict on where the jar file has to reside, or provide the list of the classes in a different way (for example via the manifest file).

A: Remember that JAR files are just ZIP files renamed, and it's very easy to read the contents of ZIP files in Java:
    File jarName = null;
    try
    {
        jarName = new File (Dir.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    try
    {
      ZipFile zf=new ZipFile(jarName.getAbsoluteFile());
      Enumeration e=zf.entries();
      while (e.hasMoreElements())
      {
          ZipEntry ze=(ZipEntry)e.nextElement();
          System.out.println(ze.getName());
      }
      zf.close();
   } catch (IOException e)
   {
      e.printStackTrace();
   }


text:
Q: org.springframework.expression.spel.SpelEvaluationException: EL1027E:(pos 4): Indexing into type 'com.test.domain.Employee' is not supported I am developing an Spring Roo application and while displaying the Objects in list (in list.jspx), I am getting all the properties of the referenced object. For example:
@RooJavaBean
@RooToString
@RooJpaActiveRecord

public class Employee {
    @NotNull
    private String empName;
    @ManyToOne
    private Department department;
}

And the Department
@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class Department {
    @NotNull
    private String deptName;

   @NotNull
   private String deptLocation;
}

Now after building a web project in roo, and adding department entries and employee entries, I am getting an ugly looking table in employee list. All the properties from Department entity are being displayed, where as my intention was to show the Department Name (deptName).
Tried to change in list.jspx as follows:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:page="urn:jsptagdir:/WEB-INF/tags/form" xmlns:table="urn:jsptagdir:/WEB-INF/tags/form/fields" version="2.0">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <jsp:output omit-xml-declaration="yes"/>
    <page:list id="pl_com_test_domain_Employee" items="${employees}" z="user-managed">
        <table:table data="${employees}" id="l_com_test_domain_Employee" path="/employees" z="user-managed">
            <table:column id="c_com_test_domain_Employee_Department" property="department.deptName" z="user-managed"/>
            <table:column id="c_com_test_domain_Employee__DeptLocation" property="deptLocation" z="user-managed"/>
        </table:table>
    </page:list>

The error:
org.springframework.expression.spel.SpelEvaluationException: EL1027E:(pos 4): Indexing into type 'com.test.domain.Employee' is not supported
    at org.springframework.expression.spel.ast.Indexer$PropertyIndexingValueRef.getValue(Indexer.java:208)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:81)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:98)
    at org.springframework.web.servlet.tags.EvalTag.doEndTag(EvalTag.java:125)
    at org.apache.jsp.tag.webform.fields.table_tagx._jspx_meth_spring_005feval_005f4(table_tagx.java:1390)
    at org.apache.jsp.tag.webform.fields.table_tagx._jspx_meth_c_005fset_005f14(table_tagx.java:1357)
    at org.apache.jsp.tag.webform.fields.table_tagx._jspx_meth_c_005fotherwise_005f0(table_tagx.java:1324)
    at org.apache.jsp.tag.webform.fields.table_tagx._jspx_meth_c_005fchoose_005f0(table_tagx.java:1115)
    at org.apache.jsp.tag.webform.fields.table_tagx._jspx_meth_c_005fforTokens_005f1(table_tagx.java:1015)
    at org.apache.jsp.tag.webform.fields.table_tagx._jspx_meth_c_005fforEach_005f0(table_tagx.java:949)
    at org.apache.jsp.tag.webform.fields.table_tagx._jspx_meth_c_005fif_005f0(table_tagx.java:342)
    at org.apache.jsp.tag.webform.fields.table_tagx.doTag(table_tagx.java:269)
    at org.apache.jsp.WEB_002dINF.views.autoscalingtasks.list_jspx._jspx_meth_table_005ftable_005f0(list_jspx.java:126)
    at org.apache.jsp.WEB_002dINF.views.autoscalingtasks.list_jspx.access$0(list_jspx.java:108)
    at org.apache.jsp.WEB_002dINF.views.autoscalingtasks.list_jspx$Helper.invoke0(list_jspx.java:225)
    at org.apache.jsp.WEB_002dINF.views.autoscalingtasks.list_jspx$Helper.invoke(list_jspx.java:256)
    at org.apache.jsp.tag.webform.list_tagx._jspx_meth_c_005fwhen_005f0(list_tagx.java:444)
    at org.apache.jsp.tag.webform.list_tagx._jspx_meth_c_005fchoose_005f0(list_tagx.java:412)
    at org.apache.jsp.tag.webform.list_tagx.access$0(list_tagx.java:402)
    at org.apache.jsp.tag.webform.list_tagx$Helper.invoke0(list_tagx.java:526)
    at org.apache.jsp.tag.webform.list_tagx$Helper.invoke(list_tagx.java:544)
    at org.apache.jsp.tag.webutil.panel_tagx._jspx_meth_c_005fif_005f0(panel_tagx.java:193)
    at org.apache.jsp.tag.webutil.panel_tagx.doTag(panel_tagx.java:139)
    at org.apache.jsp.tag.webform.list_tagx._jspx_meth_util_005fpanel_005f0(list_tagx.java:397)
    at org.apache.jsp.tag.webform.list_tagx._jspx_meth_c_005fif_005f0(list_tagx.java:221)
    at org.apache.jsp.tag.webform.list_tagx.doTag(list_tagx.java:185)
    at org.apache.jsp.WEB_002dINF.views.autoscalingtasks.list_jspx._jspx_meth_page_005flist_005f0(list_jspx.java:103)
    at org.apache.jsp.WEB_002dINF.views.autoscalingtasks.list_jspx._jspService(list_jspx.java:72)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:605)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:544)
    at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:954)
    at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:684)
    at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:678)
    at org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:103)
    at org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:96)
    at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:44)
    at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
    at org.apache.tiles.renderer.impl.ChainedDelegateAttributeRenderer.write(ChainedDelegateAttributeRenderer.java:76)
    at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:336)
    at org.apache.tiles.template.InsertAttributeModel.renderAttribute(InsertAttributeModel.java:210)
    at org.apache.tiles.template.InsertAttributeModel.end(InsertAttributeModel.java:126)
    at org.apache.tiles.jsp.taglib.InsertAttributeTag.doTag(InsertAttributeTag.java:311)
    at org.apache.jsp.WEB_002dINF.layouts.asg_005flist_005fbody_jspx._jspx_meth_tiles_005finsertAttribute_005f2(asg_005flist_005fbody_jspx.java:234)
    at org.apache.jsp.WEB_002dINF.layouts.asg_005flist_005fbody_jspx._jspService(asg_005flist_005fbody_jspx.java:96)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:241)
    at org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:222)
    at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:44)
    at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:690)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:644)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:627)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:321)
    at org.springframework.web.servlet.view.tiles2.TilesView.renderMergedOutputModel(TilesView.java:124)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:180)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

What should I do?

A: I got the answer and here I am sharing it:
To avoid above error, I had changed the table.tagx as follows:
table.tagx: line-84 :
Replace this:
<spring:eval expression="item[column]" htmlEscape="false" />

with this:
<spring:eval expression="item.${column}"  htmlEscape="false" />

table.tagx: line-95 :
Replace this:
<spring:eval expression="item[typeIdFieldName]"/>

with this:
<c:set var="itemId"><spring:eval expression="item.${typeIdFieldName}"/></c:set>

Now you can access the properties from an object like this :
 <page:list id="pl_com_test_domain_Employee" items="${employees}" z="user-managed">
    <table:table data="${employees}" id="l_com_test_domain_Employee" path="/employees" z="user-managed">
        <table:column id="c_com_test_domain_Employee_Department"  property="department.deptName" z="user-managed"/>
        <table:column id="c_com_test_domain_Employee_DeptLocation" property="deptLocation" z="user-managed"/>
    </table:table>
</page:list>

Thank you!!!
Chandan

A: Just for the googlers of the future:
Spring roo has its own table taglib, which requires the typeIdFieldName attribute! This typeIdFieldName defaults to id, if you didn't gave that.
About your annotations deep in your domain model, it doesn't know anything!
This, if the identifier property of your listed entity isn't id, you need to give it with this typeIdFieldName field manually. For example:
<table:table data="${exampleusers}" typeIdFieldName="userId" id="l_com_project_Example_ExampleUser" path="/exampleUserList">

In my case, the identifier of the exampleUser entity was userId, instead of the common id. It costed me around 2 hours of debugging... good luck!


text:
Q: Same string with different translation I have one string that can be translated in varius part of my code in two different way.
Now if Use django-admin makemessages -l it
I get in django.po this:
#: pingapi/ping.py:17 pingapi/nots.py:10
msgid "may"
msgstr "maggio"

But I would want two different translation:
#: pingapi/ping.py:17
msgid "may"
msgstr "posso"

#: pingapi/nots.py:10
msgid "may"
msgstr "maggio"

If I run django-admin compilemessage with the translation file posted up, I get:
Error: errors happened while running msgmerge
 error 'duplicate message definition'

Any Hints? I'm using Django.

A: You can use gettext's context for that. Django has added support for that in 1.3 release (in code) and 1.4 (for templates), see https://docs.djangoproject.com/en/dev/topics/i18n/translation/#contextual-markers
Update:
For example following code:
from django.utils.translation import pgettext, ugettext

month = pgettext("month name", "May")
month = pgettext("fifth month", "May")
month = ugettext("May")

Translates to:
#: foo/views.py:4
msgctxt "month name"
msgid "May"
msgstr ""

#: foo/views.py:5
msgctxt "fifth month"
msgid "May"
msgstr ""

#: foo/views.py:6
msgid "May"
msgstr ""

Each message being different and can be translated differently.

A: In case you need also to pass the variable to your front-end
views.py
from django.utils.translation import pgettext
from django.shortcuts import render

def index(request):

our_masculine = pgettext("masculine", "Our")
our_feminine = pgettext("feminine", "Our")

return render(request,'index.html', {'our_masculine': our_masculine,'our_feminine': our_feminine })

django.po
#: index/views.py:16
msgctxt "masculine"
msgid "Our"
msgstr "I nostri"

#: index/views.py:17
msgctxt "feminine"
msgid "Our"
msgstr "Le nostre"

index.html
<h4>{{ our_masculine }}</h4>


text:
Q: Bash scripts and file conflicts and thanks in advance for any advice.
I'm having trouble finding an answer to my question elsewhere. I've been working on a script that will watch a directory, and then move files to various other directories based on certain criteria. Here's what I've got so far:
cd `dirname $0`/watch
  while true
  do
    inotifywait -e moved_to ../watch --format "%f" | while read FILE
    do
      if $(echo "$FILE" | grep -q ".jpg"); then
          cp "./$FILE" "../images/"
      elif $(echo "$FILE" | grep -q ".mp4"); then
          cp "./$FILE" "../videos/"
      elif $(echo "$FILE" | grep -q ".mp3"); then
          cp "./$FILE" "../audio/"
      else
          cp "./$FILE" "../other/"
    fi
    done
  done

This script works as it should if one file at a time is moved into ./watch, but if multiple files are moved, only the first of them gets moved from ./watch to the corresponding directory. Here's another idea I have, but am unsure how this would handle problems such as trying to sort/move incomplete files:
while true
do
inotifywait -e moved_to `dirname $0`/watch && /bin/bash `dirname $0`/autotorrent.sh
done

which will launch the following script when files are added:
cd `dirname $0`/watch
for i in *; do
    if $(echo "$FILE" | grep -q ".jpg"); then
        cp "./$FILE" "../images/"
    elif $(echo "$FILE" | grep -q ".mp4"); then
        cp "./$FILE" "../videos/"
    elif $(echo "$FILE" | grep -q ".mp3"); then
        cp "./$FILE" "../audio/"
    else
        cp "./$FILE" "../other/"
    fi
done

I'm just not sure how best to handle moving multiple files which may or may not take considerable time to copy. I've got several ideas, but none of them really seem to be the robust solution I'm looking for.
Thanks again to anyone who has some advice for me

A: Since your files could be Large, the cp takes non-zero time. During this time, you probably miss notifications. Try tossing all the cp commands into the background by appending a & to each. That will get you back to the inotifywait quicker.
Also, you could eliminate a bunch of calls to grep by doing:
    j=${i##*.}
    case "$j" in
        jpg) cp $i ../images/ & ;;
        mp4) cp $i ../videos/ & ;;
        mp3) cp $i ../audio/ & ;;
        *) cp $i ../other/& ;;
    esac

Although I don't see why you want to keep a copy of each file both directories, why not use mv instead of cp?
@zpawwn: On further man inotifywait reading, I found --monitor, so, your script should be:
cd `dirname $0`/watch
inotifywait -e moved_to ../watch --format "%f" --monitor | while read FILE
do
    j="${FILE##*.}"
        case "$j" in
            jpg) mv "$FILE" ../images/ & ;;
            mp4) mv "$FILE" ../videos/ & ;;
            mp3) mv "$FILE" ../audio/ & ;;
            *) mv "$FILE" ../other/& ;;
        esac
 done

Let inotifywait manage the file event queueing, and spit out filenames as it notices them. The old way had inotifywait finding ONE new file and exiting, letting your cp stuff run, then restart watching. The other files (that arrived at the same time) are no longer new (they were there when the 2nd inotifywait started).


text:
Q: Flight path for SSTO Is there an optimal altitude profile for an SSTO spaceplane? I'm guessing it might depend on the mass and lift profiles, but I'm looking for a general outline, if possible.
By altitude profile, I'm thinking altitude vs time vs speed to get an SSTO into orbit.

A: With the new aerodynamics system it is quite hard to tell, because the ideal path depends on the aerodynamic drag, lifting surface to mass ratio and thrust to mass ratio. So you should experiment with your craft to find the ideal ascend profile.
But in general you should try to get to an altitude above 10km as fast as you can, which means a climb angle of about 40°. Oh, and don't forget to retract your landing gear.
When you reached the middle atmosphere (between 10km-20km) you want to gain as much horizontal speed as you can from your air-breathing engines as long as they can still get intake air, which usually means a very flat angle between 10° and 20°. The limit how flat you can go depends on the maximum speed the craft can still withstand aerodynamically without losing any parts. Monitor the thrust of your jet engines (right-click) and switch to rocket engines (closed-cycle mode with RAPIERs) as soon as their thrust becomes negligible.
During the coast-phase to the apoapsis, make sure your craft stays pointed prograde. There isn't much drag anymore above 40km, but when your craft rotates so that the wings are perpendicular to the heading, you will still lose considerable speed even in the upper atmosphere.

A: The initial climb and acceleration phase are similar - first climb to 10,000 ASAP (not to waste any fuel on prolonged climb), then accelerate to about 1000m/s in a mostly horizontal, possibly somewhat climbing flight.
Then comes the decision depending on the construction of your SSTO. There are two fundamental "schools" of making them:
"Fish jump" - your SSTO has an "intermediate engine(s)" - maybe a set of Rapiers, maybe Airspike, or a pair of Reliants, people have even used Poodle or Rhino. An engine of reasonable ISp and a very good thrust. You climb sharply up, 30-45 degrees, even more if you can pull it off - enough to get your apoapsis above the atmosphere. You may or may not use the intermediate engine during the climb - you may fly entirely unpowered towards the upper atmosphere if your jets gave you enough momentum. Once near apoapsis, you rapidly accelerate until your orbit is circularized, then you can switch to more efficient (lower thrust) engines.
"Arduous climb" - this one uses only LV-N "NERV" engines in conjunction with turbojets, maybe one small extra engine (aerospike? Rapier?) to get a little initial burst, but often not even that. Your climb profile with the jets is fairly flat, about 10 degrees, maybe less. Once they start losing power (your speed stops climbing or climbs very slowly) activate the nukes and keep a very shallow ascent profile - around 5 degrees, or less. As you gain speed, your lift increases allowing you to climb higher, and your gravitational drag drops as you approach orbital speed. Still, it's a long, slow process as the nukes provide little thrust and need to accelerate you by a good 1200m/s. Try to keep "time to Apoapsis" constant, at about half a minute. Once you reach orbital speed, your apoapsis will rise rapidly. Bring it to some 75-80km (it will drop to about 70km during the climb due to drag) and finish circularizing near the upper edge of the atmosphere - there will be very little speed to gain to bring the periapsis up; something of order of 80m/s.
The latter tends to get a good payload ratio or yield good remaining delta-V while in orbit thanks to relatively light build, but requires the airplane to be very streamlined, little drag, good balance. It's good for passenger flights or bringing small satellites into orbit, but it's hard to execute with anything bigger as the drag will overpower the limited thrust of LV-N.
The former scales well with size of the plane - it's difficult to build a small "fish jump SSTO" as the required TWR necessitates heavy intermediate engines and large fuel tanks to power them, but while the payload fraction will be worse, and remaining delta-V lower, the payload total mass can be better as you can afford to lift large, draggy MK3 parts and you can build true monsters of spaceplanes.

A: if you have a substantial enough thrust to weight ratio with your air breathing engines alone, and i mean a REALLY substantial thrust to weight ratio, point strait up. a few moments after you engines start to lose thrusting power due to lack of oxygen, if your apoapsis isn't already above the atmo by a large enough margin that shutting your engines down won't reduce the apoapsis to below atmo byn the time you reach it, swap to your oxidized engines until that predicted apoapsis altitude is met. Then function like a normal rocket and set your maneuver node


text:
Q: How to add an extension to all files via terminal I would like to add the .zip extension to all files. I tried this, however it does not work:
ls | awk '{print $1 " " $1".zip"}' | xargs mv -f

A: Searching - few links:

*

*Recursively add file extension to all files - Stack Overflow

*Add file extension to files with bash - Stack Overflow
man rename:
NAME
       rename - renames multiple files

SYNOPSIS
       rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

DESCRIPTION
       "rename" renames the filenames supplied according to the rule specified as
       the first argument.  The perlexpr argument is a Perl expression which is
       expected to modify the $_ string in Perl for at least some of the filenames
       specified. If a given filename is not modified by the expression, it will not
       be renamed.  If no filenames are given on the command line, filenames will be
       read via standard input...

man wiki: http://en.wikipedia.org/wiki/Man_page

A: A very simple way to do that is :
if you want to keep current extension:
for i in *; do mv $i ${i}.zip; done

if you want to replace current extension:
for i in *; do mv $i ${i%.*}.zip; done

A: for f in * ; do
  mv "$f" "$f.zip"
done

A: rename 's/$/\.zip/' *

Don't use xargs for that!

A: This should do the trick:
mmv "./*" "./#1.zip"

(Although I have no idea why you would want to do this...)


text:
Q: Consider the subspaces U = span{2 + x, 1 − x^2}, and W = span{−1 + x + x^2 , −x + x^2} of P2(R). Find U ∩ W The question:
Consider the subspaces U = span{2 + x, 1 − x^2},
and W = span{−1 + x + x^2, −x + x^2} of
P2(R).
a) Find U ∩ W:
Theres no examples in my textbook of how to solve any of this so I have no clue what I'm doing. By reading around heres what I have so far:
Let a,b,c,d ∈ R.
a(2 + x) + b(1 − x^2) = c(−1 + x + x^2) + d(−x + x^2)
we can simplify this to be:
(-b)x^2 + (a)x + (2a+b) = (c+d)x^2 + (c-d)x + (-c)
we can see that:
-b = c + d,
a = c - d,
2a + b = -c
I eventually found b,c,d in terms of a:
b = -5a,
c = 3a,
d = 2a
What do I do now? How do I show U ∩ W?

A: If your computation is correct, i.e. $b = -5a, c = 3a, d = 2a$ holds, then you simply insert the result in the description of $U$ or $W$. That is, using the description of $U$, the intersection $U \cap W$ can be expressed as the set
$$ \{ a(2 + x) + -5a(1 − x^2) | a \in \mathbb{R} \} = \{ a(5x^2 + x - 3) | a \in \mathbb{R} \} $$
or, equivalently, using the description of $W$
$$ \{ c(−1 + x + x^2) + d(−x + x^2) \} = \{ 3a(−1 + x + x^2) + 2a(−x + x^2) | a \in \mathbb{R} \} $$
which is again the same descrption as the one given above, i.e.
$$ \{ a (5x^2 + x - 3 ) | a \in \mathbb{R} \}  \ . $$

A: You have shown that any element in $U∩W$ if and only if is of form $5ax^2+ax-3a$. You could conclude that $U∩W=\{5ax^2+ax-3a:a\in\mathbb{R}\}$


text:
Q: Ansible doesn't pick up group_vars without loading it manually In my local.yml I'm able to run the playbook and reference variables within group_vars/all however I'm not able to access variables within group_vars/phl-stage. Let's assume the following.
ansible-playbook -i phl-stage site.yml

I have a variable, let's call it deploy_path that's different for each environment. I place the variable within group_vars/< environment name >. If I include the file group_vars/phl-stage within vars_files it works but I would've thought the group file would be automatically loaded?
site.yml
- include: local.yml

local.yml
- hosts: 127.0.0.1
  connection: local

  vars_files:
    - "group_vars/perlservers"
    - "group_vars/deploy_list"

group_vars/phl-stage
[webservers]
phl-web1
phl-web2

[perlservers]
phl-perl1
phl-perl2

[phl-stage:children]
webservers
perlservers

Directory structure:
group_vars
  all
  phl-stage
  phl-prod
site.yml
local.yml

A: You're confusing the structure a bit.

*

*The group_vars directory contains files for each hostgroup defined in your inventory file. The files define variables that member hosts can use.

*The inventory file doesn't reside in the group_vars dir, it should be outside.

*Only hosts that are members of a group can use its variables, so unless you put 127.0.0.1 in a group, it won't be able to use any group_vars beside those defined in group_vars/all.

What you want is this dir structure:
group_vars/
   all
   perlservers
   phl-stage
hosts
site.yml
local.yml

Your hosts file should look like this, assuming 127.0.0.1 is just a staging server and not perl or web server:
[webservers]
phl-web1
phl-web2

[perlservers]
phl-perl1
phl-perl2

[phl-stage]
127.0.0.1

[phl-stage:children]
webservers
perlservers

So you define which hosts belong to which group in the inventory, and then for each group you define variables in its group_vars file.