text:
Q: Data not populating on update trigger I have a update trigger which retrieve aggregate results from a object. They need to be populated in another object (Funding_Cycles_TA__c). There is no run time errors or compile errors. but data is not populating as i wanted. My code is
trigger PopulateFCTAFromTP on Training_Plan__c (after update) {

    Set<Id> TAIds = new Set<Id>();
    // List< Training_Agreement__c> tasForUpdate = new List<Training_Agreement__c>();
      List<Funding_Cycles_TA__c> FCTAToUpdate = new List<Funding_Cycles_TA__c>();
    Training_Plan__c[] TPs = null;

    if(Trigger.isInsert||Trigger.isUpdate){
        TPs = Trigger.new;
    }else if(Trigger.isDelete){
        TPs = Trigger.old;
    }
    //select the Training plans
    for (Training_Plan__c TP : TPs) {
        if((TP.Training_Agreement__c != null)
           ||(TP.TEC_Status__c=='Active')
           ||(TP.TEC_Status__c=='Grace')
           ||(TP.TEC_Status__c=='Complete')
           ||(TP.TEC_Status__c=='On Hold')
           ||(TP.TEC_Status__c=='Withdrawn')
           ||(TP.TEC_Status__c=='Pending Transfer')){
               TAIds.add(TP.Training_Agreement__c);
           }
    }
     system.debug('TESTTEST') ;

    //Aggregate SOQL from Funding_Cycles_TPS__c
    List<AggregateResult> agrResults =
        [SELECT
         Reporting_Year__c reportingYear,
         sum(Achieved_Credits_Total__c) achievedCredits,
         sum(Funded_Achieved_Credits__c) fundedCredits,
         Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c ita
         FROM Funding_Cycles_TPS__c
         WHERE Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c in :TAIds
         //where  Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c = 'a0w0M00000VpgtI'
         GROUP BY Reporting_Year__c, Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c
         Order BY Reporting_Year__c];
     //system.debug('TESTTEST' + count(id)) ;

    //Corrosponding Funding_Cycles_TA__c(Child records)need to be updated from Training Agreement
    List<Funding_Cycles_TA__c>  fctasToUpdate = [Select id,Reporting_Year__c,
                                                 Achieved_Credits_in_Rpting_Yr_Funded__c,
                                                 Achieved_Credits_in_Rpting_Yr_Total__c,
                                                 Achieved_Credits_to_Rpting_Yr_End__c
                                                 From Funding_Cycles_TA__c
                                                 where Training_Agreement__c in: TAIds order by Reporting_Year__c ];

    /*  for (AggregateResult ar: agrResults)
    {fctasToUpdate.add(new Funding_Cycles_TA__c(Achieved_Credits_in_Rpting_Yr_Funded__c = (Decimal)ar.get('fundedCredits'),
          Achieved_Credits_in_Rpting_Yr_Total__c = (Decimal)ar.get('achievedCredits')));  }  */

    for (AggregateResult ar: agrResults)
    {
         for(Funding_Cycles_TA__c eachFCTA : fctasToUpdate)
        {
                system.debug('TCTA ID ' +eachfcta.id);
                system.debug('aggregate year        ' +(Date)ar.get('reportingYear'));
                system.debug('reportingYear of fcta ' +eachFCTA.Reporting_Year__c );
            if(eachFCTA.Reporting_Year__c == (Date)ar.get('reportingYear')
               && eachFCTA.Reporting_Year__c != Null)
             //  && eachFCTA.Achieved_Credits_to_Rpting_Yr_End__c!=Null
             //  && eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c !=NULL)
                system.debug('FCTA ID ' +eachfcta.id);
            {
                eachFCTA.Achieved_Credits_in_Rpting_Yr_Funded__c = (Decimal)ar.get('fundedCredits');
                eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c = (Decimal)ar.get('achievedCredits');
                eachFCTA.Achieved_Credits_to_Rpting_Yr_End__c = eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c + (Decimal)ar.get('achievedCredits');
                 system.debug('Agr Total  ' + (Decimal)ar.get('achievedCredits'));
                 system.debug('fcta Total ' + eachFCTA.Achieved_Credits_in_Rpting_Yr_Funded__c);
            }
        }
    }
    if(!fctasToUpdate.isEmpty()){
      update fctasToUpdate; }
}

A: EachFCTA is the temp variable to the loop there is no change in the fctasToUpdate list that portion is commented. Try to use a new List to update data.

A: Updating fctasToUpdate has no meaning in your code. Also eachFCTA is temp variable that you use to loop through fctasToUpdate. You would need a new list List<Funding_Cycles_TA__c> NewfctasToUpdateList = new List<Funding_Cycles_TA__c>(); that would contain objects of type Funding_Cycles_TA__c i.e. eachFCTA, with its fields populated with appropriate aggregated values. This is what you need to change:
 //Corrosponding Funding_Cycles_TA__c(Child records)need to be updated from Training Agreement
            List < Funding_Cycles_TA__c > fctasToUpdate = [Select id, Reporting_Year__c,
             Achieved_Credits_in_Rpting_Yr_Funded__c,
             Achieved_Credits_in_Rpting_Yr_Total__c,
             Achieved_Credits_to_Rpting_Yr_End__c
             From Funding_Cycles_TA__c
             where Training_Agreement__c in : TAIds order by Reporting_Year__c
            ];

            /*  for (AggregateResult ar: agrResults)
            {fctasToUpdate.add(new Funding_Cycles_TA__c(Achieved_Credits_in_Rpting_Yr_Funded__c = (Decimal)ar.get('fundedCredits'),
                  Achieved_Credits_in_Rpting_Yr_Total__c = (Decimal)ar.get('achievedCredits')));  }  */
            // This list will be used to update the Funding_Cycles_TA__c record fields
            List < Funding_Cycles_TA__c > NewfctasToUpdateList = new List < Funding_Cycles_TA__c > ();

            for (AggregateResult ar: agrResults) {
             for (Funding_Cycles_TA__c eachFCTA: fctasToUpdate) {
              system.debug('TCTA ID ' + eachfcta.id);
              system.debug('aggregate year        ' + (Date) ar.get('reportingYear'));
              system.debug('reportingYear of fcta ' + eachFCTA.Reporting_Year__c);
              if (eachFCTA.Reporting_Year__c == (Date) ar.get('reportingYear') && eachFCTA.Reporting_Year__c != Null)
              //  && eachFCTA.Achieved_Credits_to_Rpting_Yr_End__c!=Null
              //  && eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c !=NULL)
               system.debug('FCTA ID ' + eachfcta.id); {

               eachFCTA.Achieved_Credits_in_Rpting_Yr_Funded__c = (Decimal) ar.get('fundedCredits');
               eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c = (Decimal) ar.get('achievedCredits');
               eachFCTA.Achieved_Credits_to_Rpting_Yr_End__c = eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c + (Decimal) ar.get('achievedCredits');
               NewfctasToUpdateList.add(eachFCTA); // add the record to new list to update
               system.debug('Agr Total  ' + (Decimal) ar.get('achievedCredits'));
               system.debug('fcta Total ' + eachFCTA.Achieved_Credits_in_Rpting_Yr_Funded__c);
              }
             }
            }
            if (!NewfctasToUpdateList.isEmpty()) {
             update NewfctasToUpdateList;
            }

Update - You have a flaw in the logic that is why your list is getting duplicates. You are looping through fctasToUpdate again and again inside the loop of AggregateResult. What you need is a Map to avoid this multiple looping. Create a Map like below:
 //Aggregate SOQL from Funding_Cycles_TPS__c
    List<AggregateResult> agrResults =
        [SELECT
         Reporting_Year__c reportingYear,
         sum(Achieved_Credits_Total__c) achievedCredits,
         sum(Funded_Achieved_Credits__c) fundedCredits,
         Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c ita
         FROM Funding_Cycles_TPS__c
         WHERE Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c in :TAIds
         //where  Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c = 'a0w0M00000VpgtI'
         GROUP BY Reporting_Year__c, Training_Plan_Standard__r.Training_Plan__r.Training_Agreement__c
         Order BY Reporting_Year__c];

    Map<Id,AggregateResult> aggregatedMap = new Map<Id,AggregateResult>();
    For(AggregateResult ar : agrResults){

    // aggregatedMap.put('key',ar); // use a Key which is available in fctasToUpdate List. Example if you can get the Id of Funding_Cycles_TA__c in your above query use that here or use anyfield which is common between `Funding_Cycles_TA__c` and `Funding_Cycles_TPS__c`

    }

Once you have the map , you can use it in the for loop to get the corespoding aggregate value for each Funding_Cycles_TA__c record in fctasToUpdate.
        List < Funding_Cycles_TA__c > NewfctasToUpdateList = new List < Funding_Cycles_TA__c > ();

         for (Funding_Cycles_TA__c eachFCTA: fctasToUpdate) {
          system.debug('TCTA ID ' + eachfcta.id);

          if (eachFCTA.Reporting_Year__c == (Date) ar.get('reportingYear') && eachFCTA.Reporting_Year__c != Null)

           system.debug('FCTA ID ' + eachfcta.id); {

           eachFCTA.Achieved_Credits_in_Rpting_Yr_Funded__c =  (Decimal)aggregatedMap.get(eachFCTA.id).get('fundedCredits'); // Use the appropiate key that you decide.For example here I used eachFCTA.id
           eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c = (Decimal)aggregatedMap.get(eachFCTA.id).get('achievedCredits');
           eachFCTA.Achieved_Credits_to_Rpting_Yr_End__c = eachFCTA.Achieved_Credits_in_Rpting_Yr_Total__c + (Decimal)aggregatedMap.get(eachFCTA.id).get('achievedCredits');

           NewfctasToUpdateList.add(eachFCTA); // add the record to new list to update

          }
         }

        if (!NewfctasToUpdateList.isEmpty()) {
         update NewfctasToUpdateList;
        }


text:
Q: How to evaluate if a data exist in the browser? I have the following code that prints one item per column on the browser.
What I would like to do is in another page when a button is click is to check to see if any instance of that item is found in the page.
Page that prints out item

  <title> <%= title %></title>

    <% for(var i=0; i< rows.length; i++) { %>

        <% for(var f=0; f< fields.length; f++) { %>

          <%= rows[i][fields[f].name] %>

        <% } %>

      <% } %>

Code that should check if item exist in that page
$("#checkHashtag").click(function() {
    var hashtag = document.getElementById("codeInput").value;
// Check to see if user enter hashtag exist in that page
if(hashtag == ....**(thats where i need help)**

});

Thanks in advance
Below is the data page

I want to check to see if any instance of that data exist on that page upon button click

A: If there is a value in var hashtag = document.getElementById("codeInput").value; it could have a value which might evaluate to true. So you can simply do:
if(hashtag) {
    // do something
}

A: OK, based on your comments above, if you are trying to check if the hash is in the DOM on a page you are currently on, you could do something like this:

$("#checkHashtag").click(function() {
    var hashtag = document.getElementById("codeInput").value;
if(hashtag) {
  var cells = $('td');
  cells.each(function() {
  if($(this).text() == hash) {
    console.log('foo'); // Do something if hash is found
  }

});

If you need to access the list of values from multiple pages, then storing them in the DOM isn't the best strategy. You could either create an endpoint to get the values via an ajax request, or the simpler, less elegant solution would be to use you templates to put the values you need in a script tag on every page so you can simply access the variable on the client side.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot submit h:form on conditionally rendered rich:panel I'm having an issue submitting the contents of a form that is within a conditionally rendered rich:panel.  I have a commandButton within the form whose action is supposed to execute a method on my backing bean, but the method is never invoked and instead the entire page is re-rendered.  I've read in similar questions that the issue is related to theView state, but I've tried to follow the answers people have given with no luck.
Here is a snippet from my main xhtml page that is used to set the boolean controlling the panel render to 'true' (it is within a data grid):
<a4j:commandLink execute="@this" value="#{tableData.itemNumber}" render="edit editRowPanel editForm" title="View/Edit Record Detail"
                                action="#{navigate.setShowEdit(true)}" oncomplete="RichFaces.$('pleaseWaitView:searchWaitPanel').hide()" >
   <f:setPropertyActionListener target="#{context.currentItem}" value="#{tableData}" />
</a4j:commandLink>

The above code is rendering the panel as it should.
Here is the code from the main xhtml page that displays the panel:
<h:panelGroup id="edit">
   <rich:panel id="editRowPanel" rendered="#{navigate.isShowEdit()}" style="padding: 10px" >
      <f:facet name="header">
         <h:outputText value="Edit Row"/>
      </f:facet>
      <ui:include src="detail-page.xhtml" />
   </rich:panel>
</h:panelGroup>

Here is the submit button code that is within the form on detail-page.xhtml:
<h:commandButton styleClass="button" value="#{bundle.SaveChangesButton}" action="#{pplSuspenseBean.performRecordSave}" />

If I set "rendered="true"" on my editRowPanel everything works fine, it is only when render based on the condition that it does not work.  Any suggestions to fix this would be greatly appreciated, thanks!

A: I've decided to just use the CSS "display" property to show and hide my panel, since security is not much of a concern in this case (just an input form that allows editing only if the user is a certain role).
I created a CSS class to hide the panel:
.nodisplay {
    display: none;
}

I then set the styleClass on my the h:panelGroup to "nodisplay":
<h:panelGroup id="edit" styleClass="nodisplay">
   <rich:panel id="editRowPanel" style="padding: 10px" >
      <f:facet name="header">
         <h:outputText value="Edit Row"/>
      </f:facet>
      <ui:include src="detail-page.xhtml" />
   </rich:panel>
</h:panelGroup>

and changed my a4j:commandLink to remove this style class onClick:
<a4j:commandLink value="#{tableData.itemNumber}" title="View/Edit Record Detail"
   render="editRowPanel" oncomplete="RichFaces.$('pleaseWaitView:searchWaitPanel').hide()"
   onclick="$(edit).removeClass('nodisplay');>
   <f:setPropertyActionListener target="#{context.currentItem}" value="#{tableData}" />
</a4j:commandLink>

I also have another link within the panel that reapplies this style class so the panel is once again hidden.
This is an adequate solution for what I am trying to accomplish.


text:
Q: database connection through spring boot in PostgreSQL I am connecting spring boot application to PostgreSQL database. I have created the table using "create query tool" of PostgreSQL. It has been put in the default public schema. But when I tried to insert values in table, it does not accept values.
I have used the following command:
 Insert into User values(1,"ABC","pass_1");

What is the proper way to insert?


text:
Q: Where on Stack Exchange can I ask questions about internships? I've looked through some of the sites, and I don't know where's a good place to ask questions about data science research opportunities?

A: You question could also be on-topic in The Workplace.
Be sure to read the tour and how to ask so your question is well-received and you may get help.
There on TWP you can ask almost anything that is workplace-related, and that includes internships (we even have a tag for that). Just, make sure you ask something answerable. If you pretend to ask "Where can I find Data Science internships" I'm afraid that will be off-topic.

A: Your question may be on topic on Academia

If you have a question about a decision you need to make, please focus on how to make the decision, the pros and cons of a certain choice, or what relevant aspects you should consider. We cannot possibly know or judge all the details of your situation, in particular your personal preferences and the quality of your work and qualifications. Therefore you still have to make the decision yourself. Also, consider which details may be really important for what you wish to know. Try to extract the fundamental question from the specific problem at hand. As a rule of thumb, to attract answers that are most helpful to you, ask a question that would also help others in a similar situation.

See https://academia.stackexchange.com/help/on-topic


text:
Q: Why no exists() method? I send data in the view using an Ajax request:
def ajax_username_check(request):
    result = 'default'

    if request.method == "POST" and request.is_ajax():
        username = request.POST.get('username', '')

        username_req = User.objects.get(username=username)

        if username_req.exists():
            result = '1'
        else:
            result = '0'

    data = {'result': result}

    return HttpResponse(json.dumps(data), content_type='application/json')

As a result written to the log the following error message:
Internal Server Error: /accounts/ajax_username_check/
Traceback (most recent call last):
  File "/home/kalinins/.virtualenvs/zapsum/lib/python3.4/site-packages/django/core/handlers/base.py", line 112, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/kalinins/.virtualenvs/zapsum/zapsum/app_accounts/views.py", line 88, in ajax_username_check
    if username_req.exists():
AttributeError: 'User' object has no attribute 'exists'

Why does exists() not work? I do everything on the documentation:
https://docs.djangoproject.com/en/1.6/ref/models/querysets/#exists

A: exists() is a method on a queryset. However username_req is a user object, not a queryset, so you get the attribute error.
Instead of using get(), you can use filter(), which returns a queryset. You can then use exists().
username_req = User.objects.filter(username=username)

if username_req.exists():
    result = '1'
else:
    result = '0'

Another issue with using get() in your original code is that it could raise a User.DoesNotExist exception, which you are not catching.


text:
Q: assign multi-line text containing quotes to a variable in r in python I can assign a multi-line text to a variable using triple quotes like this:
s = '''  "hello world",
       'hello world again'  '''

It seems like it does not work in R this way. Does anyone how to do the same thing in R? Thanks a lot.

A: You actually can accomplish the same behaviour using only double/single quotes.
In console:
> s = 'hello world,
+      hello world again'

In script:
s = 'hello world,
     hello world again'


text:
Q: Auth assignment database call yii2 I am using Yii2 and using the yii\rbac\DbManager for auth assignment.
I was looking at the logs to see where all the database calls are coming from and this query
SELECT `b`.* FROM `auth_assignment` `a`, `auth_item` `b` WHERE
((`a`.`item_name`=`b`.`name`) AND (`a`.`user_id`='91')) AND (`b`.`type`=1)

Keeps running  again and again, sometimes 10/15 times in succession.
I have added
    'authManager' => [
        'class' => 'yii\rbac\DbManager',
        'cache' => 'cache'
    ],

As the docs say that will cache the auth assignments (I am using Memcached). But it doesnt seem to work...
Anyone have any idea? Either how to cache it or why it keeps getting called so many times?
Cheers

A: https://github.com/yiisoft/yii2/issues/3168
Only cache auth_item, auth_rule and auth_item_child data. All these
 data are cached as a single entry in cache. Note that
 auth_assignment is too big to be cached (imagine a system with
 millions of users).

A: Add caching in
vendor/yiisoft/yii2/rbac/DbManager.php
(Also in all places you need caching)
this code:

$all_data = $this->db->cache(function ($db) use ($query) {
                 return $query->all($db);
                },360);

public function getAssignments($userId)
    {
        if (empty($userId)) {
            return [];
        }

        $query = (new Query)
            ->from($this->assignmentTable)
            ->where(['user_id' => (string) $userId]);

        $all_data = $this->db->cache(function ($db) use ($query) {
                   return $query->all($db);
                  },360);

        $assignments = [];
        foreach ($all_data as $row) {
            $assignments[$row['item_name']] = new Assignment([
                'userId' => $row['user_id'],
                'roleName' => $row['item_name'],
                'createdAt' => $row['created_at'],
            ]);
        }

        return $assignments;
    }


text:
Q: Empty Scene is taking time to unload in Unity I have a normal project with about 30 Scripts and 30 Scenes (approx). When unloading any scene, it takes about 2 seconds.
For testing, I have made 2 empty scenes with 1 button each and want to transition back and forth. But again the Scene unload is taking time approx 2 seconds for an empty scene (Both scenes are empty). When I deleted other Scripts and Scenes from the Project, the Scene unloads and loads immediately. It means that in projects with minimum Assets, Unity unloads and load Scene immediately, but when project size increases, Unity takes time to unload even an empty scene. I have also tried SceneManager.LoadSceneAsync("SceneName");, but it still took time after clicking the button. What might be the problem? Does Unity takes time to unload an empty scene when the project size is large? I don't want to show loading animation or any sort of such things. I want to load an empty scene immediately even if the project size is large. Project size or number of Assets in the Assets folder must not affect the scene unloading time as scene loading time is dependent on the number of GameObjects and Scripts attached in that scene.

A: you shouldn't have the problem after you build the project


text:
Q: How to get the Eye tracking data for HoloLens 2 and MRTK in Unity? My question is how can I retrieve and store the eye-tracking/eye gaze data (such as the coordinate position of where the user is looking at different timestamps or the heatmap) with HoloLens 2 and MRTK in Unity?
I have seen some C# codes for getting the direction and origin of the gaze but I have no idea where to put them or where/how to add them (and to what).
Is it possible to retrieve and store such data without doing coding and directly from within the Unity and MRTK?
If no, then how can I do that with coding? and where to find the retrieved data?
Appreciate your help.

A: To access eye tracking data, simply use CoreServices.InputSystem.EyeGazeProvider in your MonoBehaviour script.
The GazeOrigin property of EyeGazeProvider will return gaze ray origin and GazeDirection property will return gaze ray direction. More infromation please see: Accessing eye tracking data in your Unity script


text:
Q: How to export env variables from file in bash script I need to export a lot of variables like
export x1=1
export x2=2
I moved all variables in file .env and tried
source .env
After it I executed
printenv
and all of this variables were absent in the list of env variables.
Also I tried
export $(xargs <.env)
But I have commented lines in .env file and I got following messages
#': not a valid identifier
So how can I export variables from file and skip commented lines?

A: Try naming a file like variables.env and then try
        export variables.env
        echo $somevariable_name


text:
Q: Gherkin - simply re-use Given statements as When statements... acceptable? Here are three example BDD statements that should help explain my question:
Scenario: User logs in
Given I am on the login screen
When I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
Then I should see the login successful page

Scenario: User buys a product
Given I am logged into the system using username "myUsername" and "myPassword"
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory

vs
Scenario: User buys a product
Given I am on the login screen
And I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory

So scenario 1 above is fine, but which is best out of statement 2 and 3.  Statement 2 reads nicely and more concisely.  But my step definition for
      "Given I am logged into the system using username "myUsername" and "myPassword""
will need to repeat calls to the Page Objects (or equivalent) that scenario 1 called... seems like more dev effort.
So really just wondering if anyone knows which is best practise.  I have searched online and found the following document:
http://docs.behat.org/guides/1.gherkin.html
This suggestions scenario 2 is best, but then writes: "Authenticate a user (An exception to the no-interaction recommendation. Things that "happened earlier" are ok)" which kinda lends itself to scenario 3.
Cheers,
Charlie

A: Here is my review of the scenarios you've written.
Scenario 1
Scenario: User logs in
Given I am on the login screen
When I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
Then I should see the login successful page

Pros : You are correctly using the Given, When and Then statements. In this scenario the Given sets the initial state of the system, the When indicates actions which a user will take and the Then details the assertions made to verify the behaviour of the system.
Cons : Whilst what you have written will work, the problem you have is that this test is brittle. If your company was to mandate that a time-dependent security token also had to be specified during log-in (for example), you'd have to add another step to input this additional field. However if you rewrote this step to be declarative e.g.
Given I am on the login screen
When I submit valid log-in criteria
Then I should see the login successful page

Then if the log-in process was changed, you would only need to alter the code, the scenario would remain the same.
Scenario 2
Scenario: User buys a product
Given I am logged into the system using username "myUsername" and "myPassword"
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory

Pros : Same as above.
Cons : Again the test is brittle as it's imperative i.e. you are specifying the exact log-in credentials and a specific product. I'd re-write this as:
Given I am logged into the system
When I purchase a product
Then I should have that product in the product inventory

You can save the product specified in the "When" step in ScenarioContext.Current. You would then be able to re-use this value in your "Then" step to assert that it is present in the product inventory.
Scenario 3
Scenario: User buys a product
Given I am on the login screen
And I enter the valid username "myUsername"
And I enter the valid password "myPassword"
And I press the login button
When I purchase the product "myProduct"
Then I should have "myProduct" in the product inventory

Cons : This is the worst of your scenarios as you are incorrectly using the Given statement. A Given statement should be used to define an initial system state for the test, so in this case "Given I am on the login screen" is a correct use, but "Given I enter the valid username "myUsername"" is an incorrect use. It is incorrect as it is indicating a user action, hence it should be covered by a When. Yes, you can use a Given to perform the same programmatic steps as a When, but it doesn't make it right!
I'd change this scenario to the version I suggested in Scenario 2.

A: Firstly, there is absolutely nothing in Gherkin that prevents you from writing specifications in any order, you can even produce compound specifications such as
Given ...
When...
Then ...
When ...
Then ...
Given ...
When ...
Then ...

So why would you want to do this?
Well first lets consider a fourth variant of your scenario
Scenario: User logs in and buys a product
  Given I am on the login screen
  When I enter the valid username "myUsername"
  And I enter the valid password "myPassword"
  And I press the login button
  Then I should see the login successful page
  When I purchase the product "myProduct"
  Then I should have "myProduct" in the product inventory

This is of course just a compound of 1 and 2. You might have written this because you had finished testing login and wanted to quickly write and test buying a product. You already have the code for the Bindings in scenario one and now simply need to write the bindings for scenario two. You might consider this your simplest pragmatic change, and you will refactor it later. This nothing wrong with it, running the tests could be quicker, but also its not exactly ideal.
Now imagine that due to the nature of your shop you have written many tests that test different buying processes. We could be testing what happens when you add the same item again to your basket,  or if you try to buy something out of stock, or different checkout experiences if you want special delivery. In fact your shop is so successful that you need to be really secure on the web and change your login process. Unfortunately you now have those three lines
Given I am on the login screen
When I enter the valid username "myUsername"
And I enter the valid password "myPassword"

repeated throughout your scenarios. If we accidentally break our login process with some bad code, suddenly all of our tests fail. You are presented with a wall of red and can't really narrow down where to start looking at the problems. Because we are dependant on logging in before we run our scenario we cannot isolate login from purchase.
This really is the difference between a Given and a When. A When is there to indicate that we are performing a process, a Given is a means of directly affecting the run time environment so that we simply have the correct state. It's basically the difference between
//Given
isLoggedIn = true

//When
if CheckValidPasswordForUser(user, password)
   isLoggedIn = true

The Given has no way to fail.
So coming all the way back to your original question,
Can you re-use Givens as Whens? Yes, but it in the long term it will confuse you.
But if you ask Can you re-use Whens as Givens? then I would definitely advise you not to. This will hide the fact that something that could break is being tested.
Finally there is one other thing to consider and that is the domain of your specification. Dan North has a really good article on this Whose Domain is it anyway?, but the general gist as applied to your example here is that when you are looking at product buying you can simply write
Given I am logged in as a customer

or
Given I am logged in as an administrator

because the username and password parts are to with login and not products, and that way you are protected from re-writing all your scenarios when you change your login process to use something else.


text:
Q: Question on returning no value from method I have a function that works as intended:
        public IWebElement ParseTheSelectElement(string byElement, int byRandomValue)
        {
            new SelectElement(_driver.FindElement(CustomSelector.Parse(byElement))).SelectByIndex(byRandomValue);
            return null;
        }

I'm using Selenium to select an index from a dropdown going by an index, i don't need anything returned from the method as the code executes fine, i know if nothing is to be returned to use void i had to return something to avoid an error so i did return null; i'm trying to learn if this is the correct way to handle this?
I have no errors, i'm just really wanting to learn if this is valid, it does not look correct to me as i'm not returning anything. Thank you for any input.

A:
I have no errors, i'm just really wanting to learn if this is valid, it does not look correct to me as i'm not returning anything.

It seems your intentions are to not return anything, rather perform an action, if that's the case, then make it a routine and or method and not a function that is intended to return something.
 public void ParseTheSelectElement(string byElement, int byRandomValue)
    {
        new SelectElement(_driver.FindElement(CustomSelector.Parse(byElement))).SelectByIndex(byRandomValue);
    }

You may be trying something like:
 _driver.FindElement(CustomSelector.Parse(byElement)).SelectByIndex(byRandomValue);

If you do the above, FindElement may not return an element, if so, then SelectByIndex would throw. With this in mind, you may want to check if the FindElement actually return's an element before doing anything with it.
Again, not sure though what your intentions are here, you're creating a new instance of SelectElement, but why, you're not doing anything with it.


text: Q: Using the One Column with Sidebar and wish to reduce the width of the toolbar I am currently using the One Column with sidebar Text Layout and the sidebar contains 3 web parts within it and having reduced the width of the web parts, I wish to reduce the width of the sidebar in order for the column to take the main stage. Unfortunately our company does not permit SPD therefore looking to see if there is any code which can added to the page in order to manipulate the width. any help would greatly appreciated.


text:
Q: Enrichment of mutations in particular region of the gene I have a gene say "X" of 3000 base pairs. 300 of those 3000 bp belong to ring domain. Rest 2700 do not belong to ring domain. In a particular tumor, the ring region has 4 alterations and the rest of the region has 4 alterations too. Clearly the frequency in ring region is higher, but is there a statistical test that will give me a p value that tells the probability of having a mutation in ring region is higher or not?

A: As I wrote in comments, I don't know how complicated your question is. Maybe I'm exaggerating a bit with those models or you don't know anything else about the situation.
If that is question should be very simple (homework or something like that) you could have a look on simplest Welch's T test.
With this test you could check wheter two non-overlapping populations have the same means.
Let's say, you have two populations $\mathfrak{F}$ (RING - foreground) and $\mathfrak{B}$ (the rest - background) represented by two arrays of lengths $L_F = 300$ and $L_B = 2700$, respectively. In the picture below, with blue balls are marked positions of bases which were altered.

For array $\mathfrak{F}$ we have independent binary random variables $F_1, \dots, F_{L_F}$, where $F_i = 1$ denotes at this position $i$ an alternation took place. I assume that any position in $\mathfrak{F}$ the probablity of alternation is the same(, but unknown) $p_f$ and each variable $F_i$ denotes single Bernoulli trial, so $F_i \sim Bernoulli(p_f)$.
For array $\mathfrak{B}$ we have the same situation, but corresponding variables $B_1, \dots, B_{L_B}$ are distributed with maybe different probablity $p_b$, so $B_i \sim Bernoulli(p_b)$.
According to the Central Limit Theorem (we have more than 30 random variables with each array, so CLT may be used) the mean of $F_i$s and mean of $B_i$s have Normal distribution:
$$\text{(mean of $F_{i}$)} ~~~~~~ \mu_F =\frac{\sum\limits_{i} F_i}{L_F} \sim Normal(p_f, \frac{p_f \cdot (1 - p_f)}{L_F} )$$
$$\text{(mean of $B_{i}$)} ~~~~~~ \mu_B = \frac{\sum\limits_{i} B_i}{L_B} \sim
Normal(p_b, \frac{p_b \cdot (1 - p_b)}{L_B})$$
Because you don't know anything about variations, thus use Welch's T test https://en.wikipedia.org/wiki/Welch's_t_test (rather than Student's T test).
In this test you may compare the corresponding means with hypotheses:
$$H_0 : \mu_F = \mu_B ~~ \text{against} ~~ H_A: \mu_F > \mu_B$$
In R you use method t.test{stats}:
t.test(arr_f, arr_b, alternative = "greater", paired = FALSE, var.equal = FALSE)
arr_f and arr_b are simply an 0-1 arrays where 1 points to alternated bases and 0 elsewhere.
The two trailing parameters are by default false, but I put them to make you aware of them. The last var.equal = FALSE indicates the Welch's T test instead of Student's T test with TRUE.


text:
Q: how to add dynamic image with horizontal scrollview/listview I have to develop five to six horizontal scrolling view,in this scrolling image add dynamic using adapter.
Feature:
1) Image can be drag and drop one scroll view to another
2) image can be move one horizontal scrolling to another view
3) image can be selected/unselected
4) with with all version
i am using this library, but sometime scrolling is not that much smooth(chopping)

A: Check this links may be it's useful to you.
1) Insert a view dynamically in a HorizontalScrollView in Android
2) http://android-er.blogspot.in/2012/07/implement-gallery-like.html
3) Horizontal ListView like Google Catalogs

A: Using this code you can add android control programatically to linear layout and just add Horizontal Scrollview to Linear Layout through xml
You will get horizontally listview.
//My coding here.
String[] name={"PRASHANT","PRASHANT","PRASHANT","PRASHANT","PRASHANT","PRASHANT","PRASHANT"} ;

myLInearLayoutmain =(LinearLayout) findViewById(R.id.linearLayoutmain);

for(int i =0;i<6;i++)
{
    LinearLayout li=new LinearLayout(getApplicationContext());
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    li.setOrientation(LinearLayout.VERTICAL);
    LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    LinearLayout.LayoutParams paramsnew = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

    params1.setMargins(30, 20, 30, 0);
    //add textView
    valueTV = new TextView(this);
    valueTV.setText(""+name[i]);
    valueTV.setId(5);
    valueTV.setLayoutParams(paramsnew);
    valueTV.setGravity(Gravity.CENTER);

    // adding Button to linear
    valueB = new Button(this);
    valueB.setText(""+name[i]);
    valueB.setId(i);
    valueB.setLayoutParams(params);
    valueB.setOnClickListener(this);
    valueB.setGravity(Gravity.CENTER);

    // adding Imageto linear
    img = new ImageView(this);
    img.setImageResource(R.drawable.ic_launcher);
    img.setLayoutParams(paramsnew);

    //add the textView and the Button to LinearLayout
    li.addView(valueTV);
    li.addView(valueB);
    li.addView(img);

    li.setLayoutParams(params1);
    myLInearLayoutmain.addView(li);
}


text:
Q: Handle new dynamic table creation in a div in robot framework I am currently doing web UI automation using Robot Framework. For my current task I have a div tag which shows a table inside. The table only shows 25 elements at load time. See image of elements for reference.

After scrolling the top div tag slowly, it creates new set of tables. See below image:

The point is it doesn't show all tables at one go. Also it keeps on adding tables with _startrow attribute to a random value. It also deletes tables from earlier rows on scrolling.
I am not sure how to deal with such dynamic content. Using Execute Javascript keyword has not helped as well.
Any new help would be appreciated. Thank you.

A: Your situation is a bit specific (on the js framework, and the html it produces), but I'll take a stab of providing a bit generic answer - with pseudo code you'll need to adapt.
What does a user do to make sure the new data is loaded? They see an entry, scroll a bit, wait for that entry to disappear, and for a new one to be visualized. So let's try to simulate it; "see" the current entry:

${old table}=    Get Webelement    ${locator for a generic table in the div}   # something like //div/table[@summary="Task Types"]

Now the value of that variable is going to be a specific webelement - an actual object in the DOM, not the "current <table> tag in the html, in any given moment".
Then, you do the operation that will make the system reload the tables - and wait for the one that was present to disappear:
Operation So Data Is Changed
Wait Until Element Is Not Visible    ${old table}

Once the "Wait For" returns execution/completes, you are sure the old table is no longer visible. And then - you need to wait for the new one to appear:
Wait Until Element Is Visible    ${locator for a generic table in the div}   # something like //div/table[@summary="Task Types"]

This approach is based off the SeleniumLibrary, and YMMV on the exact operations and locators, but that's the general idea.


text:
Q: Find all references to a table column in SQL Server 2008 Is there a way to find all references to a table column in a SQL Server 2008 database? I need to know which other tables or stored procedures or views the column is referenced from.

A: If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??

A: When I need to analyze impact due to table schema change, I use following steps for analysis. This may not be complete but helpful!

*

*Sp_help [TableName] : This helps me to find all FOREIGN KEY constraints References. I can also find any other tables referencing this table as FOREIGN Key.

*Sp_depends [TableName]: This helps to find Procedures, Functions, and Views using this table.

*Brute force method: I use different System tables and functions to check for specific keyword in SQL Jobs, modules, etc

FYI:
    Sp_help [TableName]
    Sp_depends [TableName]
select top 10 * from msdb.dbo.sysjobsteps where command like '%%'

SELECT top 10 Name, OBJECT_DEFINITION(OBJECT_ID)
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%%'

SELECT top 10 OBJECT_NAME(object_id), *
FROM sys.sql_modules
WHERE definition LIKE '%%'

A: You can try using a tool such as ApexSQL Search. It searches for object names but it also searches for a list of dependent objects even if columns in dependent tables/views are named differently.
Other solution is to use system views and/or system functions to get the data you need. Suggestion is to use sys.foreign_keys, sys.objects, sys.all_columns to get the data you need.

A: I have spent a good amount of time trying to find a way to identify column level dependencies in a quick way without having to search text or use third party applications.  The other challenge is finding dependencies across multiple databases where table names may repeat, which will cause false positives when searching SP text.
As of SQL 2008, there is a function that returns dependencies across databases on a field level.
The code below works with a few exceptions:

*

*It will fail if there are stored procedures with invalid references on tables/fields that have been deleted (Incidently I found this to be useful to find SPs that had been accidentally broken by table modifications).

*It doesn't find all dependencies in cases where the SP is using temp tables in unusual ways.

*In some cases I found that it was returning false positives for complex stored procedures.

MSDN Documentation
This code should be run from within the database where the SP is in order to be able to cross to other database dependencies.
SELECT
--SP, View, or Function
ReferencingName = o.name,
ReferencingType = o.type_desc,

--Referenced Field
ref.referenced_database_name, --will be null if the DB is not explicitly called out
ref.referenced_schema_name, --will be null or blank if the DB is not explicitly called out
ref.referenced_entity_name,
ref.referenced_minor_name,

--this will tell you the reference type
ref.is_selected,
ref.is_updated

FROM sys.objects AS o
cross apply sys.dm_sql_referenced_entities('dbo.' + o.name, 'Object') ref
where o.type in ('FN','IF','V','P','TF')


text:
Q: Reducing the number of queries in Django I'm creating a Django app that tracks awards that a person receives. Below is a simplified representation of two models that I have:
class AwardHolder(models.Model):
    name = models.CharField()

    def get_total_awards(self):
        entries = self.award_set.all()
        calc = entries.aggregate(sum=Sum('units_awarded'))
        return calc.get('sum') or 0

class Award(models.Model)
    date_awarded = models.DateField()
    units_awarded = models.IntegerField()
    award_holder = models.ForeignKey(AwardHolder)

I created a summary page for the award holder where he can see his total awards. I use the get_total_awards function above. That all works well, but then I created an overview page to display the total awards per award holder. I use the function below to get the total awards per award holder:
def get_all_awards():
    qs = AwardHolder.objects.all()
    awards = []
    for ah in qs:
        awards.append((ah, ah.get_total_awards())
    return awards

This generates a large number of queries since it hits the db every loop. Is there a way I can use prefetch_related or some other db trick to reduce the number of db queries, without having to rewrite get_all_awards()?
The actual code I use has a lot more fields and is more complicated than this example. There's about 10 functions similar to get_all_awards(), so rewriting it will be quite some work. However, for 100 award holders my code generated a whopping 18000 queries, so I know I have to fix this somehow.

A: get_all_awards does not necessarily have to call get_total_awards. You're repeating the same query for each entity instead of using a functionality Django already provides: annotate.
You can modify get_all_awards to use annotate and use get_total_awards only when the award applies to a single entity.
def get_all_awards():
    qs = AwardHolder.objects.annotate(sum=Sum('award__units_awarded'))
    awards = []
    for ah in qs:
        awards.append((ah, ah.sum))
    return awards

You may even drop the for loop and use the result from the queryset qs directly.
So you get the advantage of an optimized query when multiple objects and their related objects are being fetched, as opposed to running individual queries for each entity.

A: Use a model manager to always annotate AwardHolders
class AwardHolderQuerySet(models.QuerySet):
    def all(self):
        return self.annotate(Count('award__units_awarded'))

class AwardHolder(models.Model):
    name = models.CharField()
    objects = AwardHolderQuerySet.as_manager()
    ...


text:
Q: How to call Swift from an Objective C project App Delegate? This code is from a Swift project App delegate. It is used to help configure Stripe with a publishable key.
//Appdelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
//The code helps configure Stripe with a publishable key.
STPPaymentConfiguration.shared().publishableKey = Constants.publishableKey
...
}

Two errors are displayed when building the app after adding the Swift line to the Objective C App Delegate
//AppDelegate.h
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
STPPaymentConfiguration.shared().publishableKey = Constants.publishableKey

Property 'shared' not found on object of type 'STPPaymentConfiguration'
Use of undeclared identifier 'Constants'

This was a similar error in compiling before @objc was added to the demo Swift function, MockApiClient. Should it be added elsewhere? I've tried adding @objc to the enum as mentioned in the answer here to no avail yet.
//Constants.swift
//This is the file the original Swift app delegate accesses
import Foundation

  enum Constants {
  static let publishableKey = "pk_live_..."
  static let baseURLString = "http://54.33.123.227:1234"
  static let defaultCurrency = "usd"
  static let defaultDescription = "Receipt" //change to describe actual app & charge
  }

Steps taken:

*

*Opened the Objective C project and created a bridging header

*Created a demo class in Swift while still in the Obj C project to make sure it can be used, in this case to print from an Objective C file when the view is loaded. Specifically derived from an NSObject. Adding the override to the initializer and using the @objc prefix.
//  MockApiClient.swift
import Foundation
class MockApiClient: NSObject
{
override init()
{
print("Initializer called in Mock API client")
}
@objc func executeRequest()
{
print("The execute request has been called in the Mock API Client")
}
}

//ViewController.h
//Prints the Swift request written in the MockApiClient the the view loads

@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MockApiClient *client = [MockApiClient new];
[client executeRequest];
}

*Copied the #import "ViewController.h" import to the automatically generated project-Bridging-Header.h file to expose the Objective C in it to swift

*Added the necessary Swift files to the Objective C project so that the Constants.publishablekey data from Constants.swift can be found
How can this Swift App delegate code be added to the App delegate of an Objective C project?
Edit: error when adding @objc to the enum declaration in Constants.swift

A:
Edit: error when adding @objc to the enum declaration in Constants.swift

Swift enums used as namespace cannot be exposed to Objective-C.
You may need to use class to make it work both for Swift and Objective-C:
@objcMembers
class Constants: NSObject {
    static let publishableKey = "pk_live_..."
    static let baseURLString = "http://54.33.123.227:1234"
    static let defaultCurrency = "usd"
    static let defaultDescription = "Receipt" //change to describe actual app & charge

    private override init() {}
}

A: The ability of Objective-C to see things defined in Swift depends on the automatically generated header file. This is not the bridging header. It is a header file buried in your derived data called YourProject-Swift.h. Your Objective-C .m file needs to #import "YourProject-Swift.h" (using the correct name).
Then, your Swift things need to get into that file. For that to happen, they need to be of a type that Objective-C can see at all (i.e. classes) and they need to be explicitly exposed to Objective-C with appropriate @objc attributes.


text:
Q: Is there a way to generate a QR code with a custom logo in the middle in Perl? We've been successfully using GD::Barcode::QRcode to generate QR codes on the fly.
We now want to try to embed our small custom logo in every QR code we generate.
Is there a way to do that in Perl?


text:
Q: How to change the value of a JSON data while diplaying in a list? I am getting the data from the database as key value pairs and trying to populate the values in a list view. While looping I would like to change the value of a data (item.student_class) into 'Your next class is 2' if its value is class1. When I try it as below, it changes all the values in the list.
 var buffer="";

 $.each(data, function(index, val){

              for(var i=0; i < val.length; i++){

              var item = val[i];
//If the student's class is class1, change its value as below

   if(item.student_class= 'class1'){var studentclass='Your next class is 2';}

 buffer+='
' + item.student_name+''+studentclass+'
'+item.join_date+'
';
             }
      $('#student_list').html(buffer); });

Could someone please help me how I can acheive it ?

A: you are assigning a value, rather than comparing one , try as follows:
if(item.student_class== 'class1'){var studentclass='Your next class is 2';}

When you are assigning a value, it will work every time, and for that all of them will be changed. (probably you know, but it is common miss :-)
If you have multiple options, you can use the switch statement as follow:
var studentClass;
switch (item.student_class){
   case ('class1'):
     studentClass='Your next class is 2';
     break;
   case ('class2'):
     studentClass="Your next class is 3';
     break;
   default:
     studentClass= "Whatever should it be if nothing from cases apllies";
}

// Add rest of your code

A: Fix the conditional to not do an assignment.
You are initializing the variable inside the condition and thus it might be undefined in some cases.  Set it to "" first: i.e.
var buffer = "";
$.each(data, function (index, val) {
    for (var i = 0; i < val.length; i++) {
        var studentclass = "";
        var item = val[i];
        //If the student's class is class1, change its value as below
        if (item.student_class == 'class1') {
            studentclass = 'Your next class is 2';
        }
        buffer += '
' + item.student_name + '' + studentclass + '
' + item.join_date + '
';
    }
    $('#student_list').html(buffer);
});


text:
Q: Wiggling path transitions with D3 I use a line generator for my paths and try to transition them, but even if I don't use interpolation, I end up with wiggling paths.
const createLineData = d3.svg.line()
  .x(d => d.x)
  .y(d => d.y)

...

path.enter()
  .append('path')
  .attr('stroke', '#f00')
  .attr('stroke-width', 1)
  .attr('fill', 'none')

path
  .transition()
  .duration(200)
  .attr('d', createLineData)

path.exit().remove()

How do I prevent the wiggling?


text:
Q: Custom PC Won't POST After RAM Upgrade A few days ago, my custom computer broke. I will include all information possible in case some of it may help. Please let me know if I need to post more information. The last thing I did while it was functional was cloning my main SSD (running Garuda Linux) to an internal HDD for a backup, then I rebooted to the HDD to test. Then I shut it down (but the PSU was still on) and disconnected the HDD from both power and SATA. SATA is hotpluggable so it shouldn't have been a problem, but it could have been.
Next, I flipped the switch on the PSU to turn off all power to the computer then installed an extra stick of RAM (bought from eBay, more information at the end of the post). I have heard that installing three DIMMs will make the system use dual-channel until it uses up all of the first two RAM sticks then switch to single-channel on the third, but this may have caused problems (Edit: Apparently this is only for Intel). This was on carpet because I didn't want to move my computer for such a small thing, so I could have caused an ESD problem.
I then booted into the BIOS to make sure XMP was configured correctly and everything was detected as 3200MT/s RAM. I didn't check the CAS latency. I then selected the RAM speed option and the BIOS froze. The mouse wouldn't move and the arrow keys wouldn't change anything. I held the power button to shut it down. I booted into the BIOS again and tried again, and the same thing happened. I then tried to boot into the OS (Garuda Linux) on the SSD (250GB Samsung 870 Evo) and it froze with some text on the screen--I forgot to take a picture of the text. I then tried to reboot into Windows, which froze at a black screen. On my next reboot, the computer stopped POSTing. The fans would spin (the GPU fan even sped up and slowed down in a pattern similar to the beginning of the boot process), but nothing would display on the screen and my keyboard wouldn't initialize.
Once I realized how big of a problem it was, I removed the RAM stick. Unfortunately, this did not help. Resetting the CMOS did not help either. I then replaced every part of the system with a known-working part except the CPU, motherboard, and RAM, which I didn't have extras of (yes, the CMOS battery works). I have tried each stick of RAM in each slot to eliminate all possible variables. I have also removed and re-installed the CPU and cooler. Nothing helped.
Finally, I connected a buzzer that I had in another system. It had three beeps, paused at the same time as the GPU fan slowed down, then gave another three beeps. The AMI BIOS beep codes say that three beeps is a dead RAM stick, so I once again replaced the DIMM I was using with each of the other DIMMS and tried each one in every slot. Every one had the same error.
Based on this information, I decided that it must be either the RAM or the motherboard that was dead. It could be the CPU, but that seemed unlikely. Does anybody recognize the symptoms? Could it be the RAM stick that caused the problem or did I cause it? Was it the CPU, RAM, or motherboard that died?
Specs:
CPU: AMD Ryzen 5 2600
Motherboard: ASRock B450M Pro4
RAM:

*

*First kit: G.Skill Ripjaws V 16GB (8GBx2) CL16 DDR4-3200

*Upgrade kit: G.Skill Ripjaws V 8GB (8GBx1) CL19 DDR4-3600 (not perfectly identical but it should be close enough)
PSU: EVGA 450 BR
GPU: XFX Radeon R7 260X


text:
Q: Passing Data into Fragment outside ViewPager and FragmentPagerAdapter What I want to do is, pass a sorting variable into specific ViewPager's fragment
My ViewPager is work. I used OnPageChangeListener to get the current fragment and current tab position.
But, when I pass the variable outside the Listener, it always changed to 0
code: currentPos = arg0; (arg0 is returning correct position)
System.out.println("Current:" + currentPos);

All Tab Display result: Current:0
ThirdTab.java:
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
public Fragment fragment;
public int currentPos;

public String getSorting() {
    return sorting;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.third_tab, container, false);
    setHasOptionsMenu(true);

    tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.slidingTabStrip);
    pager = (ViewPager) rootView.findViewById(R.id.pager);
    adapter = new MyPagerAdapter(getChildFragmentManager(), getActivity().getApplicationContext());
    adapter.setTitle(catType);
    pager.setAdapter(adapter);
    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
            .getDisplayMetrics());
    pager.setPageMargin(pageMargin);
    tabs.setViewPager(pager);

    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int arg0) {
            // TODO Auto-generated method stub
            System.out.println("Good" + arg0);
            fragment = ((MyPagerAdapter) pager.getAdapter()).getFragment(arg0);
            currentPos = arg0;
            if (arg0 == 1 && fragment != null) {
                fragment.onResume();
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    });
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle item selection

    switch (item.getItemId()) {
    case R.id.menuSortRecentCreate:
    case R.id.menuSortRecentUpdate:
    case R.id.menuSortLowestPrice:
    case R.id.menuSortHighestPrice:
        if (item.getItemId() == R.id.menuSortRecentCreate) {
            sorting = "0";
        } else if (item.getItemId() == R.id.menuSortRecentUpdate) {
            sorting = "1";
        } else if (item.getItemId() == R.id.menuSortLowestPrice) {
            sorting = "2";
        } else if (item.getItemId() == R.id.menuSortHighestPrice) {
            sorting = "3";
        }

        System.out.println("Current:" + currentPos);
        System.out.println("Current Page:" + pager.getCurrentItem());

        return true;
    case R.id.action_search:
        return true;
    case R.id.action_setting:
        ThirdTabTaskSettingActivity fragment = new ThirdTabTaskSettingActivity();
        mainActivity.pushFragments(getResources().getString(R.string.title_third_tab), fragment, true, true);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

MyPagerAdapter in ThirdTab.java
 public class MyPagerAdapter extends FragmentStatePagerAdapter {
            private String[] TITLES = {};

            private String[] PERSONAL_TITLES = { getString(R.string.personal_category1), getString(R.string.personal_category2), getString(R.string.personal_category3),
                    getString(R.string.personal_category4), getString(R.string.personal_category5), getString(R.string.personal_category6) };

            private String[] BUSINESS_TITLES = { getString(R.string.business_category1), getString(R.string.business_category2), getString(R.string.business_category3),
                    getString(R.string.business_category4), getString(R.string.business_category5) };

            HashMap<Integer, Fragment> hm = new HashMap<Integer, Fragment>();

            private Map<Integer, String> mFragmentTags;
            private FragmentManager mFragmentManager;
            private Context mContext;

            public MyPagerAdapter(FragmentManager fm, Context context) {
                super(fm);
                mFragmentManager = fm;
                mFragmentTags = new HashMap<Integer, String>();
                mContext = context;
            }

            public void setTitle(String category) {
                if (category.equals("personal")) {
                    TITLES = PERSONAL_TITLES;
                }
                else {
                    TITLES = BUSINESS_TITLES;
                }
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return TITLES[position];
            }

            @Override
            public int getCount() {
                return TITLES.length;
            }

            @Override
            public Fragment getItem(int position) {
                Fragment fragment = null;

                switch (position) {
                case 0:
                    fragment = ThirdTabContentFragment1.newInstance(position, sorting, keyword);
                    return fragment;
                case 1:
                    fragment = ThirdTabContentFragment2.newInstance(position, sorting, keyword);
                    return fragment;
                case 2:
                    fragment = ThirdTabContentFragment3.newInstance(position, sorting, keyword);
                    return fragment;
                case 3:
                    fragment = ThirdTabContentFragment4.newInstance(position, sorting, keyword);
                    return fragment;
                case 4:
                    fragment = ThirdTabContentFragment5.newInstance(position, sorting, keyword);
                    return fragment;
                case 5:
                    fragment = ThirdTabContentFragment6.newInstance(position, sorting, keyword);
                    return fragment;
                }
                return fragment;
                // return SuperAwesomeCardFragment.newInstance(position, sorting, keyword);
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                System.out.println("instantiate");
                Object obj = super.instantiateItem(container, position);
                if (obj instanceof Fragment) {
                    Fragment f = (Fragment) obj;
                    String tag = f.getTag();
                    mFragmentTags.put(position, tag);
                }
                return obj;
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }

            public Fragment getFragment(int position) {
                System.out.println("In:" + position);
                String tag = mFragmentTags.get(position);
                if (tag == null) { return null; }
                return mFragmentManager.findFragmentByTag(tag);
            }
        }

ReceiveData's Fragment
public class ThirdTabContentFragment1 extends BaseContainerFragment implements AsyncResponse {

    public static ThirdTabContentFragment1 newInstance(int position, String vSorting, String vKeyword) {
        ThirdTabContentFragment1 f = new ThirdTabContentFragment1();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);
        System.out.println("a" + position);
        return f;
    }

    @Override
    public void onResume() {
        System.out.println("Resume1");
        super.onResume();
    }

}


text:
Q: External packages (jars) in pyspark shell - How To What is the proper way to include external packages (jars) in a pyspark shell?
I am using pyspark from a jupyter notebook.
I would like to read from kafka using spark, via the spark-sql-kafka library, as explained here: https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html#deploying.
I am trying to import the library via the --packages option, set in the environment variable PYSPARK_SUBMIT_ARGS.
But

*

*I am not sure about the exact version and name of the package to use,

*I don't know whether I also need to include spark-streaming or not, whether I have to specify some repository with --repositories or not,

*I don't know whether it's better to download the jar and specify local paths (do they have to be on the machine where jupyter is running, or on the machine where yarn is running? I'm using --master yarn and --deploy-mode client) or to rely on --packages

*I don't know whether options specified after pyspark-shell in PYSPARK_SUBMIT_ARGS are left out or not (If I try to specify --packages options before pyspark-shell I can't instantiate the spark context at all)

*How can I check whether some package was correctly downloaded and is available to be used

*I don't know what is the route that such downloaded jars (or jars in general) take. How many times are they replicated? Do they pass through the driver? Do these things change if I'm using a cluster manager as YARN? Do they change if I'm using everything from a spark-shell in a jupyter notebook?

Resources I read so far:

*

*Docs and guides:

*

*Structured streaming kafka integration

*Spark configuration

*Spark submitting applications

*Zeppelin notebook on cluster mode documentation

*jaceklakowski on spark-submit, config options, notebooks, spark context, etc.

*pyspark docs

*cloudera building spark applications

*Spark structured streaming programming guide

*Examples:

*

*notebook with spark structured streaming and spark sql kafka

*dzone basic example for spark structured streaming

*Issues and questions:

*

*structured streaming using kafka as source with python

*Java gateway process exited before sending the driver its port number

*does pyspark support spark streaming kafka 0-10-lib

*adding custom jars to pyspark in jupyter notebook

*Repositories:

*

*spark-sql-kafka on search.maven.org

*spark-sql-kafka on MVNrepository

A: For simplicity, I would try to get things working outside Jupyter first

the exact version and name of the package to use

The version needs to match your Spark version. Use the package that you want to download.

I don't know whether I also need to include spark-streaming or not

Do not. It's already on the classpath of your Spark workers.

whether I have to specify some repository with --repositories or not,

If you are available to download files directly from Maven Central, then no.

whether it's better to download the jar and specify local paths

You should probably use --packages, which will download the files for you. The deploy-mode and cluster don't interfere with this.

whether options specified after pyspark-shell in PYSPARK_SUBMIT_ARGS are left out or not

Shouldn't be, though I typically see pyspark-shell as the last option.
import os
os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages ... pyspark-shell'

import pyspark
from pyspark.streaming.kafka import KafkaUtils
from pyspark.streaming import StreamingContext

sc = pyspark.SparkContext()
ssc = StreamingContext(sc,1)

How can I check whether some package was correctly downloaded

You would get a NoClassDefFound, for example when running if it wasn't downloaded.

what is the route that such downloaded jars (or jars in general) take

There's $SPARK_HOME/jars, but any --jars or --packages are cached in the ~/.m2 folder on each machine for the user running the job, usually, then symlinked into the running YARN container / Spark executor.

A: When you want to import external packages in Pyspark shell , During launching itself we can call it like way we are doing spark-submit.
> ./bin/pyspark --packages
> org.apache.spark:spark-sql-kafka-0-10_2.11:2.2.0,com.databricks:spark-avro_2.11:3.2.0
> --conf spark.ui.port=4055 --files /home/bdpda/spark_jaas,/home/bdpda/bdpda.headless.keytab --conf
> "spark.executor.extraJavaOptions=-Djava.security.auth.login.config=/home/bdpda/spark_jaas"
> --conf "spark.driver.extraJavaOptions=-Djava.security.auth.login.config=/home/bdpda/spark_jaas

Note : This pyspark submit used for same use use case to connecting Pyspark with Kafka structured streaming .


text:
Q: Execute php code after giving the user 200 response I am building an API. In it, there is some code that does not need to be executed for giving a response to the user. So I would like to give the response after the mandatory code is executed and also run the remaining code in the background.
This is a Linux server running apache and PHP7.2
        ignore_user_abort(true);
        set_time_limit(0);

        ob_start();

        $api_key = $request->get('api_key');
        $clientToken = ClientToken::where('token', $api_key)->where('is_blocked', 0)->get();
        if (count($clientToken) > 0) {
            $dateTime = date_create_from_format('d-m-Y H:i:s a', $request->get('date_time'));
            $missCallRequest = new MissCallRequest();
            $missCallRequest->client_token_id = $clientToken[0]->id;
            $missCallRequest->called_number = "+" . $request->get('called_number');
            $missCallRequest->caller_number = $request->get('caller_number');
            $missCallRequest->datetime = date_format($dateTime, 'Y-m-d H:i:s');
            $missCallRequest->operator = $request->get('operator');
            $missCallRequest->circle = $request->get('circle');
            $missCallRequest->request_url = urldecode($request->fullUrl());
            $missCallRequest->save();

        }

        $response = [
            "status" => 200,
            "message" => "Request Received",
        ];

        echo json_encode($response); // send the response

        // Get the size of the output.
        $size = ob_get_length();

        // Disable compression (in case content length is compressed).
        header("Content-Encoding: none");

        // Set the content length of the response.
        header("Content-Length: {$size}");

        // Close the connection.
        header("Connection: close");

        // Flush all output.
        ob_end_flush();
        ob_flush();
        flush();

        echo "hello";

This is responding after the mandatory code but it's not executing the rest of the code after responding.

A: Use this to make sure the 200 is sent immediately
ignore_user_abort(true);
ob_start();
header("HTTP/1.1 200 OK");
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
ob_flush();
flush();


text:
Q: Reclassify Slope using SAGA Raster Calculator I am looking for the right formula for reclassifying a slope raster.
I need to switch the values 1 = bad, 10 = good to 1 = good, 10 = bad.
This Formula worked fine using the normal raster calculator:
10 - %"Recoded@1"% + 1
but I can't figure out the right formula using the SAGA or Gdal Raster Calculator for my processing model.
Any ideas!?

A: A direct answer using SAGA Raster Calculator, would be 11- g1 (same as 10 - g1 + 1).
Alternatively, SAGA | Raster tools Invert grid does the same job.
If we test with this example (sorry... I forgot to input 1... and ended up with 10 - g1 + 2).

Since OP's equation had been successful with QGIS raster calculator, I will not worry too much about continuous data.
If input was continuous data (e.g. 1.23 - 10.00), the output gets funny and easily recognized.

A: Try using the SAGA Tool "Reclassify values". Here you can easily replace one value with another one (for example 1 with 10). Depending on your data, you might have to repeat the process several times to achieve the desired format


text:
Q: sort sorted list as data table order i fill sorted list from ordered datatable but after fill sorted list my order changing
     for (int i = 0; i < d.Rows.Count; i++)
        {
              int EmpID = Convert.ToInt32(d.Rows[i]["Fd_Emp"].ToString().Trim());
            string type=d.Rows[i]["Fd_Type"].ToString().Trim();
            emp.Add(EmpID, type);

        }

my datatable order is 31e,32e,33e,7i
my sortedlist order become 7i,31e,32e,33e
how to keep my datatable order in my sorted list

A: The idea of using a sorted list is that it keeps the added elements in a sorted order.  This means that if the elements in the database are not sorted (or not sorted the same way as the sorted list sorts) the elements in the sorted list will have a different order
If the values in the DB are sorted and you want to get the same ordering from your sorted list, you can provide a custom sorting method for your elements, in which you duplicate the comparison logic that the DB uses for its values.

A: The SortedList<T> class sorts elements based on a comparison function you provide, or, if you don't provide one, based on the default comparer for the type.  Your sorting logic, however, depends on data that's not in the sorted list (you said "I ordered the query by another column).  So you can't sort the list.
The List<T> class holds an ordered sequence of elements; the order is the order in which they are added.  In other words, List<T> will keep the elements in the same order.  Since you want the elements to retain the order in which you retrieved them from the database, You should use List<T>.

no sorry but i have my logic so i have to use sorted list

If you need to use SortedList<T> then you will have to do it in a complicated way so you can refer to the values in the column you used for ordering the data.  There are a few possibilities for that.  But I would be far more strongly inclined to change the dependency on SortedList<T>.  Why do you need to use SortedList<T>?  If you can provide more context, we may be able to help you solve the bigger problem.  The smaller problem you've reduced it to seems overly complicated.


text:
Q: Put a Label and a TextField in a same row I would like create a calculator in Java Swing but I have a problem I want to put one label and one textfield in same row, not two columns but in the same row ex: Number 1:(label) (textfield here) in a same row, sorry for my English.
My code :
private JPanel mainPan; //= new JPanel();
private JLabel title;
private JLabel nb1;
private JLabel nb2;
private JButton button;
private JTextField textField; //= new JTextField();

public Fenetre() {
    super ("Calculator");
    mainPan = new JPanel();
    title = new JLabel();
    nb1 = new JLabel();
    nb2 = new JLabel();
    button= new JButton();
    textField = new JTextField();

    setMinimumSize(new Dimension(400, 500));
    setSize(400, 500);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(Fenetre.EXIT_ON_CLOSE);
    setResizable(true);

    setIconImage(new ImageIcon("C:\\Users\\sidot\\Desktop\\download.png").getImage());

    mainPan.setBackground(Color.darkGray);
    mainPan.setLayout(new GridLayout(2,0));
    Border border = LineBorder.createBlackLineBorder();

    title.setText("Calculator 1.0");
    title.setFont(new Font("MONOSPACED", Font.PLAIN, 20));
    title.setForeground(Color.WHITE);
    title.setHorizontalTextPosition(JLabel.CENTER);
    title.setVerticalTextPosition(JLabel.BOTTOM);
    title.setBorder(border);
    mainPan.add(title);

    nb1.setText("Number 1");
    nb1.setFont(new Font("MONOSPACED", Font.BOLD, 15));
    nb1.setForeground(Color.WHITE);
    nb1.setHorizontalTextPosition(JLabel.LEFT);
    nb1.setVerticalTextPosition(JLabel.CENTER);
    nb1.setBorder(border);
    mainPan.add(nb1);

    nb2.setText("Number 2");
    nb2.setFont(new Font("MONOSPACED", Font.BOLD, 15));
    nb2.setForeground(Color.WHITE);
    nb2.setHorizontalTextPosition(JLabel.LEFT);
    nb2.setVerticalTextPosition(JLabel.CENTER);
    nb2.setBorder(border);
    mainPan.add(nb2);

    this.setContentPane(mainPan);
    this.setVisible(true);
}

I want have after number 1 and number 2 a textfield.
Thanks

A: The default layout for a JPanel is the FlowLayout. So you can use a JPanel to hold the label and text field:
JPanel rowPanel = new JPanel();
rowPanel.add( label1 );
rowPanel.add( textField1 );
mainPanel.add( rowPanel );

The main point is you can nest panels with different layout managers and components to achieve your desired layout. Read the section from the swing tutorial on Layout Manger for more information.


text:
Q: Pingdom speed test downloads both woff2 and woff of the same font I noticed when running Pingdom speed test and viewing the file requests section, the test server downloads both .woff2 and .woff versions of each font from my site, declared using the standard @font-face css like below:
@font-face
 {
  font-family:'Roboto Condensed';
  src:url('../fonts/roboto-condensed-v16-latin-regular.woff2')
  format('woff2'),url('../fonts/roboto-condensed-v16-latin-regular.woff')
  format('woff');
  font-weight:400;
  font-style:normal;
 }

(I self host the Google fonts.)
So basically with 8 fonts used the test server requests 8 extra .woff files it doesn't really need.
Why is this happening? I tested the site using Chrome/Firefox developer tools and only .woff2 is retrieved as expected. Is this a bug with Pingdom?
Interestingly, I noticed that the test server only requested the .woff2 version of FontAwesome, even though the fontawesome css also referenced both .woff2 and .woff versions.


text:
Q: Using height_field and width_field attribute in ImageField of Django I have a model
class Anh_chi_tiet(models.Model):
    du_an       = models.ForeignKey(Du_an)
    title       = models.CharField(max_length=120)
    url         = models.ImageField(upload_to='images', height_field='50', width_field='100')
    url_detail  = models.ImageField(upload_to='images', height_field='200', width_field='400')

I always receive this error:
'Anh_chi_tiet' object has no attribute '100'

It seems Django require both the fields in the same table Anh_chi_tiet to save height_field and width_field.
How can I directly set these values without append new fields in my table?

A: height_field represents a property of your model which is used to store the height.
class Anh_chi_tiet(models.Model):

  url_height=models.PositiveIntegerField()
  url_width=models.PositiveIntegerField()
  url = models.ImageField(upload_to='images', height_field='url_height', width_field='url_width')

Notice height_field='url_height'

A: I think you are misunderstanding what the height_field and width_field attributes are for.
The height_field isn't used to change the height. It's used to record what the height already is.
This way you can do something like
<img src="..." height={{my_instance.my_height_field}} />

without having to read the file.
If you are trying to resize all images uploaded via an ImageField, check here:
Image resizing with django?


text:
Q: Likelihood Function for the Uniform Density. Let the random variable $X$ have a uniform density given by
$$
f(x;\theta)=I_{[\theta-\frac{1}{2},\theta+\frac{1}{2}]}
$$
where $-\infty\leq\theta\leq\infty $
the likelihood function for a sample of size $n$ is
$$L(\theta;x_1,\ldots,x_n)=\prod_{i=1}^nf(x_i;\theta)=f(x_1;\theta)\ldots f(x_n;\theta)$$
Why the likelihood function for a sample of size $n$ is the "joint density" of the $n$ random variables?

*

*I am asking the question because I knew that we have to select $\hat \theta$ in such a way that the random variables $X_1,\ldots,X_n$ assume a particular value $x\prime_1,\ldots,x\prime_n$ such that $f_{X_1,\ldots,X_n}(x_1,\ldots,x_n;\theta) $ is a maximum.

But here, for the Uniform density function, there is no hint that the value $x_1$ of the random variable $X_1$ maximizes the function $f_{X_1}(x;\theta),\ldots,$ the value $x_n$ of the random variable $X_n$ maximizes the function $f_{X_n}(x;\theta).$ Then how $x_1,\ldots,x_n$ maximizes $f_{X_1,\ldots,X_n}(x_1,\ldots,x_n;\theta) $ for the given density function , ie, for the Uniform density function?
Again,
$$L(\theta;x_1,\ldots,x_n)=\prod_{i=1}^nf(x_i;\theta)=\prod_{i=1}^n I_{[\theta-\frac{1}{2},\theta+\frac{1}{2}]} (x_i)=I_{[y_n-\frac{1}{2},y_1+\frac{1}{2}]} (\theta)$$
where $Y_1$ is the smallest of the observations & $Y_n$ is the largest.

*

*Why have we changed the range? Is it so as Likelihood-function is a function of $\theta$ and here $x_1,\ldots,x_n$ fixed?

*Again i have not understand the point: if we subtract $\frac{1}{2}$ from the largest value $y_n$ then it will be the lower limit of $\theta$ and if we add $\frac{1}{2}$ to the smallest value $y_1$ then it will be the upper limit of $\theta$.
Can you please give me a numerical example of the situation?

A: 1) If n rv's (not one) are independent, then their joint density is the product of their individual densities (this extends the notion of the probability of intersection of n independent events in the case of rv's). If, moreover, they are (assumed) identically distributed, then
$$ L(X_1,\ldots,X_n| \theta)=\prod_{i=1}^nf(X_i|\theta)=f(X_1|\theta)\ldots f(X_n|\theta)$$
is the joint density.
If we view this expression as a function of $\theta$, then it becomes
$$ L(\theta|x_1,\ldots,x_n)=\prod_{i=1}^nf(\theta|x_i)=f(\theta|x_1)\ldots f(\theta|x_n)$$
and now it is the likelihood function of the sample. Is there a difference? Big one: In the joint density, the argument/variable of the function is the X's while the $\theta$'s are treated as constants. In the likelihood function, the arguments/variables are the $\theta$'s while the x's are treated as constants (changing from uppercase to lowercase for the x's is a usual -and good- mnemonic) So the likelihood function is not the joint density - they may have the same functional form, but they are functions of different variables.
2) In view of 1), we do not select the $\theta$'s "so as the rv's assume a particular value...etc" as you write. We select the $\theta$'s given the specific values that the r.v's have already taken (values that constitute our sample), so as the resulting value of the function is maximum. Then we flip our point of view again and say (very loosely speaking), that this value of $\theta$ "maximizes the probability that the sample comes from the assumed distribution".
3) The uniform distribution is special in that the variable itself does not appear in the density function. The specific case we study is even more special, because not even the limits of the interval into which the rv ranges appear in it: the density is equal to unity for the specified range, and zero elsewhere (even though the range of the rv is not [0,1]). Instead of writing a piece-wise density we write compactly $$ f_U (X_i)=I_{[\theta-\frac{1}{2},\;\theta+\frac{1}{2}]} (X_i)$$ Then the joint density for the case of n i.i.d rv's is $$ L(X_1,\ldots,X_n| \theta)=\prod_{i=1}^nf(X_i|\theta)=\prod_{i=1}^n I_{[\theta-\frac{1}{2},\;\theta+\frac{1}{2}]} (X_i) =\min\{I_{[\theta-\frac{1}{2}\le X_1\le\theta+\frac{1}{2}]} ,...,I_{[\theta-\frac{1}{2}\le X_n\le\theta+\frac{1}{2}]}\}$$ where the last equality comes from basic properties of indicator functions.
Consider now the joint density as a likelihood function of $\theta$, with given x's. Then we should maximize this likelihood function? No. We are applying here maximum likelihood estimation, and the ML estimators are M-estimators, which maximize the expected value of the likelihood function (or its sample analogue, whatever is feasible). So our estimation problem here can be stated as
$$  \max_{\theta}E\min\{I_{[\theta-\frac{1}{2}\le x_1\le\theta+\frac{1}{2}]} ,...,I_{[\theta-\frac{1}{2}\le x_n\le\theta+\frac{1}{2}]}\}$$
Let's start the optimization procedure. Note that if we choose some $\hat \theta$ such that some of the realized values in the sample fall outside the specified range, the min{} expression will be equal to zero. But if the chosen $\hat \theta$ has a value that leaves all realized values of the rv's inside the resulting common interval, then the min{} expression will be equal to unity. I adopt the notation $x_1=x_{min}$ and $x_n=x_{max}$. So a first conclusion is that we must have  $$ x_1\ge \theta-\frac 12  \text{and} \ x_n\le \theta+\frac 12 \\ \Rightarrow x_n-\frac 12\le \theta\le   x_1+\frac 12$$
(Parenthesis: For $\hat\theta$ to be able to obtain a value in the reals this interval must exist. So we must have $$x_n-\frac 12\le  x_1+\frac 12 \Rightarrow x_n-x_1 \le 1$$
In other words, if in the sample at hand the difference between the maximum realized value and the minimum realized value is greater than unity, then one of the initial assumptions is wrong: either the n rv's do not have the postulated distribution, or they are not identically distributed). Assume that $x_n-x_1 \le 1$ holds. Then our maximization problem has been transformed (after this first step of optimization) as
$$  \max_{\theta}EI_{[x_n-\frac 12\ \, \le \,  \theta \, \le  \, x_1+\frac 12]}$$
The $\min$ operator has disappeared because all indicator functions have become identical.
Now by the properties of indicator functions,
$$  EI_{[x_n-\frac 12\ \, \le \,  \theta \, \le  \, x_1+\frac 12]} = P\left(\left[x_n-\frac 12\ \, \le \,  \theta \, \le  \, x_1+\frac 12\right]\right)$$
where P() is the probability of the interval. Next we can write the upper bound for $\theta$ as a constraint and solve the constrained maximization problem
$$  \max_{\theta}P\left(\left[x_n-\frac 12\ \, , \,  \theta\right]\right) \qquad \text{s.t.}\ \theta\le   x_1+\frac 12$$
Obviously this probability increases with the length of the interval, and so
$$ \hat \theta : [x_n-\frac 12\ ,  \hat \theta] = \text{maximum}$$
which obviously results in
$$ \hat \theta_{\text{ML}} = x_1+\frac 12$$
Then the maximum likelihood estimate of the common distribution of the n rv's is $$U\left(x_1\, , \, x_1+1\right).$$


text:
Q: Formating price value in xslt my xml file has multiple plant tags in it. Basic code is:
<plant>
    <common>snakeroot</common>
    <botanical>cimicifuga</botanical>
    <zone>5</zone>
    <light>shade</light>
    <price>$5.63</price>
    <availability>071114</availability>
</plant>

I want to sort this file based on price. If i use
 <xsl:sort select="//price" data-type="number" order="descending" />
but its not sorting and the reason is i have a dollar sign infront of it. Can someone advice on how to remove it or format it so that i get desired result.
Thanks

A: If it's always a dollar sign then you could do
<xsl:sort select="substring-after(price, '$')" data-type="number"
          order="descending" />

You definitely don't want the leading // as this makes it an absolute path which will pick out exactly the same sort key value for every single plant (namely the very first price element in the entire document), as opposed to a relative path to pick out a price from within the particular plant it's looking at at the time.


text:
Q: karaf - How to handle: "Error installing bundles"? I created a simple karaf application that just run some calculations.
After that I did mvn clean install and then I added the bundle to the local maven repository with install:install-file -Dfile=bundle1-1.0-SNAPSHOT.jar -DgroupId=prg.ogra -DartifactId=bundle1 -Dversion=1.0-SNAPSHOT -Dpackaging=jar
Now I run karaf with ./apache-karaf-4.2.0/bin/karaf debug and when I do install mvn:org.orga/bundle1/0.0.1-SNAPSHOT
I get an error: Error executing command: Error installing bundles: Unable to install bundle mvn:org.orga/bundle1/0.0.1-SNAPSHOT: org.osgi.framework.BundleException: Unable to cache bundle: mvn:org.orga/bundle1/0.0.1-SNAPSHOT
What should I do?
Where am I wrong?

A: In karaf, run the following:
maven:summary

and make sure karaf is actually linked to the correct local repository.
In addition, navigate to your local repository on the file system and verify that the bundle is located at the maven coordinates you are specifying in the install command. Edit as needed.