text:
Q: How to bind a Feign Client url from the YAML when the url is located at a index of a List Hello new to Java and Springboot.  I currently have my integrations set up in this way.  It needs to stay as a List so I could add the clients in one place instead of two.
application.yaml
lr:
  main-product-client.url: http://localhost:8081
  product-client-properties:
    - type: productone
      use-proxy: false
      url: someUrl
    - type: producttwo
      use-proxy: true
      url: someUrl
    - type: productthree
      use-proxy: true
      url: someUrl

ProductOneClient.java
@FeignClient(
    value = "productOneClient",
    url = "${lr.product-client-properties(0).url}",
    configuration = ProductOneClient.ProductOneClientConfig.class)
public interface ProductOneClient {
...

This fails to read the placeholder for ${lr.product-client-properties(0).url}. What's the proper way to retrieve the integration url for my ProductOne client? Thank you for your time!

A: Can you change your yaml file to be like this?:
lr:
  main-product-client.url: http://localhost:8081
  product-client-properties:
    client-one:
      type: productone
      use-proxy: false
      url: someUrl
    client-two:
      type: producttwo
      use-proxy: true
      url: someUrl
    client-three:
      type: productthree
      use-proxy: true
      url: someUrl

and use in @Value like this:
@Value( "${lr.product-client-properties.client-one.url}")


text:
Q: TypeError: destroy() takes 0 positional arguments but 1 was given That is the error that I get when I try to remove a sprite from it's list so that it is erased from the screen. I am able to bring up that sprite by pressing a key but this happens when I try to remove it.
I was kind of winging my own code with the help of Purpongie's collision detection video.
For now I will show you mine with most unrelated things omitted:
Main.py
while True:
    process(Select)
    H2Ps.destroy()
    H2Ps.List.draw(screen)

Classes.py
class BaseClass(pygame.sprite.Sprite):
allsprites = pygame.sprite.Group()
def __init__(self, x, y, image_string):

    pygame.sprite.Sprite.__init__(self)
    BaseClass.allsprites.add(self)

    self.image = pygame.image.load(image_string)

    self.rect = self.image.get_rect()
    self.rect.x = x
    self.rect.y = y

def destroy(self, ClassName):
    ClassName.List.remove(self)
    BaseClass.allsprites.remove(self)
    del self

class H2Ps(BaseClass):
List = pygame.sprite.Group()

def __init__ (self,x,y,image_string):
    BaseClass.__init__(self,x,y,image_string)
    H2Ps.List.add(self)

@staticmethod
def destroy():
    for test in H2Ps.List:
        if (pygame.key.get_pressed()[pygame.K_ESCAPE]):
            test.destroy(H2Ps)

Process.py
def process(Select):
    if Select.rect.collidepoint(370,400): #How to play
        if keys[pygame.K_RETURN]:
            HowToPlay = H2Ps(0,0,"Images/How To Play.png")

I believe that the error is pointing out that there is something wrong with test.destroy(H2Ps) in Classes.py. I have run it earlier and it seemed to have worked but now I am unsure of what I may have changed that would break it. I would greatly appreciate some solutions.

A: You have overridden destroy(self, ClassName) in BaseClass with your destroy() static method in H2Ps.  You need to change the name of one of them!
So, when you call H2Ps.destroy() in main.py, you are calling your static method, this then loops through List:
for test in H2Ps.List:
    if (pygame.key.get_pressed()[pygame.K_ESCAPE]):
        test.destroy(H2Ps)

test here is an H2Ps object, and when you do test.destroy(H2Ps), so are still calling the static method defined on H2Ps, not the method destroy(self, ClassName) on BaseClass.
Unlike in some other languages, methods can be differentiated by their arguments, so in Java for example, the compiler can tell the difference between these methods:
public void destroy(String className);
public static void destroy();

Python doesn't work like that, and chooses which method to call by name only.  When you override destroy in H2Ps you are replacing the definition of destroy(self, ClassName) with destroy().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why we can't find dynamically allocated array size? So, I've developed some applications in C++, so I'm not that new in the C++ world, but I can't figure out why we can't find the size of a dynamically allocated array in C++.
In particular, looking at the documentation, if I write:
delete[] array;

it will delete all the elements in the array (allocated on the heap)... now, in order to delete it, there must be something wrote on the memory to tell the deallocator "how many bytes compose that array"... and therefore the question, why can't we also have that information?


text:
Q: How to prove this partial derivative? Consider $u:\mathbf{R}\times\omega\rightarrow\mathbf{R}$, where $\omega\subset\mathbf{R}^{n-1}$ is a bounded domain. For each $y\in\omega$ and each $\lambda>0$, consider $y^\lambda=(x,2\lambda-y_1,y_2,...,y_{n-1})$ the reflection of $y$ in the plane $\{y_1=\lambda\}$. Suppose that
$$w_\lambda(x,y)=u(x,y)-u(x,y^\lambda)<0.$$
If $y_1>0$ then
$$\frac{\partial u}{\partial y_1}\leq0.$$

A: Claim: If $w_\lambda(x,y)\leq0$, then $\frac{\partial u}{\partial y_1}(x,\lambda,y_2,\dots,y_n)\leq0$.
Suppose the theorem is not true, that is, $w_\lambda(x,y)\leq0$ and $\frac{\partial u}{\partial y_1}(\bar x,\bar y)=\ell>0$ for some $(\bar x,\bar y)\in \mathbb R^n$. Then, by the definition of the partial derivative, $$\ell=\lim_{\delta\to0} \frac{u(\bar x,\bar y+\delta)-u(\bar x,\bar y-\delta)}{2\delta},$$ (where $\bar y+\delta=(\bar y_1+\delta,\bar y_2,\dots,\bar y_{n-1})$ above). Thus we have for some $\delta$ such that $\epsilon<\ell$, $$0<2\delta(\ell-\epsilon)<u(\bar x,\bar y+\delta)-u(\bar x,\bar y-\delta)=w_{\bar y_1}(\bar x,\bar y+\delta).$$
This is a contradiction, so for any $\lambda$ such that $w_\lambda(x,y)\leq0$, we have $\frac{\partial u}{\partial y_1}(x,\lambda,y_2,\dots,y_n)\leq0$. Note that this conclusion is not true for points $y_1\neq\lambda$: If $$u(x,y_1)=\frac{\lambda-y_1}{(y_1-\lambda)^2+1}\Rightarrow\frac{\partial u}{\partial y_1}=\frac{(y_1-\lambda)^2-1}{(1+(y_1-\lambda)^2)^2},$$ with $\omega=\mathbb R$ and $\lambda>0$, then $w_\lambda(x,y_1)=(\lambda-y_1)\frac2{(y_1-\lambda)^2+1}<0$ if $y_1>\lambda$, but $\frac{\partial u}{\partial y_1}>0$ for $y_1>\lambda+1>0$.
Please tell me if I'm missing anything, but it seems as if the problem is a lot simpler than it sounds at face value (the multidimensional stuff doesn't matter at all in this proof). I'm also assuming that your constraint $w_\lambda(x,y)\leq0$ only applies for $y_1\geq\lambda\Rightarrow y_1\geq y_1^\lambda$, because $w_\lambda(x,y)=-w_\lambda(x,y^\lambda)$, so the constraint would make no sense otherwise unless $w_\lambda(x,y)=0$ everywhere.

A: Is the first inequality(apparently there must be $\leq$ instead <) true for each $\lambda\in\ (0,sup_\omega\ y_1)$ or just for certain value of $\lambda$ ? If this is true for each value of $\lambda$ then it seems to me that the second inequality turns to equality

A: One may forget about the variables $x$, $y_2$, $\ldots$, $y_{n-1}$. So we are given an open interval $\Omega\subset{\mathbb R}$ and a differentiable function $$u:\quad \Omega\to{\mathbb R},\qquad y\mapsto u(y)\ .$$
For each $\lambda\in \Omega$ the expression
$$w_\lambda(y):=u(y)-u(2\lambda -y)$$
is defined in a neighborhood of $y=\lambda$, and it is assumed that $w_\lambda(y)\leq0$ wherever the left side makes sense.
I claim that under these circumstances the function $u$ is constant in $\Omega$.
Proof. Consider a fixed $y_0\in\Omega$, and write $y=y_0+h$ for small $|h|$. Choose $\lambda:=y_0$. Then
$$w_\lambda(y)=u(y_0+h)-u(y_0-h)=\bigl(2u'(y_0)+o(1)\bigr) h\qquad (h\to 0)\ .$$
As the left side is $\leq0$ for all $h$ it follows that necessarily $u'(y_0)=0$, and since this is true for all $y_0\in\Omega$, the function $u$ has to be constant.


text:
Q: ActiveAdmin sort column clears filters I have a column called Shifts on an index page of a resource:
column "Shift", sortable: :start do |booking|
   ...

If I have some filters on the page already present, here filtering for one worker (note the bit that says worker_id_eq%5D=621) so the URL is something like:
http://localhost:3000/admin/bookings?utf8=%E2%9C%93&q%5Bshift_id_eq%5D=&q%5Bworker_id_eq%5D=621&q%5Bstate_eq%5D=&q%5Bstart_gteq%5D=2015-12-01&q%5Bstart_lteq%5D=&q%5Bshift_finalised_eq%5D=&q%5Bworker_id_equals%5D=&commit=Filter&order=id_desc

Then hovering over the Shifts column header, I'm given a "target" URL of:
http://localhost:3000/admin/bookings?order=start_desc&q%5Bshift_finalised_eq%5D=&q%5Bshift_id_eq%5D=&q%5Bstart_gteq%5D=2015-12-01&q%5Bstart_lteq%5D=&q%5Bstate_eq%5D=&q%5Bworker_id_eq%5D=621&q%5Bworker_id_equals%5D=&utf8=%E2%9C%93

However, when I click this, I end up clearing all the filters.
Note that the target URL even has worker_id_eq%5D=621 in it.
How do I make the column sortable, without clearing the filters?


text:
Q: Marker Clusterer, cluster at 1 marker also I am using marker clusterer with google maps. All is working very well but I would like to know how to cluster a marker even if there is only 1 marker with that grid. At the moment on page load you will see the odd marker darted around and others are within a clustered icon. I would like all even the single markers to display a cluster icon also.

A: Set the option minimumClusterSize to 1 (default is 2)
new MarkerClusterer(map, markers,{minimumClusterSize:1});


text:
Q: Websphere Liberty Profile JPA 2.1 .and JAXB errors When I have feature
<feature>jpa-2.1</feature>

enabled in my server.xml (WLP 8.5.5.7) I get a JAXB context initialization error
 java.lang.RuntimeException: Errors getting JAXB context for class
Caused by: javax.xml.bind.JAXBException: Unable to create context

- with linked exception:
[java.lang.reflect.InvocationTargetException]
[err]   at javax.xml.bind.ContextFinder.find(ContextFinder.java:116)
[err]   at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:65)
[err]   at com.lca.phoenix.common.util.JsonProcessor.getJaxbContext(JsonProcessor.java:110)

When I remove that feature, I don't get the JAXB errors.  I am curious what the connection is between those two seemingly disparate things
I'm on Java 1.8.131 on Win 8.1
Thanks!


text:
Q: How do I get the size of a download when a HEAD request doesn't report ContentLength? Using this code in Delphi for getting a web page size: (I mean page source size)
uses
  IdHTTP

function URLsize(const URL : string) : integer;
var
  Http: TIdHTTP;
begin
  Http := TIdHTTP.Create(nil);
  try
    Http.Head(URL);
    result := round(Http.Response.ContentLength / 1048576);   //MB
  finally
    Http.Free;
  end;
end;

I can get file size easily for some URLs like http://sample.com/test.exe. It returns the size in MB.
But I cannot get URL size using this code for a URL like http://stackoverflow.com/; it returns 0 or -1.
How can I get the size in that case?

A: Not all HTTP HEAD responses contain content-length. So, what you are trying to do is impossible in general. If you encounter a response that does not contain the content length you need to download the contents in order to find the length.

A: Even if a web server does return the proper content length, you're dividing it by 1048576 to get the megabyte value. Since http://stackoverflow.com/ is much less than a single megabyte, it is returning 0. I'm still stumped however where your -1 came from - because http://stackoverflow.com/ returns 194569 for me, without dividing. Did you get a -1 from another website? And are your results the divided value or the raw value from Http.Response.ContentLength?


text:
Q: Build a select with optgroups/options based on a 3-way entities relation Well, the title isn't really explicit, but it's hard to explain my problem in only 1 sentence.
I'm using Symfony 2 with Doctrine.
What I want doesn't seem over complicated, yet I can't get it. (Though, I already solved problem which seemed much more complicated than this one...)
Here is my Foo entity. One Foo can have multiple Bar, but a Bar only have 1 Foo.
class Foo
{
    /**
     * @OneToMany(targetEntity="Bar", mappedBy="foo")
     */
    private $bars;
}

Here is my Bar entity. It has 1 Foo. It can have multiple Baz, and a Baz can belong to many Bar :
class Bar
{
    /**
     * @ManyToOne(targetEntity="Foo", inversedBy="bars")
     */
    private $foo;

    /**
     * @ManyToMany(targetEntity="Baz")
     * @JoinTable(name="BarsBazs")
     */
    private $bazs;

}

Finally, here is the Baz entity. It belongs to one or more Bar :
class Baz
{

}

If I have a Foo entity instance, how can I get a <select> containing all the Baz of Foo, grouped by Bar (with <optgroup> ), with a minimum of db request?
Edit:
Ok, I went further.
My Bar entity is now:
class Bar
{
    /**
     * @ManyToOne(targetEntity="Foo", inversedBy="bars")
     */
    private $foo;

    /**
     * @ManyToMany(targetEntity="Baz", inversedBy="bars")
     * @JoinTable(name="BarsBazs")
     */
    private $bazs;

}

And my Baz entity is now :
class Baz
{
    /**
     * @ManyToMany(targetEntity="Bar", mappedBy="bazs")
     */
    private $bars;
}

In my form builder, when adding the field, I set it like that ($foo contains my Foo entity instance):
$builder->add('baz', 'entity', array(
    'property' => 'name',
    'query_builder' => function($repository) use ($foo) {
        return $repository->createQueryBuilder('z') // Baz
                    ->addSelect('r')                // Bar
                    ->join('z.bars', 'r')
                    ->where('r.foo = :fooId')
                    ->setParameter('fooId', $foo->getId())
                    ;
    }
));

It's almost OK. Now I have a select containing all the baz associated to the current foo. But I can't group them by Bar.
I tried the option group_by in many ways, but nothing works:
'group_by' => 'bars.name'
'group_by' => 'bar.name'
'group_by' => 'r.name'

A: Ok, I finally got it!
In my Baz entity, I added this method:
getFirstBar() {
    return $this->bars->first();
}

And in the options array of my field, I added this option:
$options['group_by'] = 'firstBar.name'

Now I have a <select> with all my bazs grouped by bar :)


text:
Q: Why is it incorrect to say "I lonely walked around the park."? And how do I say it right?
This should be an explanation:

but I still don't understand that why does the sentence "I lonely walked around the park" does not make any sense

A: You actually can say that, but it sounds very poetic/old fashioned rather than like natural, everyday speech and you probably need some extra punctuation to clarify for modern speakers.
As the passage that you quoted explains, lonely is an adjective, not an adverb, so it can only describe a noun, not a verb (that is, it can describe a person, place, or thing, but can't describe an action). This means lonely cannot describe the way the person in your sentence is walking, but it could describe the person.
The problem with the sentence as-written is the placement of the word lonely. English usually puts adjectives in front of the noun they modify (red rose, beautiful dreamer, happy children, etc.), so without any other clues we are going to want to connect lonely with the word the word that follows it. In this case, that word is walked, but this doesn't work because it's not a noun.
We can "fix" this by interpreting lonely as an attributive clause. Attributive clauses modify the noun that immediately precedes them. Usually they're more than one word, but they don't have to be.
As I mentioned, this will sound poetical, and actually parallels some existing poetry:

When, in disgrace with fortune and men's eyes,
  I all alone beweep my outcast state
  —William Shakespeare, Sonnet 29
Soon as the portals ope; I lonely tread
  The sacred paths conductive thro' the choir
  —Rev. Alsop, A Description of the Choir at St. Peter's Church, 1738
Thus wrapped in gloom I lonely walk
  Life's dark and dreary way
  —Joshua Ross, "My Ruling Star", 1855

As you can tell from the dates, it's also a very old-fashioned construction (there are other examples, but all that I've found are at least a hundred years old), so this won't be the first interpretation that most modern speakers will guess. We can make it a bit clearer by enclosing lonely in commas:

I, lonely, walked around the park.

However, if you want to have a more straightforward sentence that everyone will understand, you probably need to reword to something like

[Feeling] Lonely, I walked around the park.

or

I walked around the park, all alone.


text:
Q: Can proxy created by servicedelegate.getport reusable? is it Thread-safe? We are using webservice (through websphere), to improve performance, we believe we can cache proxy created by servicedelegate.getport(..) since creating proxy every time is expensive.
Now, our question is, is it thread safe? Just image, we have 10 threads running at the same time, they will grab the same proxy, and use it at the same time.
Thx

A: Instead of letting your application cache it, just have it injected using WebServiceRef and let the container manage it for you.

A: Ports are not thread safe. They keep state, like javax.xml.ws.handler.MessageContext. But port object can be safely reused later!
Cache ports in LinkedBlockingQueue and peek before call and then return after with offer.
In following implementation port object doesn't leak out of call code so it is safe to reuse it:
private LinkedBlockingQueue<Port> portCache = new LinkedBlockingQueue<>();

public Rsp call(Req req) {
    Port port = portCache.poll();
    if (port == null) {
        port = createPort();
    }
    BindingProvider provider = (BindingProvider) port;
    try {
        return portMethod.invoke(port, req);
    } finally {
        portCache.offer(port);
    }
}


text:
Q: AWS Cognito AccessToken vs IdToken I created a .net Core API using the AWS Cognito SDK to authenticate and authorize users by posting credentials to my API and returning a JWT to a simple client side app (plain HTML/TypeScript). The request contains the user name and password.
...
var response = await cognito.AdminInitiateAuthAsync(request);

return Ok(response.AuthenticationResult.AccessToken);

vs
return Ok(response.AuthenticationResult.IdToken);

The problem I'm having is understanding why there are ID Tokens and Access Tokens. I'm able to secure controller endpoints with the [Authorize] attribute. The client app uses the Authorization header with Bearer {token}.
In my Startup.cs I'm able to AddAuthentication and verify the Signature, Issuer, Audience and Lifetime of the ID Token. However, I read that the ID Token contains claims about the identity of the user but not claims about the groups for authorization of the user. If I send the Access Token to my client and try to send this back to my API, I'm getting unauthorized. Maybe I'm not verifying the token properly but I still don't understand why there are two different types of tokens. The Access Token makes more sense to use for creating different auth policies based on claims the token contains.
The way I understand how JWT's work is that once a client obtains a token it stores it and uses it for all request to an API. I don't understand how this is supposed to work with two tokens.
Here is how I'm trying to validate the access token:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>{
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
                    {
                        // get JsonWebKeySet from AWS
                        var json = new WebClient().DownloadString(parameters.ValidIssuer + "/.well-known/jwks.json");
                        // serialize the result
                        var keys = JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;

                        // cast the result to be the type expected by IssuerSigningKeyResolver
                        return (IEnumerable<SecurityKey>)keys;
                    },
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Authentication:Cognito:MetadataAddress"],
                    ValidateIssuer = true,
                    ValidAudience = Configuration["Authentication:Cognito:ClientId"],
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    RequireSignedTokens = true
                };
            });

There is no aud claim in the access token so I'm getting an error "Invalid token, audience = 'empty' is invalid.
Even if I remove ValidateAudience, I still get the error

A: ID token is sent to the client application as part of an OpenID Connect flow and is used by the client to authenticate the user. Access tokens enable clients to securely call APIs protected by identity provider .
The ID token contains information about an End-User which is not used to access protected resource , while Access token allows access to certain defined server resources .
So that while using OpenID Connect , it will return ID token and access token back to your client , client app will get user's info from id token and sign in user , and use access token to access the protected resource .

If I send the Access Token to my client and try to send this back to my API, I'm getting unauthorized.

The ID token will be validated by your client app  app to get user claims , so the audience claim in token is your client app's client ID . Access token is passed to your protected resource(web api) and should be validated by protected resource(web api) , so the audience is web api's name . You should check the validation options like audience , issuer .

A: For others, as me arriving through google, you can take a look to this other answer https://stackoverflow.com/a/70836794/9219975
I read several answers and the majority recomended setting
ValidateAudience = false

Since I didn't want to do that I ended up defining AudienceValidator, to do it you have to define a delegate in the options when configuring your application. So in Startup you have to include this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Audience = configuration["AWS:Cognito:ClientId"];
                    options.Authority = configuration["AWS:Cognito:Authority"];
                    options.TokenValidationParameters.AudienceValidator = (audiences, securityToken, validationParameters) =>
                    {
                        //This is necessary because Cognito tokens doesn't have "aud" claim. Instead the audience is set in "client_id"
                        return validationParameters.ValidAudience.Contains(((JwtSecurityToken)securityToken).Payload["client_id"].ToString());
                    };
                });

This will check that the claim "client_id" corresponds with the audience you're expecting


text:
Q: mapping many-many relationship kodo jdo 4.2 xml I have the following in my package.jdo file
        <field name="entitlements" table="LEAFENTITLEMENT"/>
            <collection element-type="Entitlement"/>
            <join>
              <column name="LEAFID" target-field="ID"/>
           </join>
           <element>
             <column name="ENTITLEMENTID" target-field="ID"/>
           </element>

 the DB relationship is that we have 3 tables
Entitlement - primary key id
Leaf - primay key id
LeafEntitlement - leafid,entitlementid - both foreign keys to respective tables
This is part of the mapping for the Leaf Table. I am getting a classCastException when trying to Enhance this using kodo.ant.PCEnhancerTask.
The collection is a set of entitlements for the Leaf Table.
Thanks for any help or suggestions

A: there is a trailing / in your field tag
<field name="entitlements" table="LEAFENTITLEMENT" />

try removing it.


text:
Q: Laravel5.6 phpexcel package install error Hi I'm trying to install phpexcel package in laravel5.6.26 via composer but it failed.Please find the attachment of issue i'm getting.enter image description here

A: Have you tried installing Laravel Excel via composer as showed here ?

A: Add this lines to your composer.json
"repositories": [
      {
        "type": "composer",
        "url": "https://packagist.org"
      },
      { "packagist": false }
    ]


text:
Q: @Qualifier not working in unit test, while injecting in constructor I have a application whose unit tests work correctly. I am trying to move the application to use dependency injection instead of using @AutoWired annotation.
After I make the change, some unit tests fail randomly(No changes have been made to the tests, just the dependency injection part of the application has been changed). I am assuming that the system is unable to create the AmazonS3 client correctly when the dependencies are injected.
See screenshot below, I am trying to create a s3ClientAlphaBeta instance but the application is creating a s3ClientGammaProd instance.
What could I be missing?
Abreviated code:
S3Accessor.java:
    @Component
    public class S3Accessor {
        private AmazonS3 s3ClientAlphaBeta;
        private AmazonS3 s3ClientGammaProd;
        @Inject
        public S3Accessor(@Qualifier("s3ClientAlphaBeta") AmazonS3 s3ClientAlphaBeta,
                @Qualifier("s3ClientGammaProd") AmazonS3 s3ClientGammaProd) {
            this.s3ClientAlphaBeta = s3ClientAlphaBeta;
            this.s3ClientGammaProd = s3ClientGammaProd;
        }
public String getHtmlContent(final String deviceType, final String s3Key, final String region) {
        final String filePath = generateFilePath(deviceType.toLowerCase(Locale.ROOT), s3Key);
        AmazonS3 amazonS3 = s3ClientAlphaBeta;
        final String regionSpecificLegoBucket = S3BUCKET_NAME_BETA;
        final AmazonS3 regionSpecificAmazonS3 = amazonS3;
        return this.getHtmlContentFromS3(regionSpecificLegoBucket, filePath, regionSpecificAmazonS3);
    }

    private String getHtmlContentFromS3(final String bucketName, final String filePath, final AmazonS3 amazonS3) {
        String s3HtmlContent = amazonS3.getObjectAsString(bucketName, filePath);
        return s3HtmlContent;
    }

S3AccessorTest.java:
public class S3AccessorTest {
@InjectMocks
private S3Accessor s3Accessor;
@Spy
@Qualifier("s3ClientAlphaBeta")
private AmazonS3 s3ClientAlphaBeta;
@Spy
@Qualifier("s3ClientGammaProd")
private AmazonS3 s3ClientGammaProd;
private static final String TEST_VALID_STRING_DESKTOP = "Some Content For DESKTOP";
private static final String TEST_VALID_WRAPPED_STRING_DESKTOP =
        PAINTERS_LEGO_OPENING_DIV + TEST_VALID_STRING_DESKTOP + PAINTERS_LEGO_CLOSING_DIV;
private static final String TEST_VALID_S3_KEY = "/test/.1/main";
private static final String SLASH = "/";
static {
    AppConfig.destroy();
    AppConfig.initialize("TestApp",
            "TestGroup",
            new String[] { "--root=configuration/", "--domain=test", "--realm=Ramu" });
}
@BeforeEach
public void setup() {
    MockitoAnnotations.openMocks(this);
    s3Accessor.setup();
}
@Test
public void getHtmlContentForDesktop() {
    // Arrange
    when(s3ClientAlphaBeta.getObjectAsString(anyString(), eq(TEST_VALID_S3_KEY + SLASH + DESKTOP_VIEW)))
            .thenReturn(TEST_VALID_STRING_DESKTOP);
    // Act
    final String outputString = s3Accessor.getHtmlContent(DESKTOP, TEST_VALID_S3_KEY, US_ALPHA_BETA_REGION);
    // Assert
    assertEquals(TEST_VALID_WRAPPED_STRING_DESKTOP, outputString);
}

CustomRootConfig.java:
    @Configuration
@ComponentScan("com.service.controller")
@Import({SmokeTestBeanConfiguration.class })
public class CustomRootConfig {
    private static final String NA_S3_SESSION_NAME = "S3Content";
    private static final int S3_SESSION_REFRESH_TIME = 3600;
    private static final String S3BUCKET_ARN_BETA = "arn:aws:iam::471963992020:role/ProdAccessForAccount";
    private static final String S3BUCKET_ARN_PROD = "arn:aws:iam::568948772290:role/ProdAccessForAccount";

    @Bean(name = "s3ClientAlphaBeta")
    @Singleton
    public AmazonS3 s3ClientAlphaBeta() {
        return AmazonS3ClientBuilder.standard()
                .withRegion(Regions.valueOf(US_ALPHA_BETA_REGION))
                .withCredentials(new STSAssumeRoleSessionCredentialsProvider
                        .Builder(S3BUCKET_ARN_BETA, NA_S3_SESSION_NAME)
                        .withRoleSessionDurationSeconds(S3_SESSION_REFRESH_TIME).build())
                .build();
    }

    @Bean(name = "s3ClientGammaProd")
    @Singleton
    public AmazonS3 s3ClientGammaProd() {
        return AmazonS3ClientBuilder.standard()
                .withRegion(Regions.valueOf(US_GAMMA_PROD_REGION))
                .withCredentials(new STSAssumeRoleSessionCredentialsProvider
                        .Builder(S3BUCKET_ARN_PROD, NA_S3_SESSION_NAME)
                        .withRoleSessionDurationSeconds(S3_SESSION_REFRESH_TIME).build())
                .build();
    }

A: I don't think Mockito actually recognizes the @Qualifier annotation from Spring. The reason it worked before is that Mockito was doing property injection, as there was no other way to do it.
After changes, with the constructor in place, Mockito switched from property injection to constructor injection. What's important is that both s3ClientAlphaBeta and s3ClientGammaProd are of the same type (AmazonS3). Apparently, with constructor injection, Mockito isn't doing so well to differentiate the parameters by its name. Possible reason is that the names of the parameters aren't preserved after compilation, so there's no way for Mockito to match them. Instead, it uses the first mock (spy) it finds with a matching type (either s3ClientAlphaBeta or s3ClientGammaProd) and uses it for both parameters to construct an instance of S3Accessor.
To avoid your issue and gain more control over how the tested object is being created, I'd suggest abandoning usage of @InjectMocks and using the constructor directly in the tested class i.e. doing:
s3Accessor = new S3Accessor(s3ClientAlphaBeta, s3ClientGammaProd);

somewhere below MockitoAnnotations.openMocks(this).
You can find more information on how @InjectMocks annotation works here.


text:
Q: selecting digits right of the last zero in SQL Server I have a table with a number NA0000000012345. I'd like to select 12345, and then when it is NA0000000123456 I'd like the select statement to correct for it. So i need a condition in the RIGHT statement essentially and I'm not sure how to structure this in SQL Server.
ex
Right(Mystring,left of last 0 starting from the left)

Thanks for all your help

A: You can grab from the 1st non-zero numeric character;
declare @value varchar(20) = 'NA000000123456'

select substring(@value, patindex('%[1-9]%', @value), len(@value))

A: In case you have a mix of letters and number and only want the last number, here is the syntax. The script starts from the right side of the 'value' and search for the first none number.
declare @t table(value varchar(20))

insert @t values ('NA000000123a456')
insert @t values ('NA0100000123456')
insert @t values ('NA0100a00123456')

SELECT CAST(RIGHT(value, patindex('%[^0-9]%', reverse(value)) -1) as BIGINT)
FROM @t

Result:
456
100000123456
123456


text:
Q: Itext: Show paragraph at absolute position Is there a way to position a paragraph absolutely, in a way that also works when a list is added to the paragraph?
A google search shows that I should use ColumnText, but I can't get that to work if there is a list in the paragraph. It simply shows the list items next to each other on the same linie. Here is my test program:
        PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("/tmp/output.pdf"));
        document.open();
        ColumnText ct = new ColumnText(writer.getDirectContent());
        ct.setSimpleColumn(0,0,300,300);
        Paragraph p=new Paragraph();
        List list=new List();
        list.add(new ListItem("First item"));
        list.add(new ListItem("second item"));
        list.add(new ListItem("third item"));
        p.add(list);
        ct.addElement(p);
        ct.go();
        document.close();
        writer.close();

A: I looked in the changelogs of iText and I discovered that this was fixed in iText 5.2.1, released on March 31st, 2012. That's over a year ago. Please upgrade to the latest version and the problem will disappear.
Note that all 5.2.x versions were removed from SourceForge because they contained a bug that occasionally produced PDFs that weren't compliant with ISO-32000-1. Based on the description of your problem, I know that you're using a version of iText that is even older than the 5.2.x series, so you definitely need to upgrade.

A: A different way to organize you content in PDF file is that you can use PdfPTable . first write list content into the table using loop instruction and then define the position of that PdfPTable in your output pdf file.

A: You can use this function:
private void PlaceChunck(String text, int x, int y) {
    PdfContentByte cb = writer.DirectContent;
    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.SaveState();
    cb.BeginText();
    cb.MoveText(x, y);
    cb.SetFontAndSize(bf, 12);
    cb.ShowText(text);
    cb.EndText();
    cb.RestoreState();
}

see also: itext positioning text absolutely;


text:
Q: Package or setting required for proper aligned equations I've installed Tex2png, a PHP-based solution to produce png math images.
Simple expressions render fine, but some environments do not (with unhelpful "LaTeX error" messages).
It seems my Linux server had very few packages. I unzipped these:

*

*amsmath

*amscls

*tools

to
/usr/local/texlive/texmf-local/tex/latex/local
This got some expressions to at least render something, but not correctly. For example, this:
\begin{aligned}\text{Vol}&=\pi\int_1^b{\frac{1}{x}}^2dx\\ &=\pi\int_1^b{x^{-2}}dx\\ &=\pi\left[-\frac{1}{x}\right]_1^b\\ &=\pi\left(1-\frac{1}{b}\right)\end{aligned}

gives this (partial screen shot), with everything horizontal:

I've tried \align, \align*, \aligned and \aligned*, but they either give "LaTeX error" or the vertical alignment is ignored. So presumably I'm missing a package or two, but I thought amsmath and tools should handle most of these cases.
I don't know:

*

*Which packages are already on the server

*Whether I've unzipped the packages to the right places

*Which packages I need add to address the above

Any pointers would be very welcome.

A: This isn't quite an answer to your question.  I don't have or know much about Tex2png.  It seems to me that perhaps Tex2png is limited in the extent to what sorts of environments it can handle.  Namely, it looks like it doesn't handle math environments very well.
But, you can create something similar just running pdflatex.  Here's an example:
\documentclass[border=6pt]{standalone}
\usepackage{amsmath}
\begin{document}

\begin{math}
\begin{aligned}
  \text{Vol}&=\pi\int_1^b{\frac{1}{x}}^2dx      \\
            &=\pi\int_1^b{x^{-2}}dx             \\
            &=\pi\left[-\frac{1}{x}\right]_1^b  \\
            &=\pi\left(1-\frac{1}{b}\right)
\end{aligned}
\end{math}

\end{document}

which produces:

Granted, this will be a pdf document.  Perhaps you can use it as is.  But, if you actually need to work with a png, there are various tools available that will allow you to convert from one kind of format to another.
The provided solution to How to output a multiline equation with no margins may be of interest to you.
The solution to Compile a LaTeX document into a PNG image that's as short as possible also talks about how to convert between file formats.
Using other environments
If you want to use other environments like align, then you can still do something similar, but you will need to somehow pass align a page width to work with.  That can be achieved by using the preview option passed to the documentclass:
\documentclass[border=6pt,preview]{standalone}

Since you're likely to get an image much wider than you want with this approach, look at the answer provided in the first link suggested above.
However, there is a work around.  You could put the align environment within a minipage and do something like the following
\documentclass[border=6pt]{standalone}
\usepackage{amsmath}
\usepackage{etoolbox}
\makeatletter
\pretocmd\start@align{%
  \if@minipage\kern-\topskip\kern-\abovedisplayskip\fi
}{}{}
\makeatother
\begin{document}

\begin{minipage}{0.2in}
\begin{align*}
  \text{Vol}&=\pi\int_1^b{\frac{1}{x}}^2dx      \\
            &=\pi\int_1^b{x^{-2}}dx             \\
            &=\pi\left[-\frac{1}{x}\right]_1^b  \\
            &=\pi\left(1-\frac{1}{b}\right)
\end{align*}
\end{minipage}

\end{document}

I believe the minipage width here is not really a concern if all you're going to do is create the environment for displaying mathematics.
Now, there is some extra code here that makes this look a bit complicated.  Namely, the code starting from \makeatletter.  This is to get around a peculiar issue in which the align* environment expects  it's being called midparagraph.  Therefore, align* adds extra whitespace at the top of the environment.  For details about this workaround see egreg's solution to Spurious space above align environment at top of page/minipage.


text:
Q: if there any command in Matlab Programming that can be used to do Cholesky decomposition for a positive semi-definite matrix?a In Matlab Programming, the "chol" command can be used to simply apply this to only a positive definite matrix.When it comes to a positive semi-definite matrix,"chol" fails.I want to ask if there any command in Matlab Programming that can be used to a positive semi-definite matrix?

A: Caution: a positive semi-definite matrix is not a stable thing.  A tiny roundoff error may make it positive definite or indefinite.
It is possible that chol will work on your positive semi-definite matrix.
For example:
A = [  2 2 2; 2 4 6; 2 6 10 ];
chol(A)

ans =
1.4142    1.4142    1.4142
     0    1.4142    2.8284
     0         0    0.0000

If it doesn't work, try making the matrix (slightly) positive definite by adding a small multiple of the identity matrix.


text:
Q: SVG find orientation(angle) of a point to the x axis on a path I am making parallax by moving an object on a path and it is working fine with getPointAtlength() but I also need to rotate this object with the path.
I need something like getPointAtLength() but for angles that I get the angle of the point. Rapheal seems to have a method to it but it isn't friendly to svg elements that is created in html or I don't know how to deal with it. Any ideas?
var l = document.getElementById('path');
var element=$('#svg_26')
$(window).scroll(function(){
    var pathOffset=parseInt($('#l1').css('stroke-dashoffset'));
    var p = l.getPointAtLength(-1*pathOffset);
    translation = 'translate('+p.x+'px,'+p.y+'px)'
    $(element).css('transform',translation);
})

A: Using a library for this kind of task would be overkill. Its actually quite simple to write your own function to calculate the angle. All you have to do is use pointAtLength two time with a little offset:
var p1 = path.getPointAtLength(l)
var p2 = path.getPointAtLength(l + 3)

and then calculate the angle of the resulting line and the x-axis using Math.atan2
var deg = Math.atan2(p1.y - p2.y, p1.x - p2.x) * (180 / Math.PI);

here is a little example using the above formula

var path = document.getElementById("path")
var obj = document.getElementById("obj")
var l = 0
var tl = path.getTotalLength()

function getPointAtLengthWithRotation(path, length) {
  var p1 = path.getPointAtLength(length)
  var p2 = path.getPointAtLength(length + 3)
  var deg = Math.atan2(p1.y - p2.y, p1.x - p2.x) * (180 / Math.PI);
  return {
    x: p1.x,
    y: p1.y,
    angle: deg
  }
}

setInterval(function() {
  l += 1
  if (l > tl) l = 0;
  var p = getPointAtLengthWithRotation(path, l)
  obj.setAttribute("transform", "translate(" + p.x + "," + p.y + ") rotate(" + (p.angle + 180) + ")")
}, 30)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="200">
  <path id="path" d="M 81.713425,82.629068 C 77.692791,85.788547 73.298237,77.367896 68.194886,79.039107 63.091534,80.710434 58.027628,96.952068 53.04637,97.140958 48.065112,97.329732 50.503508,75.285207 45.397105,74.05952 40.290703,72.833834 38.487501,93.968537 33.85932,91.287114 29.23114,88.605807 32.245641,70.914733 29.647307,66.19971 27.048973,61.484686 19.604932,68.733636 17.542589,63.315055 15.480245,57.896474 32.172733,59.004979 32.053727,53.363216 31.93472,47.721442 8.0865997,39.989401 9.2246856,34.665848 10.362772,29.342295 28.830448,38.693055 31.065274,33.7132 33.300101,28.733334 22.734045,13.601966 26.210126,9.6067771 29.686208,5.6115765 41.809938,29.357138 46.524268,27.383715 c 4.71433,-1.973424 3.011846,-23.1001292 8.022646,-23.3332919 5.0108,-0.2331744 4.529056,18.3713929 9.45006,20.4259809 4.921003,2.054588 12.017373,-15.4803016 16.717604,-13.058602 4.700233,2.421699 -6.261038,14.180819 -2.913997,18.778859 3.347041,4.59804 12.339067,-3.78046 13.896719,1.543011 1.557652,5.323471 -9.713912,13.199372 -9.176986,18.679109 0.536926,5.479772 19.347976,2.957331 18.124596,8.213665 -1.223374,5.256392 -21.036293,1.236997 -24.253076,5.968111 -3.216785,4.731114 9.342224,14.869033 5.321591,18.028511 z"
  fill="none" stroke="grey" />
  <path id="obj" d="M-5 -5 L5 0L-5 5z" fill="green" />
</svg>

A: getPointAtLength in Raphael returns an object with attribute 'alpha'. Alpha is the angle that you need along the curve. In the example above it would be p.alpha
So you should be able to apply a rotation to the object rotated by p.alpha,
Eg..
myRaphElement.transform('t' + p.x + ',' + p.y + 'r' + p.alpha).
The last part will rotate the element around its center.
If you can't create the raph element itself as the svg is inline, I suspect you may be better off with a library like Snap.svg (which has mostly same commands as by same author), or you could possibly dynamically rotate by css transform using something like 'rotate('+l.alpha+','+l.x+','+l.y+')'
Edit: I misread as it had Raphael in the tags, when its not being used.
I personally would use Snap for this case, as Raphael doesn't add a lot here. You could possibly create a Raphael element off screen with the same path as the inline element just to use the angle, but feels like overkill to load a library for that.
In Snap you could access the element with..
myElement = Snap('#svg_26')
p = myElement.getPointAtLength(-1*pathOffset);
myElement.transform('t' + p.x + ',' + p.y + 'r' + p.alpha)

A: <animateMotion rotate="auto" ... performs the guidance of automatically

<svg viewBox="0 0 150 100" width="300" height="200">
  <path id="path" d="M 81.713425,82.629068 C 77.692791,85.788547 73.298237,77.367896 68.194886,79.039107 63.091534,80.710434 58.027628,96.952068 53.04637,97.140958 48.065112,97.329732 50.503508,75.285207 45.397105,74.05952 40.290703,72.833834 38.487501,93.968537 33.85932,91.287114 29.23114,88.605807 32.245641,70.914733 29.647307,66.19971 27.048973,61.484686 19.604932,68.733636 17.542589,63.315055 15.480245,57.896474 32.172733,59.004979 32.053727,53.363216 31.93472,47.721442 8.0865997,39.989401 9.2246856,34.665848 10.362772,29.342295 28.830448,38.693055 31.065274,33.7132 33.300101,28.733334 22.734045,13.601966 26.210126,9.6067771 29.686208,5.6115765 41.809938,29.357138 46.524268,27.383715 c 4.71433,-1.973424 3.011846,-23.1001292 8.022646,-23.3332919 5.0108,-0.2331744 4.529056,18.3713929 9.45006,20.4259809 4.921003,2.054588 12.017373,-15.4803016 16.717604,-13.058602 4.700233,2.421699 -6.261038,14.180819 -2.913997,18.778859 3.347041,4.59804 12.339067,-3.78046 13.896719,1.543011 1.557652,5.323471 -9.713912,13.199372 -9.176986,18.679109 0.536926,5.479772 19.347976,2.957331 18.124596,8.213665 -1.223374,5.256392 -21.036293,1.236997 -24.253076,5.968111 -3.216785,4.731114 9.342224,14.869033 5.321591,18.028511 z"
  fill="none" stroke="grey" />
  <polygon points="0,0 -5,-5 -5,5"  style="fill:green">
    <animateMotion begin="0s" dur="10s" rotate="auto" repeatCount="indefinite">
        <mpath xlink:href="#path"></mpath>
    </animateMotion>
  </polygon>
</svg>


text:
Q: The reason for the different answer in a benchmark run When i run a benchmark on Cplex with concert C++ on two systems the optimal solution is the same but one of the systems  in consul shows 284 nodes and the other one shows 414 nodes?
I am sure that i run one code on the both systems. What is the reason for this difference? Is it multiple Optimal Solutions? If yes, How do I get the same number of nodes?

A: This is expected and is known as "performance variability". As soon as you change something in the system or algorithm configuration (cores, threads, operating system, parameters) you can get different solution paths.
This means that if there are alternate optimal solutions then you may get alternate solutions. If there is only one optimal solution it may take a different number of nodes to find it.
The only way to guarantee the exact same behavior between two solves is to use the exact same configuration on the exact same hardware.


text:
Q: jquery insert html into list before a child ul-tag I have this:

1

2

3

3-1

But want this:

1

2

3

3-1

With other words I need to insert

after the 3 in the list. I have played with .append and .prepend but witout beeing able to insert at the right place.
Any help would be appreciated
Br. Anders

There is a correct answer below. If you use that then it will run through only one level. But same example is is capable of running through multible levels. Just change  ('>li>ul') to ('ul') and all nested ul's will be found and handled. Perfect!
(will run through endless levels of nested ul's)
$('#pickme').find('ul').each(function() {
    $(this).wrap('

').parent().insertAfter($(this).parent().parent());
});

In this case this:

1

2

3

3-1

3-1-1

Will be:

1

2

3

  <<new li

3-1

  <<new li

3-1-1

A: This will work for you;
// get the #pickme element
var pickme = $('#pickme');

// find all the LI elements that are directly under #pickme
var pickmeLIs = pickme.find('>li');

// find all the UL elements that are directly under our found LI elements
var pickmeULs = pickmeLIs.find('>ul');

// loop through our UL elements
pickmeULs.each(function() {

    // wrap this UL element in the new LI element
    $(this).wrap('

');

    // select the wrapping LI we just added to the UL element
    var wrapingLI = $(this).parent();

    // find our original parent LI element
    var originalParent = $(this).parent().parent();

    // move this and the new wrapping LI to the right place
    wrapingLI.insertAfter(originalParent);
});

this can be condensed down to;
$('#pickme').find('>li >ul').each(function() {
    $(this).wrap('

').parent().insertAfter($(this).parent().parent());
});

A: If you have a way of knowing how many list items there are in #pickme you can use $('#pickeme li:eq(theIndex)') otherwise, use this:
$('#pickme li:last').after('

3-1

');

Tested and works.
UPDATE
Thanks to bobince and Myra I now have the following which does exactly what you're asking for:
$('#pickme li:last-child').replaceWith('

3-1

');

Output:

1

2

3-1

A: last-child selector will ensure that you add new item after it.
You can use that as
$('
4
').appendTo("ul#pick_me > li:last-child");

A: Use .html(), which will get you the inner text.  Manipulate the string. Then use .html(newHtml) to set the new inner text.
Your problem with prepend and append is that you don't need to prepend or append, you need to insert in the middle (after the 3).


text:
Q: How do I add a picture of myself at the login screen? I need to add a image of myself in the login screen (when user credentials are asked). How can I do this?

A: System Preferences>Users & Groups. Click on your account name in the sidebar and you'll have the option to change your picture if you mouseover it in the right pane and click edit picture.

A: To edit the image associated with your login go to System Preferences > Users & Groups, click on your account in the left hand pane,  click on the image in the Password tab on the right, then select Edit Image….

You also have to be certain that Display login window as List of Users is selected under Login Options of the Users & Groups preferences pane.


text:
Q: Change the wording of the character-limit error from "X characters too much" to "X characters too many" on the Chat.SE profile On my chat.SE profile, I entered a few characters too many and saw this error:

Can we change that to "X characters too many", or "Too long by X characters" to be consistent with the comment errors, and also because we don't want... "too much characters"?


text:
Q: Separating invariant of a group action Let $G = (\mathbb{R},+)$ be a group, $M = \mathbb{R}^2$,
$$\omega \colon \mathbb{R}\times\mathbb{R}^2\to \mathbb{R}^2, \quad \left(t, (x,y)\right) \mapsto(x+t,y-2t)$$
and
$$\iota \colon\mathbb{R}^2 \mapsto \mathbb{R}^2, \quad (x,y) \mapsto y+2x.$$
Show that $\iota$ is a separating invariant.
Well, $G$ operates on $M$ since:
1) $\omega(1_G,(x,y)) = (x+0, y+2\cdot0) = (x,y)$
2) $g,h \in G: \omega((g+h),(x,y)) = (x+(g+h),y-2\dot(g+h)) = ((x+g)+h, (y-2g)-2h) = \omega(g,(x+h,y-2h)) = \omega(g,\omega(h,(x,y))$
$\iota$ is an invariant of $G$ because $\iota((x+t,y-2t)) = (y-2t)+2(x+t) = y-2t+2x+2t = y+2x = \iota((x,y)).$
Now I don't know exactly how to show that $\iota$ is an separating invariant. I have to show that if $\iota(m) = \iota(m')$ implies $Gm = Gm'$ with $m \in \mathbb{R}^2$.
My approach is
$$x+t = x' \Rightarrow t = x' - x$$ and $$y-2t = y' \Rightarrow -2t = y' -y \Rightarrow -2(x'-x) = y' -y \Rightarrow 0 = (y'-y) + 2(x'-x).$$
Is that the right approach to show that the orbits $Gm$, $Gm'$ are equal with $m = (x,y) \in \mathbb{R}^2$?

A: You have to show that $Gm = G m'$ if and only if $\iota(m) = \iota(m')$.
If $G m = G m'$, that is, $m' \in Gm$, then $m' = (x + t, y - 2 t)$ for some $t$, where $m = (x, y)$. Now $\iota(m') = y - 2 t + 2 (x + t) = y + 2 x = \iota(m)$.
Conversely, if $m = (x, y)$ and $m' = (u, v)$, suppose $\iota(m) = \iota(m')$. Then
$$
v + 2 u = y + 2 x,
$$
that is
$$
v - y = 2(x - u).
$$
Set $u - x = t$ to get
$$
m' = (u, v) = (x + t, y - 2 t) \in G m.
$$


text:
Q: How can I subtract or add dates by some number and get value in epoch milliseconds? Is there a library which can easily achieve subtracting or adding months, day or time from a date object? I am using angularjs and looking for a solution for the following

*

*some date - 3 months or 2 weeks back from the same some date.

*some date + 3 months or 2 weeks forward from the same some date.

I tried below link but date subtraction does not work.
var from = Date.now() - 60;
var previous = new Date(2014, 10, 20);
console.log(from+", "+previous+", "+from.getDate() + "/" + from.getMonth() + "/"+from.getFullYear());

error in chrome console
TypeError: undefined is not a function

A: I suggest momentjs module. It has wide variety of choices for parsing, manipulating, display dates in javascript.
Here is the link: http://momentjs.com/


text:
Q: Cannot invoke "Telegram.Bots.NotImposterEntityRepo.findByUsername(String)" because "this.NotImposterEntityRepo" is null При вызове метода "поиска по юзернейму", получаю ответ будто, репозиторий пустой, хотя в самом MySQL он существует
Код там где применяется метод из репозитория (пробовал через @Autowired не выходит)
package Telegram.Bots;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

public class Schedule_U32_bot extends TelegramLongPollingBot{

    ArrayList<String> imposters = new ArrayList<String>();

    // Тут был @Autowired
    private NotImposterEntityRepo NotImposterEntityRepo;

    // Тут был @Autowired
    private NotImpostersEntity Entity;

    @SuppressWarnings("unused")
    @Override
    public void onUpdateReceived(Update update) {
        String username = update.getMessage().getFrom().getUserName();
        String name = update.getMessage().getFrom().getFirstName();
            if (update.hasMessage() && update.getMessage().hasText() && NotImposterEntityRepo.findByUsername(username) == null) {...}
            else if (update.hasMessage() && update.getMessage().hasText() && NotImposterEntityRepo.findByUsername(username) != null) {...}

    @Override
    public String getBotUsername() {...}

    @Override
    public String getBotToken() {...}

    public void sendMessage(Update update, String text) {
        try {
            execute (SendMessage.builder()
            .parseMode("Markdown")
            .chatId(update.getMessage()
            .getChatId())
            .text(text)
            .build());
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

Entity класс
package Telegram.Bots;

import javax.persistence.*;

@Entity
public class NotImpostersEntity {
    public NotImpostersEntity() {}

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long Id;

    private String username;

    private String name;

    private boolean imposter;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isImposter() {
        return imposter;
    }

    public void setImposter(boolean imposter) {
        this.imposter = imposter;
    }
}

Repo класс
package Telegram.Bots;

import org.springframework.data.repository.CrudRepository;

public interface NotImposterEntityRepo extends CrudRepository<NotImpostersEntity, Long> {
    NotImpostersEntity findByUsername(String username);
}

Все данные находятся в одном пакете с SpringApplication


text:
Q: How to convert string to integer in android? i want to convert userid(string) to integer but app get to crashed why?
if i removes converted method then no crashed but i want integer value what i do?
  public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    handler = new Handler();
  }
  @Override
  protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
       /**
        * Get stored session data userid from other class
        **/
        userid = "";
        session = new SessionManager(getApplicationContext());//<-- this
        HashMap<String, String> user = session.getUserDetails();
        userid = user.get(SessionManager.KEY_userid);

        /*i want convert userid to int, when i try to
          convert then app is carashed. pls help me what i am missing here*/

        Integer U_ID = Integer.valueOf(userid);
        if(U_ID >0){
            Toast.makeText(GcmMessageHandler.this, "new on id="+userid, Toast.LENGTH_LONG).show();
        }

if i removes convert function then app not crashed, but i want integer valued what i do?

A: EDIT:
if(userid != null && !userid.trim().isEmpty()){
     int  U_ID = Integer.parseInt(userid)
}


text:
Q: jquery ajax load each post I'm working on a wordpress theme with ajax load of some content from featured posts that will be displayed on homepage after a click or other trigger on post image.
Basiclly its something like this:

    title

    title

    title

The jquery code is like this:
$(".image_link").click(function () {
    $(".ajax_loaded_info").load($(this).attr("href") + " .title");
});

It does success loading the content but it shows the same content (of the last post) for all the posts..
I tried to look for a solution and try some stuff wuthout success..
Hope you guys will help me out in here.
Thanks!!

A: Here you go, a simple sub query with the 'this', doesnt look like much changed, but try it :)
$(".image_link").each(function(){
    $(this).click(function () {
        $(".ajax_loaded_info",this).load($(this).attr("href") + " .title");
    });
})


text:
Q: Django email attachment issue I have a form model:
class ManuscriptForm(forms.Form):
    name = forms.CharField(label='Your Name')
    sender = forms.EmailField(label='Your Email')
    attach  = forms.Field(label='Attach Your Manuscript', widget = forms.FileInput, required=False) # upload field!
    subject = forms.CharField()
    message = forms.CharField(widget = forms.Textarea)
    cc_myself = forms.BooleanField(required=False)

and a view:
def manuscript_form(request):
if request.method == 'POST': # If the form has been submitted...
    form = ManuscriptForm(request.POST, request.FILES) # A form bound to the POST data
    if form.is_valid(): # All validation rules pass
        name = form.cleaned_data['name']
        sender = form.cleaned_data['sender']
        attach = request.FILES['attach']
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        cc_myself = form.cleaned_data['cc_myself']

        recipients = ['info@example.com']
        if cc_myself:
            recipients.append(sender)

        from django.core.mail import send_mail, EmailMessage
        mail = EmailMessage(subject, message, sender, recipients)
        mail.attach(attach.name, attach.read(), attach.content_type)
        mail.send()
        return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
    form = ManuscriptForm() # An unbound form

return render_to_response('manuscript_form.html', {
    'form': form,
}, context_instance=RequestContext(request))

The problem is I keep getting a:"Key 'attach' not found in <MultiValueDict: {}>" error. With attachment capability taken out, all works fine. Any suggestions?

A: replace the attach = request.FILES['attach'] with attach = request.FILES.get('attach') so that the variable attach will be None when no files are "attached" by the user.
When you do request.FILES['attach'] you're assuming that the key is present, which might have been caught by your form error checker, except that the field is not required.


text:
Q: ArcGIS 10.2/10.2.1 for Desktop with Data Interoperablilty not seeing GPX files? I have ArcGIS 10.2 and 10.2.1 both with Data Interoperablilty extension. But there is a problem with GPX files. ArcGIS simply doesn't see it. In 10.1 there was no problem to drag n drop them but now it's impossible. In quick import tool, when I open FME reader gallery I can't find gpx on the list. What's going on? Have you the same problem?

A: Have you tried the GPX to Feature tool in the Arc Toolbox? It is located in the Conversion Tools > From GPS > GPX To Features.
If I attempt to drag and drop a .gpx file, a message that says 'Could not open the specified file' appears.

Try this then:  In ArcCatalog, click on Customize > ArcCatalog Options > Click on the File Types Tab and manually add in the .GPX file extension. The file will then be recognized.


text:
Q: How to force text wrapping with floated elements Here is an image of my problem.
See how the hamburger/menu icon is pushed down to the next line? I want the text to go to the next line instead, keeping the menu button and header text next to eachother. The title text and menu are floated left and right respectively.
This doesn't seem to be a clear problem (since I'm trying to do the opposite), and I can't think how the white space property could be used in this case.
The only thing that works is setting a max width on the title, but that messes up the layout at some screen sizes.
I have no custom css on these elements, just what comes with Bootstrap 3
Markup (basically lifted straight from the new Bootstrap 3 docs):

      <a class = "navbar-brand" href="<%= request.protocol + request.host_with_port%>/weather"> Weather

  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
    Toggle navigation

  </button>

  <form id="search" class="navbar-form navbar-right form-inline" method="get" action="/weather">

      <input type="text" placeholder="Search for your city or zip" class="form-control" id = "searchbox" name="search">

    <button type="submit" class="btn btn-default"></button>
  </form>

`

A: Stephen,
Two changes are required to get your desired result.
First, set .navbar-brand padding right to 70px or what you needed.
.navbar-brand {
    padding-right:70px;
}

And second, make .navbar-toggle position:absolute, right:0;
.navbar-toggle {
    position:absolute;
    right:0;
    top:0;
}

And you are done! :).
Here is demo: http://jsfiddle.net/sARaY/


text:
Q: SQLite taking user id and data from activity I have two tables in DataBaseHelper Activity one for user and one to log measurements from 5 diffenrent activities. My DataBaseHelper has the addreaiding(); to take the data. Here is the code from DataHelper
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "UserManager.db";

    // User table name
    private static final String TABLE_USER = "user";

    // Reading table name
    private static final String TABLE_READING = "reading";

    // User Table Columns names
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_NAME = "user_name";
    private static final String COLUMN_USER_EMAIL = "user_email";
    private static final String COLUMN_USER_PASSWORD = "user_password";

    //Readings Table Columns names

    private static final String COLUMN_READING_USERREFERENCE = "reading_user_reference";
    private static final String COLUMN_READING_DATETIME = "reading_datetime";
    private static final String COLUMN_READING_WEIGHT = "reading_weight";
    private static final String COLUMN_READING_AGE = "reading_age";
    private static final String COLUMN_READING_HEIGHT = "reading_height";
    private static final String COLUMN_READING_CALORIES_ = "reading_calories";
    private static final String COLUMN_READING_BMR = "reading_bmr";
    private static final String COLUMN_READING_BMI = "reading_bmi";
    private static final String COLUMN_READING_BF = "reading_bf";
    private static final String COLUMN_READING_FFMI = "reading_ffmi";

    // create table users sql query
    private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT,"
            + COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";

    // create table readings sql query
    private static final String CREATE_READING_TABLE =
            "CREATE TABLE IF NOT EXISTS " + TABLE_READING +
                    "(" +
                    COLUMN_READING_USERREFERENCE + " INTEGER NOT NULL, " +
                    COLUMN_READING_DATETIME + " TEXT DEFAULT CURRENT_TIMESTAMP, " +
                    COLUMN_READING_WEIGHT + " INTEGER," +
                    COLUMN_READING_AGE + " INTEGER , "+
                    COLUMN_READING_HEIGHT + " INTEGER," +
                    COLUMN_READING_CALORIES_ + " REAL," +
                    COLUMN_READING_BMR + " REAL," +
                    COLUMN_READING_BMI + " REAL," +
                    COLUMN_READING_BF + " REAL , "+
                    COLUMN_READING_FFMI + " REAL "+
                    ")";

    // drop table sql query
    private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
    private String DROP_READING_TABLE = "DROP TABLE IF EXISTS " + TABLE_READING;

    /**
     * Constructor
     *
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USER_TABLE);
        db.execSQL(CREATE_READING_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        //Drop User Table if exist
        db.execSQL(DROP_USER_TABLE);
        db.execSQL(DROP_READING_TABLE);

        // Create tables again
        onCreate(db);

    }

    /**
     * This method is to create user record
     *
     * @param user
     */
    public void addUser(User user) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        // Inserting Row
        db.insert(TABLE_USER, null, values);
        db.close();
    }
    public long addReading(int userreference, long datetime, int age,int weight,int height, double calories,
            double bmi, double bmr, double bf, double ffmi) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

        cv.put(COLUMN_READING_USERREFERENCE,userreference);
        cv.put(COLUMN_READING_DATETIME,sdf.format(datetime));
        cv.put(COLUMN_READING_AGE,age);
        cv.put(COLUMN_READING_WEIGHT,weight);
        cv.put(COLUMN_READING_HEIGHT,height);
        cv.put(COLUMN_READING_CALORIES_,calories);
        cv.put(COLUMN_READING_BMR,bmr);
        cv.put(COLUMN_READING_BMI,bmi);
        cv.put(COLUMN_READING_BF,bf);
        cv.put(COLUMN_READING_FFMI,ffmi);
        return db.insert(TABLE_READING,null,cv) ;
    }

I have two major problems. Firts how  ill take user ID after user logging as userreference key in the READINGS TABLE and second how to use the addreading in my activities to take the data. As an example this is Calories Activity from where i need date, age,height,weight, and calories result. I assume that the other fields (bmr,bmi,bf) should be default 0.
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import eu.healthydev.bodymeasure.R;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Calories extends BaseActivity implements AdapterView.OnItemSelectedListener{

    Spinner sp, goal_sp;
    double valofactlevel = 0;
    int goalnum = 0;
    Calendar calander;
    SimpleDateFormat simpledateformat;
    String Date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calories);
        TextView cal_pound_to_gram = (TextView)findViewById(R.id.cal_pounds_view);
        EditText weight_num = (EditText) findViewById(R.id.cal_weight_num);

        DatabaseHelper databaseHelper  = new DatabaseHelper(this);
        databaseHelper.addReading(  );

        if (MainActivity.unit_is_gram){
            cal_pound_to_gram.setText("Kilograms");
        }

        if(MainActivity.unit_is_meter){
            TextView cal_inches_to_cent = (TextView)findViewById(R.id.cal_inches_view);
            cal_inches_to_cent.setText("Centimeters");
            //cal_inches_to_cent.setWidth(200);
            EditText cent_num = (EditText)findViewById(R.id.cal_inches_num);
            cent_num.setWidth(595);
            TextView cal_feet_to_meter = (TextView)findViewById(R.id.cal_feet_view);
            cal_feet_to_meter.setText(""); //meters
            EditText cal_disappear = (EditText)findViewById(R.id.cal_feet_num);
            cal_disappear.setVisibility(View.INVISIBLE);

        }

        Button resetButt = (Button)findViewById(R.id.cal_reset_button);
        resetButt.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        EditText weight_num_reset = (EditText) findViewById(R.id.cal_age_num);
                        weight_num_reset.setText(null);

                        EditText waist_num_reset = (EditText) findViewById(R.id.cal_weight_num);
                        waist_num_reset.setText(null);

                        EditText wrist_num_reset = (EditText) findViewById(R.id.cal_feet_num);
                        wrist_num_reset.setText(null);

                        EditText hip_num_reset = (EditText) findViewById(R.id.cal_inches_num);
                        hip_num_reset.setText(null);

                        TextView bf_answer_reset = (TextView) findViewById(R.id.cal_answer);
                        bf_answer_reset.setText("");

                    }
                }
        );

        sp = (Spinner) findViewById(R.id.cal_actlevel_list);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.levelofact,android.R.layout.simple_spinner_item);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(this);

        goal_sp = (Spinner) findViewById(R.id.cal_goal_spinner);
        ArrayAdapter goal_adapter = ArrayAdapter.createFromResource(this,R.array.goalsarr,android.R.layout.simple_spinner_item);
        goal_sp.setAdapter(goal_adapter);
        goal_sp.setOnItemSelectedListener(this);

        Button calculate_calories_button = (Button)findViewById(R.id.calc_calories_button);
        calculate_calories_button.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {

                        EditText age_num = (EditText) findViewById(R.id.cal_age_num);
                        String age_s = (age_num.getText().toString());
                        double age;
                        if(TextUtils.isEmpty(age_s)){
                            age_num.setError("Field can't be empty");
                            age = 0;
                            return;
                        }
                        age = Integer.parseInt(age_num.getText().toString());

                        EditText weight_num = (EditText) findViewById(R.id.cal_weight_num);
                        String weight_s = (weight_num.getText().toString());
                        double weight = 0;
                        if(TextUtils.isEmpty(weight_s)){
                            weight_num.setError("Field can't be empty");
                            weight = 0;
                            return;
                        }
                        weight = Integer.parseInt(weight_num.getText().toString());

                        double feet = 0;
                        if (!MainActivity.unit_is_meter){
                            EditText feet_num = (EditText) findViewById(R.id.cal_feet_num);
                            String feet_s = feet_num.getText().toString();

                            if(TextUtils.isEmpty(feet_s) && !MainActivity.unit_is_meter){
                                feet_num.setError("Field can't be empty");
                                feet = 0;
                                return;
                            }
                            feet = Integer.parseInt(feet_num.getText().toString());
                        }

                        EditText inch_num = (EditText) findViewById(R.id.cal_inches_num);
                        String inch_s = inch_num.getText().toString();
                        double inches;
                        if(TextUtils.isEmpty(inch_s)){
                            inch_num.setError("Field can't be empty");
                            inches = 0;
                            return;
                        }
                        inches = Integer.parseInt(inch_num.getText().toString());

                        RadioGroup rad_group = (RadioGroup)findViewById(R.id.cal_radioGroup);
                        int check = rad_group.getCheckedRadioButtonId();
                        if (check == -1){
                            Toast.makeText(Calories.this, "Select gender", Toast.LENGTH_SHORT).show();
                        }

                        RadioButton fem_button = (RadioButton) findViewById(R.id.cal_fem_button);
                        boolean fem = fem_button.isChecked();

                        RadioButton male_button = (RadioButton) findViewById(R.id.cal_male_button);
                        boolean male = male_button.isChecked();

                        TextView calResult = (TextView) findViewById(R.id.cal_answer);
                        double bmrr = doCalories(fem, male, age, weight, feet, inches);
                        bmrr = (bmrr*valofactlevel)+goalnum;
                        String bmrstring = "";
                        bmrstring = String.valueOf(Math.round(bmrr));
                        if (goalnum == 0){
                            bmrstring = bmrstring.concat(" calories to maintain weight.");
                        }
                        else if (goalnum > 0){
                            bmrstring = bmrstring.concat(" calories to gain weight.");
                        }
                        else if (goalnum < 0){
                            bmrstring = bmrstring.concat(" calories to lose weight.");
                        }

                        if (check != -1){
                            calResult.setText(bmrstring);
                        }

                    }
                }

        );
    }

    public double doCalories(boolean fem, boolean male, double age, double weight, double feet, double inches){

        double bmrResult = 0;
        double height_in_inches;

        if (MainActivity.unit_is_gram){
            weight = weight * 2.2;
        }

        if (MainActivity.unit_is_meter){
            height_in_inches = 0.39370* inches; //actually is 0.39370 * centimeters
        }

        else height_in_inches = (feet*12)+inches;

        if (fem == true) {
            //if it is a female use this formula
            bmrResult = 10*(weight/2.2)+6.25*(height_in_inches*2.54)-5*age-161;
        }

        else if (male == true){
            //if it is a male use this formula

            bmrResult = 10*(weight/2.2)+6.25*(height_in_inches*2.54)-5*age+5;
        }

        calander = Calendar.getInstance();
        simpledateformat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date = simpledateformat.format(calander.getTime());

        return bmrResult;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Spinner one = (Spinner)parent;

        if(one.getId() == R.id.cal_actlevel_list){
            TextView myText = (TextView) view;
            if (position == 0) valofactlevel = 1.2;
            else if (position == 1) valofactlevel = 1.375;
            else if (position == 2) valofactlevel = 1.55;
            else if (position == 3) valofactlevel = 1.725;
            else if (position == 4) valofactlevel = 1.9;
        }
        else if(one.getId() == R.id.cal_goal_spinner){
            if (position == 0){
                goalnum = 0;
            }
            else if (position == 1){
                goalnum = -500;
            }
            else if (position == 2){
                goalnum = 500;
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

        //Toast.makeText(this,"Select activity level ",Toast.LENGTH_SHORT).show();

    }

}

I would apriciate any help considering that i m new in android and totally beginner in SQLite. The part of SQLite whith the fantastic help from @MikeT

A: think you may use userreference key from Reading Table as user ID in User Table instead id autoincrement. It is one to one relationship: one user - one measuring

A: Solutions:
Problem 1: You can use user_id as foreign key in reading table.
FOREIGN KEY (user_id) REFERENCES TABLE_USER(user_id)

Problem 2: Update data or you can write data also to reading table
                userId = // id of the user //

                ContentValues Values = new ContentValues();
                Values.put(COLUMN_READING_CALORIES, 500);
                            //...
                getContext().getContentResolver().update(TABLE_READING.CONTENT_URI,
                        Values,
                        TABLE_READING.user_id + " = " + userId,
                        null);

I suggest you to use Room lib as its the new successor


text:
Q: C# args.Cancel = true; not stopping my worker thread I have an application which controls some industrial processes.  Some of these processes are time-consuming so the application creates a worker thread to run them.  The thread is set to be cancellable and to report progress.
    CertifyBWThread.WorkerSupportsCancellation = true;
    // this allows the worker to report progress during work
    CertifyBWThread.WorkerReportsProgress = true;

A button is supplied to cancel the thread before it would normally finish.
if (CertifyBWThread != null)
{
    CertifyBWThread.CancelAsync();
}

As the thread runs it periodically checks to see if a cancellation has been scheduled.  args is DoWorkEventArgs .
//check for cancellation here
if (CertifyBWThread.CancellationPending)
{
    args.Cancel = true;
}

... I routinely hit this code in the debugger.   Once I've called CancelAsync() it hits this every time through a loop that controls the industrial process and sets args.Cancel to true.    But still merrily the thread runs.    What is supposed to happen when args.Cancel is set to true?

A: When your DoWork() handler checks CancellationPending, it is not sufficient to simply set DoWorkEventArgs.Cancel to true. Your DoWork handler must also stop working.
Setting DoWorkEventArgs.Cancel to true is important, because that's how the BackgroundWorker object itself will be able to tell the difference between your DoWork handler returning having cancelled the operation and returning having actually completed the operation. This addresses the possible race condition between code trying to cancel the operation and the operation itself (i.e. this way the code trying to cancel the operation can determine whether the operation was in fact cancelled, or if it completed successfully before it had a chance to check on the cancellation).
But it's up to you to write your DoWork event handler such that it will in fact interrupt its operation when the CancellationPending property gets set to true.

I've based this answer on inferences from the incomplete code example in your question. If the above does not address your concern, then please improve your question so that it includes a good, minimal, complete code example that reliably reproduces the problem.


text:
Q: corresponding align How to align first and second part od table please?
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs, makecell}
\usepackage[output-decimal-marker={,}]{siunitx}

\begin{document}
\begin{table}[htb]
    \small
    \setlength\tabcolsep{0pt}
\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}
                            c
                            S[table-format=1.6(2)]
                            S[table-format=5.3(2)]
                            S[table-format=1.4(2)]
                            S[table-format=3.1(2)]
                            cc
                            }
\Xhline{4\arrayrulewidth}
&&&&&&\\[-10pt]
\makecell[t]{Číslo\\ zdroje}
    &   {\makecell[t]{$a$\\ ($\mathrm{M}_{\odot}$)}}
        &   {\makecell[t]{$i$\\ (\si{\degree})}}
            &   {\makecell[t]{$q = \frac{M_2}{M_1}$}}
                &   {\makecell[t]{$\omega$\\ (\si{\degree})}}
                    &   {\makecell[t]{$i$\\ ($\mathrm{M}_{\odot}$)}}
                        &   {\makecell[t]{$a$\\ ($\mathrm{M}_{\odot}$)}}    \\
    \midrule
5 & 43,9(3)         & 81,0(11)          &   0,3821              &               &               &       \\

\Xhline{4\arrayrulewidth}
    \multicolumn{7}{l}{\footnotesize \textit{Pozn:}
Čísla v závorkách jsou chyby posledních uvedených cifer.}
\end{tabular*}
    \end{table}

    \end{document}

EDIT
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs, makecell,amsmath, graphicx}
\usepackage[output-decimal-marker={,}]{siunitx}
\newcommand\stack[1]{\multicolumn{1}{c}{\shortstack{#1}}}
\begin{document}

\begin{table}[htb]
    \small\centering
    \begin{tabular}{@{}
            c
            S[table-format=3.2(2)]
            S[table-format=3.2(2)]
            S[table-format=1.4]
            S[table-format=2.3(2)]
            S[table-format=2.3(2)]
            S[table-format=6.0]
        }\Xhline{4\arrayrulewidth}
        &&&&&&\\[-10pt]
        \shortstack{Číslo\\ zdroje}
        &   \stack{$q = \dfrac{M_2}{M_1}$}
        &   \stack{$M_1$\\ ($\mathrm{M}_{\odot}$)}
        &   \stack{$M_2$ \\ ($\mathrm{M}_{\odot}$)}
        &   \stack{$R_1$\\ ($\mathrm{R}_{\odot}$)}
        &   \stack{$R_2$\\ ($\mathrm{R}_{\odot}$)}
        &   \stack{$V_{\gamma}$\\ (\si{\kilo\meter\per\second})}    \\\midrule
        5 & 43,9(3)         & 81,0(11)          &   0,3821              &3,534(55)  &
        5,615(84)   &   30000   \\
        6 & 43,0(24) &      76,4                &   0,3906          &
        &               &               \\
        \Xhline{4\arrayrulewidth}
    \end{tabular}

\smallskip
\resizebox{\linewidth}{!}{\textit{Pozn:}
Čísla v závorkách jsou chyby posledních uvedených cifer. $^*$značí fixované
parametry.}

    \caption{Příklady zjištěných parametrů II}
\end{table}
\end{document}

A: Use
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs, makecell,amsmath, graphicx}
\usepackage[output-decimal-marker={,}]{siunitx}
\newcommand\stack[1]{\multicolumn{1}{c}{\shortstack{#1}}}

\begin{document}
    \begin{table}[htb]
        \small\centering
        \begin{tabular}{@{}
                c
                S[table-format=3.2(2)]
                S[table-format=3.2(2)]
                S[table-format=1.4]
                S[table-format=2.3(2)]
                S[table-format=2.3(2)]
                S[table-format=6.0]
            }\Xhline{4\arrayrulewidth}
            &&&&&&\\[-10pt]
            \shortstack{Číslo\\ zdroje}
            &   \stack{$a$\\ ($\mathrm{M}_{\odot}$)}
            &   \stack{$i$\\ ($\si{\degree}$)}
            &   \stack{$q = \dfrac{M_2}{M_1}$}
            &   \stack{$\Omega_1$\\ ($\si{\degree}$)}
            &   \stack{$\Omega_2$\\ ($\si{\degree}$)}
            &   \stack{$T_1$\\ ($\mathrm{K}$)}    \\\midrule
            5 & 43,9(3)         & 81,0(11)          &   0,3821              &3,534(55)  &
            5,615(84)   &   30000$^*$   \\
            6 & 43,0(24) &      76,4$^*$                &   0,3906          &
            &               &               \\

            \Xhline{4\arrayrulewidth}
        \end{tabular}

    \smallskip
    \resizebox{\linewidth}{!}{\textit{Pozn:}
    Čísla v závorkách jsou chyby posledních uvedených cifer. $^*$značí fixované
    parametry.}

        \caption{Příklady zjištěných parametrů II}
    \end{table}

\end{document}

A: by exploiting loaded packages and on the basis of the my previous answer on yours (almost the same) questions:
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs, makecell}
\usepackage{amsmath, amssymb, bm}
\usepackage[output-decimal-marker={,},
            table-align-text-post=false]{siunitx}

\begin{document}
\begin{table}[htb]
    \small
    \setlength\tabcolsep{0pt}
\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}
                            c
                            S[table-format=2.1(1)]
                            S[table-format=2.1(2)]
                            S[table-format=1.4]
                            S[table-format=1.3(2)]
                            S[table-format=1.3(2)]
                            S[table-format=5.0,
                              table-space-text-post={*}]
                            }
    \toprule
\makecell{Číslo\\ zdroje}
    &   {\makecell{$a$\\ ($\mathrm{M}_{\odot}$)}}
        &   {\makecell{$i$\\ (\si{\degree})}}
            &   {\makecell{$q = \frac{M_2}{M_1}$}}
                &   {\makecell{$\omega$\\ (\si{\degree})}}
                    &   {\makecell{$i$\\ ($\mathrm{M}_{\odot}$)}}
                        &   {\makecell{$a$\\ ($\mathrm{M}_{\odot}$)}}    \\
    \midrule
            5 & 43,9(3)         & 81,0(11)          &   0,3821              &3,534(55)  &
            5,615(84)   &   30000$^*$   \\
            6 & 43,0(24) &      76,4$^*$                &   0,3906          &
            &               &               \\
    \midrule[\heavyrulewidth]
    \multicolumn{7}{l}{\footnotesize \textit{Pozn:}
Čísla v závorkách jsou chyby posledních uvedených cifer.}
\end{tabular*}
    \end{table}
\end{document}


text:
Q: C# style Action, Func, etc in C++0x C# has generic function types such as Action<T> or Func<T,U,V,...>
With the advent of C++0x and the ability to have template typedef's and variadic template parameters, it seems this should be possible.
The obvious solution to me would be this:
template <typename T>
using Action<T> = void (*)(T);

however, this does not accommodate for functors or C++0x lambdas, and beyond that, does not compile with the error "expected unqualified-id before 'using'"
My next attempt was to perhaps use boost::function:
template <typename T>
using Action<T> = boost::function<void (T)>;

This doesn't compile either, for the same reason.
My only other idea would be STL style template arguments:
template <typename T, typename Action>
void foo(T value, Action f) {
    f(value);
}

But this doesn't provide a strongly typed solution, and is only relevant inside the templated function.
Now, I will be the first to admit that I am not the C++ wiz I prefer to think I am, so it's very possible there is an obvious solution I'm not seeing.
Is it possible to have C# style generic function types in C++?

A: I think the syntax should be like this:
template <typename T>
using Action = void (*)(T);

I couldn't get that to compile either, though (g++ v4.3.2).
The general STL style function template is not strongly typed in the strictest sense, but it is type safe in the sense that the compiler will ensure that the template is only instantiated for types that fulfill all the requirements of the function. Specifically it will be a compiler error if the Action is not callable with one parameter of type T. This a very flexible approach since it doesn't matter if Action is instantiated to be a function or some class that implements operator().
The old non-C++0x workaround for the missing templated typedef would be to use a templated struct with a nested typedef:
template <typename T>
struct Action {
   typedef boost::function<void (T)> type;
};

template <typename T>
void foo(T value, typename Action<T>::type f) {
    f(value);
}

A: Gcc doesn't support yet template aliases (see here), and I'm not sure if variadic template alias are considered. I don't think other compilers support already this feature.
I will just use std::function or std::function instead of Action or Func.
Of course you can define variadic template classes Action or Func from std::function but I don't see the benefit.

A: I don't think a generic function type is intuitive C++, because C++ templates work differently to generics.
The C++ way is to use function objects - anything which you can put () after and it makes sense to the compiler.  This can be a function pointer, a class with operator(), and so on.  This works because C++ templates are like fancy macros, and as long as the code makes sense with the types substituted you're OK.
C# generics don't work like that - they're more restrictive, probably in an effort to improve error messages (since getting C++ templates wrong is famously verbose in the output).  I don't know too much about C# generics, but I think they rely on something which is more like callbacks, hence the usefulness of the function generics.


text:
Q: Getting Id of standard controller to query info from a custom object I have a object, Student, and I want to display a list of courses the student is taking. I have a junction object between Student and Courses called StudentCourseDtlAssc__c.
I am showing the list on the student page (see below):

The list below shows every entry in the StudentCourseDtlAssc__c object.
I want to show only the coures assigned to, in this case, Charlie Brown.
<apex:page standardController="Students__c" extensions="StudentCourseList">
    <apex:form >
        <apex:pageBlock title="Student Schedule" id="student_schedule">
            <apex:pageBlockTable value="{!CourseDetails}" var="st">
                <apex:column >
                    <apex:commandLink action="{!deleteCourse}" value="Del" id="commandLinkDelete" >
                        <apex:param name="studentcourse_id" value="{!st.id}" assignTo="{!studentcourse_id}"/>
                    </apex:commandLink>
                </apex:column>
                <apex:column value="{!st.Course_Detail__r.FKCourse__r.Name}"/>
                <apex:column value="{!st.Course_Detail__r.Professor__c}"/>
                <apex:column value="{!st.Course_Detail__r.FKRoom__r.Name}"/>
                <apex:column value="{!st.Course_Detail__r.DOW_Abbr__c}"/>
                <apex:column value="{!st.Course_Detail__r.StartDate__c}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Here is my controller
public class StudentCourseList {
    private ApexPages.StandardController controller {get; set;}
    public string studentcourse_id {get;set;}
    private Students__c s;
    public StudentCourseList(ApexPages.StandardController controller){
    this.controller = controller;
    this.s = (Students__c)controller.getRecord();
    }
    public List<StudentCourseDtlAssc__c> CourseDetails;
    public List<StudentCourseDtlAssc__c> getCourseDetails(){
        List<StudentCourseDtlAssc__c> courses = Database.query(
        'SELECT StudentCourseDtlAssc__c.Course_Detail__r.FKCourse__r.Name,'+
        'StudentCourseDtlAssc__c.Id, ' +
        'StudentCourseDtlAssc__c.Course_Detail__r.DOW_Abbr__c,' +
        'StudentCourseDtlAssc__c.Course_Detail__r.Professor__c,' +
        'StudentCourseDtlAssc__c.Course_Detail__r.FKRoom__r.Name,' +
        'StudentCourseDtlAssc__c.Course_Detail__r.StartDate__c FROM StudentCourseDtlAssc__c ' +
        '');
        return courses;
    }

    public PageReference deleteCourse() {
        List<StudentCourseDtlAssc__c> deleteObj = [SELECT Id FROM StudentCourseDtlAssc__c WHERE StudentCourseDtlAssc__c.Id =:studentcourse_id];
        delete deleteObj;
        return null;
    }
}

I tried to write my query as
'SELECT StudentCourseDtlAssc__c.Course_Detail__r.FKCourse__r.Name,'+
            'StudentCourseDtlAssc__c.Id, ' +
            'StudentCourseDtlAssc__c.Course_Detail__r.DOW_Abbr__c,' +
            'StudentCourseDtlAssc__c.Course_Detail__r.Professor__c,' +
            'StudentCourseDtlAssc__c.Course_Detail__r.FKRoom__r.Name,' +
            'StudentCourseDtlAssc__c.Course_Detail__r.StartDate__c FROM StudentCourseDtlAssc__c WHERE StudentCourseDtlAssc__c.Student__r.Id =:s.Id'

I get an error:
Variable does not exist: s.Id

How do I pass the student id so I can query only course to that student?

A: You can't use an sObject binding within a dynamic SOQL query. Try assigning that to another variable and then reference it:
Id sId = s.Id;
query = 'YourQuery WHERE StudentCourseDtlAssc__c.Student__r.Id = :sId';


text:
Q: Get instance of AppBar Button In my xaml I have 2 different AppBarrs in resources:
 <phone:PhoneApplicationPage.Resources>

    <shell:ApplicationBar x:Key="appbar1" IsVisible="True">
        <shell:ApplicationBarIconButton x:Name="abMain1" IconUri="/icons/appbar.radeos.png" Text="radeos"
                                        Click="abMain_Click" />
    </shell:ApplicationBar>

    <shell:ApplicationBar x:Key="appbar2" IsVisible="True">
        <shell:ApplicationBarIconButton x:Name="abMain" IconUri="/icons/appbar.radeos.png" Text="radeos"
                                        Click="abMain_Click" />
        <shell:ApplicationBarIconButton x:Name="abLast" IconUri="/icons/appbar.back.rest.png" Text="last"
                                        Click="abLast_Click" />
        <shell:ApplicationBarIconButton x:Name="abNext" IconUri="/icons/appbar.next.rest.png" Text="next"
                                        Click="abNext_Click" />
        <shell:ApplicationBarIconButton x:Name="abClosePopup" IconUri="/icons/appbar.cancel.rest.png" Text="close"
                                        Click="abClosePopup_Click" />
    </shell:ApplicationBar>

</phone:PhoneApplicationPage.Resources>

And I switch it in code, when I need it using:
ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar) Resources["appbar1"];

or
ApplicationBar = (Microsoft.Phone.Shell.ApplicationBar) Resources["appbar2"];

Question is: How get instance of AppBarr Buttons (ex. abMain1) in any place in code?  Visual Studio see this field, but it always null (because it in resources).

A: You should be able to access like so
ApplicationBarIconButton abMain1Button = (ApplicationBarIconButton) ApplicationBar.Buttons[0];


text:
Q: NSAutoReleasePool Leaking Can anyone tell me why is NSAutoreleasePool leaking in this code. I am using instruments to check leaks & this code is somehow leaking. Can anyone guide me to the right direction. I have the exact same code elsewhere & its running fine.
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:self.url];
 [request setDelegate:self];

 NSOperationQueue *queue = self.downloadQueue;
 [queue addOperation:request];
 [request release];

A: It should go away if you create an NSAutoreleasePool around that code. This usually happens if this code is not being run on the main thread.
NSAutoreleasePool* pool = [NSAutoreleasePool new];
// Your code goes here
[pool drain];

Also, be aware that if you are looping inside an NSAutoreleasePool new/drain block, you will appear to leak until you hit the drain. The upshot of this is if you are allocating too much memory inside the loop your app can still run out of memory. In that case you may need to create and drain a second NSAutoreleasePool every time through the loop (or possibly every nth time through the loop to avoid some of the overhead).

A: Are you running this code on a secondary thread?  If so did you setup an autorelease pool on entry?


text:
Q: XSLT: Getting rid of elements with duplicated text values and keeping one with latest timestamp I have the following XML:
<root>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-16T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-24T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-07-07T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Late</status>
        <timestamp>2022-08-05T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Delivered</status>
        <timestamp>2022-09-02T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-13T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Late</status>
        <timestamp>2022-08-01T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Late</status>
        <timestamp>2022-07-03T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-13T00:00:00Z</timestamp>
    </entry>
</root>

Is there a way using XSLT to remove <entry> elements with duplicated <status> values and to keep only the <entry> with the latest <timestamp> xs:dateTime value? The elements are in a random order with other many other possible status type values intermingled all under the <root> element.
My desired output:
 <root>
    <entry>
        <status>On Time</status>
        <timestamp>2022-07-07T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Late</status>
        <timestamp>2022-08-05T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Delivered</status>
        <timestamp>2022-09-02T00:00:00Z</timestamp>
    </entry>
</root>

A: Please try the following XSLT.
Input XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-16T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-24T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-07-07T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Late</status>
        <timestamp>2022-08-05T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Delivered</status>
        <timestamp>2022-09-02T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-13T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Late</status>
        <timestamp>2022-08-01T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>Late</status>
        <timestamp>2022-07-03T00:00:00Z</timestamp>
    </entry>
    <entry>
        <status>On Time</status>
        <timestamp>2022-06-13T00:00:00Z</timestamp>
    </entry>
</root>

XSLT 2.0
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" method="xml"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/root">
        <xsl:copy>
            <xsl:for-each-group select="entry" group-by="status">
                <xsl:sort select="current-grouping-key()" order="descending"/>
                <xsl:for-each select="current-group()">
                    <xsl:sort select="timestamp" order="descending"/>
                    <xsl:if test="position() = 1">
                        <xsl:copy-of select="."/>
                    </xsl:if>
                </xsl:for-each>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output
<?xml version='1.0' ?>
<root>
  <entry>
    <status>On Time</status>
    <timestamp>2022-07-07T00:00:00Z</timestamp>
  </entry>
  <entry>
    <status>Late</status>
    <timestamp>2022-08-05T00:00:00Z</timestamp>
  </entry>
  <entry>
    <status>Delivered</status>
    <timestamp>2022-09-02T00:00:00Z</timestamp>
  </entry>
</root>