text:
Q: Is a "master preferences" class a good idea? I have a class that manages user preferences for a large software project.  Any class in the project that may need to set or retrieve a user preference from a persistent store is to call the static methods on this class.  This centralized management allows the preferences to be completely wiped programmatically - which would be impossible if each pref was handled close to its use code, sprinkled throughout the project.
I ran into another implication of the centralization design in the course of this.  The software has a public API.  That API can be provided by itself in a jar.  Classes in that API might refer to the pref management class.  So, the pref manager has to go in the API jar.
Each preference might have a default value.  Upon software startup, that default might be computed.  The algorithm depends on the preference, and thus tends to reside near the use code.  So if the pref manager needs to come up with a default, it calls the class in question.
But now that pref manager has become an "octopus class", sucking in all sorts of classes into the API jar that shouldn't be there.  If it doesn't, then programs using the API jar quickly run into ClassDef exceptions.  If it does, then the API jar is now bloated, as each of those other classes may refer to still others.
In general, do other Java programmers manage their preferences with a centralized class?
Does it make sense to distribute that static pref management class as part of a public API?
Should that pref manager be the keeper of the code for determining defaults?

A: Can't you just handle preferences in a really generic way? You'd then just use the preference manager to handle the persistence. So from a class you'd  just say to the preference manager PreferenceManager.setPreference(key, value) and it doesn't care what it's saving in terms of the semantics of the data.
Or am I simplifying this too much?

A: I'm no Java Dev, but as far as the whole "octopus class" thing goes, can you not just supply an interface to the jar and connect the calls between the interface and the prefs manager at runtime, using the application configuration file to determine the prefs manager to instantiate?
Something like the .NET provider pattern?
That way you can decouple your jar from the prefs manager.

A: IMHO, I think that the answer to your first question is "yes" and "no".
Preferences are commonly handled as a centralized class, in the sense that the class is a "sink" for many classes in the project. Trying to do it closer to the calling code means that if the same preference is later useful elsewhere, you are in trouble. In my experience, trying to put the preferences "too close" also results in a very inconsistent handling.
That being said, it is often preferable to use multiple preference classes or "preference set", each supporting a module or submodule. If you look at the main components of your architecture, you will often find that the set of preferences can be logically partitioned. This reduces the mess in each preference class. More importantly, it will allow you to split your program into multiple jars in the future. Now, the "default value" calculators can be placed in the module but still in a global enough area.
I would also suggest not setting preferences directly as static methods, but rather using some getInstance() like  operation to obtain a shared instance of the preferences manage, and then operating on it. Depending on your semantics, you may want to lock that object for a while (e.g., while the user is editing preferences in a UI) and this is easier if you have an actual object.
For your other questions, I would say that your public API should have a way of letting users change preferences, but only if you can document well enough what the results of these changes could be.
If you use a single API function to get the "reference manager", you can give users the possibility of providing their own "default values calculator". The preference manager will ask this calculator first before resorting to the one you have provided by default.

A: You might want to look at Cocoa's NSUserDefaults class for inspiration.  It handles the problem you describe by having several layers of preferences, called domains.  When you look up the value for a key, such as "PrintUsingAllCaps", it first checks for a value in the user's local domain.  If it isn't found there, it can check the system-wide domain, or a network-level domain, and so on.
The absolute last place it checks is called the "Registration Domain", which is basically where hard coded defaults are supposed to go.  So, at any point in my code, I can write a preference into the registration domain, and NSUserDefaults will only serve that value if the user hasn't overridden it.
So, in your case, you could provide a method for classes to set a default value for a key before it accesses the (possibly) user defined value.  The preferences class doesn't have to know anything about the classes it is serving.
As somebody else suggested, if you need something more sophisticated, you could set a DefaultValueProvider callback object instead of a straight value.

A: I deleted my first answer since I misunderstood what the author was asking.
To actually address the actual question--it feels like your desire to place preferences (and the calculation of the default values) with the code that uses them makes sense.
Could you meet both requirements by using a preferences container class for each area that follows a pattern for that area, but having it register with a "Global" preference object collection?
Your global collection could do things like iterate over each set of preferences and reset it to defaults but your preferences themselves would still be locally defined and maintained so that it doesn't spider out into other parts of the code.
The only problem I can see is that if you allow the preference object to register itself when instantiated, you run the risk of trying to "reset to defaults" with some of the preferences not instantiated yet.
I suppose this could be fixed by having the main "preference" class instantiate all the others, then any piece of code could retrieve it's local preference object from the central one though a static getter.
This seems to be a lot like how some loggers work.  There is a central mechanism for maintaining log levels, output streams and such, but each class has it's own instance of a "log" method and logs to it.
I hope this was more on target.  Oh, I also agree with the accepted answer, don't ever make all your methods public static, always use a getter--you'll be glad you did some day.

A: The JSR-10 (java.util.prefs.*) API uses a factory method with a Class<?> parameter to create Preferences instances. That way the API can store preferences from different classes belonging to the same package in a single file.


text:
Q: PSR-2 compatible inline PHP tags in HTML templates PSR-2 doesn't mention anything that would apply to the use of inline php tags in HTML templates, yet the php-cs-fixer tool seems to have a standard for it.
This is my template file, before running php-cs-fixer on it:

            Link
<?php
if (! empty($subnav)) {
?>

<?php
    foreach ($subnav as $link) {
?>

<?=$link?>

<?php
    }
?>

<?php
}
?>

Link

Link

And after running php-cs-fixer fix views/ui/nav.php --level=psr2:

            Link
<?php
if (! empty($subnav)) {
    ?>

<?php
    foreach ($subnav as $link) {
        ?>

<?=$link?>

<?php

    }
    ?>

<?php

}
?>

Link

Link

This just looks wrong, so I must be missing something.

*

*Is there a correct way to write such inline PHP that will conform to PSR-2?

*Would there be anything wrong with using PHP's Alternative syntax for control structures? Again, no mention in PSR-2 and the php-cs-fixer doesn't seem to have any problem with them, but for some reason they feel a bit dirty!

A: As requested: comment posted as answer:
PSR only applies to PHP code, it doesn't have anything to say regarding inline HTML, because the HTML simply isn't PHP.
The output you get merely adds whitespace where, according to the standard, there should be whitespace
- New lines after an opening {
- lines after an { are indented using 4 spaces
- ...
That's why this:
<?php
if(!empty($subnav)){//note no spaces
?>

Will be changed to:
<?php
if (!empty($subnav)) {
    ?>

In your foreach code, you'll notice that the everything is already indented with 4 spaces, because the code is inside the if block.
Either way, if you're going to mix PHP into markup, it might be best to use the alternative, more template-friendly syntax:
<?php
if (!empty($subnav)):
?>
//markup
<?php
    foreach ($subnav as $link):
        //do stuff
?>
//markup
<?php
    endforeach;
endif;
?>

Note that the indentation of the closing tags will probably be altered still by php-cs-fixer. Maybe inlining the end<blockName>; like so:
<?php endforeach; ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if user meta field is empty in conditional else statement Hello all I have a custom post type set up for my wordpress site within this custom post type i have a meta box with about 11 meta fields that I have added programatically. What I would like to do is check if one of the fields (which i have programmed to be a radio box)has a value if it does i would like to display the value of the field. If not then i would like to echo out the word Available. This is what I have been trying so far:
<?php

 $consignment= get_post_meta($post->ID, 'availability', true);

if (empty ($consignment)) {
    echo "avaliable";
} elseif ($consignment > 1) {
    echo "$consignment";
}
?>

I would really appreciate the help.

A: Does this do the trick?
$consignment= get_post_meta($post->ID, 'availability', true);

if ($consignment == '') {
// code to run if the above is empty, eg.
  echo "avaliable";

} else {
    // else the code, eg.
    echo $consignment;
}


text:
Q: Moment - Get the start of day of the local time and add a different timezone Imagine that we have a timestamp, for example 1571140569 (Tuesday, 15 October 2019 11:56:09). I need to get the start, in this case Tuesday, 15 October 2019 00:00:00. Then i need to apply timezone, imagine "America/Lima" (GTM -7h), we want to show Tuesday, 14 October 2019 07:00:00
I use this code
  moment_timezone(1571140569).startOf("day").tz("America/Lima");

But doesn´t work. Return Tuesday, 15 October 2019 00:00:00.
So: Somebody know how can i get the start of timestamp  and then apply timezone?

A: Hope this helps you to get the output you are expecting.

const date = moment(moment.unix(1571140569).utc().startOf('day')).tz("America/Lima").format('LLLL');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.js"></script>


text:
Q: Form validation - Required one of many in a group In the project I'm working on at the moment I currently have three textboxes and I need to validate that at least one of the text boxes has been populated.
I've been reading into custom validation with Angular directives and I understand you can set the validity of an input in a directive's link function using the following:
ctrl.$parsers.unshift(function(viewValue) {
  // validation logic here
});

The problem I have is that I don't need to set an individual input's validity.. I need to invalidate the entire form if the criteria isn't met. I just wonder how to approach this?
I'm thinking maybe I should create a directive that's placed on the enclosing form itself and then make the form invalid?
I suppose I'm just looking for some guidance into how I should go about this because I'm a little unclear where to start - all the material I'm reading on custom validation seems to be for when you're validating a specific input as opposed to a set of conditions on a form.
I hope I've made myself clear! Thanks..

A: You can use ng-required to force the user to fill at least one field by checkingthe length attribute of the string.
You can do the following for example:
<form name="myForm">
            <input type="text" ng-model="fields.one" name="firstField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" />

            <input type="text" name="secondField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" ng-model="fields.two" />

            <input type="text" ng-model="fields.three" name="thirdField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" />

            <button type="submit" ng-disabled="!myForm.$valid">Submit</button>
</form>

See this working fiddle example for more details.
You can have more details about required vs ng-required by reading this question

A: There are several approaches and the best option depends on your exact requirements.
Here is one approach that I found to be generic enough and flexible.
By "generic" I mean it doesn't only work for text-fields, but also for other kinds of inputs, such as check-boxes.
It's "flexible" because it allows any number of control-groups, such that at least one control of each group must be non-empty. Additionally, there is no "spacial" constraint - the controls of each group can be anywhere inside the DOM (if required, it is easy to constrain them inside a single form).
The approach is based on defining a custom directive (requiredAny), similar to ngRequired, but taking into account the other controls in the same group. Once defined, the directive can be used like this:
<form name="myForm" ...>
  <input name="inp1" ng-model="..." required-any="group1" />
  <input name="inp2" ng-model="..." required-any="group1" />
  <input name="inp3" ng-model="..." required-any="group1" />

  <input name="inp4" ng-model="..." required-any="group2" />
  <input name="inp5" ng-model="..." required-any="group2" />
</form>

In the above example, at least one of [inp1, inp2, inp3] must be non-empty, because they belong to group1.
The same holds for [inp4, inp5], which belong to group2.

The directive looks like this:
app.directive('requiredAny', function () {
  // Map for holding the state of each group.
  var groups = {};

  // Helper function: Determines if at least one control
  //                  in the group is non-empty.
  function determineIfRequired(groupName) {
    var group = groups[groupName];
    if (!group) return false;

    var keys = Object.keys(group);
    return keys.every(function (key) {
      return (key === 'isRequired') || !group[key];
    });
  }

  return {
    restrict: 'A',
    require: '?ngModel',
    scope: {},   // An isolate scope is used for easier/cleaner
                 // $watching and cleanup (on destruction).
    link: function postLink(scope, elem, attrs, modelCtrl) {
      // If there is no `ngModel` or no groupName has been specified,
      // then there is nothing we can do.
      if (!modelCtrl || !attrs.requiredAny) return;

      // Get a hold on the group's state object.
      // (If it doesn't exist, initialize it first.)
      var groupName = attrs.requiredAny;
      if (groups[groupName] === undefined) {
        groups[groupName] = {isRequired: true};
      }

      var group = scope.group = groups[groupName];

      // Clean up when the element is removed.
      scope.$on('$destroy', function () {
        delete(group[scope.$id]);
        if (Object.keys(group).length <= 1) {
          delete(groups[groupName]);
        }
      });

      // Update the validity state for the 'required' error-key
      // based on the group's status.
      function updateValidity() {
        if (group.isRequired) {
          modelCtrl.$setValidity('required', false);
        } else {
          modelCtrl.$setValidity('required', true);
        }
      }

      // Update the group's state and this control's validity.
      function validate(value) {
        group[scope.$id] = !modelCtrl.$isEmpty(value);
        group.isRequired = determineIfRequired(groupName);
        updateValidity();
        return group.isRequired ? undefined : value;
      }

      // Make sure re-validation takes place whenever:
      //   either the control's value changes
      //   or the group's `isRequired` property changes
      modelCtrl.$formatters.push(validate);
      modelCtrl.$parsers.unshift(validate);
      scope.$watch('group.isRequired', updateValidity);
    }
  };
});

This might not be so short, but once included into a module, it is very easy to integrate into your forms.

See, also, this (not so) short demo.

A: modification to ExpertSystem's answer (https://stackoverflow.com/a/24230876/4968547) so that his code works in the latest angularjs.
i changed the updateValidity() to set parse also to true/false
function updateValidity() {
            if (group.isRequired) {
                modelCtrl.$setValidity('required', false);
                modelCtrl.$setValidity('parse', false);
            } else {
                modelCtrl.$setValidity('required', true);
                modelCtrl.$setValidity('parse', true);
            }
        }

now its working fine for me

A: It's too late but might be can save some one's time:
If there are only two fields, and want to make one of them required then
<input type="text"
      ng-model="fields.one"
      ng-required="!fields.two" />

<input type="text"
      ng-model="fields.two"
      ng-required="!fields.one"  />

If you have three like in question then
<input type="text"
      ng-model="fields.one"
      ng-required="!(fields.two || fields.three)" />

<input type="text"
      ng-model="fields.two"
      ng-required="!(fields.one || fields.three)"  />

<input type="text"
      ng-model="fields.three"
      ng-required="!(fields.one|| fields.two)" />

If more than this, I will suggest to write a function on scope and watch it.
See the working example

A: Ran into this same problem last week; ExpertSystem's solution was a good start, but I was looking for a few enhancements to it:

*

*Use Angular 1.4.3

*Use ngMessages

I eventually wound up with this example on JSFiddle - hope that helps inspire others in the same boat! Relevant JS code from the Fiddle:
var app = angular.module('myApp', ['ngMessages']);
app.controller('myCtrl', function ($scope) {
    $scope.sendMessage = function () {
        $scope.myForm.$submitted = true;

        if ($scope.myForm.$valid) {
            alert('Message sent !');
        }
    };
});

app.directive('requiredAny', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function postLink(scope, elem, attrs, ctrl) {
            // If there is no 'ngModel' or no groupName has been specified,
            // then there is nothing we can do
            if (!ctrl || !attrs.requiredAny) { return };

            // If this is the first time we've used this directive in this scope,
            // create a section for it's data. If you need / want to make use of
            // an isolate scope you'll need to make 'var groups' scoped to the directive;
            // but then you may want to look in to clearing out group entries yourself
            if (!scope.__requiredAnyGroups) {
                scope.__requiredAnyGroups = {}
            }
            var groups = scope.__requiredAnyGroups;

            // Create a bucket for this group if one does not yet exist
            if (!groups[attrs.requiredAny]) {
                groups[attrs.requiredAny] = {};
            }
            var group = groups[attrs.requiredAny];

            // Create the entry for this control
            group[attrs.ngModel] = {
                ctrl: ctrl,
                hasValue: false
            };

            ctrl.$validators.requiredAny = function(view, value) {
                var thisCtrl = group[attrs.ngModel],
                        ctrlValue = (typeof value !== 'undefined') && value,
                        oneHasValue = false;

                thisCtrl.hasValue = ctrlValue;

                // First determine if any field in the group has a value
                for (var prop in group) {
                    if (group.hasOwnProperty(prop) && group[prop].hasValue) {
                        oneHasValue = true;
                        break;
                    }
                }

                // Set the validity of all other fields based on whether the group has a value
                for (var prop in group) {
                    if (group.hasOwnProperty(prop) && thisCtrl != group[prop]) {
                        group[prop].ctrl.$setValidity('requiredAny', oneHasValue);
                    }
                }

                // Return the validity of this field
                return oneHasValue;
            };
        }
    };
});

A: You can add required attribute for each of them , and at the end , you can rely your validation on each/all/or just one of them
        <form name="form" novalidate ng-submit="submit()">
        // novalidate is form disabling your browser's own validation mechanism

          <input type="text" required ng-model="texts.text1">
          <input type="text" required ng-model="texts.text2">
          <input type="text" required ng-model="texts.text3">
          // you can do validation in variety of ways , but one of them is to disable your submit button until one of the textboxes are filled correctly like this :

          <button type="submit" ng-disabled="form.text1.$invalid && form.text2.$invalid && form.text3.$invalid"></button>

        </form>

This way if just one of them is filled , button will be enable
I don't know how you're gonna show that form is not valid , but I think desabling the submit button is the general way

A: Here is a refactored take on ExpertSystems great post.  I didn't need the destroy method so I gutted it.
I also added a grayed out explanation that may help in your code.  I use this directive for ALL my required fields.  Meaning when I use this directive I no longer use ng-required, or required.
If you want a field required just pass in a unique group name.  If you don't want the field required then pass in null, and if you want to have many different groups just pass in a matching group name.
I believe there is a little more refactoring that could be done here.  Angularjs states that when using $setValidity, that instead you should use $validators pipeline instead, but I could not get that to work.  I am still learning this complex animal.  If you have more info, post it!
app.directive('rsPartiallyRequired', function () {

 var allinputGroups = {};

 return {
   restrict: 'A',
   require: '?ngModel',
   scope: { },

   link: function(scope, elem, attrs, ctrl) {
     if( !ctrl || !attrs.rsPartiallyRequired ){ return } // no ngModel, or rsPartialRequired is null? then return.

    // Initilaize the following on load
    ctrl.$formatters.push( validateInputGroup ); // From model to view.
    ctrl.$parsers.unshift( validateInputGroup ); // From view to model.

    if ( ! allinputGroups.hasOwnProperty( attrs.rsPartiallyRequired )){ // Create key only once and do not overwrite it.
    allinputGroups[ attrs.rsPartiallyRequired ] = { isRequired: true } // Set new group name value to { isRequired: true }.
  }

    scope.inputGroup = allinputGroups[ attrs.rsPartiallyRequired ] // Pass { isRequired: true } to form scope.

    function validateInputGroup(value) {
    scope.inputGroup[ scope.$id ] = !ctrl.$isEmpty( value ); // Add to inputGroup ex: { isRequired: true, 01E: false }.
    scope.inputGroup.isRequired = setRequired( attrs.rsPartiallyRequired ); // Set to true or false.
    updateValidity(); // Update all needed inputs based on new user input.
    return scope.inputGroup.isRequired ? undefined : value
  }

    function setRequired(groupName) {
      if( ! allinputGroups[ groupName ] ){ return false } // No group name then set required to false.
      return Object.keys( allinputGroups[ groupName ] ).every( function( key ) { // Key is 'isRequired' or input identifier.
      return ( key === 'isRequired' ) || ! allinputGroups[ groupName ][ key ]
    });
  }

    scope.$watch('scope.inputGroup.isRequired', updateValidity); // Watch changes to inputGroup and update as needed.

    function updateValidity() { // Update input state validity when called.
      ctrl.$setValidity('required', scope.inputGroup.isRequired ? false : true );
    }
  }
 }
});

// This directive sets input required fields for groups or individual inputs.  If an object in the template is given
// to the directive like this:
// Object: { "name": "account_number", "attrs": { "required": { "group": "two"  }}}.
// HTML: <input type="text" rs-partially-required="{{ field.attrs.required.group }}" />
// Or anything where the evaluation is a string, for example we could use "groupOne" like this...
// HTML: <input type="text" rs-partially-required="groupOne" />
// Then this directive will set that group to required, even if it's the only member of group.
// If you don't want the field to be required, simply give the directive a null value, like this...
// HTML: <input type="text" rs-partially-required="null" />
// However, when you want to use this directive say in an ngRepeat, then just give it a dynamic string for each input
// and link the inputs together by giving the exact matching string to each group that needs at least one field. ex:

// <input type="text" rs-partially-required="null" />
// <input type="text" rs-partially-required="one" />
// <input type="text" rs-partially-required="two" />
// <input type="text" rs-partially-required="one" />
// <input type="text" rs-partially-required="null" />
// <input type="text" rs-partially-required="three" />
// <input type="text" rs-partially-required="three" />
// <input type="text" rs-partially-required="three" />

// In the above example, the first and fifth input are not required and can be submitted blank.
// The input with group "two" is the only one in the group, so just that input will be required by itself.
// The 2 inputs with "one" will be grouped together and one or the other will require an input before
// the form is valid.  The same will be applied with group "three".
// For this form to be valid, group "two" will be required, and 1 input from group one will be required,
// and 1 input from group three will be required before this form can be valid.

A: I had similar grouping requirement in my project and I wrote this.Interested people can use this
.directive('group',function(){
        return {
            require: '^form',
            link : function($scope,element,attrs,formCtrl){
                var ctrls =[];

                element.find(".group-member").each(function(){
                    var member = angular.element($(this));
                    var mdlCtrl = member.data("$ngModelController");
                    if(!mdlCtrl){
                        throw "Group member should have ng-model";
                    }
                    ctrls.push(mdlCtrl);
                });

                var errKey = attrs['name']+"GrpReqd";
                var min = attrs['minRequired'] || 1;
                var max = attrs['maxRequired'] || ctrls.length;

                $scope.validateGroup = function(){
                    var defined=0;
                    for(i=0;i<ctrls.length;i++){
                        if(ctrls[i].$modelValue){
                            defined++;
                        }
                    }
                    if(defined < min || defined > max){
                        formCtrl.$setValidity(errKey,false);
                    } else {
                        formCtrl.$setValidity(errKey,true);
                    }
                };

                //support real time validation
                angular.forEach(ctrls,function(mdlCtrl){
                    $scope.$watch(function () {
                          return mdlCtrl.$modelValue;
                       }, $scope.validateGroup);
                });

            }
        };
    })

HTML usage :

            <input type="text" class="form-control group-member" style="width:100%;" name="Field1" ng-model="data.myField"  />
            <input type="text" class="form-control group-member" style="width:100%;" name="Field1" ng-model="data.myField2"  />
            <input type="text" class="form-control group-member" style="width:100%;" name="Field2" ng-model="data.myField3"  />

Here group directive identifies the logical grouping. This directive sits on an element without ng-model, a div in the above example. group directive receives 2 optional attribute min-required and max-required. Group members are identified using group-member class on individual fields. Group members are supposed to have an ng-model for binding. Since group directive doesn't have an ng-model error will be emitted under yourForm.$error.CancellationInfoGrpReqd in the above case. Unique Error key is generated from the element name on which group directive is sitting with GrpReqd appended to it.


text:
Q: Custom WP_Query 'posts_per_page' is not working I'm having trouble with multiple posts showing when I've declared 'posts_per_page'.
During my research my code has developed but with still no results. I've tried
'ignore_sticky_posts' => 1, 'nopaging' => true (pagination)
switching theme and deactivating plugins. I can't seem to find the issue. Any help would be much appreciated. Here is the current result - alderneyfootball.co.uk
I have two loops on the page and it's a custom page template. I'm using the WP-Club-Manager Plugin
<?php
     // the query
     wp_reset_query();

     $wpb_next_game = array('post_type'=>'wpcm_match', 'post_status' => 'future', 's' => 'Alderney', 'posts_per_page' => 1 );

     $wpb_next_game = new WP_Query($wpb_next_game);
      if ( have_posts() ) : while ( $wpb_next_game->have_posts() ) : $wpb_next_game->the_post();

             $date = date_i18n( get_option( 'date_format' ), strtotime( $post->post_date ) );
             $time = date_i18n( get_option( 'time_format' ), strtotime( $post->post_date ) );
             $side = wpcm_get_match_clubs( $post->ID );

             // badge
             $badges = wpcm_get_match_badges( $post->ID, 'crest-medium', array( 'class' => 'home-logo' ) );
             $badges = wpcm_get_match_badges( $post->ID, 'crest-medium', array( 'class' => 'away-logo' ) );
             $format = get_match_title_format();
             if( $format == '%home% vs %away%') {
                $badge = $badges[0];
             } else {
                $badge = $badges[1];
             }
             ?>

<?php echo $side[0]; ?>

<?php echo $side[1]; ?>

Next Match at <?php echo $time; ?> on <?php echo $date; ?>

         <?php endwhile; ?>

     <?php else : ?>

<?php _e( 'Sorry, scheduled matches' ); ?>

     <?php endif; ?>

A: If the two loops data is overwridden then, i your first code wp_reset_query() is incorrect. If you are using WP_Query then
wp_reset_postdata() //remove wp_reset_query() which is used for wp_query()

should be used after the end of the WHILE loop which means that in your two loops you have to have
wp_reset_postdata()  // use this at both loops

at both loops in the end of the while loop.
Now you codes looks like this:
<?php

 $wpb_next_game = array('post_type'=>'wpcm_match', 'post_status' => 'future', 's' => 'Alderney', 'posts_per_page' => 1 );

 $wpb_next_game = new WP_Query($wpb_next_game);
  if ( have_posts() ) : while ( $wpb_next_game->have_posts() ) : $wpb_next_game->the_post();

         $date = date_i18n( get_option( 'date_format' ), strtotime( $post->post_date ) );
         $time = date_i18n( get_option( 'time_format' ), strtotime( $post->post_date ) );
         $side = wpcm_get_match_clubs( $post->ID );

         // badge
         $badges = wpcm_get_match_badges( $post->ID, 'crest-medium', array( 'class' => 'home-logo' ) );
         $badges = wpcm_get_match_badges( $post->ID, 'crest-medium', array( 'class' => 'away-logo' ) );
         $format = get_match_title_format();
         if( $format == '%home% vs %away%') {
            $badge = $badges[0];
         } else {
            $badge = $badges[1];
         }
         ?>

<?php echo $side[0]; ?>

<?php echo $side[1]; ?>

Next Match at <?php echo $time; ?> on <?php echo $date; ?>

     <?php endwhile;
     wp_reset_postdata();
        ?>

 <?php else : ?>

<?php _e( 'Sorry, scheduled matches' ); ?>

 <?php endif; ?>

Hope this works for you
Thank You

A: Perhaps your next loop takes query from previous.
Make sure you're using wp_reset_query() for query_posts and/or wp_reset_postdata() for wp_query
After each loop.

A: I was facing same issue. If you have added below in code then remove it and it will work for you.
wp_reset_postdata()

Thanks


text:
Q: Help understanding command line We are starting our Jenkins CI with the following bash command that I would like understand. Could someone explain what is doing (the only bit I get is "java -jar jenkins.war"). Thanks!
nohup java -jar jenkins.war > $HOME/jenkins.log 2>&1 < /dev/null &

A: nohup

detaches the following command from the current terminal session, which prevents the process from being closed on terminal exit.
java

then runs the java VM with the options
-jar jenkins.war

which tells java to run the main class from the jar-archive jenkins.war
>

forwards the standard output (what usually appears in the terminal) into the given file, in this case into $HOME/jenkins.log
2>&1

means that the optput of the error channel is connected to the output of the standard output channel.
< /dev/null

sends "nothing" as input stream to the java command.
Finally & forces the task into backgrount such that the control returns to the prompt.

A: The nohup means it will continue to run when you exit the shell.
The > means redirect the standard output to a file
The file it is being redirected to is $HOME/jenkins.log. You can find the value of $HOME by running echo $HOME
2>&1 means redirect standard errors to standard output, so in this example will also go into $HOME/jenkins.log.
The < /dev/null means read data in from /dev/null. So if the script is expecting input it will read that instead of waiting for user input.
And the & means run as a background task, and return you to the command line.
If you want more detail, ask in the comments.


text:
Q: Mule - mixing exchange patterns I am trying to understand what is going one when i mix exchange patterns.
If i call a vm request-response inbound endpoint with a ones-way outbound endpoint, there is no error but it appears as though the flow is never run for example:
    <flow name="main" doc:name="main" processingStrategy="asynchronous">
        <poll frequency="60000">
            <set-payload value="main"></set-payload>
        </poll>
        <set-variable value="xxx" variableName="var1"></set-variable>
        <logger level="ERROR" message="MAIN1 #[flowVars.var1]" />

        <vm:outbound-endpoint address="vm://vm" />
        <logger level="ERROR" message="MAIN2 #[flowVars.var1]" />
    </flow>

    <flow name="p1">
        <vm:inbound-endpoint address="vm://vm" exchange-pattern="request-response" />
        <logger level="ERROR" message="PRIVATE #[flowVars.var1]" />
    </flow>
</mule>

This configuration logs the following, but never prints 'PRIVATE xxx'.
ERROR 2014-03-26 13:22:35,794 [[test].main.stage1.01] org.mule.api.processor.LoggerMessageProcessor: MAIN1 xxx
ERROR 2014-03-26 13:22:35,812 [[test].main.stage1.01] org.mule.api.processor.LoggerMessageProcessor: MAIN2 xxx
INFO  2014-03-26 13:22:35,816 [[test].connector.VM.mule.default.dispatcher.01] org.mule.lifecycle.AbstractLifecycleManager: Initialising: 'connector.VM.mule.default.dispatcher.784920740'. Object is: VMMessageDispatcher
INFO  2014-03-26 13:22:35,817 [[test].connector.VM.mule.default.dispatcher.01] org.mule.lifecycle.AbstractLifecycleManager: Starting: 'connector.VM.mule.default.dispatcher.784920740'. Object is: VMMessageDispatcher
And if I mix them the other way around MAIN2 xxx never prints. Can someone explain what actually is going on here?

A: Mule docs state the following:

request-response:
When using request-response endpoints, messages are
delivered directly from an outbound vm endpoint to the inbound vm
endpoint that is listening on the same path. This delivery is blocking
and occurs in the same thread. If there is no inbound request-response
vm endpoint in the same Mule application listening on this path, then
dispatching of the message from the outbound endpoint will fail.
one-way:
When using one-way endpoints, messages are delivered to the
corresponding inbound endpoint via a queue. This delivery is
non-blocking. If there is no inbound one-way endpoint in the same Mule
application listening on this path, then, although dispatching of the
message will succeed, the message will remain in the queue. By
default, this queue is in memory, but it is also possible to configure
a persistent queue that will use the file system as its persistence
mechanism.

http://www.mulesoft.org/documentation/display/current/VM+Transport+Reference
I would guess the case with request-response outbound just remains waiting for a response, as the message gets dispatched and received contrary to the docs.

A: I don't mean to be rude, but It doesn't make sense to mix echange patterns this way. I believe one should never do something like this. In fact it's better to configure your exchange pattern on the vm endpoint globally, so that you have have consistent endpoints and you can't make mistakes.
<vm:endpoint name="vm-endp" path="vm-endp" exchange-pattern="request-response" />

<flow name="main" doc:name="main" processingStrategy="asynchronous">
    <http:inbound-endpoint exchange-pattern="one-way" name="http-endpoint" host="localhost" port="2003" path="mule" doc:name="HTTP"/>
    <set-variable variableName="var1"  value="xxx"  doc:name="XXX" />
    <logger level="INFO" message="MAIN1 #[flowVars.var1]" />
    <set-payload value="#[flowVars.var1]" />
    <vm:outbound-endpoint ref="vm-endp" />
    <logger level="INFO" message="MAIN2 #[flowVars.var1]" />
    <logger level="INFO" message="PAYLOAD #[message.payloadAs(java.lang.String)]" />
</flow>

<!-- flowVars are FLOW VARIABLES, hence they're not accessible from multiple flows -->

<flow name="flow">
    <vm:inbound-endpoint ref="vm-endp" />
    <logger level="INFO" message="PRIVATE #[flowVars.var1]" />
    <append-string-transformer message=" added to the payload" />
</flow>

It should output:
INFO [[VMtest].main.stage1.01] org.mule.api.processor.LoggerMessageProcessor: MAIN1 xxx
INFO [[VMtest].main.stage1.01] org.mule.lifecycle.AbstractLifecycleManager: Initialising: 'connector.VM.mule.default.dispatcher.1221995064'. Object is: VMMessageDispatcher
INFO [[VMtest].main.stage1.01] org.mule.lifecycle.AbstractLifecycleManager: Starting: 'connector.VM.mule.default.dispatcher.1221995064'. Object is: VMMessageDispatcher
INFO [[VMtest].main.stage1.01] org.mule.api.processor.LoggerMessageProcessor: PRIVATE null
INFO [[VMtest].main.stage1.01] org.mule.api.processor.LoggerMessageProcessor: MAIN2 xxx
INFO [[VMtest].main.stage1.01] org.mule.api.processor.LoggerMessageProcessor: PAYLOAD xxx added to the payload


text:
Q: Can't Install ffi -v '1.9.18' on macos Catalina Can't install specific ffi version. If I run gem install ffi, everything works just fine but I need specific version 1.9.18 and it doesn't work.
Fetching ffi 1.9.18
Installing ffi 1.9.18 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /Users/chille/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/ffi-
1.9.18/ext/ffi_c
/Users/chille/.rbenv/versions/2.6.5/bin/ruby -I
/Users/chille/.rbenv/versions/2.6.5/lib/ruby/2.6.0 -r
./siteconf20200928-22154-72wopi.rb extconf.rb
checking for ffi_call() in -lffi... yes
checking for ffi_prep_closure()... yes
checking for ffi_raw_call()... yes
checking for ffi_prep_raw_closure()... yes
checking for shlwapi.h... no
checking for rb_thread_blocking_region()... no
checking for rb_thread_call_with_gvl()... yes
checking for rb_thread_call_without_gvl()... yes
checking for ffi_prep_cif_var()... yes
creating extconf.h
creating Makefile

current directory: /Users/chille/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/ffi-
1.9.18/ext/ffi_c
make "DESTDIR=" clean

current directory: /Users/chille/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/ffi-
1.9.18/ext/ffi_c
make "DESTDIR="
compiling AbstractMemory.c
compiling ArrayType.c
compiling Buffer.c
compiling Call.c
Call.c:355:5: error: implicit declaration of function 'rb_thread_call_without_gvl' is
invalid in C99
[-Werror,-Wimplicit-function-declaration]
rbffi_thread_blocking_region(call_blocking_function, data, (void *) -1, NULL);
^
./Thread.h:78:39: note: expanded from macro 'rbffi_thread_blocking_region'
# define rbffi_thread_blocking_region rb_thread_call_without_gvl
                                  ^
1 error generated.
make: *** [Call.o] Error 1

make failed, exit code 2

Gem files will remain installed in

/Users/chille/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/ffi-1.9.18 for inspection.
Results logged to /Users/chille/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/extensions/x86_64-
darwin-19/2.6.0/ffi-1.9.18/gem_make.out
An error occurred while installing ffi (1.9.18), and Bundler cannot continue.
Make sure that gem install ffi -v '1.9.18' succeeds before bundling.
In Gemfile:
bootstrap-sass was resolved to 3.3.7, which depends on
sass was resolved to 3.5.5, which depends on
sass-listen was resolved to 4.0.0, which depends on
rb-inotify was resolved to 0.9.10, which depends on
ffi

A: On an M1 Catalina 11.6, I was able to get past the error by first doing:
bundle update ffi
Then because I did not care about which version:
gem install ffi -- --with-cflags="-Wno-error=implicit-function-declaration"
If you need a version, other answers have that.

A: To get past that error, install ffi using:
gem install ffi -v '1.9.18' -- --with-cflags="-Wno-error=implicit-function-declaration"

A: if you want bundle install ffi 1.9.8
bundle config --local build.ffi --with-cflags=-Wno-error=implicit-function-declaration

bundle install

A: For those who can, I think bumping ffi version should be preferred here. bundle update ffi took me from from 1.9.18 to 1.13.1 and built successfully for me.
@denis-osmerovic, unless you have another dependency holding ffi back, you should also be able to bump ffi. Checking my dependency chain, my ffi dependency is also coming from rb-inotify 0.9.10, same as yours. The listed requirement is for ffi (>= 0.5.0, < 2), so 1.13.1 should be acceptable.
Other background:
I previously had a working copy of ffi 1.19.18, and I don't remember needing to pass any special build flags. In order to reproduce this I uninstalled and tried to reinstall that version. I'm guessing other library or toolchain updates in the meantime broke this.
I am running ruby 2.6.3 on OS X 10.15.7 alongside Xcode 12.0.1

A: Due to the very nature of what the ffi gem does, it is tightly bound to the internals of the YARV engine. Therefore, you need to make sure you use a version of YARV that matches the version of the ffi gem.
In 2017, that would have been Ruby 2.4. Note that as of April 2020, Ruby 2.4 is no longer supported.


text:
Q: Getting PLS-00103 error while trying to write procedure in Oracle SQL Developer First off, if this code is absolutely butchered sorry. I am having trouble with some code for my database programming class. The point of the code is to make it so that if the last letter of a course name is in a certain range, it will automatically change the grades of everyone enrolled in that class to a certain grade. I put the code together essentially trying to substitute the relevant column names based off of an assignment I did on triggers as well as a very basic procedure the professor uploaded. When I run it I get a host of PLS-00103 errors stating "Encountered the symbol '([I get one for each of these] course/section/grades/if)' when expecting one of the following: :=;..." Between not being a programming major and losing a week of lecture due to COVID-19 I'm just stumped. Thank you for taking the time to look at it, and sorry again if it's riddled with mistakes. The code looks like:
CREATE or replace PROCEDURE grading AS
begin
DECLARE
    CURSOR grading_cursor
    IS SELECT student.student_id,
                course.course_name,
                section.section_id,
                grades.grade
       FROM student
    JOIN grades
    ON student.student_id   = grades.student_id
    JOIN section
    ON grades.section_id   = section.section_id
    JOIN course
    ON section.course_id   = course.course_id;

mycoursename VARCHAR(20) course.course_name%type;
    mySectionID number(10) section.section_id%type;
    myGrade varchar(20) grades.grade%type;

begin

    open grading_cursor;
    loop
        fetch grading_cursor
        into myFirstName, myLastName,myCourseName, mySectionID, myGrade
        if myCourseName is between '%a' and '%f' then
        then myGrade = 'A'
        elsif myCourseName is between '%g' and '%k' then
        then myGrade = 'B'
        elsif myCourseName is between '%l' and '%p' then
        then myGrade = 'C'
        elsif myCourseName is between '%q' and '%t' then
        then myGrade = 'D'
        elsif myCourseName is between '%u' and 'z' then
        then myGrade = 'E'
        EXIT WHEN grading_cursor%notfound;
        end loop;
    close grading_cursor;
end;

end;

A: Code you wrote would compile if it looked as follows:
CREATE OR REPLACE PROCEDURE grading
AS
   CURSOR grading_cursor
   IS
      SELECT student.student_id,
             course.course_name,
             section.section_id,
             grades.grade
        FROM student
             JOIN grades ON student.student_id = grades.student_id
             JOIN section ON grades.section_id = section.section_id
             JOIN course ON section.course_id = course.course_id;

   mystudent_id  student.student_id%TYPE;
   mycoursename  course.course_name%TYPE;
   mySectionID   section.section_id%TYPE;
   myGrade       grades.grade%TYPE;
BEGIN
   OPEN grading_cursor;

   LOOP
      FETCH grading_cursor
         INTO mystudentid,
              myCourseName,
              mySectionID,
              myGrade;

      EXIT WHEN grading_cursor%NOTFOUND;

      IF myCourseName BETWEEN '%a' AND '%f'
      THEN
         myGrade := 'A';
      ELSIF myCourseName BETWEEN '%g' AND '%k'
      THEN
         myGrade := 'B';
      ELSIF myCourseName BETWEEN '%l' AND '%p'
      THEN
         myGrade := 'C';
      ELSIF myCourseName BETWEEN '%q' AND '%t'
      THEN
         myGrade := 'D';
      ELSIF myCourseName BETWEEN '%u' AND 'z'
      THEN
         myGrade := 'E';
      END IF;
   END LOOP;

   CLOSE grading_cursor;
END;
/

What you did wrong was

*

*named PL/SQL procedures don't have DECLARE keyword

*variables that inherit datataype from a column can't have explicitly named datatype

*if cursor contains some set of columns, you can't fetch it into another (undeclared) set of variables (e.g. you aren't selecting first nor last name, but still fetch into those undeclared variables), while student_id is left out

*if requires end if

*you doubled all thens

*when setting variable's value, you have to use :=, not just =

*missing semi-colon ; command terminator in IFs

However, consider this - simpler - option:
CREATE OR REPLACE PROCEDURE grading
AS
   myGrade  grades.grade%TYPE;
BEGIN
   FOR cur_r
      IN (SELECT LOWER (SUBSTR (course.course_name, -1)) last_char
            FROM student
                 JOIN grades ON student.student_id = grades.student_id
                 JOIN section ON grades.section_id = section.section_id
                 JOIN course ON section.course_id = course.course_id)
   LOOP
      myGrade :=
         CASE
            WHEN cur_r.last_Char BETWEEN 'a' AND 'f' THEN 'A'
            WHEN cur_r.last_Char BETWEEN 'g' AND 'k' THEN 'B'
            WHEN cur_r.last_Char BETWEEN 'l' AND 'p' THEN 'C'
            WHEN cur_r.last_Char BETWEEN 'q' AND 't' THEN 'D'
            WHEN cur_r.last_Char BETWEEN 'u' AND 'z' THEN 'E'
         END;
   END LOOP;
END;

*

*it uses cursor FOR loop which is simpler as Oracle does a lot of thing s for you (opening the cursor, fetching from it, paying attention about exiting the loop, closing the cursor)

*I removed columns you don't use

*as you want to check the last character, that's what I really do. Checking whether something is between, with a wildcard %, isn't the best option

See if it helps.


text:
Q: How to upload multiple image with array? I have a form, How to insert in database one by one.For example :-
 <form method="post">
  <input type="file" name="img[]">
  <input type="file" name="img[]">
  <input type="file" name="img[]">
 </form>

A: if(isset($_POST['submit'])){
if(count($_FILES['img']['name']) > 0){
    //Loop through each file
    for($i=0; $i<count($_FILES['upload']['name']); $i++) {
      //Get the temp file path
        $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

        //Make sure we have a filepath
        if($tmpFilePath != ""){

            //save the filename
            $shortname = $_FILES['upload']['name'][$i];

            //save the url and the file
            $filePath = "uploaded/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];

            //Upload the file into the temp dir
            if(move_uploaded_file($tmpFilePath, $filePath)) {

                $files[] = $shortname;
                //insert into db
                //use $shortname for the filename
                //use $filePath for the relative url to the file

            }
          }
    }
}

this may help you


text:
Q: Why aren't all Shapefile vector features displayed correctly? I am a new user of QGIS 1.8.0. I do not display correctly SHP layer. When I want zooming layer so that half of the layer is outside the map window - display layer disappears. In the settings I can not find a way to stop this.
SHP layer is visible only when the complete layer fits in the map window.

Update:
The problem is solved. Viewing layers functioning incorrectly in layers containing. Qix file. If I leave only at layer shp, dbf and shx everything is fine. Qix I have to delete all the layers are displayed well.

A: Need to elaborate i think. Did you create the layer? Check scale dependent rendering in the properties panel under general and then tick it off.


text:
Q: How to make the functions run in a certain sequence in android programming? I'm a new android programmer, and recently I found some problem when programming.
In the main activity, there are three functions, a(), b(), c(), for example. So what can I do to make sure that c() will run after a() and b() are finished?
Like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    a();//get view
    b();//do sth for view like set text in text view

    //trigger.setOnClickListener(new OnClickListener() {
        //@Override
        //public void onClick(View v) {
        //  c();
        //}
    //});
    //this is using a button to call the function, but I want it run automatically after a() and b() finish
}

A: to be sure, create a new functions B() outside onCreate(). Then call C() at the end of B() and B() at the end of a()...

A: Try to create a(), b() and c() out of onCreate and call them in the order that you want like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    a();
    b();
    c();
}
private void a(){...}
private void b(){
...
trigger.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
      c();
    }
//});
}
private void c(){...}

if you have any async tasks then you will have to implementate the onPostExecute() method after every AsyncTask call

A: I've solve it by using runnable. I should make sure that the main thread only deal with the change of control


text:
Q: Postscript, EPS and PSTricks: what are the differences at this conditions? The program that I use as an editor for vector based images is able to export using the following standards:

*

*Postscript 2 and 3 ( .ps )

*PSTricks macro written in Latex ( .tex )

*Eps ( .eps )

*SVG ( .svg )

Now after using latex for some time I can't really say which one is better for a latex based workflow, but I have been able to write down some requirements, I need support for :

*

*static images only ( no need for animations at this point, also my final goal is always a pdf anyway )

*inclusion from external file ( I often use relative paths to organize everything in their own directories )

*usable in styles .sty files

*lightweight and easy to render in the final pdf ( sometimes latex creates some really hard-to-render images )

*easy to avoid aliasing / not prone to poor rendering

*text as path or text as text ( be able to incorporate the text from the image as "normal" text or viceversa )

*a format that copes well with layouts properties like margins, the center of each element, scaling, etc etc .

Since I'm not new to the imaging world and to the graphics world in general, I see Postscript as the old ancestor of pretty much anything that fits in a pipeline for the production of documents and vector images, I don't wanna sound like I have a biased opinion but probably PS works better for pdf production ? I don't know, I'm just thinking out loud. Anyway I'm more interested in the points I gave, especially the quality of the final product is everything to me.
As a special note I would like to know if latex uses an internal representation of a given vector image and what language is used for that.


text:
Q: Page number UI on Pagination on AngularJS Datatables I have configured this module on AngularJS angular-datatables and i have found out that there is a UI error when i try to hover on the page number on the lower right side of the table.. see pic

As you can see, when i try to hover on page 25, there is this grey square that will appear as i try to move to the next number (26) it will also move.
I have followed the file inclusion on the site. are there any files that i need to include? it does not state on the site that there are files i need to include other than what is being mentioned.
Added Inpect Detail:


text:
Q: Amazon SES failing after 25 API calls I am using PHP to send emails via Amazon SES. I am calling the API repeatedly in order to send around 1000 personalised emails. However, after every 25 calls to the API I receive the following error:
Fatal error: Uncaught exception 'Aws\Ses\Exception\SesException' with message 'Error executing "SendEmail" on "https://email.eu-west-1.amazonaws.com"; AWS HTTP error: cURL error 77: error setting certificate verify locations: CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 77: error setting certificate verify locations: CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' in phar:///home/robcowen/public_html/scripts/aws.phar/GuzzleHttp/Handler/CurlFactory.php:187 Stack trace: #0 phar:///home/robcowen/public_html/scripts/aws.phar/GuzzleHttp/Handler/CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 phar:///home/robcowen/public_html/scripts/aws.phar/GuzzleHttp/Handler/CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handl in phar:///home/robcowen/public_html/scripts/aws.phar/Aws/WrappedHttpHandler.php on line 159

I can't find any reference in the documentation to a limit. I have tried to delay my loop by either sleep(30) after each block of 20 API calls, or sleep(1) after each call. Neither works.
Does anybody have any ideas, please?

A: In my experience with such errors, it occurs when there's a multiple requests to read the file through socket, so at some point during the loop it cannot find the certificate and creates an error.
A bad way to fix it is to add sleep(1) before each call, to give it time to load the cert on each request.
A better way to fix it, is by sending a json list of 1000 users to the API or using a mailing list (I did it on other providers than SES though). One request, 1000 users, much more efficient and CPU friendly for both machines in interaction.


text:
Q: Disaster recovery plan - Having multiple servers I work in an organization where departments are in different buildings. I have a data centre in the main building. All the in-house applications connect to the SQL Server residing in the server in the main building datacenter.
Sometimes during weekends, if the network fails or the software throws a bug, it is very hard to come back to office and fix the problem.
It was suggested that a local machine be placed in one building (other than the datacenter) and install SQL Server on it. Have this SQL Server store the data first, and then replicate it on main datacenter every few minutes.
This will help in case the network gets disconnected with the main datacenter.
I would like to know if this the only solution we can adopt? What problems would we face with this strategy?

A: It sounds like what you're talking about is more aligned with High Availability.
If you are already on SQL Server 2012, or you have the ability to upgrade then it sounds like AlwaysOn Availability Groups could be right up your alley.  This is a technology that will allow you to create a cluster and you could have two geographically separate servers (i.e. your current database server and your remote database server that you're planning on standing up).  If the network latency isn't a performance impact between the two servers you could set up a two node cluster and have each of those nodes hosting a replica of the Availability Group (or Groups).  With synchronous commit, you could configure automatic failover when there is a network outage or some other service-hindering event.
By creating an Availability Group Listener you could have the client applications connecting to the listener which will direct traffic to the current primary replica.
If you don't have the ability to get onto SQL Server 2012 to leverage AlwaysOn Availability Groups, then Database Mirroring could also be another high availability solution for you.  If the session is operating synchronously with a witness server, you could also have the ability for automatic failover in the event of the principal becoming disconnected.
The reason I am recommending these two is two-fold: replication is pushing out articles, and it sounds like you want your entire database (or databases) to be ready for a failover.  Traditional failover clusters could also be another solution but you would have to also consider shared storage between the two nodes.  That might get complicated with the geographically separate servers.

if the network fails or the software throws a bug, it is very hard to come back to office and fix the problem.

What do you mean by "the software throws a bug"?  There will need to be the proper error handling and error recovery in order to ensure this type of behavior doesn't cause an outage.

A: This really doesn't sound like HA to me.  The database is still up, there's just a network problem between them.  HA on the network needs to be looked into.
You could resolve this on the SQL Server side of things by using either merge replication or peer to peer replication between the two SQL Servers.
I would start by resolving the network issues and the software bugs before I started working on things from the SQL Server side.


text:
Q: CUDA: Unable to copy character array from host to unified device memory using cudaMemcpyToSymbol I am pretty new to Cuda programming. I am trying to copy a character array from host to unified device memory. The code does not throw any error but shows the device's memory as blank lines.
int main(int argc, char **argv)
{
    int i = 0, n = 0;
    unsigned char * buff;
    char inp[512] = "abc";
    n = 10;

    while (i < n)
    {
         int num = i, size = 0;
         while(num > 0)
         {
             ++size;
             num /= 10;
         }
         size += strlen(inp);
         num = i;
         inp[size--] = '\0';
         while(num > 0)
         {
              inp[size--] = '0' + num%10;
              num /= 10;
         }
         size = strlen(inp);
         cudaMallocManaged(&buff, (size+1)*sizeof(char));
         cudaMemcpyToSymbol(buff, &inp, sizeof(inp), 0, cudaMemcpyHostToDevice);
         printf("%s\n", inp);
         printf("%s\n", buff);
    }

    cudaDeviceReset();
    return 0;
 }

This is the output of the above code:
abc

abc1

abc12

abc123

abc1234

abc12345

abc123456

abc1234567

abc12345678

abc123456789

Please help me out.

A: Here, the buff is allocated in the unified memory and is not a device symbol. Hence, in this context, we need to forget about device symbols.
Data in Unified memory can be accessed directly by the host as well as device as and when required. The device automatically fetches the desired data from unified memory without the need to explicitly moving data to the device memory.
The problem here can be solved by using memcpy instead of cudaMemcpyToSymbol. cudaMemcpyToSymbol is used to write data in device memory and not the unified memory.
cudaMemcpyToSymbol(buff, &inp, sizeof(inp), 0, cudaMemcpyHostToDevice);

should be replaced with
memcpy(buff, inp, size+1);

Thanks @talonmies for the suggestion.


text:
Q: How to pass value from one function to another Hello I want to pass value "valuey" from method veikia() to method
checkButtonClick(). I`m newby on Java so sorry if this question is already answered, because I do not understand:)
Have a nice day :)
Here is my code:
public class ListViewCheckboxesActivity extends Activity {

    MyCustomAdapter dataAdapter = null;
    PrekesDBController controller = new PrekesDBController(this);

    //private Context mContext;
    ScrollView sv;
    TextView infotext;
    CheckBox check;
    LinearLayout ll;
    Spinner spinner2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
       // mContext = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main123);

       // mContext = this;

        //Generate list View from ArrayList
        displayListView();

        checkButtonClick();

        veikia();

    }

  public String veikia() {
      ArrayList<HashMap<String, String>> data2 = controller.getpavadinimas();
      String valuey = "";
      for (int kl = 0; kl < data2.size(); kl++) {
          spinner2 = (Spinner) findViewById(R.id.spinner11);

          ScrollView sv = (ScrollView) findViewById(R.id.myscroll123);
          LinearLayout ll = (LinearLayout) findViewById(R.id.mylinearLayout123);

          LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          View view = inflater.inflate(R.layout.naujasuzsakymailist123, null);

          ll.addView(view);

          //sikna = int kl;
          Spinner jopapa = new Spinner(this);
          jopapa = (Spinner) findViewById(R.id.spinner11);
          jopapa.setId(kl);

          List<String> list = new ArrayList<String>();
          list.add("1");
          list.add("2");
          list.add("3");
          list.add("4");
          list.add("5");
          list.add("6");
          list.add("7");
          list.add("8");
          list.add("9");
          list.add("10");
          ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                  android.R.layout.simple_spinner_item, list);
          dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          jopapa.setAdapter(dataAdapter);
          valuey = String.valueOf(jopapa.getSelectedItem());
          System.out.println(valuey);
      }

     return valuey;
  }

    public void checkButtonClick() {

        Button myButton = (Button) findViewById(R.id.findSelected);
        myButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                StringBuffer responseText = new StringBuffer();
                responseText.append("The following were selected...\n");

                ArrayList<Country> countryList = dataAdapter.countryList;
                for(int i=0;i<countryList.size();i++){
                    Country country = countryList.get(i);
                    if(country.isSelected()){
                        responseText.append("\n" + country.getName());
                    }
                }

                Toast.makeText(getApplicationContext(),
                        responseText, Toast.LENGTH_LONG).show();

            }
        });

    }

}

A: Just pass the return value of veikia() to checkButtonClick() when you call it:
public String veikia() {
    ...
    return valuey;
}

// Added parameter valuey
public void checkButtonClick(String valuey) {
    ...
}

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    // Call checkButtonClick() with the parameter valuey returned from veikia()
    checkButtonClick(veikia());
}

A: Change the signature of your checkButtonClickmethod from:
public void checkButtonClick(){...}

to:
public void checkButtonClick(String myString) {
  // Use the value of myString here
}

And then on your onCreate method, instead of calling:
checkButtonClick();

veikia();

Call the functions in reverse order, like:
String valuey = veikia();
checkButtonClick(valuey)

EDIT:
In order to have access to valuey from inside a method you're overriding, like OnClickListener.onClick(View v) you will have to define valuey as a member variable. The final result would look something like this:
public class ListViewCheckboxesActivity extends Activity implements View.OnClickListener {

  private String valuey;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // ...
    valuey = veikia();
  }

  @Override
    public void onClick(View view) {
      // do something with valuey, for example print it to the logger
      Log.d("TAG", valuey);
  }
}


text:
Q: React formik partialy update initial values In my react component I have these two initial values
 const [initialValues, setInitialValues] = useState({
    name: 'Tom',
    age: 85,
  });

And I have a text field to change the values for the name field. And I have a button to change the age field.
If I type name as 'Jerry' and press that button to update the age It will update the age to 75 and reset the name 'Jerry' to 'Tom' again.
This is my code
Type Jerry in the text box and hit the button to see that it changes to the "Tom"
How do I fix this?
Anyhelp!
Thanks in advance! =)

A: You cannot reset form values like that to initial values.
What you need to do is to use method resetForm() from Formik form ref.
You provide only once what are initial values, and reset when ever you need to.
I forked your codesanbox and modified code.
https://codesandbox.io/s/formik-re-render-initialvalues-forked-i84sy
Here are parts of the code related to what you need to do
import React, { useState, useRef } from "react";
...

const Page = () => {
  const formikRef = useRef();

  const setValues = () => {
    console.log("hh");
    setInitialValues({ ...initialValues, age: 75 });
    formikRef.current.resetForm();
  };
  ...
  return (
    <div>
      <button onClick={setValues}>API Call</button>

      <Formik
        ref={(ref) => {
          formikRef.current = ref;
        }}
        initialValues={initialValues}
        onSubmit={submit}
        validationSchema={validationSchema}
        enableReinitialize
      >
        ...
      </Formik>
    </div>
  );
};

EDIT
I added one more part that covers modifying initial values. First you need to set initialValues and than do formikRef.current.resetForm().
NOTE
If you upgrade Formik to 2.x.x ref is changed to innerRef:
<Formik
  innerRef={(ref) => {
    formikRef.current = ref;
  }}
></Formik>;


text:
Q: sublimegdb can not stop in the breakpoint I hava install sublimeGDB in my sublime text 2, and my setting is right.
Then I press F9 in a line to set a breakpoint. When I press F5 to run, I found my program can not stop on the breakpoint, and the program finished running.
The information show below is "GDB session ended". The GDB view is appear in just 0.5 sec., and then disappear.

A: You have to compile your executable with debug information included by adding -g option to the GDB command line which is not being added by default by Sublime Text C++ build system. Check this answer for more details how to do it.


text:
Q: Prove $G$ is Abelian if $N$ is in the centre of $G$ and $G/N$ is cyclic I need some help on this one.

$G$ is a group. If $N$ is a subgroup of $G$ contained in the centre of $G$ and $G/N$ is cyclic, show that $G$ is Abelian.

My attempt is only half way and stuck at the bit at the end...

If $G$ can be shown to be cyclic, then it is Abelian, since $G=<g>$ then $g_1,g_2 \in G$ are $g_1=g^n,g_2=g^m$ for some $n,m$ and $g_1g_2=g^ng^m=g^{n+m}=g^{m+n}=g_2g_1$.
By definition of a centre of $G$, $\forall n \in N$, $gn=ng$ for any element in $G$. Namely, $N$ must be a normal subgroup.
  (Here, I pondered if I should just proceed or change gears to looking at homomorphisms of $G$ since $N$ is normal).
Now $G/N$ is cyclic so $G/N=<gN>$ for some $g \in G$. Then, $\forall g'N \in G/N$ there is some $m$ so that $(gN)^m=g^mN=g'N$. Therefore, for the representative elements of $G/N$, I have $g^m$.

Here I get stuck. So if $g'N$ then I have that each $g'$ is cyclic but as an equivalent class, I cannot guarantee that all $g'$ can be represented in the form $g^m$. The only thing I can guess is the canonical map $p:G \to G/N$ that might be relevant to solving this but again, I don't know how specifically it would help.
Does anyone know how to solve this?

A: $G/Z(G) \cong (G/N) / (Z(G)/N) $ is a homomorphic image of the cyclic group $G/N$ and so is cyclic.
It is well known that if $G/Z(G)$ is cyclic then $G$ is abelian.

A: Hint: don't try showing $G$ is cyclic. Rather, suppose $gN$ is a generator for $G/N$, so for every $x\in G$ there exists $n$ such that $xN=g^mN$, that is, there exist $m$ and $x'\in N$ with $x=g^nx'$. So, if $x,y\in G$, you can write $x=g^mx'$ and $y=g^ny'$. Consider $xy$ and $yx$…

A: Your approach is doomed to failure, because you're trying to show that the group $G$ is cyclic, and this does not follow from the hypotheses.  Indeed, take $G=C_2\times C_2$; then we have a normal subgroup $C_2\subset G$ that is contained in the centre of $G$ (since $G$ is abelian) and $G/C_2=C_2$ is cyclic.  But $G$ is not cyclic.
I'm not going to tell you how to do this question, since it'll be better for you if you work it out on your own, but try to keep this example - and other similar ones - in mind when you investigate the question.

A: $(1) \ \langle xN \rangle = G/N$ for some $x \in G$.
$(2)$ Let $aN, bN \in G/N$ then $aN = (xN)^j, bN = (xN)^k$
$(3)$ Since $N$ is normal $(xN)^j = x^jN$ and $(xN)^k = x^kN$
$(4)$ Now $aN = x^jN \Rightarrow a = x^jn_1$ anf $bN = x^kN \Rightarrow b = x^kn_2$ for some $n_1, n_2 \in N$
$(5)$ Now show $ab = ba$ using these representations and the fact that $n_1, n_2$ commute

A: $G/N$ cyclic means everything in $G$ may be written in the form $g^m h$ for some $h\in N$. Combine this with the fact $N$ is contained in the centre to show $(g^a x)(g^b y) = (g^b y)(g^a x)$.


text:
Q: Jquery data attribute change and affect CSS I'm using a data attribute in my css however when I change it via jquery it's not changing on screen on in the dom.

$('#new-1').data('count', 5);
.fa-stack[data-count]:after {
  position: absolute;
  right: -20%;
  top: -20%;
  content: attr(data-count);
  font-size: 90%;
  padding: .4em;
  border-radius: 999px;
  line-height: .75em;
  color: white;
  background: rgba(255, 0, 0, 1);
  text-align: center;
  min-width: 1.5em;
  font-weight: bold;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

A: $('#new-1').attr('data-count', 5);

A: If you check JQuery's documentation on this link
https://api.jquery.com/data/
it clearly states

Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.

Hence you should use the .attr("key", value); function.
The code would be
$('#new-1').attr('data-count', 5);


text:
Q: Using AngularJS inside Rails framework. "ng-repeat" is working, but "ng-submit" is not
My data is being displayed from the controller. "ng-repeat" works fine when displaying the data, but "ng-submit" is not adding new data to the model using the following code:
pages.js.coffee

  @PagesController = ($scope) ->
   $scope.entries = [
     {name:"Larry"}
     {name:"Curly"}
     {name:"Mo"}
     {name:"Ralph"}
    ]

    $scope.addEntry = ->
     $scope.entries.push($scope.newEntry)
     $scope.newEntry = {}

index.html.erb

Angular & Rails

    <form ng-submit="addEntry">
      <input type="text" ng-model="newEntry.name">
      <input type="submit" value="Add">
    </form>

        {{entry.name}}

A: function have to execute it, so addEntry() should solve it.


text:
Q: Magento2 SOAP API for multi-store Background:
I am planning to use Magento2 web-service using SOAP. This will be for Mobile App where customer are allowed to add to cart then checkout.
The store will be a multi-store website where the customer can easily change the store of their choice.
Question:
To initialize quote / empty cart, we can use web-service:
http://magento210.dev/soap/?services=quoteGuestCartRepositoryV1
but this doesn't have storeId as an input request (unlike Magento1)
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:def="http://magento210.dev/soap/default?services=quoteGuestCartManagementV1">
   <soap:Header/>
   <soap:Body>
      <def:quoteGuestCartManagementV1CreateEmptyCartRequest/>
   </soap:Body>
</soap:Envelope>

Since website will be multi-store one, store_id of quote needs to be updated as they switch the store. The following questions remain unanswered for me:

*

*How will we update the store_id of a quote?

*OR How can we add to cart as per store?

A: See our dev docs page for SOAP.  Works the same in REST to.  the store code is an optional URL parameter, we assume 'default' store code.
So for API's baseurl let's Magento know which website the API impacts.
Store code is part of the API's url, it's optional and we assume default
There's a special store code 'all' so catalog operations work just like using the admin panel GUI (extensible object to define which store views that product shows up in) or you can do individual catalog calls per store view (if you're doing different languages in each store view/etc).

*

*Soap:  http:///soap/...

*Rest:  http:///rest/...


text:
Q: $outputstring error with html class So I'm not that great at php and I have a basic comment system that I'm trying to implement that calls and writes to a comments.php file.
everything works all well an good until I try and style the $outputstring a bit.
this is the code I have
$outputstring = "

Name: " .$name. "

Comment:" .$message. "

";

I know whats causing it is the

but can anyone tell me why?
the script I got was just one off youtube while im experimenting with site building.
the full script is like this.
<?php
$act = $_POST['act'];
if($act == "post") {
$name = $_POST['name'];
$message  = $_POST ['message'];
@$fp = fopen("comments.php", 'a');
if (!$fp) {
    //The file could not be opened
    echo "There was an error! Please try again later!";
    exit;
} else {
    //The file was successfully opened, lets write the comment to it.
    $outputstring = "

Name: " .$name. "

Comment:" .$message. "

";

    //Write to the file
    fwrite($fp, $outputstring, strlen($outputstring));

    //We are finished writing, close the file for security / memory management purposes
    fclose($fp);

    //Post the success message
    echo "Your post was successfully entered. Click here to continue.";
}
} else {
//We are not trying to post a comment, show the form.
?>

comments:

<?php include("comments.php"); ?>

Post a comment:

<form action="index.php" method="post">
Name:
<input type="text" name="name" value=""></input>

Comment:
<textarea name="messages"></textarea>
<input type="hidden" name="act" value="post"></input>

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

If anyone could tell me what I would need to do to be able to add the span with a class that would be swell.
thanks.

A: You cannot use double quotes inside double quotes until you escape them with backslashes, in this case use single quotes instead like this
$outputstring = "

Name: " .$name. "

Comment:" .$message. "

";

A: $outputstring = "

Name: " .$name. "

Comment:" .$message. "

";

This line is wrong because you break your line delimiters.
Use simple quotes instead of double quotes for the class attribute :
$outputstring = "

Name: " .$name. "

Comment:" .$message. "

";

Or, as stated by chandresh_cool, escape your double quotes.

A: $outputstring = '

Name: ' .$name. '

Comment:' .$message. '

'; This should solve your problem use '' when you don't have dynamic values.


text:
Q: How to find out whether child widget of QScrollArea is visible? I am displaying multiple QLabels on a QFrame, placed into a QScrollArea.
I am able to tell QScrollArea to make any of the QLabels visible with QScrollArea.ensureWidgetVisible(QLabel), but I cannot seem to find a method to find out whether the child widget is currently visible or not. I would expect something like QScrollArea.isWidgetVisible(QWidget).
I tried using the child's own method, i.e. QLabel.isVisible() but no matter whether the QLabel is visible or not in the QScrollArea, it always returns True (see example below). What's the solution to this?
#!/usr/bin/env python

import sys
from PyQt4 import QtGui, QtCore

application = QtGui.QApplication(sys.argv)

class Area(QtGui.QScrollArea):

    def __init__(self, child):
            super(Area, self).__init__()
        self.child = child
        self.setWidget(self.child)
        self.setFixedSize(100, 100)

class MainWidget(QtGui.QFrame):

    def __init__(self, parent=None):
            QtGui.QFrame.__init__(self, parent)
        self.layout = QtGui.QVBoxLayout()
        n = 1
        while n != 10:
            label = QtGui.QLabel('<h1>'+str(n)+'</h1>')
            self.layout.addWidget(label)
            n += 1
        self.setLayout(self.layout)

    def wheelEvent(self, event):
        print "Wheel Event:"
        for child in self.children()[1:]:
            print child.isVisible()
        event.ignore()

mainwidget = MainWidget()
area = Area(mainwidget)
area.show()
application.exec_()

A: isVisible is different from what you want to do. It tells whether the widget is hidden or not. Even though it is not in the viewport a widget is visible unless you hide it.
You could use visibleRegion. It is the region of the widget that paint events should occur. If the label is outside of the viewport, then it's region should be an empty region.
def wheelEvent(self, event):
    print "Wheel Event:"
    for child in self.children()[1:]:
        print child.text(), 'is visible?', not child.visibleRegion().isEmpty()
    event.ignore()

A: QScrollArea::ensureWidgetVisible would do.
You can use QSCrollArea::childAt ( int x, int y ).isvisble() for checking widget visibility.


text:
Q: Converting string to integer and vice versa in Python I have a string for example
>>> sample = "Hello World!"

What I want to make a function which can convert sample to int. I know about chr() and ord(). I've used this so far:
For String to Int
>>> res="".join([str(ord(char)) for char in sample])
>>> print(res)
72101108108111328711111410810033

Now the problem arise. How can I convert res back to sample. Any suggestion would be appreciated.
Note: sample string can also have unicode characters in it
Edit :
nchars=len(sample)
res = sum(ord(sample[byte])<<8*(nchars-byte-1) for byte in range(nchars)) # string to int
print(''.join(chr((res>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))) #int to string

I found this solution but this is very slow do someone know to improve this

A: I am saving the num seperated by " " so it is possible to go back through convert it easier
This works and is simple:
i = "Hello World"
num = ""
for char in i:
    num += str(ord(char))+" "

print(''.join(num.split()))

back = ""
for n in num.split():
    back += chr(int(n))

print(back)

output:
721011081081113287111114108100
Hello World

A: sample = "Hello World!"
d1={k:str(ord(v)) for k,v in list(enumerate(sample))}
''.join(d1.values())
'72101108108111328711111410810033'
res1="".join([chr(int(char)) for char in d1.values()])
res1
'Hello World!'

In order to avoid the problem of which ord(chr) belongs to which chr? we need a mapping like data structure and dict is the best to store the each string and assign them to unique key using enumerate which will generate the keys on fly.
Our d1 looks like this:
{0: '72',
 1: '101',
 2: '108',
 3: '108',
 4: '111',
 5: '32',
 6: '87',
 7: '111',
 8: '114',
 9: '108',
 10: '100',
 11: '33'}

then comes the easy part converting the string values to int and applying chr on it to convert back into string.
Since OP donot want to use multiple variables or data structures.
sample = "Hello World!"
l_n=[str(ord(i))+str(ord('@')) for i in list(sample)]
text="".join(l_n)
n_l=[chr(int(i)) for i in text.split('64') if i.isnumeric()]
''.join(n_l)

The problem is we need to know where to apply char so I've added an extra @ to each letter so that it would be easy to convert it back


text:
Q: How to call 2 jQuery functions on change in dropdownlist? I have a simple dropdownlist with a scrollto jQuery onchange (it brings you to a specific place on the website). If one specific selection from the list is clicked, I want to call a change function in jQuery that will show a hidden div element (and will hide it again when an other selection is made after). I manage to get them working separately but not together. Is it possible to have both functions working in the same dropdownlist? I'm quite new to this.
My code parts are as follows:
<select id="dropdownlist">
<option value="one">Scroll to place 1</option>
<option value="two">Scroll to place 2</option>
<option value="three">Show hidden div</option>
</select>

scollto jQuery:
<script>
$(document).ready(function(){
$("#dropdownlist").on('change',function(){
var project = "#" + $(this).val();
$.scrollTo($(project), 1100);
});
});
</script>

show / hide jQuery (seen in this example: http://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-selectbox):
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="three"){
$(".box").hide();
$(".three").show();
}
});
}).change();
});
</script>

CSS:
.box { display: none; }
.three{ background: #FFF; }

Thank you in advance for thinking along!

A: I initiallly said: break the actions out into two functions and call the functions from your onchange based on the selection of the dropdown - but you really don't even need to do that if you won't be reusing them, just include an if statement in your onchange to complete the desired action:
$(document).ready(function(){
    $("#dropdownlist").on('change',function(){
        if ($(this).val() == "three") {
            $(".box").hide();
            $(".three").show();
        } else {
            var project = "#" + $(this).val();
            $.scrollTo($(project), 1100);
        }
    });
});


text:
Q: Rails4 create a one to many relationship no need to add references in Migration? This is my Migration code:
    create_table :ploys do |t|
      t.string :name, null: false

      t.references :user

      t.timestamps
    end

Then i run this command:
rake db:migrate

Then i check my database structure
But i not seen  foreign key and refercences
I use rails4 and mysql

A: That's because rails by default don't create the foreign keys, you can use the gem: foreigner to do this. and then add to your migration code:
 add_foreign_key(:ploys, :users)

The references only will create the foreign_key column (user_id) on the database. Take a look at: Active Record and Referential Integrity


text:
Q: Assign variable value to div This is my JavaScript code:
$("#rate").live('blur', function(){
    var rate=$(this).val();
    var qty =$('#quantity').val();
    var amt=rate*qty;
    alert(amt);
    document.getElementById("amount").innerHTML = amt;
});

Here I am getting the correct amount in amt variable . Now I just want to assign it to amount div. So how do I do that?

A: Which version of jquery you are using. If it's greater than or equal to the version 1.9 , than the live function will not work. If so than use .on function instead. use the code be low
$("#rate").on('blur', function(){
    var rate=$(this).val();
    var qty =$('#quantity').val();
    var amt=rate*qty;
    alert(amt);
    document.getElementById("amount").innerHTML = amt;
});

Hope this helps you

A: Hudixt's answer is right, however you'll need to parse the values as int (or float) if they are coming from inputs of a text type, as they are strings. i.e
$("#rate").on('blur', function(){
    var rate=$(this).val();
    var qty =$('#quantity').val();
    var amt= parseInt(rate) * parseInt(qty);
    alert(amt);
    document.getElementById("amount").innerHTML = amt;
});

Trying to multiply two strings with give you a NaN

A: Try this:
$('#amount').text(amt);

instead of:
document.getElementById("amount").innerHTML = amt;

A: $("#amount").html(amt);  //in jquery

document.getElementById("amount").value = amt; //in Javascript

A: You should user setAttribute method. There is my solution for your case :
$("#rate").live('blur', function(){
 var rate=$(this).val();
 var qty =$('#quantity').val();
 var amt=rate*qty;
 document.getElementById("amount").setAttribute('amt',amt);
});

To get attr :
var amt = document.getElementById("amount").getAttribute('amt');


text:
Q: sqldatareader which must be closed error but it has not been used? All,
This is my code:
Public Class frmFindRoute
    Private Sub frmFindRoute_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim cmdroad As SqlCommand
        Dim sdrroad As SqlDataReader

        cmdroad = conRouteMapping.CreateCommand
        cmdroad.CommandText = "Select title, uniqueref from road order by title"

        sdrroad = cmdroad.ExecuteReader
        PopulateListviewHeaders(lvwFromRoad, 1, sdrroad)
        PopulateListview(lvwFromRoad, sdrroad)
        sdrroad = cmdroad.ExecuteReader
        PopulateListviewHeaders(lvwToRoad, 1, sdrroad)
        PopulateListview(lvwToRoad, sdrroad)
        sdrroad.Close()
    End Sub

    Private Sub cmbFind_Click(sender As Object, e As EventArgs) Handles cmbFind.Click
        Dim cmdLanes As SqlCommand
        Dim sdrLanes As SqlDataReader

        cmdLanes = conRouteMapping.CreateCommand
        cmdLanes.CommandText = "Select direction, number,uniqueref from lane where roadref='" & lvwFromRoad.SelectedItems(0).SubItems(1).Text & "'"
        sdrLanes = cmdLanes.ExecuteReader
        sdrLanes.Read()

        FindRoute(sdrLanes.GetValue(2))
    End Sub

    Private Sub FindRoute(ByVal LaneRef As Guid)
        Dim cmdDestRoad As SqlCommand
        Dim sdrDestRoad As SqlDataReader
        Dim cmdNextJunction As SqlCommand
        Dim sdrNextJunction As SqlDataReader

        cmdDestRoad = conRouteMapping.CreateCommand
        cmdDestRoad.CommandText = "Select roadref from lane where uniqueref='" & LaneRef.ToString & "'"
        sdrDestRoad = cmdDestRoad.ExecuteReader ' << error here
        If sdrDestRoad.GetValue(0) <> lvwToRoad.SelectedItems(1).SubItems(0).Text Then
            cmdNextJunction = conRouteMapping.CreateCommand
            cmdNextJunction.CommandText = "Select tolane from junction where fromlane='" & LaneRef.ToString & "'"
            sdrNextJunction = cmdNextJunction.ExecuteReader
            Do While sdrNextJunction.Read
                'FindRoute(sdrNextJunction.GetValue(0))
            Loop
            sdrNextJunction.Close()
        End If
        sdrDestRoad.Close()
    End Sub
End Class

Where I've marked "error here" I get the error:

There is already an open DataReader associated with this Command which
  must be closed.

I don't know why? I've already verified that cmdDestRoad and sdrNextJunction aren't used anywhere else in the solution. The data readers in form_load and find_click work fine.
I've also used breakpoints to confirm that it fails the first time it runs this section of code.

A: Mary's answer was correct. You can not have two open readers on a connection. I can't accept it as answer as it's a comment.
The line
sdrDestRoad = cmdDestRoad.ExecuteReader

Fails because a reader is already opened with the following line in cmbFind_Click:
sdrLanes = cmdLanes.ExecuteReader

The lines:
cmdDestRoad = conRouteMapping.CreateCommand
        cmdDestRoad.CommandText = "Select roadref from lane where uniqueref='" & LaneRef.ToString & "'"

are not part of the problem. Opening a second command on the connection didn't cause the error. Trying to open a second reader did.


text:
Q: Whats does -- do exactly I was doing a simple if(left(cells IN NUMBER FORMAT);things;otherthings) formula and it was not working. I evaluated it and it turns out the left was returning "7" instead of 7. It bugs me.
I have double checked and even converted the range to number multiple times. Still return the number as string.
I don't understand why I need the --left() which from my understanding was turning the value of a string into number if possible otherwise return error.
There has to be something I'm missing.
SWITCH(--left(cell IN NUMBER FORMAT);6;things;7;otherthings;otherotherthings)

Without -- It will always take the otherotherthings route. With it works fine.
Can share the WB if required.
I'm contesting the duplicate. I'm not converting a bool to a number, and if I am i'd like to know exactly why my function is working and how LEFT(cell) can return a boolean.