text:
Q: How to create a data validation system in Symfony EasyAdmin3 To put in context there is an editor who can modify his information according to his id and his information must be validated by the admin before persisting in the database.
I have in mind to create a temporary table to store the information that the editor will modify and the admin can access his information via the interface of EasyAdmin then as soon as the admin validates the information it will persist in the original table.
I did not find in the documentation the way to recover the information of the form of the edit page.
I join the crud controller that I want to target:
class OperateurCrudController extends AbstractCrudController
{
private $crudUrlGenerator;
private $adminContextProvider;

public function __construct(AdminUrlGenerator $adminUrlGenerator, AdminContextProvider $adminContextProvider)
{
    $this->adminUrlGenerator = $adminUrlGenerator;
    $this->adminContextProvider = $adminContextProvider;

}

public static function getEntityFqcn(): string
{
    return Operateur::class;
}

public function configureFields(string $pageName): iterable
{
        return [
            IdField::new('id')->hideOnForm(),
            TextField::new('name', 'Nom'),
            TextEditorField::new('description', 'Description')->hideOnIndex(),
            TextareaField::new('address', 'Adresse'),
            TextField::new('city', 'Ville')->hideOnIndex(),
            TextField::new('postal_code', 'Code Postal')->hideOnIndex(),
            TextField::new('email', 'Email'),
            TelephoneField::new('phone', 'Téléphone'),
            UrlField::new('website', 'Site Web')->hideOnIndex(),
            TextEditorField::new('opening_hours', 'Horaires d\'Ouverture'),
            NumberField::new('latitude', 'Latitude')->hideOnIndex()->setNumDecimals(15),
            NumberField::new('longitude', 'Longitude')->hideOnIndex()->setNumDecimals(15),
            TextField::new('slug', 'Slug')->hideOnIndex()->setPermission('ROLE_ADMIN'),
            DateTimeField::new('created_at', 'Date Création')->onlyOnIndex(),
            DateTimeField::new('updated_at', 'Date Modification')->onlyOnIndex(),
            AssociationField::new('thematiques', 'Thématiques')

        ];

}

public function configureActions(Actions $actions): Actions
{
    $batchAction = Action::new('approve', 'Approuver', 'fa fa-user-check')
        ->linkToUrl('approveOperators');

    $updateOperator = Action::new('update', 'Enregistrer les modifications', 'fa fa-save')
        ->linkToCrudAction('saveOperator');

    if($this->isGranted('ROLE_ADMIN')){
        return $actions
            ->add(Crud::PAGE_INDEX, $batchAction)
            ->add(Crud:: PAGE_INDEX, Action::DETAIL)
            ->setPermission(Action::DELETE, 'ROLE_ADMIN')
            ->setPermission(Action::NEW, 'ROLE_ADMIN')
            ->setPermission(Action::EDIT, 'ROLE_ADMIN')
            ->setPermission($batchAction, 'ROLE_ADMIN');
    }

    if($this->isGranted('ROLE_EDITOR')){
        return $actions
            ->add(Crud:: PAGE_INDEX, Action::DETAIL)
            ->add(Crud::PAGE_EDIT, $updateOperator)
            ->setPermission(Action::DELETE, 'ROLE_ADMIN')
            ->setPermission(Action::NEW, 'ROLE_ADMIN')
            ->setPermission($updateOperator, 'ROLE_EDITOR')
        ->disable( Action::SAVE_AND_RETURN, Action::SAVE_AND_CONTINUE);
    }

}

public function approveOperators(): Response{

    $this->addFlash('notice', 'Modification effecuté ');

    $url = $this->adminUrlGenerator
        ->setAction(Action::INDEX)
        ->generateUrl();

    return $this->redirect($url);

}

public function saveOperator(){
    //$this->addFlash('notice', 'Modification pris en compte ! ');

    //Create my own save button in page edit

}

public function configureCrud(Crud $crud): Crud
{
    return $crud
        ->setEntityPermission('ROLE_EDITOR');
}

public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{

    $response = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
    if(!$this->isGranted('ROLE_ADMIN')){
        $response->where('entity.id = :id');
        $response->setParameter('id', $this->getUser()->getOperateur());
    }

    return $response;

}

public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
    parent::updateEntity($entityManager, $entityInstance); // TODO: Change the autogenerated stub
}

Thank you for reading

A: you should use BeforeEntityPersistedEvent::class
It will autotrigger just before persisting an element in database
class EasyAdminSubscriber extends AbstractController implements EventSubscriberInterface
{

  public function __construct( )
      {

      }

  public static function getSubscribedEvents(){

    return [
      BeforeEntityPersistedEvent::class => ['functionName']
    ];
  }

  public function functionName(BeforeEntityPersistedEvent $event){

    $entity=$event->getEntityInstance();

    $user = $this->getUser();
    $userRole = $user->getRole();
    $check = $this->checkRole($userRole);

    if ($entity instanceof yourEntity && $check== true) {

           //Do your magic with changing the value you want in the table you
       }
    }

}
Sorry to no comment, i dont have enough reputation for it so i answer there.


text:
Q: Convergence of probability densities I appreciate if you can give me some guidance on how to approach this question:
Suppose $f_n(x) \text{ and } g(x)$ are densities such that for all x, $f_n(x) \rightarrow g(x)$ as $n \rightarrow \infty$. I need to show two things:
1) $\int |f_n(x) - g(x)|dx \rightarrow 0$ as $n \rightarrow \infty$
2) if $X_n$ has density  $f_n(x)$ and X has density g(x), and if $\int |f_n(x) - g(x)|dx \rightarrow 0$ as $n \rightarrow \infty$, then:
$$sup_A |P(X_n \in A) - P(X \in A)|\rightarrow 0 \text{ as } n \rightarrow \infty$$
Thanks for your help.

A: For (1), do you have any other assumption on $f_n$ (eg, bounded)? If so, you can use the Dominated Convergence Theorem.
For (2), observe that for any Borel set $A$,
$$
\left|\mathbb P\{X_n\in A\} - \mathbb P\{X\in A\}\right| = \left|\int_\mathbb{R}\mathbb{1}_A(f_n-g)\right| \leq
\int_\mathbb{R}\mathbb{1}_A|f_n-g|
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find number then replace it with number+1 Google Sheet I have some a group of cells on Google sheets with the following text:
KelleshaParkAfterChoice1_36
KelleshaParkAfterChoice1_37
KelleshaParkAfterChoice1_38
KelleshaParkAfterChoice1_39
KelleshaParkAfterChoice1_40
KelleshaParkAfterChoice1_41
KelleshaParkAfterChoice1_42
Now what i want to do is replace the last 2 digits(36,37,38,etc..) with those digits+1 (37,38,39,etc..) e.g:
KelleshaParkAfterChoice1_37
KelleshaParkAfterChoice1_38
KelleshaParkAfterChoice1_39
KelleshaParkAfterChoice1_40
KelleshaParkAfterChoice1_41
KelleshaParkAfterChoice1_42
KelleshaParkAfterChoice1_43
Trying to learn how to do that i stumbled upon regular expressions and Regex, so i learned that i can capture the last numbers with "(?\d{2})", and then i can access the numbers with $1, what i didn't find how to do yet is to make operations with the captured numbers, anyone knows the solution to this?

A: You can use the following formula
=ArrayFormula(IFERROR((REGEXEXTRACT(A2:A,".*_")
             &REGEXREPLACE(A2:A,"(.*_)","")+1)))

(Please alter ranges to your needs)
Functions used:

*

*ArrayFormula

*IFERROR

*REGEXEXTRACT

*REGEXREPLACE


text:
Q: How to add current user as author to blog using Express and Mongodb I am working on a basic Blog site using Express, MongoDB and using JWT for authentication. On valid authentication I am attaching the current user ID to the req object.
I am adding the current User ID as the author of the Blog.
Here're the Blog and User models
const BlogSchema = new mongoose.Schema({
   title: {type: String, required: true},
   body: {type: String, required: true},
   author : {type:mongoose.Schema.Types.ObjectId, ref: "UserSchema"}
  })
module.exports = mongoose.model("Blog", BlogSchema);

const UserSchema= new mongoose.Schema({
   name: {type: String, required: true},
   email: {type: String, required: true},
   blogs : [{type:mongoose.Schema.Types.ObjectId, ref: "BlogSchema"}]
 })
module.exports = mongoose.model("Blog", UserSchema);

I am adding the current user that I am getting from the JWT validation and adding it to the Blog Model instance. This works but the blog ids are not getting added to the User's blog array
How to get around it? Please help


text:
Q: Should I use "her" or "she"? In the blank below:

Everyone likes you but _____.

Should I use "her" or "she"?
I think both of them are okay. If "her" is used, I'll perceive the sentence as "Everyone likes you, but everyone does not like her"; using "she", I'll perceive the sentence as "Everyone likes you, but she does not like you."
Please tell me which one is correct, or if neither of them are correct.

A: "But" functions as both a conjunction and a preposition. If you look at "but" as a conjunction, it leads to that other sentence -- "she does not like you".
But if you look at "but" as a preposition, it means "except for". https://www.merriam-webster.com/dictionary/but
If "except for" were substituted for "but", the preposition would take an object, in the accusative case. One of the examples given for this use by the Merriam-Webster dictionary at the link I cited is "no one there but me", where "me" is the proper case for a prepositional object.
For the sentence cited in the question, the equivalent correct pronoun would be "her".
Since so many native English speakers would use "her" in this instance, it's probable that this is the way they hear the sentence, and just naturally treat the word "but" as a preposition. This makes "her" not just commonly used, but also arguably correct.

A: I think this is another case of and when used as conjunction linking two nominative pronouns, as has been discussed here.
In formal writing, she should be used. However, her is more common in daily speech and there is nothing wrong with saying: "Everyone likes you but her."


text:
Q: What evidence is there that infinities exist anywhere around or within a black hole? I've often seen black holes referred to as having a "singularity", which is described as a point of "infinite density", presumably due to the mass of the black hole occupying a point with zero volume (rather than having infinite mass in a finite volume).
Is there any evidence that this singularity is actually infinitely small, as opposed to just "extremely small"? For example, if it's the size of a quark (i'm just choosing a quark as an example of a "extremely small thing") then it's not infinitely small, it's just extremely small, and the density will just be extremely high rather than infinitely high.
I understand that due to the event horizon, we don't really know what's going on in there.  But, since we know that the event horizon has a finite volume, why not assume that the black hole itself (or "the thing at the middle" - i'm not sure if the term "black hole" includes the event horizon or not) has a finite volume too?
Is the "infinite density" thing actually just a common misperception by writers?
EDIT - i just realised that a quark is a bad example of a "small thing" since i don't know if it's believed to have a volume.  But you get the idea anyway, i hope.

A: It is a misperception by (non-scientist) writers. The black hole physical model is a model based on General Relativity only. This tells something about real black holes, and have many interesting and complicated properties. Still, all scientists know that in the local conditions of very small scale and high density it is the realm of quantum mechanics, that don't accept such notion as point singularity. And the point is that nobody knows for now how to mix quantum mechanics and relativity, at least in these extreme conditions.
Now, whether "maths-like singularity" or "quantum-blurred" singularity, it is hidden inside the Schwarzschild sphere (which is indeed the "black hole"), so you will never know what happens inside, and it will never impact anything on the outside. So it will be difficult to experiment and test  (and have "evidences" of anything inside), and indeed whatever you assume (e.g. "interior of black holes are made of cockroaches") will be compatible with correct physics outside. :-)


text:
Q: how to retrieve largest value from a particular column in cassandra? how can i retrieve largest value from a particular column in Cassandra ? i am storing tag name as name and number of clicks as value in Cassandra. Now i need to find out what are the most popular tags(based on the click)? Please Help me
example :

*

*supercolumn : movies
columnname : "matrix"
value      : 10(number of clicks)

*supercolumn : movies
columnname : "titanic"
value      : 0(number of clicks)

*supercolumn : movies
columnname : "avatar"
value      : 5(number of clicks)
now i need to get the result like matrix,avatar and titanic respectively(based on the value desc)

A: You'd need to have another CF with movie names as row keys, and column values as cnames -- then the ordering of column names makes "get the one with largest value" trivial.


text:
Q: VirtualizingPanel.ScrollUnit="Pixel" not working for .Net 4.6.2. Need alternatives I have a Datagrid with more than 2000 rows and the initial loading was very very slow but once everything was loaded, the srolling down was pretty fast. I added the following properties to my style and the performance improved by 5 times.
<Setter Property="VirtualizingStackPanel.IsVirtualizing" Value="True"/>
<Setter Property="VirtualizingStackPanel.VirtualizationMode" Value="Recycling"/>
<Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="True"/>
<Setter Property="ScrollViewer.CanContentScroll" Value="True"/>

But after this, my scrolling became slower. I know that this is happening because now I'm loading as I scroll down.
I have read some posts about pixel loading and I have to set ScrollViewer.CanContentScroll = false and I don't want to do that because turning that to false is slowing my application down.
I have also read that in .Net 4.5 and higher versions, there is a hack to set the pixel scrolling by doing VirtualizingPanel.ScrollUnit="Pixel". I'm using .Net 4.6.2 and I don't see this improving my scroll performance. Is there something that can be done to not compromise either on application performance or the scroll performance?


text:
Q: How to mock a protected field? I am attempting to mock a protected field in the class NodeIdGenerator. I want to set the value of the field in a constructor an then call the GetNext() method which belongs to NodeIdGenerator.
Im pretty sure my test is OK:
public class NodeIdGeneratorTests
{

    [Fact(DisplayName = "Throws OverflowException when Int32.MaxValue " +
        "IDs is exceeded")]
    public void ThrowsOverflowExceptionWhenInt32MaxValueIdsIsExceeded()
    {
        var idGenerator = new NodeIdGeneratorMock(Int32.MaxValue);
        Assert.Throws(typeof(OverflowException),
            () => { idGenerator.GetNext(); });
    }

    /// <summary>
    /// Mocks NodeIdGenerator to allow different starting values of
    /// PreviousId.
    /// </summary>
    private class NodeIdGeneratorMock : NodeIdGenerator
    {
        private new int? _previousId;

        public NodeIdGeneratorMock(int previousIds)
        {
            _previousId = previousIds;
        }
    }

}

My problem is in the mock class. When I call GetNext() in my test, it uses the _previousId object belonging to the superclass, not the one which I want it to use (in the mock class.)
So, how do I mock the protected field?
PS: I have read this question but I can't seem to make head nor tail of it!

A: If possible it would be better to make previousId a virtual property and override the getter in the mock:
public class NodeIdGenerator
{
    protected virtual int? PreviousId { ... }
}

private class NodeIdGeneratorMock : NodeIdGenerator
{
    protected override int? PreviousId
    {
        get { return _previousId; }
    }
}

A: The code you've posted declares _previousId as new, so it hides the base class' field - it doesn't override it. The base class won't use that value when you call GetNext, it will use its own field.
Try removing your declaration and just access the base class' protected field.


text:
Q: How to return all value of column after calculation laravel 8 I have a table that stores the bets from users. This bets table has relationship with users table.

id
user_id
bet_type
bet_price
bet_round

1
1
1
10
1

2
2
1
15
1

I select all from the bets table where bet_type = 1 and bet_round = $x_game_round . When I get them, I can calculate on bet_price column. In my case, I have two users with user_id=1 and user_id=2 who bet on bet_type=1. When I return, I can only see winning price for user_id=1.
What I want is to return win_price for each user that bets with bet_type = 1.
I try in my controller as below.
$x_game_round = $x_value["gameRound"];

    if($x_value["winner"] === 1) {

        $winners = DB::table('bets')
        ->where('bet_type', '=', '1')
        ->where('bet_round', '=', $x_game_round)
        ->get();

        if($winners){
            foreach($winners as $winner) {
                $bet_price = $winner->bet_price;
                // echo $winner->user_id;
                $win_price = $this->calculateBasicPayout('1', $bet_price);
                return $win_price;

            }
        }

    }

public function calculateBasicPayout($bet_type, $bet_price){

        $commission = 5;

        if($bet_type === '1')
        {
            // take out 5% of Winning amount.
            $commissionAmount = ($commission / 100) * $bet_price;
            $payoutAmount = ($bet_price * 2) - $commissionAmount;
            return $payoutAmount;

        }elseif($bet_type === '2')
        {
            $payoutAmount = $bet_type * 2;
            return $payoutAmount;

        }elseif($bet_type === '3')
        {
            $payoutAmount = $bet_type * 8;
            return $payoutAmount;
        }

   }

A: You're only ever looping a single $winner as in your foreach loop you have a return statement which breaks out of your execution.
Instead you want to assign $winning_price to your $winner, or some other variable and remove the return statement.


text:
Q: Which of these two Java insertion sort algorithms is better? This is my solution to the insertion sort algorithm:
void insertionSort(int[] array) {

    for(int i = 1; i < array.length; i++) {
        for (int j = i; j > 0; j--) {
            if(array[j] < array[j-1]) {
                int tmp = array[j];
                array[j] = array[j-1];
                array[j-1] = tmp;
            }
        }
    }
}

This is the "standard" solution:
void sort(int arr[])
    {
        int n = arr.length;
        for (int i=1; i<n; ++i)
        {
            int key = arr[i];
            int j = i-1;
            while (j>=0 && arr[j] > key)
            {
                arr[j+1] = arr[j];
                j = j-1;
            }
            arr[j+1] = key;
        }
    }

Is there something wrong with my solution? Is it in any way less effective because the tests so far have shown that it works.

A: If you set up a performance measurement, you can easily see which one is faster.
insertionSort : [0.0, 0.0, 0.0, 0.5, 35.0, 3289.5]
         sort : [0.0, 0.0, 0.0, 0.3, 15.6, 1163.1]

The sort method is much faster than the insertionSort method, because it is very similar to a quick-sort (which uses a pivot).
Example code
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class SortCompare {
    public static void main(String[] args) {
        int tests = 2;
        int runs = 10;
        int size = 6; // 1 -> 100,000
        long[][][] times = new long[tests][size][runs];
        double[][] avgs = new double[tests][size];

        for (int run = 0; run < runs; run++) {
            System.out.printf("Run #%d...%n", run);

            for (int magnitude = 0; magnitude < size; magnitude++) {
                System.out.printf("Magnitude #%d...%n", magnitude);

                int[] a = shuffle(range((int) Math.pow(10, magnitude)));
                {
                    long start = System.currentTimeMillis();
                    insertionSort(Arrays.copyOf(a, a.length));
                    times[0][magnitude][run] = System.currentTimeMillis() - start;
                }

                {
                    long start = System.currentTimeMillis();
                    sort(Arrays.copyOf(a, a.length));
                    times[1][magnitude][run] = System.currentTimeMillis() - start;
                }
            }
        }

        for (int i = 0; i < size; i++) {
            for (int j = 0; j < tests; j++) {
                avgs[j][i] = avg(times[j][i]);
            }
        }

        System.out.printf("insertionSort : %s%n", Arrays.toString(avgs[0]));
        System.out.printf("         sort : %s%n", Arrays.toString(avgs[1]));
    }

    private static double avg(long[] times) {
        long total = 0;
        for (long time : times) total += time;
        return ((double) total) / times.length;
    }

    private static int[] range(int size) {
        int[] a = new int[size];
        for (int i = 0; i < size; i++) a[i] = i;
        return a;
    }

    private static int[] shuffle(int[] a) {
        Random rnd = ThreadLocalRandom.current();
        for (int i = a.length - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            int tmp = a[index];
            a[index] = a[i];
            a[i] = tmp;
        }
        return a;
    }

    private static void insertionSort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            for (int j = i; j > 0; j--) {
                if (array[j] < array[j - 1]) {
                    int tmp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = tmp;
                }
            }
        }
    }

    private static void sort(int arr[]) {
        int n = arr.length;
        for (int i = 1; i < n; ++i) {
            int key = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
}


text:
Q: Flash Security Policy: Is there a work around to allow the blocked IP 127.0.0.2? For local development of a Flash game we need to run servers at 127.0.0.1 and 127.0.0.2. Adobe security policy doesn't have a problem with 127.0.0.1 but it explicitly blocks 127.0.0.2.
We use Windows Azure as our hosting platform and recent changes to the Windows Azure Compute Emulator are requiring us to use both of these IP addresses.
Does anyone know a work-around for this?

A: I think the Flash Player Global Security Settings Panel may allow you to resolve this.
Add your the local directory where the SWF's are served from (or add 127.0.0.2?) to the box labeled "always trust files in these locations".


text:
Q: RuntimeException: Unable to pause activity triggered by onDestroy I'm getting an exception every time I try to start a new activity.
 03-23 10:55:17.506: E/AndroidRuntime(29210): FATAL EXCEPTION: main
    03-23 10:55:17.506: E/AndroidRuntime(29210): java.lang.RuntimeException: Unable to pause activity {com.example.elan_lifestyle/com.example.elan_lifestyle.Start}: java.lang.IllegalStateException: No activity
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3046)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3001)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2979)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.ActivityThread.access$800(ActivityThread.java:146)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1251)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.os.Handler.dispatchMessage(Handler.java:99)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.os.Looper.loop(Looper.java:137)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.ActivityThread.main(ActivityThread.java:5171)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at java.lang.reflect.Method.invokeNative(Native Method)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at java.lang.reflect.Method.invoke(Method.java:511)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at dalvik.system.NativeStart.main(Native Method)
    03-23 10:55:17.506: E/AndroidRuntime(29210): Caused by: java.lang.IllegalStateException: No activity
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1091)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.support.v4.app.FragmentManagerImpl.dispatchPause(FragmentManager.java:1898)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.support.v4.app.FragmentActivity.onPause(FragmentActivity.java:412)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at com.example.elan_lifestyle.Start.onPause(Start.java:172)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.Activity.performPause(Activity.java:5314)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1226)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3032)
    03-23 10:55:17.506: E/AndroidRuntime(29210):    ... 12 more

I've traced the problem to my onDestroy method:
protected void onDestroy() {
    super.onDestroy();

    try{
      btAdapter.cancelDiscovery();  // make sure the bluetooth is not searching
    }
    catch(Exception e){
        Log.e("start: onDestroy","btAdapter crashed");
        e.printStackTrace();
    }

      Log.e("StartActivity","ending");

    try{
    unregisterReceiver(ActionFoundReceiver);
    }
    catch(Exception e){
        Log.e("StartActivity: onDestroy","reciever crashed");
        e.printStackTrace();
    }

  }

If I call onDestroy just after starting the new activity I get the exception and crash. If I don't call onDestroy it works fine but leaves the old activity still running. Here's the section of code where onDestroy is called:
            Intent i = new Intent(Start.this, Base.class);  // setup intent
            i.putExtra("Address", name);    // add the target device name to the intent
            Start.this.startActivity(i);    // start main activity
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);    //override animation
            onDestroy();

What is causing this Exception and how can I fix it?

A: instead of calling onDestroy() (which you shouldn't ever invoke by yourself at the first place), you should invoke finish() to destroy your running activity instance.


text:
Q: In Django have created custom permissions and assigned permissions to group and user but @permission_required fails I have created a custom permission in my user model, which is in the app users:
class User(AbstractUser):
    first_name=models.CharField(max_length=40, null=True, blank=True)
    actual_user = models.CharField(max_length=20, null=True, default=None)

    class Meta:
        permissions = (("can_switch_user", "Switch user"),)

I have migrated the permissions in, added the permission to a group, and have assigned the user the permission and the group. When I test to see if the user has the permission it does not.
@login_required
def hello(request):

    context = {
        "name": request.user.username,
        "actual_user": request.user.actual_user,
        "groups": Group.objects.all(),
        "permissions": request.user.user_permissions.first(),
        "switch_user": request.user.has_perm('users.can_switch_user')}
    return render(request, "testapp/hello.html", context)

I have also tried the permission "users.user.can_switch_user'
hello.html looks as follows (base.html just has the HTML, title and body tags with the block for the body content):
{% extends "base.html" %}

{% block content %}

Hello {{name}}

Actual user: {{actual_user}}

Group: {{group}}

Perms: {{permissions}}

Can Switch User {{switch_user}}

{% endblock %}

When I display the results via hello.html I get:
Hello user1

Actual user: user1
Group:
Perms: users | user | Switch user
Can Switch User False

Why am I not getting the correct permissions?  Do I need to create a check_permissions method in my user model to make this work or am I doing something else incorrectly.


text:
Q: Sum of terms in a composition cycle Let $f, g$ be linear functions.
Define $S(x)$ as $any$ composition sequence of $f$ and $g$ like
$S(x) = (f\circ g\circ g\circ f\circ f\circ g)(x)$
Let $s$ as the fixed point of $S$ then a cycle is determined
$s \to_g g(s) \to_f (f\circ g)(s) \to_f (f\circ f\circ g)(s) \to_g (g\circ f\circ f\circ g)(s) \to_g (g\circ g\circ f\circ f\circ g)(s) \to_f s (again)$
Call $Sum_g(S)$ the sum of the terms of the cycle such that $g$ function is applied to this term.
In this example $Sum_g(S) = s + (f\circ f\circ g)(s) + (g\circ f\circ f\circ g)(s)$
Define $T(x)$ as the reversed composition sequence
$T(x) = (g\circ f\circ f\circ g\circ g\circ f)(x)$
Call $t$ the fixed point of $T$
In this example $Sum_g(T) = (f)(t) + (g\circ f)(t) + (f\circ f\circ g\circ g\circ f)(t)$
Prove that $Sum_g(S) = Sum_g(T)$

$f(x) = 3x-2$ and $g(x)=2x+1$
$S(x) = (f\circ g\circ g\circ f\circ f\circ g)(x) = 216 x + 19$ and $s = -19/215$
$T(x) = (g\circ f\circ f\circ g\circ g\circ f)(x) = 216 x - 105$ and $t = 21/43$
$Sum_g(S) = s + (f\circ f\circ g)(s) + (g\circ f\circ f\circ g)(s) = -19/215 -127/215 -39/215 = -37/43$
$Sum_g(T) = (f)(t) + (g\circ f)(t) + (f\circ f\circ g\circ g\circ f)(t) = -23/43 -3/43-11/43 = -37/43$

A visual approach
$f(x) = 3x-2$ (or any linear function)
$g(x)=x/5+1$ (or any other linear function)
Then
$ \color{red}{215/98 \to_g} \color{blue}{141/98 \to_f 227/98 \to_f} \color{red}{485/98 \to_g 195/98 \to_g} \color{blue}{137/98 \to_f} 215/98 (again)$
Obs: $215/98$ is the fixed point of $(f\circ g\circ g\circ f\circ f\circ g)(x)$
The reversed cycle is
$ 177/98 \color{red}{_g\leftarrow 395/98} \color{blue}{_f\leftarrow 197/98 _f\leftarrow 131/98} \color{red}{_g\leftarrow 165/98 _g\leftarrow 335/98} \color{blue}{_f\leftarrow 177/98} (again)$
Obs: $177/98$ is the fixed point of $(g\circ f\circ f\circ g\circ g\circ f)(x)$
why this happens?
$ \color{red}{215/98 + 485/98 + 195/98 = 395/98 + 165/98 + 335/98}$
$\color{blue}{141/98 + 227/98 + 137/98 = 197/98 + 131/98 + 177/98} $

A: Consider a composition of functions $f_i, i=1$ to $n$  with $f_i(x)=a_i x + b_i$
Then $f_1 \circ \dots \circ f_n (x) = \left(\prod_{i=1}^n a_i \right) x + \sum_{k=1}^n \left(\prod_{i=1}^{k-1} a_i \right) b_k $
So the fixed point is:
$$\frac{ \sum_{k=1}^n \left(\prod_{i=1}^{k-1} a_i \right) b_k } {1- \left(\prod_{i=1}^n a_i \right)}$$
Each term in the sum $Sum_g$ is going to be a fixed point of some cyclic permutation of the composition. $\prod_{i=1}^n a_i$ is preserved by cyclic shift and reflection, so we can ignore the denominator.
Thus each of the two sums is expressed as a sum over pairs of points in the composition (or its reflection), the first of which much has $g$ applied to it and the second of which can have anything applied to it. The term corresponding to a pair is the product of the slopes of the linear functions in between, times the intercept of the last one.
Thus we can divide into pairs where the second has $g$ applied to it and pairs where the second has $f$ applied to it. The first case is completely symmetric, so it is the same reflected and unreflected. The second case is more complicated. In the $S$, terms come from sequences beginning in $g$ and ending in $f$. In the $T$, the term comes from the sequences beginning in $f$ and ending in $g$. In both cases, the contribution of a term depends only on the number of $f$s and $g$s between them. Thus, we need the following combinatorial lemma:
For each cycle of $f$s and $g$s, and for each pair of nonnegative numbers $x$ and $y$, the number of subsequences consisting of a $g$, followed by $x$ $f$s and $y$ $g$s, followed by an $f$, is the same as the number of subsequences consisting of an $f$, followed by $x$ $f$s and $y$ $g$s, followed by a $g$
The proof is by discrete continuity. Arrange all the subsequences of length $x+y+1$ in order, and count the number of $f$s in each. This can increase or decrease by at most $1$ at each step. The first type of subsequence occurs when a subsequence of length $x+y+1$ with $x$ $f$s is followed by one with $x+1$ $f$s. The second type of subsequence occurs when a subsequence of length $x+y+1$ with $x+1$ $f$s is followed by one with $x$ $f$s. These two events must alternate, so must occur equally often.


text:
Q: "Spread" na.locf data for irregular time data I have data like the following:
data <- tibble(time = c(ymd_hms("2019-11-01 09:33:00"),
                        ymd_hms("2019-11-01 09:35:00"),
                        ymd_hms("2019-11-01 09:40:00"),
                        ymd_hms("2019-11-01 09:52:00")),
               data = c(1250, 900, 4000, 9000))
data
##  A tibble: 4 x 2
#   time                 data
#   <dttm>              <dbl>
# 1 2019-11-01 09:33:00  1250
# 2 2019-11-01 09:35:00   900
# 3 2019-11-01 09:40:00  4000
# 4 2019-11-01 09:52:00  9000

I want the data column to be resampled for every minute between the first and last observation, and I want the value of data to become the next non NAN value divided by 1 + the number of nan values from the prior non-nan value to the next non-nan value (i.e. the value of data is "spread" back minutely from its given sample point to the prior given sample point).
In this case for instance, I would expect the following
> result
# A tibble: 20 x 2
   time                 data
   <dttm>              <dbl>
 1 2019-11-01 09:33:00  1250
 2 2019-11-01 09:34:00   450
 3 2019-11-01 09:35:00   450
 4 2019-11-01 09:36:00   800
 5 2019-11-01 09:37:00   800
 6 2019-11-01 09:38:00   800
 7 2019-11-01 09:39:00   800
 8 2019-11-01 09:40:00   800
 9 2019-11-01 09:41:00   750
10 2019-11-01 09:42:00   750
11 2019-11-01 09:43:00   750
12 2019-11-01 09:44:00   750
13 2019-11-01 09:45:00   750
14 2019-11-01 09:46:00   750
15 2019-11-01 09:47:00   750
16 2019-11-01 09:48:00   750
17 2019-11-01 09:49:00   750
18 2019-11-01 09:50:00   750
19 2019-11-01 09:51:00   750
20 2019-11-01 09:52:00   750

How can I do this?

I see in Zoo how to use na.locf to do nearly what I want, but I don't see how to incorporate this "spreading" of the data instead of just filling with last value or doing linear interpolation.
I've also tried using xts and merging two series (one of which is the irregular dates) with some custom logic but this is proving challenging for me.

A: We can use dplyr and join the dataframe with the one that has all the timesteps.
Then we can use tidyr to fill upwards and finally divide by the number of records in each group (i.e. number of timesteps that were missing + 1)
library(dplyr)
library(lubridate)
library(tidyr)

data <- tibble(time = c(ymd_hms("2019-11-01 09:33:00"),
                        ymd_hms("2019-11-01 09:35:00"),
                        ymd_hms("2019-11-01 09:40:00"),
                        ymd_hms("2019-11-01 09:52:00")),
               data = c(1250, 900, 4000, 9000))

tibble(time = seq.POSIXt(from = min(data$time),
                         to = max(data$time), by="min")) %>%
  left_join(., data, by="time") %>%
  group_by(id = cumsum(is.na(data) & !is.na(lag(data)))) %>%
  fill(data, .direction = "up") %>%
  mutate(data = data/ n())

#> # A tibble: 20 x 3
#> # Groups:   id [4]
#>    time                 data    id
#>    <dttm>              <dbl> <int>
#>  1 2019-11-01 09:33:00  1250     0
#>  2 2019-11-01 09:34:00   450     1
#>  3 2019-11-01 09:35:00   450     1
#>  4 2019-11-01 09:36:00   800     2
#>  5 2019-11-01 09:37:00   800     2
#>  6 2019-11-01 09:38:00   800     2
#>  7 2019-11-01 09:39:00   800     2
#>  8 2019-11-01 09:40:00   800     2
#>  9 2019-11-01 09:41:00   750     3
#> 10 2019-11-01 09:42:00   750     3
#> 11 2019-11-01 09:43:00   750     3
#> 12 2019-11-01 09:44:00   750     3
#> 13 2019-11-01 09:45:00   750     3
#> 14 2019-11-01 09:46:00   750     3
#> 15 2019-11-01 09:47:00   750     3
#> 16 2019-11-01 09:48:00   750     3
#> 17 2019-11-01 09:49:00   750     3
#> 18 2019-11-01 09:50:00   750     3
#> 19 2019-11-01 09:51:00   750     3
#> 20 2019-11-01 09:52:00   750     3

A: 1) zoo Convert to zoo object z, insert the NAs using merge and then define the groups g as consecutive positions which are NA except for the last in the group.  Then compute the required ratios and convert to data frame using fortify.zoo.  The last line could be omitted if a zoo series result is ok.
library(zoo)

z <- read.zoo(data)
m <- merge(z, zoo(, seq(start(z), end(z), 60)))
g <- head(c(0, cumsum(!is.na(m))), -1)
data2 <- na.locf0(m, fromLast = TRUE) /  ave(m, g, FUN = length)
fortify.zoo(data2)

giving:
                 Index data2
1  2019-11-01 09:33:00  1250
2  2019-11-01 09:34:00   450
3  2019-11-01 09:35:00   450
4  2019-11-01 09:36:00   800
5  2019-11-01 09:37:00   800
6  2019-11-01 09:38:00   800
7  2019-11-01 09:39:00   800
8  2019-11-01 09:40:00   800
9  2019-11-01 09:41:00   750
10 2019-11-01 09:42:00   750
11 2019-11-01 09:43:00   750
12 2019-11-01 09:44:00   750
13 2019-11-01 09:45:00   750
14 2019-11-01 09:46:00   750
15 2019-11-01 09:47:00   750
16 2019-11-01 09:48:00   750
17 2019-11-01 09:49:00   750
18 2019-11-01 09:50:00   750
19 2019-11-01 09:51:00   750
20 2019-11-01 09:52:00   750

2) base Here is a base solution that is even shorter.  We define a function ratiofun which generates the data for one group given its length in minutes and the value of its right endpoint.  Then expand time and apply the function.
ratiofun <- function(minutes, data) rep(data/minutes, minutes)
with(data, data.frame(time = seq(min(time), max(time), 60),
  data = unlist(mapply(ratiofun, c(1, diff(time)), data))))

giving:
                  time data
1  2019-11-01 09:33:00 1250
2  2019-11-01 09:34:00  450
3  2019-11-01 09:35:00  450
4  2019-11-01 09:36:00  800
5  2019-11-01 09:37:00  800
6  2019-11-01 09:38:00  800
7  2019-11-01 09:39:00  800
8  2019-11-01 09:40:00  800
9  2019-11-01 09:41:00  750
10 2019-11-01 09:42:00  750
11 2019-11-01 09:43:00  750
12 2019-11-01 09:44:00  750
13 2019-11-01 09:45:00  750
14 2019-11-01 09:46:00  750
15 2019-11-01 09:47:00  750
16 2019-11-01 09:48:00  750
17 2019-11-01 09:49:00  750
18 2019-11-01 09:50:00  750
19 2019-11-01 09:51:00  750
20 2019-11-01 09:52:00  750


text:
Q: My CGI script cookie set and get I have a site on CGI and working fine yesterday but suddenly its cookie stop working. I am unable to set cookie and get cookie in my script. below is my code.
To set cookie
#!/usr/bin/perl
use CGI::Carp qw (fatalsToBrowser);
use CGI;
require "cookie.lib";
&SetCookies('V', $EncUID);

To get cookie
#!/usr/bin/perl
use CGI::Carp qw (fatalsToBrowser);
use CGI;
require "cookie.lib";
&GetCookies();
my $UID = $Cookies{"V"};

Please Help me regarding this.

A: Whoa, it's suddenly like 199x all over. Replace cookie.lib with CGI::Cookie.
#!/usr/bin/perl
use CGI::Carp qw(fatalsToBrowser);
use CGI;
use CGI::Cookie qw();

print CGI::header(-cookie => [CGI::Cookie->new(-name => 'V',-value => $EncUID)]);

#!/usr/bin/perl
use CGI::Carp qw(fatalsToBrowser);
use CGI;
use CGI::Cookie qw();

my %cookies = CGI::Cookie->fetch;
my $UID = $cookies{'V'}->value;


text:
Q: Get disk usage (>90%) from metricbeats system module I'm trying to check if current disk usage exceeds 90% for each host. I've ended up with such query:
GET /metricbeat-2017.04.18/_search
{
  "query": {
    "exists" : { "field" : "system.fsstat.total_size" }
  },
  "size": 0,
  "aggs": {
    "by_hostname": {
      "terms": {
        "field": "beat.hostname",
        "size": 100
      },
      "aggs": {
        "newst_fsstat": {
          "top_hits": {
            "sort": [{"@timestamp": {"order": "desc"}}],
            "size" : 1
          }
        },
        "total_size": {
          "sum": {
            "field": "system.fsstat.total_size.total"
          }
        },
        "used_size": {
          "sum": {
            "field": "system.fsstat.total_size.used"
          }
        },
        "disk_usage_percentage": {
          "bucket_script": {
            "buckets_path": {
              "total": "total_size",
              "used": "used_size"
            },
            "script": "params.used / params.total * 100"
          }
        }
      }
    }
  }
}

But I cannot put next aggs in top_hists, and thus total_size and used_size are sum of every docs.
Also, I'm having trouble to filter disk_usage_percentage to include only those > 90%.
Can you help with such query?


text:
Q: Java: Using multiple Threads to paint simultaniously on a JPanel I have a JPanel on which I wish to have several threads painting "animations" on. An "animation" consists of a JLabel with an ImageIcon on it, which is being moved from one area of the screen to another area.
Now, problem is - I want several such animations to be portrayed on screen by those threads mentioned. Problem is - the JPanel's "paint()" method can only be trigged by one thread at a time - causing the animations to execute serially, instead of in a parallel way.
Any idea how to have several such animations on screen at the same time?

A: It is impossible to use multiple threads to do what you want. Swing Toolkit is single threaded
. The correct way to do it is to use one of the animation frameworks available:

*

*Trident animation framework

*TimingFramework

A: Swing is not thread-safe, thus it's simply not a supported use-case to do UI-related stuff from several threads simultaneously.
Go for the model-view-controller (MVC) pattern:

*

*Let all threads update a (thread safe) model.

*Whenever there is an update of the model, invoke repaint.

*repaint() will schedule the UI-thread to call the proper paint-methods.

*The paint-method should then simply read the state of the model, and draw the component accordingly.


text:
Q: How can I make the spacing between Divs in my website consistent, regardless of content amount within the divs I am trying to make multiple pages of the same website with different content on each page. For instance I want each page to have the same look and feel, The spacing between each divs to be exact  regardless of the content. I tried to use display: inline-block; to autofit the divs and use a margins for the spacing.
I am also using absolute positioning on the divs inside a fixed container.

A: I assume that you can use the bootstrap to load the div such that it remain the same for every page using the predefined class .col-md-x

A: I think you can add
A
 with the div tag being white, white borders, white text.
You need to do that because someone could put their default color to BLACK. Also, change the css:
div.space {
    font-family: monospace;
}

so it will have the same position of the letters.

A: You can do this in your stylesheet
div { margin: 10px 0}

this is give you a top and bottom margin of 10px between each div.  You can use whatever px amount you want instead on 10.


text:
Q: Finding an equation for the line on a plane that makes a specific angle Find equations for the line in the plane z = 3 that makes an angle of $\pi/6$rad with $\hat{i}$ and an angle of $\pi/3$rad with $\hat{j}$. Describe the reasoning behind your answer.
The solution says that since the line makes an angle of $\pi/6$ with $\hat{i}$ and $\pi/3$ with $\hat{j}$, we can use this angle to get a vector parallel to that line as follows
$\hat{v}=\cos(\pi/6)\hat{i}+\cos(\pi/3)\hat{j}+\sqrt{1-\cos^2(\pi/6)-\cos^2(\pi/3)}\,\hat{k}$
I don't understand where this equation comes from. Firstly, I don't understand where that entire square root component for $\vec{k}$ comes from. I also don't understand why they are doing $\cos(\pi/3)\hat{j}$ and not $\sin(\pi/3)\hat{j}$ since the $\hat{j}$ vector is associated with the 'y axis'

A: Generally, let's get the unit vector $\hat{v}$ that makes an angle of $\theta_1$ with $\hat{i}$ and $\theta_2$ with $\hat{j}$.
The size of $\hat{v}$ must be $1$ by definition. Place $\hat{v}$'s tail at the origin, and let's draw the height of $\hat{v}$'s head from the $x$-axis.
The angle is given to be $\theta_1$, so if we project $\hat{v}$ to the $x$-axis, the length should be $\cos\theta_1$. This means the $\hat{i}$-component of $\hat{v}$ is $\cos\theta_1$.
Apply the same logic to the $y$-axis. Project $\hat{v}$ to the $y$-axis, and you'll see why there is no $\sin$ involved.
The size is $1$, so the sum of the squares of the components should be $1$; this is why the $\hat{k}$-component looks like that.
$$\hat{v}=\cos\theta_1\hat{i}+\cos\theta_2\hat{j}+\sqrt{1-\cos^2\theta_1-\cos^2\theta_2}\hat{k}$$

A: Suppose our desired vector is $v=(a,b,c)$. We can assume $v$ is a unit vector, so that $a^2+b^2+c^2=1$. Then
angle between $v$ and x-axis = $\pi/6 \Longrightarrow v \cdot i = \cos(\pi/6)
\Longrightarrow a = \cos(\pi/6)$
angle between $v$ and y-axis = $\pi/3 \Longrightarrow v \cdot j = \cos(\pi/3)
\Longrightarrow b = \cos(\pi/3)$
Then $c = 1 - \sqrt{a^2+b^2}$ since $a^2+b^2+c^2=1$.

A: If a lines makes angles $\alpha, \beta, \gamma$ with $x, y, z$ axes respectively, then its direction cosines are,
$l = \cos\alpha, m =\cos\beta, n=\cos\gamma$,
and $l^2+m^2 +n^2=1$.
Unit vector parallel to the line is,
$\begin{align}\hat v &= l\hat i + m\hat j + n\hat k \\&= l\hat i + m\hat j + \sqrt{1-l^2-m^2}\hat k\\& = \cos\left(\frac\pi6\right)\hat i +\cos\left(\frac\pi3\right)\hat j + \sqrt{1-\cos^2\left(\frac\pi6\right) - \cos^2\left(\frac{\pi}{3}\right)}\hat k\end{align} $


text:
Q: How to select same column twice with different format in Postgres Sql? I want actual column value along with truncated column value like below. can any one can help.
Select "sub1"."TimestampField","month_trunc1","month_trunc2"
from (
   Select  "Id", date_trunc('month', "TimestampField") as "month_trunc1", "TimestampField"
   from "Table"
) as "sub1", (
  Select  "Id", date_trunc('month', "TimestampField") as "month_trunc2", "TimestampField"
  from "Table"
) as "sub2"
WHERE "month_trunc2" = ("month_trunc1"+interval '1 month');

A: You can simplify you example by using JOIN on the same table:
 SELSECT
   "sub1"."mainfield",
   "sub1"."TimestampField" as month1,
   "sub2"."TimestampField" as month2,
   date_trunc('month', "sub1"."TimestampField") as "month_trunc1",
   date_trunc('month', "sub2"."TimestampField") as "month_trunc2"
 FROM "Table" "sub1"
 JOIN "Table" "sub2"
       ON "month_trunc2" = ("month_trunc1"+interval '1 month');


text:
Q: getting input value before submit I want to subtract an input field value from a database value
how to manage that??
what changes do i need in the MVC ??
my code in myform.ctp as follows:
echo $this->Form->input('discount', array('label' => 'Discount'));

$val1 = //---------here the input value ---------//
$val2 = $this->data['Product']['price'];  //value from database
$val3 = $val2 - $val1;

echo $val3;

after editing :
<?php
    echo $this->Form->input('discount', array('id'=>'n','label' => 'Discount %','placeholder'=>'Value in %'));

echo $this->Form->hidden('price', array('id'=>'p'));

echo $this->Form->input('finalprice', array('id'=>'c'));

        ?>
            <script>

            var a=document.getElementById('n').value;
             document.write(a);

            var b=document.getElementById('p').value;
             document.write(b);

            var c=b-a;
            document.getElementById('c').value=c;
             document.write(c);

    </script>

now im getting the inputs values, made the operation , but i need to insert the final value into database field... data['Product']['finalprice'] .........how to do that?

A: First set the value at controller
 $this->set('val1',$this->data['Product']['price']);

Then In view
<input type="hidden" value="<?php echo $val1; ?>" id="val1">
 <?php  echo $this->Form->input('discount', array('label' => 'Discount','id'=>'val2')); ?>

<script>
  $(document).ready(function(){
     var finalval=parseInt($('#val1').val())-parseInt($('#val2').val());
     alert(finalval);
  });
</script>

A: Following code wrie in your Product Model which is inbuilt functionality of cakephp
public function beforeSave($options = array()) {
    if (!empty($this->data['Product']['discount']) &&
        !empty($this->data['Product']['price'])
    ) {

     $this->data['Product']['finalprice'] =
            $this->data['Product']['price'] - $this->data['Product']['discount'];
    }
    return true;
}

Check Manual for beforeSave function in cakephp.


text:
Q: Setting up stmp mail using nodejs(nodemailer) I am trying to send an email using a simple nodejs app. But i am getting an erro
The error is:

Error: Invalid login: 534-5.7.14  Please log in via your web browser and
  534-5.7.14 then try again.
  534-5.7.14  Learn more at
  534 5.7.14  https://support.google.com/mail/answer/78754 22-v6sm29249729pfl.126 - gsmtp
      at SMTPConnection._formatError (C:\Users\USER\Desktop\codeworkr\node_modules\nodemailer\lib\smtp-connection\index.js:606:19)
      at SMTPConnection._actionAUTHComplete (C:\Users\USER\Desktop\codeworkr\node_modules\nodemailer\lib\smtp-connection\index.js:1335:34)
      at SMTPConnection._responseActions.push.str (C:\Users\USER\Desktop\codeworkr\node_modules\nodemailer\lib\smtp-connection\index.js:366:26)
      at SMTPConnection._processResponse (C:\Users\USER\Desktop\codeworkr\node_modules\nodemailer\lib\smtp-connection\index.js:762:20)
      at SMTPConnection._onData (C:\Users\USER\Desktop\codeworkr\node_modules\nodemailer\lib\smtp-connection\index.js:558:14)
      at TLSSocket._socket.on.chunk (C:\Users\USER\Desktop\codeworkr\node_modules\nodemailer\lib\smtp-connection\index.js:510:47)
      at emitOne (events.js:116:13)
      at TLSSocket.emit (events.js:211:7)
      at addChunk (_stream_readable.js:263:12)
      at readableAddChunk (_stream_readable.js:250:11)
      at TLSSocket.Readable.push (_stream_readable.js:208:10)
      at TLSWrap.onread (net.js:597:20)

And my code is this:
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  secure: false,
 // port: 25,
  auth: {
    user: 'surendrap7208@gmail.com',
    pass: ''
  }
 /* tls: {
    rejectUnauthorized: false
  }*/
});

var mailOptions = {
  from: 'surendrap7208@gmail.com',
  to: 'surendrap720@gmail.com',
  subject: 'Sending Email using Node.js',
  text: 'Hello'
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);=
  }

    });

I've removed the password for security purposes.

A: Double check your credentials and also you need to allow less secure apps in gmail.
1) Go to https://myaccount.google.com/lesssecureapps
2) Enable Less Secure Apps option

A: I have another solution for the same. If you want to remove password for security purpose, Then you can use my soltion too.
At first you need some sender account credential, you can create that from here:
https://console.developers.google.com/projectselector/apis/credentials?supportedpurview=project
Node.js, Nodemailer, SMTP issue
Here is my testing code [file:server.js]
//start server
var http = require('http');
// Create a Transport instance using nodemailer
var nodemailer = require('nodemailer');

var smtpTransport = nodemailer.createTransport({
    host: "smtp.gmail.com",
    auth: {
        type: "OAuth2",
        user: "sender_email_id",
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
        refreshToken: "YOUR_REFRESH_TOKEN"
      }
});

var htmlBody = '
Hello Body
';
// Setup mail configuration
var mailOptions = {
    from: 'serder_email_id', // sender address
    to: 'recipent_email_id', // list of receivers
    subject: 'TEST SUBJECT', // Subject line
    text: 'Hello Body', // plaintext body
    html: htmlBody // html body
  };

var app = http.createServer(function (req, res) {
    // send mail
    smtpTransport.sendMail(mailOptions, function(error, info) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        if (error) {
            console.log('error', error)
            res.write('Error');
            res.end();
        }
        console.log('Message %s sent: %s', info.messageId, info.response);
        smtpTransport.close();
        res.write('Email sent');
        res.end();
    });
}).listen(3000);


text:
Q: How do you deal with database IDs that get astronomically high This question doesn't relate to a problem that I've had (yet), but it keeps me up at night.  Theoretically, eventually, as the number of rows in a table goes up and up and up, the ID corresponding to each row will "run out" of numbers, won't it?  I guess that if you keep adding depth to the column value, you could keep it going up, but eventually there must be an upper limit, right?
I've heard of a technique called "sharding" but haven't had it explained in enough detail to satisfy my curiosity.  Is the answer that you just keep adding more numbers, or is there a clever pattern to allow "repeat" IDs in their own sandbox.  What if these sandboxes have to interact?

A: Sharding has nothing to do with the size of the IDs.
The correct way to handle it is: Don't worry about it.
A 32 bit int has enough values that you could add one row per second for over 100 years without running out.
And if that wasn't enough, with a 64 bit int you could add 1 billion rows per second and still last for over 500 years.
So basically: Don't worry about it. Pick the size of the int based on how many rows you expect times 100 and then move on.
Re sharding:
That's simply a way of splitting up a database onto multiple servers by using a rule to decide which server should get the data. The rules vary depending on what you are storing and how many servers you have.

A: From dev.mysql.com

Use a large enough integer data type for the AUTO_INCREMENT column to hold the maximum sequence value you will need. When the column reaches the upper limit of the data type, the next attempt to generate a sequence number fails. For example, if you use TINYINT, the maximum permissible sequence number is 127. For TINYINT UNSIGNED, the maximum is 255.

That's actually fascinating. I guess an easy (semi) answer is to use BIGINT - with a maximum value of 18,446,744,073,709,551,615. If you get that many columns - then... wow...


text:
Q: How do a add scroll bar with fixed header How do I modify this CSS to apply a scroll bar with fixed header?
#gradient-style {
    font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
    overflow: auto;
}

#gradient-style th {
    font-size: 12px;
}

#gradient-style td {
    height: 20px;
}

My table is like this:
<table  id="gradient-style" align="center">

A: I am assuming that you are talking about fixed table header with scrollable table content(table body).
Please check this example : http://jsfiddle.net/randeep161/n8zNq/


text:
Q: Spring MVC Hibernate No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call I want to make a POST request to save a user into my Oracle DB.
I'm using Spring MVC with jpa and hibernate.
Here is my jpaContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.licenta.ascourses" />

     <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="punit" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
            </bean>
        </property>
        <property name="jpaPropertyMap">
            <map>
                <entry key="hibernate.dialect"      value="org.hibernate.dialect.Oracle8iDialect" />
                <entry key="hibernate.hbm2ddl.auto" value="create-drop" />
                <entry key="hibernate.format_sql"   value="true" />
            </map>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url"             value="jdbc:oracle:thin:@localhost:oracle" />
        <property name="username"        value="user" />
        <property name="password"        value="pass" />
    </bean>

</beans>

Here is my UserRepoImpl class:
package com.licenta.ascourses.repositories.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.licenta.ascourses.model.User;
import com.licenta.ascourses.repositories.UserRepo;

@Repository("userRepository")
public class JpaUserRepo implements UserRepo {

    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;

    public User getUserById(Long id) {
        return em.find (User.class, id);
    }

    public List<User> getAllUsers() {
        return null;
    }

    public User createUser(User user) {
        em.persist(user);
        em.flush();

        return user;
    }
}

And this is the UserServiceImpl class:
package com.licenta.ascourses.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.licenta.ascourses.model.User;
import com.licenta.ascourses.repositories.UserRepo;
import com.licenta.ascourses.repositories.jpa.JpaUserRepo;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepo userRepo;

    public User getUserById(Long id) {
        return userRepo.getUserById(id);
    }

    public List<User> getAllUsers() {
        return userRepo.getAllUsers();
    }

    @Transactional
    public User createUser(User user) {
        return userRepo.createUser (user);
    }
}

This is the method from the REST Controller:
@Autowired
private UserService userService;

@RequestMapping(method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
public User saveUser (@RequestBody User user) {
    return userService.createUser(user);
}

I have the @Transactional annotation on my service layer. I've tried many solutions found online, using @Transactional on repository layer, or use @Scope(proxyMode = ScopedProxyMode.INTERFACES) to repository or service classes. Nothing worked for me.
I'm a newbie to Spring and Hibernate so all answers or suggestions are well welcomed
This is the exception I get when try to make a POST:
PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [ascoursesServlet] in context with path [/ASCourses] threw exception [Request processing failed; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress] with root cause
javax.persistence.TransactionRequiredException: no transaction is in progress
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.checkTransactionNeeded(AbstractEntityManagerImpl.java:1136)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1297)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
    at com.sun.proxy.$Proxy24.flush(Unknown Source)
    at com.licenta.ascourses.repositories.jpa.JpaUserRepo.createUser(JpaUserRepo.java:32)
    at com.licenta.ascourses.service.UserServiceImpl.createUser(UserServiceImpl.java:33)
    at com.licenta.ascourses.controller.TestController.saveUser(TestController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1153)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:785)

A: I finally found the right solution for me:
I've moved <tx:annotation-driven transaction-manager="transactionManager" />
to my servlet-config.xml file.
Answer here:
@Transactional doesn't work in Spring Web MVC?


text:
Q: Refresh Gtk.StatusIcon in python I'm trying to write a script that checks certain things and display a notification in the tray if something's wrong.  In this example, I'm looking at the age of a file.
What I can't seem to work out how to do is change the icon once gtk.main() is running.
import os, gtk
from time import time, sleep
from datetime import datetime

class HeartbeatTrayIcon(object):
    """
    Use GTK to create an object in the system tray
    and manipulate icon shown if there is an issue.
    """
    def __init__(self):
        rx = os.path.getmtime("test")
        self.statusIcon = gtk.StatusIcon()
        if (time() - rx) > (60*60*24):
            self.statusIcon.set_from_stock(gtk.STOCK_CANCEL)
        else:
            self.statusIcon.set_from_stock(gtk.STOCK_APPLY)
        self.statusIcon.set_tooltip("Last heartbeat received at %s" % datetime.fromtimestamp(int(rx)).strftime('%H:%M:%S %d-%m-%Y'))

    def tray(self):
        gtk.main()

if __name__ == "__main__":
    i = HeartbeatTrayIcon()
    i.tray()

A: You are only checking the file's age in the constructor for HeartbeatTrayIcon, so that code only runs once.
I'd suggest using gobject.idle_add() to register a callback function that performs the check. That function will be called when the application is idle (i.e. when no higher-priority events exist in the queue):
import os, gtk, gobject
from time import time, sleep
from datetime import datetime

class HeartbeatTrayIcon(object):
    """
    Use GTK to create an object in the system tray
    and manipulate icon shown if there is an issue.
    """
    def __init__(self):
        self.statusIcon = gtk.StatusIcon()

    def check(self):
        rx = os.path.getmtime("test")
        if (time() - rx) > (60*60*24):
            self.statusIcon.set_from_stock(gtk.STOCK_CANCEL)
        else:
            self.statusIcon.set_from_stock(gtk.STOCK_APPLY)
        self.statusIcon.set_tooltip("Last heartbeat received at %s" \
            % datetime.fromtimestamp(int(rx)).strftime('%H:%M:%S %d-%m-%Y'))
        return True

    def tray(self):
        gobject.idle_add(self.check)
        gtk.main()

if __name__ == "__main__":
    i = HeartbeatTrayIcon()
    i.tray()

In passing, note that your heartbeat message does not seem to do what you're looking for: it will always print the modification time of the file, not the time of the last check. You might want to store the value returned by time()in a variable and use that instead of rx.


text:
Q: GWT Incubator PagingScrollTable compile error I'm trying to implement this example: http://zenoconsulting.wikidot.com/blog:17 in my gwt app but when i try to compile the project i have this error :
 Compiling module com.myapp.security.GwtSpringSecurityProject
   Validating newly compiled units
      Ignored 2 units with compilation errors in first pass.
Compile with -strict or with -logLevel set to TRACE or DEBUG to see all errors.
   Scanning for additional dependencies: jar:file:/C:/_work/Eclipse/MyApp/war/WEB-INF/lib/gwt-incubator-20101117-r1766.jar!/com/google/gwt/gen2/table/client/AbstractScrollTable.java
      Computing all possible rebind results for 'com.google.gwt.gen2.table.client.AbstractScrollTable.Impl'
         Rebinding com.google.gwt.gen2.table.client.AbstractScrollTable.Impl
            Could not find an exact match rule. Using 'closest' rule <replace-with class='com.google.gwt.gen2.table.client.AbstractScrollTable.ImplIE6'/> based on fall back values. You may need to implement a specific binding in case the fall back behavior does not replace the missing binding
   Scanning for additional dependencies: jar:file:/C:/_work/Eclipse/MyApp/war/WEB-INF/lib/gwt-incubator-20101117-r1766.jar!/com/google/gwt/gen2/table/client/FixedWidthTableImpl.java
      Computing all possible rebind results for 'com.google.gwt.gen2.table.client.FixedWidthTableImpl.Impl'
         Rebinding com.google.gwt.gen2.table.client.FixedWidthTableImpl.Impl
            Could not find an exact match rule. Using 'closest' rule <replace-with class='com.google.gwt.gen2.table.client.FixedWidthTableImpl.ImplIE8'/> based on fall back values. You may need to implement a specific binding in case the fall back behavior does not replace the missing binding
   [ERROR] An internal compiler exception occurred
com.google.gwt.dev.jjs.InternalCompilerException: Failed to get JNode
    at com.google.gwt.dev.jjs.impl.TypeMap.get(TypeMap.java:140)
    at com.google.gwt.dev.jjs.impl.TypeMap.internalGet(TypeMap.java:242)
    at com.google.gwt.dev.jjs.impl.TypeMap.get(TypeMap.java:138)
    at com.google.gwt.dev.jjs.impl.TypeMap.get(TypeMap.java:71)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.processExpression(GenerateJavaAST.java:1144)
    at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.dispatch(GenerateJavaAST.java:577)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.dispProcessExpression(GenerateJavaAST.java:603)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.processStatement(GenerateJavaAST.java:1771)
    at sun.reflect.GeneratedMethodAccessor38.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.dispatch(GenerateJavaAST.java:577)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.dispProcessStatement(GenerateJavaAST.java:638)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.processStatements(GenerateJavaAST.java:1846)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.processMethod(GenerateJavaAST.java:1513)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST$JavaASTGenerationVisitor.processType(GenerateJavaAST.java:501)
    at com.google.gwt.dev.jjs.impl.GenerateJavaAST.exec(GenerateJavaAST.java:2958)
    at com.google.gwt.dev.jjs.JavaToJavaScriptCompiler.precompile(JavaToJavaScriptCompiler.java:608)
    at com.google.gwt.dev.jjs.JavaScriptCompiler.precompile(JavaScriptCompiler.java:33)
    at com.google.gwt.dev.Precompile.precompile(Precompile.java:284)
    at com.google.gwt.dev.Precompile.precompile(Precompile.java:233)
    at com.google.gwt.dev.Precompile.precompile(Precompile.java:145)
    at com.google.gwt.dev.Compiler.run(Compiler.java:232)
    at com.google.gwt.dev.Compiler.run(Compiler.java:198)
    at com.google.gwt.dev.Compiler$1.run(Compiler.java:170)
    at com.google.gwt.dev.CompileTaskRunner.doRun(CompileTaskRunner.java:88)
    at com.google.gwt.dev.CompileTaskRunner.runWithAppropriateLogger(CompileTaskRunner.java:82)
    at com.google.gwt.dev.Compiler.main(Compiler.java:177)
      [ERROR] <no source info>: public abstract class java.text.DateFormat
    extends java.text.Format
/*   fields   */
protected [unresolved] Unresolved type java.util.Calendar calendar
protected [unresolved] Unresolved type java.text.NumberFormat numberFormat
public static final [unresolved] int ERA_FIELD
public static final [unresolved] int YEAR_FIELD
public static final [unresolved] int MONTH_FIELD
public static final [unresolved] int DATE_FIELD
public static final [unresolved] int HOUR_OF_DAY1_FIELD
public static final [unresolved] int HOUR_OF_DAY0_FIELD
public static final [unresolved] int MINUTE_FIELD
public static final [unresolved] int SECOND_FIELD
public static final [unresolved] int MILLISECOND_FIELD
public static final [unresolved] int DAY_OF_WEEK_FIELD
public static final [unresolved] int DAY_OF_YEAR_FIELD
public static final [unresolved] int DAY_OF_WEEK_IN_MONTH_FIELD
public static final [unresolved] int WEEK_OF_YEAR_FIELD
public static final [unresolved] int WEEK_OF_MONTH_FIELD
public static final [unresolved] int AM_PM_FIELD
public static final [unresolved] int HOUR1_FIELD
public static final [unresolved] int HOUR0_FIELD
public static final [unresolved] int TIMEZONE_FIELD
private static final [unresolved] long serialVersionUID
public static final [unresolved] int FULL
public static final [unresolved] int LONG
public static final [unresolved] int MEDIUM
public static final [unresolved] int SHORT
public static final [unresolved] int DEFAULT
/*   methods   */
[unresolved] protected void <init>()
[unresolved] public java.lang.Object clone()
[unresolved] public boolean equals(java.lang.Object)
public final java.lang.String format(java.util.Date)
public final java.lang.StringBuffer format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
public abstract java.lang.StringBuffer format(java.util.Date, java.lang.StringBuffer, java.text.FieldPosition)
[unresolved] private static java.text.DateFormat get(int, int, int, Unresolved type java.util.Locale)
[unresolved] public static Unresolved type java.util.Locale[] getAvailableLocales()
[unresolved] public Unresolved type java.util.Calendar getCalendar()
[unresolved] public static final java.text.DateFormat getDateInstance()
[unresolved] public static final java.text.DateFormat getDateInstance(int)
[unresolved] public static final java.text.DateFormat getDateInstance(int, Unresolved type java.util.Locale)
[unresolved] public static final java.text.DateFormat getDateTimeInstance()
[unresolved] public static final java.text.DateFormat getDateTimeInstance(int, int)
[unresolved] public static final java.text.DateFormat getDateTimeInstance(int, int, Unresolved type java.util.Locale)
[unresolved] public static final java.text.DateFormat getInstance()
[unresolved] public Unresolved type java.text.NumberFormat getNumberFormat()
[unresolved] public static final java.text.DateFormat getTimeInstance()
[unresolved] public static final java.text.DateFormat getTimeInstance(int)
[unresolved] public static final java.text.DateFormat getTimeInstance(int, Unresolved type java.util.Locale)
[unresolved] public Unresolved type java.util.TimeZone getTimeZone()
[unresolved] public int hashCode()
[unresolved] public boolean isLenient()
[unresolved] public java.util.Date parse(java.lang.String) throws java.text.ParseException
[unresolved] public abstract java.util.Date parse(java.lang.String, Unresolved type java.text.ParsePosition)
[unresolved] public java.lang.Object parseObject(java.lang.String, Unresolved type java.text.ParsePosition)
[unresolved] public void setCalendar(Unresolved type java.util.Calendar)
[unresolved] public void setLenient(boolean)
[unresolved] public void setNumberFormat(Unresolved type java.text.NumberFormat)
[unresolved] public void setTimeZone(Unresolved type java.util.TimeZone)
/*   members   */
Unresolved type java.text.DateFormat$DateFormatGetter
Unresolved type java.text.DateFormat$Field

         org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding
      [ERROR] at PsTable.java(351): new SimpleDateFormat("MM/dd/yyyy").format(rowValue.getDate())
         org.eclipse.jdt.internal.compiler.ast.MessageSend
      [ERROR] at PsTable.java(351): return new SimpleDateFormat("MM/dd/yyyy").format(rowValue.getDate());
         org.eclipse.jdt.internal.compiler.ast.ReturnStatement
      [ERROR] at PsTable.java(350): public String getCellValue(Message rowValue);

         com.google.gwt.dev.jjs.ast.JMethod
      [ERROR] at PsTable.java(348): final class PsTable$DateColumnDefinition extends AbstractColumnDefinition
         com.google.gwt.dev.jjs.ast.JClassType

i have simple added the class of this example in my app and i create a new PsTable in my gwt client class.

A: GWT Incubator's latest release is only compatible with GWT 2.1, and you're apparently using GWT 2.3 or later (the Could not find an exact match rule. Using 'closest' rule… was added in 2.3 to support IE9). Add to that that GWT 2.2 breaks binary compatibility of generators (they have to be recompiled against GWT 2.2 or later) and you have a good reason for a failure.
From the GWT Incubator homepage, you should be able to replace PaagingScrollTable uses with GWT 2.4's DataGrid. It's admittedly a much different approach (cells vs. widgets) but it's the way to go nowadays: GWT Incubator is deprecated (for good reasons) and you really shouldn't use it, move away from it if your project used it, and absolutely do not start using it in new projects.

BTW, the article you link to is 3 years old. You can't expect anything good from such ancient code snippets.


text:
Q: Use OnClick or hide/show with radio buttons - more than one set within form I asked this question previously but it was closed as it was deemed too similar to another, however I have looked at the other one as well as many related questions and none really do what I am asking.
I would like a particular div to show or hide depending on yes/no radio buttons. This is within a div that shows up if a particular dropdown selection is chosen.
I really like the onclick and function method that was used for the dropdown box rather than show/hide as it gives the function a particular name and it is easier for me to track. However I am unsure whether this is possible for radio buttons.
I DO already have a similar yes/no choice which successfully does what I want. I used getResults() for the first radio button set, but I am unsure how to differentiate the code for one and call up a particular div, as the solution I got for that one used the id of the radio button but did not ID the div that would show so it would not be differentiated.
I want the text box in the latter div to only show if yes is chosen but I also need it to then disappear if the person changes their mind and chooses no again.
I almost had it but when clicking 'no' the initial question would disappear.
I think all the hide show scripts are somehow interacting too. I will put the script and codes for each below:
Can someone please let me know the code that they would use for my particular values as I really don't know what I am missing.
Basically I need to know if the first set of radio buttons can be distinguished in the script if I use a similar script for the second set of radio buttons.
Also, if it is possible to use a similar function for the dropdowm box but with radio buttons instead.
1) RADIO BUTTONS ONE: These work as intended but are not identified e.g. get results by ID
Javascript:
    ">

HTML:
Are you the legal owner?

<input type="radio" name="ifowner" id="yesowner" value="yesowner" form="landform" checked>Yes

<input type="radio" name="ifowner" id="noowner" value="noowner" form="landform" onClick="getResultsbyID("divowner")">No

Name of Legal Owner
<input style="height:20px;font-size:12pt; name="actualowner" type="text" id="actualowner" form="landform" size="50">

2) DROPDOWN BOX OPTIONS: This is the code for the dropbox which then results in differnt DIVs appearing depending upon the choice made.
Javascript:
    ">

HTML:
    How is the land accessed?
<select style="height:24px;font-size:12pt;" name="access"
  id="access"
  onChange="landaccessfunction()"
  class="form-control"
  form="landform">
  <option value="selectaccess" checked>Select One</option>
  <option value="road">Direct road access</option>
  <option value="easement">A legally deeded easement</option>
  <option value="noaccess">No legal access</option>
</select>

      Who owns and maintains the road?

      <textarea name="roadowner" cols="50" rows="2" id="roadowner" form="landform"></textarea>

Access road surface type(s) while approaching land:

      <input type="checkbox" id="ashphalt" name="roadtype" value="ashphalt" form="landform">
      ashphalt

      <input type="checkbox" id="gravel" name="roadtype" value="gravel" form="landform">
      gravel

      <input type="checkbox" id="dirt" name="roadtype" value="dirt" form="landform">
      dirt

      <input type="checkbox" id="othersurface" name="roadtype" value="othersurface" form="landform">
      other
<input style="height:20px;font-size:12pt; name="othersurfacedetails" type="text" id="othersurfacedetails" form="landform" size="40" maxlength="40">

  Easement details (e.g. approximate length, dirt/gravel, through private property, etc.):

      <textarea name="easedescr" cols="50" rows="2" id="easedescr" form="landform"></textarea>

3) RADIO BUTTONS TWO - if "No legal access" is chosen in the above dropdown box then the third hidden div will show which has the id="noaccessdetails". Within this I wish to have a second question which will then result in a text box if "yes" is chosen. I would also very much like it if NO is the default radio button:
HTML:

  Is there a way to access the property temporarily (e.g. special permission to cross private land)?

<input type="radio" name="tempaccess" id="tayes" value="tayes" form="landform>Yes

<input type="radio" name="tempaccess" id="tano" value="tano" form="landform" onClick="getResultsbyID("tempaccessdetails")" checked>No

<textarea name="tempaccessdetails" cols="50" rows="2" id="tempaccessdetails" form="landform"></textarea>

Javascript that I tried:
    ">

I feel that there should be some ID within the script to ensure only the div with id="tempaccessdetails" will be affected and that when I click no the div above won't also be hidden.


text:
Q: IE9 Errors when using videoJS-vimeo plugin Hi I am using the VideoJS-Vimeo plugin which appears to work well on all browsers except IE9 (which is spoiling the party as usual) FF, Chrome, Edge, IE11, and 10 all work fine.
I receive the following 3 errors in the IE9 console:

script5009 'Math' is undefined
  206182609?api=1&player id=vjs video 1262 Vimeo api, line 1, character 13281
script5009 'encodeURIComponent' is undefined
  206182609?api=1&player id=vjs video 969 Vimeo api, line 1, character 10215
script5009 'Object' is undefined
  206182609?api=1&player id=vjs video 1262 Vimeo api, line 1, character 13281

These errors don't seem to appear in other browsers
My code and refs are below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="bower_components/video.js/dist/video-js.min.css" rel="stylesheet" />
<script src="bower_components/video.js/dist/video.min.js"></script>
<script src="bower_components/videojs-vimeo/src/Vimeo.js"></script>
<video
    id="xvid1"
    class="video-js vjs-big-play-centered clickableVideo"
    controls
    preload="none"
    crossOrigin="anonymous"
    data-setup='{ "techOrder": ["vimeo"], "sources": [{ "type": "video/vimeo", "src": "https://vimeo.com/35982411"}], "vimeo": { "iv_load_policy": 1 } }'>
 </video>

Anyone got any ideas?


text:
Q: How to connect to SQL Server through SSMS and don't understand naming convention? Just wondering what types of naming conventions do I need to know when connecting to an instance of SQL Server via SSMS and within C# code, together with the meaning of naming conventions?
For example, why can you connect to a SQL Server database using the following as server name:  MYTESTDB001,444?
Is there another naming convention to use as we all know the likes of localhost:1433, azure.mysetup.net:444, can these be written and connected in a different way such as MYTESTDB001:444? Tried but doesn't seem to work


text:
Q: Detecting File Download Completion Status I would just like to ask if it's possible for me to check the status of a file (csv file) download in Django .
I have a template page with a button, which when clicked, opens a 'Save As' dialog box for downloading a file from the server (file content is retrieved from db).  after the download is complete i want to update my DB with its status (if download complete status = Downloaded ,if abort status = aborted , if Cancel Status= Canceled  . How can i do this ?

A: I don't know if this is exactly what you want, but you could check filesize at two timepoints and then compare the filesize. For sure if the download is pausing for some reason, this solution is not very good.


text: Q: 'Error adding system: Data not available.' fix? In Unity I've set up a system where upon walking into an object the scene changes, although when that happens 2 errors pop up: 'GI output for inputsystem: XXXX is missing' and 'Error adding system: Data not available.' The scene is also pitch black when loaded. Any solutions?


text:
Q: Positionning labels on a grouped bar chart with ggplot I am having issues positionning my labels for my grouped bar chart.
Below a reproducible example, and on the image you can see where I would like the labels to be placed.
Not all on the same line, but each label aligned with each of the 3 bar chart, and ideally each label placed right above each corresponding bar chart.
Any idea how to achieve this? I want to keep a grouped bar chart and not a stacked bar chart.
data_F <- "https://raw.githubusercontent.com/max9nc9/Temp/main/temp.csv"
data_F <- read.csv(data_F, sep = ";")
colnames(data_F) <- c("Month_Year", "Type", "Amount")
data_F$Amount <- as.numeric(data_F$Amount)

Final_Graph <-
  ggplot(data_F, aes(x = Month_Year, y = Amount, label = Amount, fill = Type)) +
  geom_bar(position="dodge", stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5), color = "black") +
  theme(axis.text.x = element_text(angle = 90)) +
  scale_fill_manual(values = c("#e62200", "#00c41d", "#f7b21e")) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.subtitle = element_text(hjust = 0.5))

Final_Graph

A: As you use position_dodge for the bars use it for the labels as well, where I use width = .9, which is the default for bars:
data_F <- "https://raw.githubusercontent.com/max9nc9/Temp/main/temp.csv"
data_F <- read.csv(data_F, sep = ";")
colnames(data_F) <- c("Month_Year", "Type", "Amount")
data_F$Amount <- as.numeric(data_F$Amount)

library(ggplot2)

ggplot(data_F, aes(x = Month_Year, y = Amount, label = Amount, fill = Type)) +
  geom_bar(position="dodge", stat = "identity") +
  geom_text(size = 3, position = position_dodge(width = .9), vjust = 0, color = "black") +
  theme(axis.text.x = element_text(angle = 90)) +
  scale_fill_manual(values = c("#e62200", "#00c41d", "#f7b21e")) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(plot.subtitle = element_text(hjust = 0.5))


text:
Q: passing a function as an argument in python Suppose I want to calculate the following f(f(...f(x)..) .
Basically many times function of itself.
Currently I am doing the following to achieve this result (and to return all the intermediate steps):
def iterator(function, x, n=4):
    x = float(x)
    arr = []
    for i in range(n + 1):
        arr.append(x)
        x = function(x)

    return arr

def funcM(x):
    return x / 4 + 12

and then I am passing my function funcM as an argument:
print iterator(funcM, 100, 5).
There is nothing wrong with this approach, and calculations are correct.
But is there a way to do the same without defining function funcM ?
May be passing lambda function as an argument to iterator function (Sorry if it does not make sense, I do not really know what lambda functions are).

A: A lambda function (or more accurately, a lambda expression) is simply a function you can define on-the-spot, right where you need it. For example,
f = lambda x: x * 2

is exactly the same thing as
def f(x):
    return x * 2

And when I say exactly, I mean it -- they disassemble to the same bytecode. The only difference between the two is that the one defined in the second example has a name.
Lambda expressions become useful because creating one is not a statement, which means that, as others have already answered, you can do
print iterator(lambda x: x / 4 + 12, 100, 5)

to get precisely what you want.
The main difference between lambda expressions and regular functions, however, is that lambdas are more limited. Lambdas can only contain expressions, not statements. An expression is anything you can put on the right side of an = assignment. (if you want to get more pedantic, Python defines an expression as http://docs.python.org/2/reference/expressions.html )
What this means is a lambda expression can not assign to a variable (in fact, it can't have local variables at all, other than its parameters). It can't print (unless it calls another function that does). It can't have a for loop, a while loop, an if test (other than the ternary operator x if cond else y), or a try/except block.
If you need to do any of those, just define a regular function. In fact, any time you think you want to use a lambda, think twice. Wouldn't the code be more readable if you used a regular function? Isn't that lambda expression something you'd like to reuse somewhere else in your code?
In the end, always do what leads to the most readable and maintainable code. There is no difference between lambdas and normal functions as far as performance is concerned.

A: Yes, you can just use lambda expressions. They are made for this.
iterator(lambda x: x/4+12, 100, 5)

Words from the docs:

Lambdas are usually used to create small, anonymous functions.
  Actually, they are just a syntatic sugar to define functions. The
  lambda expression above is exactly the same as your function, only
  without a name.

If you wish to learn more, Here is some good read:
http://www.diveintopython.net/power_of_introspection/lambda_functions.html
Why use lambda functions?


text:
Q: Finding the most common strings from arrays of strings How would I loop over a csv that has 1000 arrays of strings and find the 2 most common strings in all of the arrays?

A: def most_common_value(a)
  a.group_by(&:itself).values.max_by(&:size).first(2)
end

should work for finding them in each array. The fact that it's multiple arrays coming from a csv file doesn't really matter.


text:
Q: How can I go directly to a nested state with the back button to its parent state in Ionic Framework I'm using Ionic Framework 1.0.0-beta.14. In my case, I want to go to a nested state directly, and have the back button to its parent on the header. This sample http://codepen.io/TimothyKrell/pen/bnukj is exactly what I want to achieve. I've tested it in the latest version (1.0.0-beta.14), but it doesn't work. Here is a part of its code:
angular.module('stateBackButtonIonic', [])
    .config(function($provide) {
        $provide.decorator('$ionicViewService', function($delegate, $rootScope) {
            var registerFunction = $delegate.register;

            $delegate.register = function() {
                var viewHistory = $rootScope.$viewHistory,
                    rsp = registerFunction.apply(this, arguments);

                if (viewHistory.forcedBack) {
                    rsp.navAction = 'moveBack';
                    rsp.navDirection = 'back';
                    viewHistory.forcedBack = null;

                    this.clearHistory();
                }

                return rsp;
            };
            return $delegate;
        });
    })
    .directive('prNavBackButton', function($animate, $rootScope, $sanitize, $state, $ionicNavBarConfig, $ionicNgClick) {
        var backIsShown = false,
            viewHistory = $rootScope.$viewHistory;

        function backViewIsPresent() {
            return viewHistory.backView && viewHistory.backView.historyId === viewHistory.currentView.historyId;
        }

        function parentStateIsPresent() {
            return !$state.$current.parent.abstract;
        }

        // Everytime history changes, check if the back button should be shown
        // We ignore ionic's data saying whether it should be or not, favoring our own logic
        $rootScope.$on('$viewHistory.historyChange', function() {
            backIsShown = backViewIsPresent() || parentStateIsPresent();
        });

        return {
            restrict: 'E',
            require: '^ionNavBar',
            compile: function(tElement) {
                tElement.addClass('button back-button ng-hide');

                var hasIconChild = !!(tElement.html() || '').match(/class=.*?ion-/);

                return function($scope, $element, $attr, navBarCtrl) {

                    // Add a default back button icon based on the nav config, unless one is set
                    if (!hasIconChild && $element[0].className.indexOf('ion-') === -1) {
                        $element.addClass($ionicNavBarConfig.backButtonIcon);
                    }

                    //Default to ngClick going back, but don't override a custom one
                    if (!angular.isDefined($attr.ngClick)) {
                        $ionicNgClick($scope, $element, function() {
                            if (backViewIsPresent()) {
                                navBarCtrl.back();
                            } else if (parentStateIsPresent()) {
                                viewHistory.forcedBack = true;
                                $state.go('^');
                            } else {
                                return false;
                            }
                        });
                    }

                    //Make sure both that a backButton is allowed in the first place,
                    //and that it is shown by the current view.
                    $scope.$watch(function() {
                        if (angular.isDefined($attr.fromTitle)) {
                            $element[0].innerHTML = '' + $sanitize($scope.oldTitle) + '';
                        }
                        return !!(backIsShown && $scope.backButtonShown);
                    }, ionic.animationFrameThrottle(function(show) {
                        if (show) {
                            $animate.removeClass($element, 'ng-hide');
                        } else {
                            $animate.addClass($element, 'ng-hide');
                        }
                    }));
                };
            }
        };
    })
    .directive('ionTabs', function($rootScope, $state) {
        var viewHistory = $rootScope.$viewHistory;

        function getTabRootState(state) {
            var isRootState;

            if (state.parent.self.abstract === true) {
                isRootState = state.self.name;
            } else {
                isRootState = false;
            }

            return isRootState || getTabRootState(state.parent);
        }

        return {
            restrict: 'E',
            require: 'ionTabs',
            link: function(scope, element, attr, ctrl) {
                var selectTab = ctrl.select;

                ctrl.select = function(tab, shouldEmitEvent) {
                    var selectedTab = ctrl.selectedTab();

                    if (selectedTab && selectedTab.$historyId == tab.$historyId) {
                        if (shouldEmitEvent) {
                            viewHistory.forcedBack = true;
                            $state.go(getTabRootState($state.$current))
                        }
                    } else {
                        selectTab.apply(this, arguments);
                    }
                };
            }
        };
    });

Do you guys have any ideas? Thanks!


text:
Q: Empty variable from $_GET I have an index page that I'm enhancing with its search functionality by adding multiple choices of search. I can either type in a name in the search bar or click a link that would list items of certain group. All of this works, but I do get undefined variable error.
I am sending one variable with a value and another without in every search, but I am ordering the controller to pick both up from the URL. One will always be empty and the other might not be.
How do I "solve" this? Do I just suppress the error or ?
Controller
    public function index()
    {
        $search = $this->input->get('searchbox');
        $catsrch = $this->input->get('catname');
        $this->load->view('header');
            if (isset($search) && empty($catsrch)) {
                $this->searchByPostName($search);
            }
            elseif (isset($catsrch) && empty($search)) {
                $this->searchByCategory($catsrch);
            }
            else{
                $this->getAllPosts();
            }
        $data['cat'] = $this->blog_model->getCategoryDropdown();
        $this->load->view('categorysearch', $data);
        $this->load->view('footer');
    }

In the views, I'm doing stuff like this:
<?php
                foreach ($cat as $key) {?>

<a href="<?php echo base_url()."welcome/index?searchbox=&catname=".$key['catname']; ?>"><?php echo $key['catname']; ?>

                    <?php }?>

A: Apparently it was the empty in both if else that caused this. Only using isset() solved it.