File does not open in C

Question: File does not show up when I enter what i want but it also doesn't give me the error.
The file is:

Account Name    Balance
100 Jones   24.98
200 Doe     345.67
300 White   0.00
400 Stone   -42.16
500 Rich    224.62

int main(void)
{
    int account;
    char name[30];
    float balance;
    int request;
    char singleline[150];
    FILE * fpointer;

    fpointer = fopen("acc.txt","r");
    while (!feof(fpointer))
    {
        fgets(singleline, 150, fpointer);
    }
    if ((fpointer= fopen("acc.txt", "r"))==NULL)
        printf("File could not be opened\n");
    else
    {
        printf("Enter Request\n"
               "1 - List accounts with zero balances\n"
               "2 - List accounts with credit balances\n"
               "3 -  List accounts with debit balances\n"
               "4 - Endof run\n");
        scanf("%d", &request);
        while (request !=4)
        {
            fscanf(fpointer,"%d%s%f", &account,name, &balance);
            switch(request)
            {
            case 1:
                printf("\nAccounts with zero balnces:\n");
                while(!feof(fpointer))
                {
                    if (balance ==0)
                        printf("%-10d%-13s%7.2f\n", account, name, balance);
                    fscanf(fpointer,"%d%s%f", &account,name, &balance);
                }
                break;
            case 2:
                printf("\nAccounts with credit balances:\n");
                while(!feof(fpointer))
                {
                    if (balance<0)
                        printf("%-10d%-13s%7.2f\n", account, name, balance);
                    fscanf(fpointer,"%d%s%f", &account,name, &balance);
                }
                break;
            case 3:
                printf("\nAccounts with debit balances:\n");
                while(!feof(fpointer))
                {
                    if (balance>0)
                        printf("%-10d%-13s%7.2f\n", account, name, balance);
                    fscanf(fpointer,"%d%s%f", &account,name, &balance);
                }
                break;
            }
            rewind (fpointer);
            printf("\n?" );
            scanf("%d",&request);
        }
        printf("End of run.\n");
    }
    fclose(fpointer);
    system("pause >nul");
    return 0;
}

Comment: [`while (!feof(fpointer))` is always wrong.](http://stackoverflow.com/a/26557243/1983495) And how can you tell that the file did not open, if you are not checking that?
Comment: Are you allowed to use functions? Question: what is the first `while` loop for? and it should be `while (fgets(singleline, sizeof(singleline), fpointer)) {}`
Comment: @iharob +1 there are numerous questions about incorrect use of `feof()`
Comment: There is no clear statement as to what you are trying to do, or what the problem is. What does *"File does not show up"* mean? You didn't even check the result of `fopen()`.
Comment: I see you are using `float` and `if (balance == 0)` which is prone to inequality when `balance` is computed from values which cannot be exactly represented in `float`. See the very recent question http://stackoverflow.com/questions/29084695/c-comparing-floats-with-if-statements
Answer: Your code has a lot of problems, but the most important are

You fopen() the file for doing nothing and don't fclose() it, and I think that on a MS Windows computer you cannot fopen() it again, but you do.
You check if the file didn't open the second time, but not the first time, so it's like if you didn't check at all, moreover, you proceed to fclose() the file after the check has told you that it did not open.
while (!feof(file)) is always wrong., so you should change the condition for your while loop.

Notice that you are repeating code in every switch case, so you should consider using a function, this is your code with all the problem fixed
#include <stdio.h>

int main(void)
{
    int   account;
    char  name[30];
    float balance;
    int   request;
    FILE *fpointer;

    if ((fpointer = fopen("acc.txt", "r")) == NULL)
        printf("File could not be opened\n");
    else
    {
        int  chr;
        char line[100];
        printf("Enter Request\n"
               "1 - List accounts with zero balances\n"
               "2 - List accounts with credit balances\n"
               "3 -  List accounts with debit balances\n"
               "4 - Endof run\n");
        scanf("%d", &request);
        while ((request != 4) && (fgets(line, sizeof(line), fpointer) != NULL))
        {
            switch(request)
            {
            case 1:
                printf("\nAccounts with zero balnces:\n");
                while(fscanf(fpointer,"%d%s%f", &account, name, &balance) == 3)
                {
                    if (balance == 0)
                        printf("%-10d%-13s%7.2f\n", account, name, balance);
                }
                break;
            case 2:
                printf("\nAccounts with credit balances:\n");
                while(fscanf(fpointer,"%d%s%f", &account, name, &balance) == 3)
                {
                    if (balance < 0)
                        printf("%-10d%-13s%7.2f\n", account, name, balance);
                }
                break;
            case 3:
                printf("\nAccounts with debit balances:\n");
                while(fscanf(fpointer,"%d%s%f", &account, name, &balance) == 3)
                {
                    if (balance > 0)
                        printf("%-10d%-13s%7.2f\n", account, name, balance);
                }
                break;
            }
            rewind (fpointer);
            printf ("\n?" );

            while (((chr = getchar()) != EOF) && (chr != '\n'));
            scanf("%d", &request);
        }
        printf("End of run.\n");
        fclose (fpointer);
    }

    return 0;
}

Answer: Never use eof() inside a loop condition. It's a very bad practice.
Here's a reference which you should take a peek:
Why is "while ( !feof (file) )" always wrong?
Solution:
First take the string from fpointer to a temporary variable and check for eof() and if it permits then put that temporary string to your desired variable.
Example:
while(true){
    fgets(tmp, sizeof(tmp), fpointer);
    if(feof(fpointer)){ break;}
    text=tmp;
    }

Comment: I don't see why anyone would declare char tmp[100] while they are using 150 as the size. Anyway thanks for the tip.. and yeah, I just used feof() because the OP seems to like it...
Comment: There is absolutely no need to use break, at all. It makes the logic hard to follow. Your code is just `while ((text = fgets(tmp, sizeof(tmp), fpointer)) != NULL) {}`, and not even as good because if you make `char tmp[100]` your code is immediately broken.

File does not open in C


cron jobs on amazon aws

Question: I am currently using amazon's elastic beanstalk as my web server. I need to be able to run some cron jobs every minute (so launching machines and shutting them down is not an option).
The solutions i have found for now are:

run an ec2 machine and run those cron's over there
use aws ops that is bit complicated to setup + will eventually run an ec2 machine anyways.

both of those solutions seems like an over kill. is there any better solution out there? the perfect solution would be a "Platform as a service" (PaaS) one.
Thanks
Answer: It looks like it's possible to do it directly inside Beanstalk:
AWS Elastic Beanstalk, running a cronjob
If the endpoint to be run is external facing (to the web) you could check out Azure Scheduler:
http://azure.microsoft.com/en-us/services/scheduler/
Comment: I was hoping to use only amazon's set of tools, however, azure's service might be good for us. thanks
Comment: check this link as well : http://stackoverflow.com/questions/11616205/run-scheduled-task-in-amazon-without-cron
Answer: well, few years after. here are some new options to deal with this issue:

as Adam said, there is an option to set a recurring event in elastic beanstalks' configuration named "container commands".
the behavior is as the following code:
<code>
container_commands:
name of container_command:
command: "command to run"
leader_only: true
name of container_command:
command: "command to run"
</code>
reference: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html#linux-container-commands
Second option is using the Lambda functions with schedule events - http://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html

hope this will help anyone that bumps into this issue

cron jobs on amazon aws


Blisters on Fingers: Double Bass

Question: My band practiced for four hours tonight and I got a blister on my right middle finger, popped it (as I was playing), got another one, and got one on my index finger. We're performing twice tomorrow (I'm also playing with another group so three times, total) and I have the last lead in the last song and don't want to ruin it.
As it is, I'm not sure I'll be able to play as well as I normally can due to the blisters so my question is if there's some way I can get rid of them, make them stop hurting, etc.  by the time we play tomorrow.
Comment: Ah yes, the joy of playing music... When we played three gigs in a row and I already had blisters on both my index in middle finger before the last one, I would usually switch to playing as much as possible with the bow, or the ring finger, the index finger in _very_ angled position (so it's more the knuckle than the tips that get rubbed off), or the thumb. Strangely enough, there's also a kind of slap technique that puts considerably less strain on the fingers' skin than normal fingerstyle: not the usual pull-upwards&let-snap-down, rather a very brief hit from above&only slightly sidewards.
Comment: (My instrument is actually a 5-string cello though, not a proper double bass, so somewhat less torturous...)
Comment: I try to alternate fingers, rather than favour a couple. That way, if there's a finger problem, there's usually a finger or two that haven't been worn out. Mind you, that's on EBG, so not exactly the same. As lefta says, a slap technique is another option, and can alleviate wear and tear on certain well used digits.
Comment: I would also suggest that 4 hrs is too long for a rehearsal. In a lot of cases, everyone should go in having prepared their own parts. If you did the best part of that 4 hrs actually playing - and it seems that way with the blisters - that's a heck of a lot of songs/tunes. Or did the same ones get played over and over? There wouldn't be that much playing at a lot of gigs! Just a thought for next rehearsal...
Answer: I play 5 string EBG. Sometimes if I get a new bass or change strings, I'll get blisters.
I use this stuff - it works pretty well. Protects the tender area but you still have flexibility to play.
Just spray it on and let it dry. It smarts a bit at first.
New-Skin® Liquid Spray Bandage .
Answer: Bandage them up, or use a bandage substitute.  Then do what you have to do.  It'll hurt a bit.  You'll get through.
Comment: I'd rather play with cotton gloves than bandages!
Comment: OK, cotton gloves then.  Whatever gets you through it.  Won't be perfect, but you'll cope.   Or, if you really can't cope, dep out the gigs. No-one's THAT irreplacable.

Blisters on Fingers: Double Bass


How to add GET parameters to an ASIHttpRequest?

Question: How can I add GET parameters to an ASIHttpRequest?
I want to go from http://mysite.com/server to http://mysite.com/server?a=1&b=2 programmatically.
I have all my parameters as key-value pairs in an NSDictionary object.
Thanks
Comment: This has been discussed here:
http://stackoverflow.com/questions/718429/creating-url-query-parameters-from-nsdictionary-objects-in-objectivec
Hope this helps!
Answer: Use string format like
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"1",@"a",@"2",@"b", nil];

NSMutableString *prams = [[NSMutableString alloc] init];

for (id keys in dict) {
    [prams appendFormat:@"%@=%@&",keys,[dict objectForKey:keys]];
}
NSString *removeLastChar = [prams substringWithRange:NSMakeRange(0, [prams length]-1)];
NSString *urlString = [NSString stringWithFormat:@"http://mysite.com/server?%@",removeLastChar];

NSLog(@"urlString %@",urlString);

Comment: It does not escape special characters.


Assigning even partitions for Cross-Validation

Question: This is a very basic question about cross-validation. Say that I have a sample size of 2901(or any difficult to divide number). How do I split this up into equal partitions (other than n=1)? And how big should I make each partition?
For example, if I make each partition size 300 (which gives me approximately 10 partitions), I will have some data points that are in more than one partition, giving it an unfair weight. Is this acceptable/what do people normally do about this?
By the way, I wanted to split it into equal partitions so that I can easily write code that will perform cross validation for any number of partitions.
Answer: You could also draw a sample of size 2901 from a uniform value taking its values in {1, 2, ... 10} (for 10-CV). This sample determines a random partition of the data, with 10 sub-groups of roughly equal size (each sub-group has equal probability of being drawn for each training observation).
For each of these sub-groups you can then compute a sub-group average measure (such as MSE, as opposed to total sub-group squared error) as suggested by Matthew.
I wouldn't think small differences in subsamble sizes would matter much if you take sub-group averages, but if you are worried you can always repeat this sampling procedure multiple times to get an average 10-CV estimate.
Comment: I like this solution. It seems that it could add significantly to my storage needs if the sample size is much larger than 2901. Basically, you are adding an extra column of data (if each sample is a row). This is probably not big enough of a problem to really worry about it.
Comment: Exactly, 2901 new values is nothing for a computer.
Answer: A lot of validation measures are usually 'averaged' over the whole partition to allow for direct comparison on other data sets. For example, mean square error for continuous prediction is
$$
\text{MSE} = \frac{1}{N} \sum_{i=1}^N (\text{prediction}_i - \text{actual}_i)^2.
$$
Other examples are MAE, area under the ROC curve, Brier score, R squared (generalized or otherwise). In this way, if the difference in size between partitions is small (say, within a few) then you shouldn't be worried about any kind of imbalance. In your case for 10-fold CV, (after shuffling the data to ensure random assignment) I would take $\lfloor 2901/10 \rfloor = 290$-sized partitions and give the last data point to any of the partitions. It won't matter which.
You can always make your validation measure size-independent by dividing by the partition size. For example, if you calculate logarithmic scoring in total, then just divide the total score by the partition size.
Comment: I think I will probably end up shuffling all my data first and then do the 2901/n with remainder randomly assigned to partitions.


Sup of $p$-norms of positions of martingale and $p$-norm of its closure

Question: Let $(\Omega, (\mathcal{F}_t), P)$ be a filtered probability space.
Let $1\leq p\leq \infty$ and $M$ be a $p$-integrable $(\mathcal{F}_t)$-martingale closed by $M_\infty$. What do we need from $(\mathcal{F}_t)$, $p$, and $M_\infty$ (e.g. right-continuity of filtration, $p<\infty$, $p$-integrability of $M_\infty$) in order to have
$$
\sup_{0\leq t<\infty}\Vert M_t\Vert_p = \Vert M_\infty\Vert_p?
$$
Answer: Nothing more  is needed. Assume for the moment that $M_\infty\in L^p$. $M$ admits a right continuous modification, call it $X$. The process $X$ is a martingale with respect to $(\mathcal F_{t+})$. Being a modification of $M$, $X$ is also closed by $M_\infty$, and because $X$ is right continuous, you have $\lim_{t\to\infty} X_t=M_\infty$ a.s. and in $L^p$. Because $X$ is a modification of $M$:
$$
\sup_{0\le t<\infty}\|M_t\|_p=\sup_{0\le t<\infty}\|X_t\|_p.
$$
Also, $t\mapsto \|X_t\|_p$ increases because $|X_t|^p$ is a submartingale. It follows that $$
\sup_{0\le t<\infty}\|M_t\|_p=\sup_{0\le t<\infty}\|X_t\|_p=\lim_{t\to\infty}\|X_t\|_p =\|M_\infty\|_p.
$$
The 1-integrability of $M_\infty$ is implicit in "$M$ is closed by $M_\infty$". For $p>1$,  the $p$-integrability is not needed. Indeed, by Fatou and the previously noted monotonicity, $\|M_\infty\|_p\le\sup_{0\le t<\infty}\|M_t\|_p$. And if this last inequality is strict, then $M_\infty$ is $p$-integrable.
Comment: This is Lévy's theorem. The a.s. convergence (to some $L^1$ r.v., call it $Z$) needs only that $\sup_t\Bbb E[|M_t|]$ be finite. The a.s. limit closes the martingale, in the sense that $M_t=\Bbb E[Z|\mathcal F_t]$ for all $t$, if and only if $(M_t)$ is uniformly integrable. This is a weaker condition than $\sup_t|M_t|\in L^1$.
Comment: Thanks! So we only need $M$ to be a.s. convergent to $M_\infty$? Why is that exactly if $M_\infty$ isn't $p$-integrable or $p=1$?
Comment: I interpreted "$M$ [...] closed by $M_\infty$" to mean that $M_t=\Bbb E[M_\infty\mid\mathcal F_t]$, $t\ge 0$. Implicit in this is that $M_\infty\in L^1$.  We then know that $M_t$ converges a.s. and in $L^1$ to $M_\infty$.I interpreted "
Comment: Why do we know that $M_t$ converges a.s. to $M_\infty$? I know that is the case if the time-sup $\sup_t M_t$ is integrable, but I didn't assume that and I don't see how closedness implies $M_t$ to have an integrable time-sup either


A crazy number theoretic problem

Question: How many positive integers satisfy the condition that the product of their digits multiplied by the sum of their digits equals themselves? For example,
13 is not equal to (1+3)(1×3)
Here is how i proceeded
I defined a number n such that $10^{k+1}$$>$$n$$>$$10^k$
Next, i will expand the number in powers of tens.
Now i am trying to create a bound, but at this stage, i am unsuccessful in each of my attempts. Please help me!
Comment: There's actually a name for this sort of number! Let $n$ be a number such that

$$n = \text{(product of n's digits)} \times \text{(sum of n's digits)}$$

Then $n$ is what we call a "sum-product number." (https://en.wikipedia.org/wiki/Sum-product_number) In base $10$, there are only four such numbers, only two of which are nontrivial - 135 and 144. It has been proven that the number of such numbers in any given base is also finite.

The Wikipedia article linked will be a good starting point for looking into this topic. I don't know much offhand about proving stuff of this sort though.
Comment: *"But i assume this question will not have any such duplicates"* No. As a rule of thumb, every idea you have is unoriginal.
Comment: Did you search the site this time before posting?
Comment: What do you mean?
Comment: I  mean, whether your question is new here or already has answers, i.e., is a duplicate?
Comment: No i have not searcehed
Comment: You should always do this to avoid duplicates (which you have for several of your questions already).
Comment: I am actually new so i dont know much i joined only 2 days before
Comment: But i assume this question will not have any such duplicates
Comment: A $k$-digit solution $n$ would satisfy $10^{k-1}\le n\le k9^{k+1}$ so $90k\ge (10/9)^k$ and (by a computer search) $k\le 84$. So it may be hard to find all solutions by brute force.
Comment: Yes that is the problem now
Comment: @J.G.:  you can reduce the search a lot by thinking about factorization.  I sketch it in my edit.  I think the search space is down to tens or hundreds of millions, which is easily doable.
Answer: To set an upper bound, note that each digit is at most $9$.  If the number has $n$ digits, the computation gives at most $(9n)(9^n)=n9^{n+1}$.  An $n$ digit number is at least $10^{n-1}$.  Alpha tells us that for $n=85$ we have the number is greater than the sum of digits times the product of digits, so you only have to search up to $10^{84}$.  Happy hunting.
Now note that most of the factors of the number need to be $2,3,5,7$ because the only way you can get a larger one is from the sum of the digits.  As lulu points out you can't have both $2$ and $5$ as factors because it would end in zero and the product would be zero.  The number needs to be $2^a3^b7^cd$ or $3^a5^b7^cd$ with $d \lt 9\cdot 84$.  If you have a programming language that supports large ints, like Python, and a nice way to turn a number into a string you can just do the search.  A little cleverness can speed it up, like noting that $e$ can't be that large unless the other numbers are large.
Comment: @Md.ShamimAkhtar You could give it some thought yourself. You might learn something from it.
Comment: A bound is what you asked for.
Comment: Note: saves time to note that your number can't be divisible by both $2$ and $5$ (else it would end in $0$ and the product of its digits would be $0$).
Comment: I don't think this is a reasonable contest problem unless you can reduce the search space much more.  I don't know how and the Wikipedia article only cites the same upper limit I found.
Comment: So whats next? You just created the bound, but this is just a mere observation
Comment: @lulu:  good point.  That reduces the search space considerably.  I saw that they only used $2,3,7$ and $3,4,5$ in the Wikipedia article after I wrote this but didn't think about it.
Comment: Yes approach is good, but what if such problem coomes in any contests?

A crazy number theoretic problem


Add and remove Jar files and classes from inside JavaScript (Rhino / Nashorn)

Question: Basically I have Java a system which runs a number of "plugin" scripts using Javascript through either Rhino or Nashorn, depending on what JRE the user has installed.
I also have a system within the Java environment that allows the plugging in of extra .JAR files at runtime.
That's all fine and dandy. However I have now come across a situation where I want something slightly different: I want to load a .JAR file into the ClassPath from within the Rhino/Nashorn engine instance, so the classes are available to that instance (and that instance only), and then remove them when the engine finishes running.
I know I can easily call my existing Java routine to load the URL of the .JAR file from with JavaScript, however the classes are then permanently installed and I can't get rid of them.
The problem basically stems from the fact that a user could have multiple plugins with different versions of the same .JAR file (it's provided by a third party and used for multiple different plugins in different ways), and I need the plugins to be able to load the right one and then ditch it afterwards.
My existing URL loader is:
public static void addURL(URL u) {
    final Class[] parameters = new Class[]{URL.class};
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysloader, new Object[]{u});
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Now I don't actually have much of a clue how that works - I'm not a power Java programmer (I do C/C++ mainly).  I know that you can't "unload" a URL from the URLClassLoader, so I'm not asking that. What would be best, I guess, is if there was a way I could add the .JAR file to a "temporary" URLClassLoader which I then ditch at the end of execution. Or some way I can just load the classes directly into the script engine and not the main Java ClassPath.
If it's something I could just call from JavaScript directly that would be great, but I don't mind implementing some Java methods to do the job if needed, or even extending the scripting engine in some way.
Answer: To isolate the plugin specific classes, you may need to create a separate (custom) class loader instance and pass it to the java script engine. Any class loaded by the particular class loader will only be visible to the particular java script engine.
I found this answer which describe the class loader in context of ScriptEngine.
I hope this helps you to move forward in right direction.


Create a post method in Drupal 8

Question: I've been trying to create a post method in Drupal 8, I used the following code:
custom_rest/src/Plugin/rest/resource/CustomRestResourceUserCheck.php:
<code><?php

namespace Drupal\custom_rest\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "custom_rest_resource_user_check",
 *   label = @Translation("Custom User Check"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/custom/user_check"
 *   }
 * )
 */
class CustomRestResourceUserCheck extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('custom_rest'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to POST requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function post() {

    // You must to implement the logic of your REST Resource here.
    // Use current user after pass authentication to validate access.
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }

    return new ResourceResponse("Implement REST State POST!");
  }

}
</code>
I have activated:

I tested this functionality in Postman but I get the following error:

Someone may know that something is wrong?
Edit 1
Drupal version: 8.1.9
Comment: Are you using 8.2.* or below?
Comment: Look inside the code of ResourceBase the key for post uri_paths needs to be a URL that ends with create (or something like that).
Comment: This is being handled in a support request on d.o: https://www.drupal.org/node/2799383
Answer: Solution:
We need a different path:
<code> * @RestResource(
 *   id = "custom_rest_resource_user_check",
 *   label = @Translation("Custom User Check"),
 *   uri_paths = {
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/custom/user_check"
 *   }
 * )
</code>
Source:
https://www.drupal.org/node/2799383#comment-11619919

Create a post method in Drupal 8


drush failure on error in drupal 7

Question: My initial installation of Drush couldn't even recognize commands such as "drush migrate-status", therefore I reinstalled drush and followed the steps in the included README.
After reinstallation, drush now recognizes the command "drush migrate-status", hwoever it is throwing an error and crashing. I am confused as I have not even enabled the migrate_example module included with the Migrate module, however drush is throwing the error message below:
require_once(/var/www/drupal7/sites/all/modules/migrate_example/beer.inc):[warning]
failed to open stream: No such file or directory bootstrap.inc:3024
PHP Fatal error:  require_once(): Failed opening required '/var/www/drupal7/sites/all/modules/migrate_example/beer.inc' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/drupal7/includes/bootstrap.inc on line 3024
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: require_once(): Failed opening required
'/var/www/drupal7/sites/all/modules/migrate_example/beer.inc'
(include_path='.:/usr/share/php:/usr/share/pear') in
/var/www/drupal7/includes/bootstrap.inc, line 3024

This all seems very cryptic to me, especially when I have not enabled the migrate_example module and I have the migrate_example directory under migrate.
Could someone please explain why drush might be throwing this error?
Comment: It sounds like the file `/var/www/drupal7/sites/all/modules/migrate_example/beer.inc` is missing.  Have you checked it actually exists?
Comment: @chapabu thank you for pointing that out, my migrate_example was under migrate/, i just had to move it out..
Answer: It sounds like the file /var/www/drupal7/sites/all/modules/migrate_example/beer.inc is missing.
Comment: hmm well i recognize another issue (i don't know why drupal hates me), now that i brought the migrate_example folder to var/www/sites/all/modules, i can no longer see it under the migrate UI, but drush now recognizes it...would you know what could be wrong? i have been informed that migrate UI only displays what drush sees...
Comment: Is it actually at `var/www/sites/all/modules`?  Shouldn't it be at `var/www/drupal7/sites/all/modules` if I'm reading the rest of your folder structure correctly?
Comment: chapabu, sorry you are right i made a mistake while typing that out. it is in var/www/drupal7/sites/all/modules, i put all the modules in there but the migrate UI is not reading it
Comment: I am facing the same error, but it seems that mine is a custom .inc file in my migrate module example, only problem is that its on the right path...this didnt solve it for me, trying to troubleshoot more

drush failure on error in drupal 7


Extract an array of objects from json string and put them in ArrayList?

Question: I've a simple question, and was wondering if someone here could help me how to parse through a Json string and extract all the User and put it into a List?
Note the object key directly under Users is a random number which can change with every response!
{
    "_links": {},
    "count": {},
    "users": {
        "123321": { //*Is a random number which can be any number
            "_links": {},
            "user": {
                "id": "123321",
                "name": "...",
                "age": "...",
                "address": ""
                ..
            }
        },
        "456654": {
            "_links": {},
            "user": {
                "id": "456654",
                "name": "...",
                "age": "...",
                "address": ""
                ...
            }
        }
        ...
    },
    "page": {}
}

Ideally, it would be nice to utilize Jackson Json or Gson.
Also I would like to only construct User object with two fields (id & name) and ignore the rest of the fields!
Comment: Create a class mapping the structure of the JSON (at least what you're interested into), and use Jackson to read an instance of that class. Use a Map for the `users` member.
Comment: How do I ignore the fields that I'm not interested? Can you provide and example of this class and how to use Jackson to iteration over the tree and create this ArrayList please!
Comment: By not putting them into the class. You need to start experimenting by yourself. Extracting the values from a map is a matter of reading the javadoc of Map.
Answer: A Jackson-approach could look like this:
ObjectMapper om = new ObjectMapper();
JsonNode node = om.readTree(input);

List<JsonNode> users = node.findValues("user");

From here you can either retrieve the values directly from the JsonNode instances, e.g.:
for (JsonNode jsonNode : users) {
    System.out.println(jsonNode.get("name"));
    System.out.println(jsonNode.get("id"));
}

or convert to a POJO:
for (JsonNode user : users) {
    User pojo = om.treeToValue(user, User.class);
    System.out.println(pojo.id);
    System.out.println(pojo.name);
}

Assuming the existence of a POJO that looks something like the following:
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    public String name, id;
}

Answer: You have to parse the json...which can be done like -
JSONObject json=new JSONObject(response);
JSONObject json2=json.getJSONObject("users");
Iterator keys = json2.keys();

while(keys.hasNext()) {
    String key = (String)keys.next();
    JSONObject json3=json2.getJSONObject(key);
    ArrayList<User> list=new ArrayList<>();

    JSONObject userjson=json3.getJSONObject("user");
    User user = new User();
    String id=userjson.getString("id");
    String name=userjson.getString("name");
    user.setId(id);
    user.setName(name);
    list.add(user);
}

Hope it helps.. :)
Comment: No, the solution is not taking into account the random numbers..
This is most standard way of performing json parsing as far as i know..For 100 users it won't take time..I have implemented this in many standard apps having 5000 users.
Comment: Check the code now..It will work most probably. I have parsed random number too by ignoring them. the list will be containing only the user object, i.e list of users as you want..And What else can be a more effective way to do this, since we have to save each user object in list..so somehow we will do so in the loop only..It won't take time..Using streams class will do the same thing and the complexity will be same.
Comment: https://mvnrepository.com/artifact/org.json/json

Mark this correct if it works.. :)


Prove that the set of condensation points is closed

Question: I'm having a difficult time with this one. First off, $x$ is a condensation point of $A$ if every open nbhd $U$ of $x$ contains uncountably many points of $A$. Let us denote the set of condensation points as $A^c$ I have started a proof.
Proof. Let $X$ be a topological space and let $A \subset X$. We seek to show that $A^c$ is closed. To see this, we show that $X \setminus A^c$ is open.
Is this a good approach to the proof - to show closedness by showing openness of the complement? Also, I was wondering: does it follow that $X \setminus A^c$ contains only countably many points of $A$ or is that not the proper negation?
Answer: Let $x_0\in\overline{S^c}$ and $x_o\in U\in\tau$.
Then $U\cap S^c \setminus \{x_o\}\neq \emptyset$
Let $x_1\in U\cap S^c \setminus \{x_o\}$
$x_1\in S^c$ and $x_1\in U$ implies $U\cap S$ contains an uncountable subset of $S$.
$x_0\in U\in\tau$ is arbitrary open set, hence $x_0\in S^c$
Answer: Let $p\in X\setminus A^c$. $p$ is not a condensation point of $A$, so there exists an open neighborhood $U$ of $p$ such that $U\cap A$ is countable. Let $q\in U$. It is clear that $U$ is an open neighborhood of $q$ such that $U\cap A$ is countable. This implies that $q\in X\setminus A^c$ and $U\subseteq X\setminus A^c$.
Finally, we can conclude that $X\setminus A^c$ is open, because we showed that all of its points are interior points.
Answer: We can show directly that $A^c$ is closed. Let $p\in\overline {A^c}.$ Let $U$ be any open nbhd of $p.$ We need to show that $U\cap A$ is uncountable and that therefore $p\in A^c.$ As follows:
There exists $q\in U\cap A^c$ because $p\in\overline {A^c}.$ Now U is also an open nbhd of $q,$ with $q\in A^c,$ so $U\cap A$ is uncountable.
Comment: $1$ min late....
Comment: @SouravGhosh. I am a very slow typist. Your A appeared as I was typing & removing my usual infinite sequence of typos.


A counterexample for a result of sequences

Question: Let $(a_n)_{n\in\mathbb{N}}$ is a sequence. Define another sequence $(a^*_n)_{n\in\mathbb{N}}$ by
$$
a^*_n=\frac{a_n+a_{n+1}}{2}.
$$
Give an counterexample to show that 'if $a^*_n\to\infty$, then $a_n\to\infty$' is false.
I got stuck at this question. I know this should be incorrect but I just can't find a counterexample. Could somebody help me with this? Thanks very much.
Comment: Make the $a_n$ with $n$ odd all $0$.
Comment: @DavidMitra Thanks very much! I knew the example would be simple but I just didn't come up with this idea!
Answer: Consider the sequence:
$a_n=\begin{cases}
n & n\text{ odd} \\
0 &n\text{ even} \\
\end{cases}$
Can you see how $a_n^*\rightarrow\infty$ but $a_n$ does not (nor does it converge to any value)?
Comment: Yep I can see that $1,\frac{3}{2},\frac{3}{2},\frac{5}{2},\frac{5}{2},\dots$ which is a unbounded increasing sequence..
Comment: Yep, and importantly because every second term is 0, you can't say that $a_n\rightarrow\infty$
Answer: Define the sequence $a_n=n(1+(-1)^n)$ then $a_n \not \to \infty$ but $a_n^\star\to \infty$.


Extract part of string in PHP

Question: I have a string (message) and its values change for each transaction. Here is the sample string:
"Your transaction was successful. Transaction ID: 453712046. Reference code: 1234326. Thank you!"
How can I extract the Transaction ID to a variable $transID and the Reference code to the variable $refCode as integer values every time a transaction is made?
Thanks!
Comment: Easiest way, by using an API.
Comment: Just `explode()` with substring `Transaction ID: ` and then explode the ` ` second substring, the space. If the string is always consistent just use `explode`. Throwing regex at the problem is just using a BFG when all you need to do to keep the bugs out is close the door.
Answer: This is ugly, and I'm sure there's a better way to do it, but this works:
$str = "Your transaction was successful. Transaction ID: 453712046. Reference code: 1234326. Thank you!" ;

// get the starting and ending of your first string
$pos1 = strpos($str,'Transaction ID: ') + strlen('Transaction ID: ');
$pos2 = strpos($str,'.',$pos1) ;

// get your transaction ID
$transID = substr($str,$pos1, $pos2-$pos1);

// get the starting and ending of your second string
$pos1 = strpos($str,'Reference code: ') + strlen('Reference code: ');
$pos2 = strpos($str,'.',$pos1) ;\

// get your reference code
$refCode = substr($str,$pos1, $pos2-$pos1);

echo $transID . ' - ' . $refCode ;

Comment: By reading his code, yes it will. Until the day the service you're collecting the data from changes their message.
Comment: Will this work no matter how long the transaction ID or reference code is?
Answer: This is easily solved with a small bit of regex:
<?php

$str = "Your transaction was successful. Transaction ID: 453712046. Reference code: 1234326. Thank you!";
preg_match_all('#Reference code: (\d+)|Transaction ID: (\d+)#', $str, $matches);

$refCode = $matches[1][1];
$transID = $matches[2][0];

?>

preg_match_all() performs a global regular expression match on the string. Meaning it won't stop after the first match.
Reference code: and Transaction ID: will match the literal strings.
\d Matches a digit ranging from 0-9.
+ Matches between one and unlimited times, as many times as possible, giving back as needed
So this means it will match any number after Reference code: and Reference code: for as long as it's not interupted by a non-digital character.
Comment: Will this work no matter how long the transaction ID or reference code is?
Comment: @bool Yes. For as long as the ID and Reference code consist of numbers only and aren't interupted by a space or any other character than a digit.
Comment: How can I make sure this code only extracts the transaction id and the reference code if the string had to contain other numerical values like time and date?
Comment: @bool You can't unless those numbers come _after_ the Reference code. In that case it won't matter as they will simply be ignored. If that's not an option, Mr Glass's answer to your question is a better solution for your problem.
Comment: @bool Technically you could count the position of the number though. `$matches[0]` will match the first number found. `$matches[1]` will match the second number found. `$matches[2]` the third etc etc. If you know how the string looks, the code is easily adepted to get the correct numbers.
Comment: here is the actual message (string) from which I need to extract the transaction id and reference code: "Yello.You have received ZMW 50.00 from Grace Namuchenje (260969754144) on your mobile money account at 2018-06-20 15:57:06. Reference code: 1234326. Your new balance:50.00 ZMW. Financial Transaction ID: 453712046.
Comment: @bool So simply count the numbers. The Reference code is the 10th number in the string and the Transaction ID is the 13th number. Change `$transID = $matches[12];` and `$refCode = $matches[9];`
Comment: @bool You can have a look here: https://regex101.com/r/mDhUfs/1 It gives you a clear representation of how it works.
Comment: Is there not a solution where I only extract digits between "Reference code: "  and ".", and between "Financial Transaction ID: " and "."
Comment: @bool I've edited my answer. It will now only match the numbers you want.
Comment: @bool If any of the answers to your question provided you with the answer you needed, please make sure to check the checkmark next to that answer to accept it. This is a way of showing your appreciation to the one that helped you out and makes sure your question doesn't remain open forever.
Answer: This is another option, you can do it with several ways.
This one is probably the easy to implement and understand, so also maintain.
$str = '"Your transaction was successful. Transaction ID: 453712046. Reference code: 1234326. Thank you!"';
$find = explode(" ",$str);
$Transaction_id = (int) $find[6];
$Reference_code = (int) $find[9];
echo $Transaction_id;
echo $Reference_code;

In order to work, the text must be the same and only change the numbers.
ie.
    "Your transaction was not successful. Transaction ID: 453712046. Reference code: 1234326." wont work.
Answer: You could use regex, named preferably to avoid confusion.
some pattern like
/(?<first>Transaction ID: (?<transId>\w{1,})\.)(.*)(?<second>Reference code: (?<refCode>\w{1,})\.)/gm
play arround on this: https://regex101.com/r/fO7ezY/1
<?php
    $re = '/(?<first>Transaction ID: (?<transId>\w{1,})\.)(.*)(?<second>Reference code: (?<refCode>\w{1,})\.)/m';
    $str = 'Your transaction was successful. Transaction ID: 453712046. Reference code: 1234326. Thank you!';

    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

    // Print the entire match result
    var_dump($matches);
?>

If you are worried about the squence of the transaction ID and reference Code, you could match the pattern twice.

Extract part of string in PHP


My guitar is tuned half step down how can I play along a standard tuned song?

Question: I would like to play along some Deep Purple songs from time to time but my guitar is tuned to E flat and I find it unhandy to tune it to standard E tuning and then back to E flat tuning.
Given I have only one guitar, is there a way I can shift the pitch of the song half step down?
Thanks
Comment: 1. Use a capo on the first fret, then your guitar is in standard tuning. 2. Get a second guitar. 3. Pitch down the tunes you want to play along with (e.g., with [Audacity](http://audacityteam.org/) ).
Comment: Why don't you just transpose it a half step down?
Answer: There are pieces of software available that can transpose pieces of music (I used to use Adobe Audition, although it did take a long time for the software to export the transposed music).
Alternatively, you could use a capo on fret 1 and play as you normally would, only 1 fret higher. If you're not playing chords (or if you're good at bar-chords) you could just play 1 fret higher without the use of a capo.
Comment: You covered it.  Plus 1. Audacity linked in a comment above by Matt L. is a free software program that will quickly and easily transpose your audio file to a different key.  I keep my guitar tuned half step flat and use Audacity to transpose backing tracks that come in standard tuning. But if I just want to play along and not sing, I put a capo on first fret (or whichever fret is needed to be in tune with the record).


Failed to start glassfish server because Couldn't get lock for /opt/glassfishv3/glassfish/domains/domain1/logs/server.log

Question: admin@BRMSDEV:/opt/glassfishv3/glassfish/bin$ ./asadmin start-domain domain1
java.io.IOException: Couldn't get lock for /opt/glassfishv3/glassfish/domains/domain1/logs/server.log
at java.util.logging.FileHandler.openFiles(FileHandler.java:389)
at java.util.logging.FileHandler.<init>(FileHandler.java:287)
at com.sun.enterprise.admin.launcher.GFLauncherLogger.addLogFileHandler(GFLauncherLogger.java:85)
at com.sun.enterprise.admin.launcher.GFLauncher.setup(GFLauncher.java:148)
at com.sun.enterprise.admin.cli.StartDomainCommand.createLauncher(StartDomainCommand.java:239)
at com.sun.enterprise.admin.cli.StartDomainCommand.runCommandNotEmbedded(StartDomainCommand.java:122)
at com.sun.enterprise.admin.cli.StartDomainCommand.executeCommand(StartDomainCommand.java:117)
at com.sun.enterprise.admin.cli.CLICommand.execute(CLICommand.java:257)
at com.sun.enterprise.admin.cli.AsadminMain.executeCommand(AsadminMain.java:229)
at com.sun.enterprise.admin.cli.AsadminMain.main(AsadminMain.java:167)
Waiting for DAS to start .Error starting domain: domain1.
The server exited prematurely with exit code 0.

Before it died, it produced the following output:
   Warning:  Cannot open log file: /opt/glassfishv3/glassfish/domains/domain1/logs/jvm.log
admin@BRMSDEV:/opt/glassfishv3/glassfish/bin$ ./asadmin start-domain domain1
java.io.IOException: Couldn't get lock for /opt/glassfishv3/glassfish/domains/domain1/logs/server.log
at java.util.logging.FileHandler.openFiles(FileHandler.java:389)
at java.util.logging.FileHandler.<init>(FileHandler.java:287)
at com.sun.enterprise.admin.launcher.GFLauncherLogger.addLogFileHandler(GFLauncherLogger.java:85)
at com.sun.enterprise.admin.launcher.GFLauncher.setup(GFLauncher.java:148)
at com.sun.enterprise.admin.cli.StartDomainCommand.createLauncher(StartDomainCommand.java:239)
at com.sun.enterprise.admin.cli.StartDomainCommand.runCommandNotEmbedded(StartDomainCommand.java:122)
at com.sun.enterprise.admin.cli.StartDomainCommand.executeCommand(StartDomainCommand.java:117)
at com.sun.enterprise.admin.cli.CLICommand.execute(CLICommand.java:257)
at com.sun.enterprise.admin.cli.AsadminMain.executeCommand(AsadminMain.java:229)
at com.sun.enterprise.admin.cli.AsadminMain.main(AsadminMain.java:167)
Waiting for DAS to start .Error starting domain: domain1.
The server exited prematurely with exit code 0.

Before it died, it produced the following output:
Warning:  Cannot open log file: /opt/glassfishv3/glassfish/domains/domain1/logs/jvm.log
Warning:  Forcing option -XX:LogFile=/tmp/hs_pid2234.log
Jun 27, 2014 8:36:05 AM com.sun.enterprise.glassfish.bootstrap.ASMain main
INFO: Launching GlassFish on Felix platform
Jun 27, 2014 8:36:05 AM com.sun.enterprise.glassfish.bootstrap.ASMain main
SEVERE: the domain directory is not writable.
java.lang.RuntimeException: the domain directory is not writable.
at com.sun.enterprise.glassfish.bootstrap.ASMainHelper.verifyAndSetDomainRoot(ASMainHelper.java:233)
at com.sun.enterprise.glassfish.bootstrap.AbstractMain.run(AbstractMain.java:89)
at com.sun.enterprise.glassfish.bootstrap.ASMainOSGi.run(ASMainOSGi.java:71)
at com.sun.enterprise.glassfish.bootstrap.AbstractMain.start(AbstractMain.java:78)
at com.sun.enterprise.glassfish.bootstrap.ASMain.main(ASMain.java:82)
Command start-domain failed.

I just installed glassfish in my host machine and changed the domain.xml with my host ip and started the server through the following command
./asadmin start-domain domain1
I got the above exceptions ,I am new to glassfish please help me out how to over come this issue ,
Thanks in advance
@dinesh
Comment: This is not a question. It's a stack trace.
Comment: am getting this on windows
Answer: I had the same problem and changing the directory permissions solved that issue. Try this:

sudo chmod -R 777 /opt/glassfishv3/glassfish/
If you are using an ide like IntelliJ for example, you have to start the GlassFish Server inside the ide.
Answer: Looks like you don't have writing permissions to the folder /opt/glassfishv3/glassfish/domains/domain1/logs/ and / or file server.log
... and / or the folder / file doesn't exist.
Try sudo or change the folder's permission settings.
Comment: sorry i changed the permissions but still I am getting the same problem .
Comment: Actually I installed glassfish in my ubuntu server ,then after I just edited domain.xml listener 4848 I added address as my server address ,them I am just save it and rebooted my server ,and started server with the following cmd..  "./asadmin start-domain domain1" I try as u said I change the permissions by using the following cmd chmod -R 755 ,then i rebooted and try to start server again but no change ,getting same exceptions
Comment: This exact thing was happening to me. I had to use `sudo asadmin` instead of just asadmin


What happens technically when you accentuate on a time-signature?

Question: When you have a 4/4 time signature you typically accentuate beats "1" and (minorly) "3" for every measure. On a piano, what does that mean technically? Is beat "1" just louder or is it also a (little) bit longer than the written note?
Background: I am feeding a string of midi notes to a sampled piano (programmatically) and want to add the "feeling" of a time signature...
Answer: On the piano we really only have loudness to work with for this sort of emphasis; other instruments may additionally use other emphasis for beats, but not typically duration.  There may be styles and interpretations that mess with the durations of notes on various beats but they are not denoted by the time signature.
Answer: I think the word technically is perhaps the wrong one in this case, maybe physically would be a better one.
One of the big things that Piano players strive for is evenness in tone.  Whenever a piano run is put together it's more about the phrases they're playing than the time signature, so say for example you have a 16th note run that was in a grouping of 9 notes, then 7 notes.  The 'loudness' and attack might subtly happen on the 1st note of each group, wherever they might fall.
The generic theorybook definition for 4/4 will say that 1 is the strong beat and that 3 is the strong, yet weaker than 1 beat.  This is more to do with the way we perceive time signatures in our heads, and emphasising your notes on these beats creates a more solid feeling to the music. However
In Rag time, the emphasis is on the 2 and 4, but for a general sense of time signature you should be fine doing a blanket 1 and slightly 3 :)
As for how much to emphasise by, that will take some experimentation if you're doing it on a computer program.
Answer: In any time-signature, beat one is emphasised.Often subtly,but still a little more than the other beats. In 4/4 beat 3 is, as you state, a bit louder than 2 and 4. In 6/8 beat 4 is a bit louder than 2,3,5&6. This is generally the way folks can 'feel' the beat. I'm talking general pop music here - listen to Stravinsky, et al, and it can all change.One rarely stays longer on beat 1 in a bar of any time signature.
Check out  QUANTISING - in  recordings, etc., artists  do  play a bit early or a bit late, often not on purpose ! Digital machines have the facility to move the 'bad' notes one way or another, by a selected amount, to be back in time.
Having said all of that, some songs, and some genres of music, will specifically push or pull each bar (lead obviously by beat 1 ) on purpose, to create a different feeling to the pieces - I suppose this is the very opposite to quantising. A drummer, for instance, may be asked to play a song 'on the beat','early', or 'late'.
Comment: Thx! I will definitely check out quantizing.
Comment: Beat one is not always emphasized.  4/4 rock often emphasizes beats two and four.
Comment: @MatthewRead - having played rock ( and lots of others) for the last 50 odd years, I feel that beat 1 is emphasized by the bass drum and bass guitar at least. Beats 2 and 4 may sound emphasized with the snare drum hits, but that's more like a back beat. Listen to the bass - usually 1 and 3 or all 4. Rarely on 2 and 4. Maybe with reggae.


Text to speech Azure service: Speech is not working (not talking) C#

Question: I'm trying to use the Text to Speech service on Microsoft azure and I used the official documentation and the official code using c# language but whenever I enter a value to let the program speak nothing happen not even an error message.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

class Program
{

static string speechKey = "";
static string speechRegion = "";

static void OutputSpeechSynthesisResult(SpeechSynthesisResult speechSynthesisResult, string text)
{
    switch (speechSynthesisResult.Reason)
    {
        case ResultReason.SynthesizingAudioCompleted:
            Console.WriteLine($"Speech synthesized for text: [{text}]");
            break;
        case ResultReason.Canceled:
            var cancellation = SpeechSynthesisCancellationDetails.FromResult(speechSynthesisResult);
            Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

            if (cancellation.Reason == CancellationReason.Error)
            {
                Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
            }
            break;
        default:
            break;
    }
}
async static Task Main(string[] args)
{
    var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);

    // The language of the voice that speaks.
    speechConfig.SpeechSynthesisVoiceName = "en-US-JennyNeural";

    using (var speechSynthesizer = new SpeechSynthesizer(speechConfig))
    {
        // Get text from the console and synthesize to the default speaker.
        Console.WriteLine("Enter some text that you want to speak >");
        string text = Console.ReadLine();
        var speechSynthesisResult = await speechSynthesizer.SpeakTextAsync(text);
        OutputSpeechSynthesisResult(speechSynthesisResult, text);
    }

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
}
}

whenever I run the app and I type anything nothing happens
here is the output image
Answer: I tried in my environment and got below results:
I executed the same code in my environment and got error:
Console:

Output:

The above error is ongoing issue with Microsoft azure in that they have mentioned the Speech SDK latest impacting the wide variety of TLS-dependent service use started failing. This error only occurs in Windows other API and MacOS has been working properly.
You can use this code get the (text to speech)
Code:
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System;
using System.Threading.Tasks;
namespace TextToSpeech
{
    class Program
    {
        async static Task Main(string[] args)
        {
            await ProcessSpeech();
            Console.WriteLine("Completed");
        }
        async static Task ProcessSpeech()
        {
            var l_speechConfig = SpeechConfig.FromEndpoint(new Uri("< endpoint>"), "key");
            var l_audioConfig = AudioConfig.FromWavFileOutput("C:\\Users\\v-vsettu\\download1\\new1.wav");
            var l_synthesizer = new SpeechSynthesizer(l_speechConfig, l_audioConfig);
            await l_synthesizer.SpeakTextAsync("Hi siri");
        }
    }
}

Console:

File:

Please refer this MS-Q&A for ongoing problem in Speech-SDK for more information.


Querying Hive from Apache Drill causes Stackoverflow error

Question: I am trying to see a table named customers, in hive from drill. I am using Drill in Embedded mode. I am using the default derby database for hive metastore.
When I do a describe, it shows all the columns and types.
But, when I do a select command like this,
<code>select * from customers limit 10;
</code>
In the Web UI, this is what I got

org.apache.drill.common.exceptions.UserRemoteException: SYSTEM ERROR: StackOverflowError

Hive plugin:
<code> {
  "type": "hive",
  "enabled": true,
  "configProps": {
    "hive.metastore.uris": "thrift://ip_address:9083",
    "javax.jdo.option.ConnectionURL": "jdbc:derby:;databaseName=../sample-data/drill_hive_db;create=true",
    "hive.metastore.warehouse.dir": "/user/hive/warehouse",
    "fs.default.name": "file///",
    "hive.metastore.sasl.enabled": "false"
  }
}
</code>
Errors showed in the Log file:

org.apache.drill.exec.work.foreman.ForemanException: Unexpected
  exception during fragment initialization: java.lang.AssertionError:
  Internal error: Error while applying rule DrillPushProjIntoScan,
java.lang.StackOverflowError: null at
  org.apache.hadoop.fs.FileSystem.get(FileSystem.java:355)
  ~[hadoop-common-2.7.1.jar:na]

And, finally this

Query failed: org.apache.drill.common.exceptions.UserRemoteException:
  SYSTEM ERROR: StackOverflowError

And, the versions i am using are:
Apache Drill : 1.3.0
Hive : 0.13.1-cdh5.3.0
Hadoop : 2.5.0-cdh5.3.0
Comment: I am able to query the same table from hive but drill throws this error.
Comment: Are you trying from Drill shell or Drill Web UI? Drill embedded or cluster mode?
Comment: I tried from both the UI and the shell. Both of them say, Stackoverflow error
Comment: I've edited the question. Added the storage plugin info.
Comment: can you please check `/user/hive/warehouse`  directory in hadoop? I hope you filled all the values from `hive-site.xml`
Comment: yeah, I've filled the values in plugin from hive-site.xml.
And, .../warehouse directory exists in hadoop. It has the Customers table and two other tables which i see when i do "Show tables;"
Comment: Do one more thing please try `select count(*) from customers`
Comment: Its is giving the same thing. StackOverflow Error.
Comment: please go to /log/sqlline.log and get exact stack trace for this error
Comment: I have added a few snippets from Log file in the question.
Comment: can you please share versions for hadoop, hive & drill
Comment: Versions of s/w's updated.
Comment: can you try running hive in Remote Metastore mode rather embedded one (with derby)?
Answer: This is a version conflict I guess.
According to Drill's Documentation:

Drill 1.0 supports Hive 0.13. Drill 1.1 supports Hive 1.0.

So, for 1.1+ you may get issues with hive 0.13.
Read more here.
So upgrade hive to 1.0 or downgrade drill to 1.0 to test this.
Comment: I have downgraded Drill to v1.0 and this time i got a new error saying,
 `Error while applying rule DrillPushProjIntoScan,` followed by each column name and $(number). Something like, Column1=$0,column2=$1  and so on.
Comment: I will try tomorrow with drill 1.0 and hive 0.13 so that I can reproduce the same issue..


Probability, why my solution doesn't work out? (P of drawing a pair)

Question: The task is simple, the probability of drawing a pair of cards. You draw two cards from a stack, what is the chance that you get two kings or two fours.
My idea was the following. There are 13 different valued cards. The probability of getting lets say a pair of two is following.
$\frac{1}{52} \cdot \frac{3}{51}$
The chance of getting first card 2 is $\frac{1}{52}$, the chance of getting one of the three other cards that would make this a pair is $\frac{3}{51}$. That sounds reasonable to me. And now to account for all 13 different types you just multiply this with 13. Or add it up 13 times.
$13(\frac{1}{52} \cdot \frac{3}{51})$
This is wrong and I don't understand why. The probability of getting a random pair should be the sum of getting every type of pair.
A correct solution would be the following.
$\frac{52 \cdot 3}{52 \cdot 51}$
I try to stick with the 'count the number of beneficial outcomes in every step and multiply method' but I got stuck on why my way of thinking didn't work out here.
Comment: The probability that the first card is a 2, is $4/52$, not $1/52$. Your reasoning works out, with this correction.
Comment: Silly me. Lalalala. Thanks.
Comment: It doesn't matter what first card drawn is. Probability of matching is $3/51$.
Comment: Shouldn't it be $\frac{2}{13}\cdot\frac{3}{51}$ where the $\frac{2}{13}$ is the probability that the first card is a four or a king?
Answer: The probability that the first card is a 2, is 4/52, not 1/52 (there are four cards with a "value" of 2 and 52 cards total). Your reasoning works out, with this correction.


How to create an efficient background task in C#?

Question: I am fairly new to asynchronous programming so I need help.
What I need to do is, create a windows service that constantly checks the database for menu updates (insert/updates), tables updates (insert/updates), menu category updates (insert/updates) and so on and if any change is detected the service will then need to POST those said changes to separate APIs one by one. Keeping in mind that the service will be used for just this purpose and the database that I need to check for updates is SQL Server.
So, how do I approach this scenario efficiently ? Do I create new Tasks (System.Threading.Tasks) or create new Threads (System.Threading.Thread) for each pieces like UpdateMenu that checks the menu updates and upload to api, UpdateTable, UpdateDishes and so on and how do I go about the Posting to the API part I mean do I create a new Task for each and every API call? I want the application to be as efficient as possible and pick the changes and post them to API as soon as possible.
Thanks in advance.
Comment: Have you identified an approach of how to identify the updated/deleted/inserted rows from the table?
Comment: Why not call the API from the same code which changes the database? `how do I go about the Posting to the API part` do you know how to call Web APIs from C# code?
Comment: Can't do that because we don't have the source code of the application, we only have access to the database so.And sorry for misinformation, the api call and service development part is not the problem rather I want them to be as efficient as possible and pick changes and post to the API as fast as possible.
Comment: *"checks the database for menu updates (insert/updates), tables updates (insert/updates), menu category updates (insert/updates) and so on"* -- What are the menus, tables and menu categories? Are these separate tables in the database?
Comment: Yes they are separate tables of a Restaurant database.
Comment: Is your intention to pull the database for changes with the same frequency for all three tables (Menus, Tables and ManuCategories), or with a different frequency for each table?
Comment: Yes I need to pull the changes from each table almost at the same time and frequency, because if a menu category will be added most likely the menu will also be added for that category.
Comment: Do you have the ability/authorization to change the schema of the database, for example by adding insert/update triggers on the tables that you are interested to monitor for changes?
Comment: Are you expecting something to query your database continuously for changes? That sounds inefficient as you will have many queries taking CPU time that return nothing (assuming you have no delay in between because it needs to be as fast as possible). Perhaps figuring out how to *trigger* an event on database change, rather than querying constantly, would be the solution.
Comment: Yes, I have a stored procedure that fetches me the changes.
Comment: So, that's where my confusion comes in to play because as of now I call the procedures that bring me the changes..
Comment: What's the blocker here? You need to create Windows Service in .NET Framework. You have one or more workers to perform tasks in parallel continuously without impacting each other.. You need to write code for those workers to pull the data from the db and call the API.
Comment: Constantly querying your database with the hopes that there may be change is not efficient. Perhaps this will help: https://stackoverflow.com/questions/5288434/how-to-monitor-sql-server-table-changes-by-using-c
Comment: How do I create one or more workers to perform tasks in parallel continuously without impacting each other ? That's what I want to know.
Comment: @Ibrennan208 What are the things that I need to consider before using ENABLE_BROKER and  SqlDependency Class ? I mean do they have any impacts on the databases ?
Comment: You should do some research on internet about creating windows service using .NET https://learn.microsoft.com/en-us/dotnet/core/extensions/workers
Comment: @Ishan See: https://learn.microsoft.com/en-us/sql/database-engine/service-broker/overview?view=sql-server-ver16

And: https://learn.microsoft.com/en-us/sql/relational-databases/service-broker/event-notifications?view=sql-server-ver16

And: https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-service-broker?view=sql-server-ver16
Answer: It seems that you are worried about the overhead of the mechanism that you are going to use, in order to fetch data from the database and post these data to APIs. You are thinking that maybe Threads are fast and Tasks are slower, or vice versa. In fact choosing between these two mechanisms is likely to have no measurable impact to your service's demand for CPU, memory or other system resources.
What is likely to be impactful, is the pattern of communication of your service with the database and the APIs. For example if your threads/tasks are not coordinated with each other, and query the database all at the same time, the database might be slow to respond, and might consume larger amounts of memory while preparing the response. That's not because your threads/tasks are slow. It's because your service is querying the database with a pattern that makes it harder for the database to respond. The same might be true for the pattern of communication with the APIs. If your workers are not coordinated, the network connectivity might become a bottleneck, or the remote machines that host the APIs might suffer.
So my advice is to focus on the usability factor of the mechanisms, and not on their supposed difference in performance. If you are comfortable and familiar with threads, and know nothing about tasks, use threads. If you are familiar with both threads and tasks, use tasks because they are generally easier to use. You'd better invest your time to optimize the communication pattern between your service and its dependencies, than for doing benchmarks trying to find the best between mechanisms that for all intents and purposes are equally efficient.
Comment: Thank you for your answer, but how do I coordinate my workers and how do I optimize the communication pattern and what are these workers are they threads/tasks ?
Comment: @Ishan the workers can be whatever you are more familiar with. Threads, tasks, it doesn't matter. As for how to coordinate them, that's a more difficult question that might deserve a separate post. You should first come to a conclusion about the desirable communication pattern, based on the capabilities of your database and the weight of the queries, before asking. If you know what you want to do, we'll show you how to do it. If you don't know, and ask a generic question about the efficiency of different patterns, most likely you'll get generic and not helpful answers like this one. :-)
Comment: Can you suggest some Communication Pattern, because I don't think I know any ?
Comment: @Ishan the simplest pattern is to serialize the requests. Don't issue a new request before receiving the response of the previous request.


Using grunt-usemin with dynamically generated image paths

Question: I'm using the Yeoman Webapp generator to build my static website.
For my preloader, I have the following snippet (I'm using requireJS for the JS, if that matters).
for(var i = 1; i <= config.numSlides; i++) {
  images.push(config.imageBase + i + '.jpg');
}

As you can see, I just generate a path with a number and add .jpg to it. My images are simply called 1, 2, 3, ... .jpg.
However, since Yeoman uses grunt-usemin.. It renames my image files to something like: 7f181706.3.jpg. Because of this, my script cannot find the correct image anymore. Is there a way to solve this?
I was looking through the docs and found something like this:
assetsDir: 'images',
patterns: {
    js: [[/(image\.png)/, 'Replacing reference to image.jpg']]
}

would that be an option? I tried it without luck. Not sure what the correct pattern would be.
Answer: You can have a better code sample in the test files of this library, concretely: https://github.com/yeoman/grunt-usemin/blob/master/test/test-usemin.js#L233
Where you can find the following code:
it('should allow for additional replacement patterns', function () {
  grunt.file.mkdir('images');
  grunt.file.write('images/image.2132.png', 'foo');
  grunt.log.muted = true;
  grunt.config.init();
  grunt.config('usemin', {
    js: 'misc.js',
    options: {
      assetsDirs: 'images',
      patterns: {
        js: [
          [/referenceToImage = '([^\']+)'/, 'Replacing image']
        ]
      }
    }
  });
  grunt.file.copy(path.join(__dirname, 'fixtures/misc.js'), 'misc.js');
  grunt.task.run('usemin');
  grunt.task.start();

  var changed = grunt.file.read('misc.js');

  // Check replace has performed its duty
  assert.ok(changed.match(/referenceToImage = 'image\.2132\.png'/));
});

I hope that helps!


Form Validation with jQuery before submitting via Ajax request

Question: I'm trying to get my form to validate before using an Ajax request to submit the form to my php script. I've looked through stackoverflow and haven't found something that worked.
I have 3 inputs and a submit button:
<input type="text" name="full-name" id="full-name" value="" placeholder="Full Name" />
<input type="text" name="email" id="email" value="" placeholder="Email" />
<textarea name="message" id="message" value="" rows="8" placeholder="Message"></textarea>
<input type="submit" id="contact-submit" class="contact-submit" value="Submit">

$(document).ready(function() {

    function validator(){
        return $('form').validate();
    }

    $('form').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            dataType: 'html',
            type: 'post',
            url: 'mail.php',
            data: $('#contact-form').serialize(),
            beforeSubmit: validator,
            success: function(responseData) {
                $('#contact-submit').remove();
                $('#messageResponse').fadeIn(1000);
                $('#messageResponse').html(responseData);
            },
            error: function(responseData){
                console.log('Ajax request not recieved!');
            }
        });

        // resets fields
        $('input#full-name').val("");
        $('input#email').val("");
        $('textarea#message').val("");
    })
});

Should I use a plugin for this? All I want is the name, email, and message to validate with a red border-color. It's giving me a big headache and I'm meeting with the client tomorrow to finalize the site. I don't ask questions if I can't find a working solution.
I tried using this as well: jQuery Form Validator Plugin
Comment: FYI, you can chain things ` $('#messageResponse').fadeIn(1000).html(responseData);`
Comment: When using the jQuery Validate plugin, your `ajax` function goes inside the built-in `submitHandler` callback function which only fires on a valid form.  See:  http://docs.jquery.com/Plugins/Validation/validate#toptions
Comment: So we can get the tags and answers correct, can you confirm that you are using [the jQuery Validate plugin](http://docs.jquery.com/Plugins/Validation)?  Thank-you.
Answer: Is your $('form').validate() referring to the jQuery Validate plugin?
If so, there is absolutely no point in using a submit handler when the jQuery Validate plugin already has the submit event handler callback function built in, and this is exactly where you are supposed to put your ajax.
As per the documentation for the Validate plugin, the submitHandler callback function is:

"Callback for handling the actual submit when the form is valid. Gets
  the form as the only argument. Replaces the default submit. The right
  place to submit a form via Ajax after it validated."

Try this code, assuming your ajax function is correct:
$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        // your rules and options,
        submitHandler: function (form) {
            $.ajax({
                dataType: 'html',
                type: 'post',
                url: 'mail.php',
                data: $(form).serialize(),
                success: function (responseData) {
                    $('#contact-submit').remove();
                    $('#messageResponse').fadeIn(1000);
                    $('#messageResponse').html(responseData);
                },
                error: function (responseData) {
                    console.log('Ajax request not recieved!');
                }
            });
            // resets fields
            $('input#full-name').val("");
            $('input#email').val("");
            $('textarea#message').val("");

            return false; // blocks redirect after submission via ajax
        }
    });

});

DEMO:  http://jsfiddle.net/kUX2N/
Comment: you also should use the callback: "invalidHandler: function(event, validator) {
    var errors = validator.numberOfInvalids();
    if (errors) {
    // show messages, etc... }
  }" to handle form errors.
Comment: @Cairo, that's absolutely unnecessary as the plugin will **automatically** show validation error messages.
Comment: I just want to point the existence of that handler, but yes, it's absolutely optional.
Answer: beforeSubmit is an option of the malsup ajaxForm plugin, not jQuery ajax. Execute the ajax only if validator() returns true.
$('form').on('submit', function(e) {
    e.preventDefault();
    if (validator()){
        $.ajax({...});
    }
});

Aside:
Instead of using multiple lines asking jQuery to select the same thing more than once you can use a chain.
$('#messageResponse').fadeIn(1000).html(responseData);

Similarly, for doing the same thing to several elements
$('#full-name, #email, #message').val("");

Comment: There's no need to use a `submit` handler when the jQuery Validate plugin already has a submit handler built in.  And the built-in `submitHandler` only fires on a valid form.
Comment: @Sparky OP has not specified what `return $('form').validate();` is, but if he/she confirms it is the jQuery Validate plugin then no reason not to update the answer.
Comment: On second look, I agree... it's not entirely clear that `.validate()` is the jQuery Validate plugin.  I'm going to roll-back my tag edit and ask the OP.


focus on input text in conditional rendering react component

Question: I have Conditional Rendering component in reactJs. i use latest react version, and use MaterialUi in my application. this component use to show a span with a text and as soon as user click on it, it change to a input with a component of MaterialUi and user can change the field by this component
import React from 'react';
import EditIcon from '@material-ui/icons/Edit';
import TextField from '@material-ui/core/TextField';
import { grey400 } from 'material-ui/styles/colors';

class InlineEditInput extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hover: false,
            edit: false,
            value: this.props.children
        };

        this.textInput = React.createRef();
    }

    handleClick = event => {
        event.stopPropagation();
        if (!this.state.edit) {
            this.setState({ value: this.props.children });
            this.setState({ edit: true, hover: false });
        }
    };

    handleBlur = () => {
        this.setState({ edit: false });
        if (this.state.value.length > 0 && this.state.value !== this.props.children) this.props.onChange(this.state.value);
        else this.setState({ value: this.props.children });
    };

    handleMouseEnter = () => this.setState({ hover: true });
    handleMouseLeave = () => this.setState({ hover: false });

    render() {
        let { hover, edit, value } = this.state;
        const originalValue = this.props.children;

        const styles = {
            label: { minHeight: '2em', marginTop: '10px' },
            editIcon: { width: 20, height: 20, fill: grey400, marginLeft: 8 },
            editIconHidden: { width: 20, height: 20, fill: 'none', marginLeft: 8 }
        };
        const setFocus = () => {
            this.textInput.focus();
        };

        if (!edit)
            return (

                    {originalValue}
                    {hover ? <EditIcon style={styles.editIcon} /> : <EditIcon style={styles.editIconHidden} />}

            );
        else
            return (
                <TextField
                    id="EditField"
                    ref={input => {
                        this.textInput = input;
                        setFocus();
                    }}
                    value={value}
                    onClick={this.handleClick}
                    onBlur={this.handleBlur}
                    onChange={event => this.setState({ value:event.target.value })}
                />
            );
    }
}

export default InlineEditInput;

At first an span with value of originalvalue that comes get from its props of this component, is rendered and by click on this, edit state changed to ture and a TextField component of MaterialUi is rendered and I want to focus on this TextFieldAs soon as it is rendered.
For this purpose, I render a TextField and define its ref property that pass input to a function with name of setFocus and in this function I write focus method.
But when I click on span and re-render of component is occurred, i faced with the error that said :
this2.textInput.focus is not a function

how can i write this component?
Answer: Try using componentDidUpdate life cycle hook
componentDidUpdate(prevProps, prevState, snapshot) {
  if(this.state.edit)
    this.textInput.focus();
}

The reason your method is not getting the input to be focused might be due to the fact that the DOM is not yet inserted when you are actually creating the ref. More like the textInput element is created but it's not appended to the DOM. Just a hunch, not 100% sure.


help me to find the volume of the ice cream cone!

Question: Consider the solid shaped like an ice cream cone that is bounded by the functions  and  Set up an integral in polar coordinates to find the volume of this ice cream cone.
I tried to set up the integral but i have not got any write answer!
Answer: $z^2=x^2+y^2$ is a cone, and the other one is a sphere.
Volume to be found is intersection of these. find their intersection, its a circle of radius 4.
Now we will setup the integral in cylindrical coordinates, which are also called half polar coordinates.
$$\int\limits_{0}^{2\pi}\int\limits_{0}^{4}\int\limits_{r}^{\sqrt{32-r^2}} r \cdot dz\,dr\,d\theta$$
is the required volume.


Maven mudando o faces-config.xml

Question: Tenho um projeto EJB e meu maven fica mudando o faces-config.xml quando eu executo o "mvn install", o maven muda tudo que tem dentro dele deixando sem os caminhos que eu especifico, segue meu arquivo "pom" do projeto WEB
<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>WEB</artifactId>
    <packaging>war</packaging>
    <properties>
        <basedir>${project.basedir}</basedir>
    </properties>
    <parent>
        <groupId>br.com.empresa</groupId>
        <artifactId>Pai</artifactId>
        <version>1</version>
    </parent>
    <dependencies>
        <!-- dependencia de projetos -->

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>EJBClient</artifactId>
            <version>1</version>
            <optional>true</optional>
        </dependency>
            <artifactId>seguranca</artifactId>
            <groupId>br.com.empresa/groupId>
            <version>1.14</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <artifactId>utilitarios</artifactId>
            <groupId>br.com.empresa</groupId>
            <version>1.16</version>
        </dependency>

        <dependency>
            <artifactId>batch-api</artifactId>
            <groupId>br.com.empresa</groupId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- commons -->
        <dependency>
            <artifactId>commons-beanutils</artifactId>
            <groupId>commons-beanutils</groupId>
            <version>1.8.3</version>
        </dependency>

        <dependency>
            <artifactId>commons-collections</artifactId>
            <groupId>commons-collections</groupId>
            <version>2.1</version>
        </dependency>

        <dependency>
            <artifactId>commons-digester</artifactId>
            <groupId>commons-digester</groupId>
            <version>2.1</version>
        </dependency>

        <!-- ibm -->
        <dependency>
            <groupId>com.ibm.icu</groupId>
            <artifactId>icu4j</artifactId>
            <version>52.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <scope>provided</scope>
            <exclusions>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.ibm.websphere.j2ee</groupId>
            <artifactId>j2ee</artifactId>
            <version>126.96.36.199</version>
        </dependency>

        <dependency>
            <groupId>com.ibm.faces</groupId>
            <artifactId>jsf-ibm</artifactId>
            <version>20100702_1406</version>
        </dependency>

        <dependency>
            <artifactId>classworlds</artifactId>
            <groupId>classworlds</groupId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <artifactId>jasperreports</artifactId>
            <groupId>net.sf.jasperreports</groupId>
            <version>5.5.1</version>
        </dependency>

        <dependency>
            <artifactId>junit</artifactId>
            <groupId>junit</groupId>
            <version>3.8.1</version>
        </dependency>

        <dependency>
            <artifactId>plexus-utils</artifactId>
            <groupId>plexus</groupId>
            <version>1.0.2</version>
        </dependency>

        <dependency>
            <artifactId>poi</artifactId>
            <groupId>org.apache.poi</groupId>
            <version>3.11</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <artifactId>javax.faces-api</artifactId>
            <groupId>javax.faces</groupId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.ibm.websphere</groupId>
            <artifactId>sitelib</artifactId>
            <version>126.96.36.199</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <webappDirectory>WebContent</webappDirectory>
                    <webXml>WebContent/WEB-INF/web.xml</webXml>
                    <!-- <archive> -->
                    <!-- <manifestFile>WebContent/META-INF/MANIFEST.MF</manifestFile> -->
                    <!-- <manifest> -->
                    <!-- <addClasspath>true</addClasspath> -->
                    <!-- </manifest> -->
                    <!-- </archive> -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>
O que poderia ser?
Comment: Su XML está mal-formado. Na segunda dependência está faltando o `` logo após o `` da primeira dependência. Isto daqui também está errado: `br.com.empresa/groupId>`, pois falta o `<` antes do `/groupId>`.
Comment: Você está usando alguma IDE? Já tive problemas aonde a IDE alterava arquivos como esse automagicamente. No fim, não era o maven o culpado.
Comment: To usando o RSA, que eh uma versao do eclipse da ibm, mas ele "formata" o faces-config.xml na hora que eu executo o "mvn install" pelo prompt comando, nao e pelo RSA. O maven mexe de alguma maneira no faces-config.xml?
Comment: O maven não deveria estar mexendo neste arquivo a menos que alguma coisa muito incomum esteja acontecendo. Mas a IDE pode detectar o maven executando e então mexer no arquivo. Se você fechar o RSA completamente e rodar o `mvn clean install` pelo prompt, o que acontece?
Comment: Ele continua apagando o faces-config.xml, eu realmente não tenho a minima ideia do que pode ta acontecendo, poderia ser algum plugin, ou alguma coisa do tipo
Comment: Se você colocar o `faces-config.xml` como somente-leitura e rodar o maven, dá pau em alguma etapa do processo?
Comment: Ainda não tentei isso, como eu coloco o faces-config.xml somente como leitura?
Comment: O sistema operacional tem a possibilidade de marcar arquivos como somente-leitura.
Comment: Aparace esse erro, quando eu mudo a configuração somente pra leitura: Could not copy webapp sources [C:\Users\Documents\workspace\Projeto\Web\WebContent]: C:\Users\Documents\workspace\Projeto\Web\WebContent\WEB-INF\faces-config.xml (Acesso negado.) -> [Help 1]
Comment: Este erro é bom, e significa que o arquivo não pôde ser substituído. O maven apresenta um stacktrace? Se sim, edite a pergunta para adicioná-lo, pois neste caso o stacktrace vai denunciar qual foi a ação do maven que tentou sobreescrever o arquivo. Além disso, coloque também qual é o caminho completo do seu arquivo `faces-config.xml` que não deveria ser alterado.
Answer: No meu caso eu fiz isso:

<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>${maven-war.version}</version>
            <configuration>
                <webXml>WebContent\WEB-INF\web.xml</webXml>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                    </manifest>
                </archive>
                <webResources>
                    <resource>
                        <directory>WebContent\WEB-INF\</directory>
                        <targetPath>WEB-INF</targetPath>
                        <includes>
                            <include>faces-config.xml</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>
</code>
Comment: Podes traduzir e explicar a resposta pf?

Maven mudando o faces-config.xml


html and js not working the same with flask

Question: i have a folder which contains server.py a templates folder with index.html and a js folder with script.js
server.py:
from flask import Flask, render_template
import random

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

index.html:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sparkle Trail and Dust Cursor</title>

Sparkle Trail and Dust Cursor

script.js can be found here: https://codepen.io/sarahwfox/pen/pNrYGb its too long probably but yeah im trying to have this effect but it either doesnt show anything or it shows the trail following the cursor but not the + sparkles
Answer: I don't think it's python/flask related, as I was having the same issue as you describe with basic html page and inline css and javascript. It's also not the javascript. It's a sneaky styling issue.
Your page will not take up any vertical space by default. You need to set the style property height: 100vh in the body of your html page either inline () or with css (body { height: 100vh; }).
This is what's stopping your animation, and it's also why this is a confusing bug to sort out. You could copy codepen exactly, including the css, but the site still includes some hidden formatting just to save space for the rendered page, and in this case it made all the difference.
Comment: AVOID COMMENTS LIKE THANKS?? dont caree THANK YOU SO MUCH i didnt think the css file would make that bigga difference thank you thank you thank youuuu


How do you prove a ring homomorphism is onto using the range and kernel?

Question: The problem is:

Suppose $A$ is a commutative ring and $a \in A$. If $a^2 = a$, prove that the function $\pi_a(x) = ax$ is a homomorphism from $A$ into $A$. Show that the kernel of $\pi_a$ is $I_a$, the annihilator of $a$. Show that the range of $\pi_a $ is $\langle a\rangle$. Conclude by the Fundamental Homomorphism Theorem that $A/I_a\cong\langle a\rangle$.

I'm stuck on the last step. How has $\pi_a$ been shown to be onto/surjective by the above steps?
The question is CH19-D3 from
Pinter, Charles C. "A book of abstract algebra. Reprint of the second (1990) edition." (2010).
Comment: $\pi_a$ need not be surjective. But it is always surjective onto its image...
Comment: @JonasLinssen Could you be a bit more specific? The definition of FHT I'm working with is "Let f : A->B be a homomorphism from a ring A **onto** a ring B and K be the kernel of f. Then B is isomorphic to A/K." So I thought f needed to be onto to use the theorem.
Answer: Using your definition we can modify $\pi$ as follows $ \pi : A \to \langle a \rangle $ then $\pi$ becomes onto and then you can use your theorem about $A/\ker \pi$.
Observe this shows that for any homomorphism $\phi : A \to B$ we have $$ A/\ker\phi \cong Im \phi $$
Comment: Thank you I think I finally get it now. I'm new here but I'll update when I have enough reputation.
Answer: Note that the word onto is often used to mean surjective and should not be confused with the codomain / target of a function. Imo saying homomorphism from $A$ onto $B$ for a surjective homomorphism $A\rightarrow B$ is a very bad habit, as it may easily be confused with the strictly more general notion of homomorphism from $A$ to $B$.
To solve the exercise you need to observe / prove the following things:

The subset $\langle a \rangle = \{ra \mid r\in R\} \subseteq R$ is a ring with unit $a$ (this uses $a^2=a$!). Note that it is not a subring (unless $a=1$).
The function $\pi_a: R \rightarrow R, r \mapsto ra$ has the image $\langle a\rangle\subseteq R$. In fact, restricting the codomain to the image, it defines a surjective ring homomorphism $\overline{\pi_a}:R \rightarrow \langle a \rangle$.
The kernel of $\overline{\pi_a}$ is the kernel of $\pi_a$, which is the annihilator of $a$.

The isomorphism theorem now tells you that the canonical map $A/\ker{\pi_a} \overset{\cong}{\longrightarrow} \langle a \rangle, [r] \mapsto ra$ is an isomorphism.


JavaFX select TreeItem automatically when a node inside the TreeItem gains focus

Question: I have a TreeView that I've modified by putting an HBox in the "graphic" of the TreeItem label.  This HBox contains a MenuButton.  I want to be able to automatically select the TreeItem whenever focus is given to the MenuButton inside it -- something JavaFX doesn't do automatically.  However, when I do something like this in the TreeView's cell factory:
menuButton.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> value, Boolean oldVal, Boolean newVal)
{
    if(newVal.equals(oldVal))
        return;

    if(newVal)
    {
        TreeItem<FormationDataModel> treeItem = getTreeItem();
        System.out.println("Setting selection to " + treeItem + "...");
        treeView.getSelectionModel().select(treeItem);
    }
}});

The focus on the menu button will often cause this Exception:
java.lang.NullPointerException
at javafx.scene.Scene$ScenePulseListener.synchronizeSceneProperties(Scene.java:2148)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2210)
at com.sun.javafx.tk.Toolkit$5.run(Toolkit.java:363)
at com.sun.javafx.tk.Toolkit$5.run(Toolkit.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:361)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:384)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:463)
at com.sun.javafx.tk.quantum.QuantumToolkit$9.run(QuantumToolkit.java:332)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
at java.lang.Thread.run(Thread.java:744)

Does anyone have any idea what would cause this or how to fix it so that I can have a TreeItem selected automatically when a node inside the TreeItem gains focus?
Answer: For anyone else interested, this turns out to be one or more bugs in JavaFX 2.2 specifically where they override the implementation of the MultipleSelectionModel to fix OTHER bugs. In the process of doing that, they cause all sorts of problems because they automatically expand the children of any selected item. When you do that, many of the TreeItems are invalidated, causing all sorts of sync havoc. The workaround was to select items by INDEX instead of by OBJECT. That works perfectly fine.


Uniqueness of UUID substring

Question: We track an internal entity with java.util generated UUID. New requirement is to pass this object to a third party who requires a unique identifier with a max character limit of 11. In lieu of generating, tracking and mapping an entirely new unique ID we are wondering if it is viable to use a substring of the UUID as a calculated field. The number of records is at most 10 million.
java.util.UUID.randomUUID().toString() // code used to generate
Quotes from other resources (incl. SOF):
"....only after generating 1 billion UUIDs every second for approximately 100 years would the probability of creating a single duplicate reach 50%."
"Also be careful with generating longer UUIDs and substring-ing them, since some parts of the ID may contain fixed bytes (e.g. this is the case with MAC, DCE and MD5 UUIDs)."
We will check out existing IDs' substrings for duplicates. What are the chances the substring would generate a duplicate?
Comment: It depends on how the UUID was generated and which 11 characters you're selecting. For example, if you chose the last 11 digits of a v1 UUID, you would have tons of collisions. In general, UUIDs were designed to be unique in their entirety and make no promises about substring uniqueness.
Answer: This is an instance of the Birthday Problem. One formulation of B.P.: Given a choice of n values sampled randomly with replacement, how many values can we sample before the same value will be seen at least twice with probability p?
For the classic instance of the problem,

p = 0.5, n = the 365 days of the year

and the answer is 23. In other words, the odds are 50% that two people share the same birthday when you are surveying 23 people.
You can plug in

n = the number of possible UUIDs

instead to get that kind of cosmically large sample size required for a 50% probability of a collision — something like the billion-per-second figure. It is

n = 16^32

for a 32-character string of 16 case-insensitive hex digits.
B.P. a relatively expensive problem to compute, as there is no known closed-form formula for it. In fact, I just tried it for your 11-character substring (n = 16^11) on Wolfram Alpha Pro, and it timed out.
However, I found an efficient implementation of a closed-form estimate here. And here's my adaptation of the Python.
import math

def find(p, n):
   return math.ceil(math.sqrt(2 * n * math.log(1/(1-p))))

If I plug in the classic B.P. numbers, I get an answer of 23, which is right. For the full UUID numbers,
find(.5, math.pow(16, 32)) / 365 / 24 / 60 / 60 / 100

my result is actually close to 7 billion UUID per second for 100 years! Maybe this estimate is too coarse for large numbers, though I don't know what method your source used.
For the 11-character string? You only have to generate about 5 million IDs total to reach the 50% chance of a collision. For 1%, it's only about 600,000 total. And that's probably overestimating safety, compared to your source (and which we are already guilty of by assuming the substring is random).

My engineering advice: Do you really need the guarantees that UUIDs provide aside from uniqueness, such as non-enumerability, and assurance against collisions in a distributed context? If not, then just use a sequential ID, and avoid these complications.
Comment: The birthday paradox assumes that the choices are uniformly randomly distributed. However, UUIDs and substrings of UUIDs are not required to be uniformly randomly distributed. For example, the first character of the third block is probably 4. The first two blocks of a type 1 UUID are monotonic increasing, and the last block is constant for each generating system.
Comment: @Raymond Chen I do wave my hand at this property of UUIDs in my answer, but this comment really makes it concrete!

Uniqueness of UUID substring