text:
Q: Jupyter Basemap and Cartopy Issues I installed anaconda3-5.0.1 by pyenv. And I executed conda create -n obspy python=3.6.4 anaconda to make environment "obspy" use obspy.
I tried to use obspy along with http://docs.obspy.org/packages/obspy.clients.fdsn.html#module-obspy.clients.fdsn in Jupyter. And I executed cat.plot() the error Neither basemap nor cartopy could be imported. has occurred.
Basemap and Cartopy are already installed, and when the same commands are executed in command line they work well. I thought packages that were installed by conda command were not reflected the environment of Jupyter.
How can I reflect the environment of "obspy" to that of jupyter?

A: Make sure to have Jupyter (and basemap) installed in the obspy environment and make sure you start Jupyter Notebook from that same environment.
Usually these kind of problems arise from not all packages being present in the very same environment.


text:
Q: Objectify: how "session cache" works across instances From the caching documentation: https://github.com/objectify/objectify/wiki/Caching
The session cache is local to the Objectify instance. If you start a new session (via ObjectifyFactory.begin()), it will have a separate cache. If you use the thread-local ObjectifyService.ofy() method, the session cache will "just work" appropriately.

and
A get-by-key operation (single or batch) for a cached entity will return the entity instance without a call to the datastore or even to the memcache

My question is:
Request 1 is served by Instance A: an Object is updated and persisted. The session cache will be updated due to the object has been modified.
Request 2 is served by Instance B (which have already the Object in session cache due to a previous request): the session cache will be differente because it is another instance.
How can the request get the updated entity instead of the previous one?
The App Engine memcache is shared across instances, but the session cache is single per instance (or even Objectify instance).
Is the session-cache synchronized among all the instances in some way?
Is it possible that differente requests served by different instances can have different versions of the same object?

A: An objectify session is short lived and defines its own scope. It prevents multiple datastore gets for the same entity in disparate parts of your code by using memory, on the assumption that extra calls are typically wasteful.
If you require read/write consistency then you must use an idempotent transaction (which won't share the session cache and also does dirty checking and automatically retries).
By reading, mutating, then writing within the transaction you always avoid the issue of what could be happening in other requests (on other instances or otherwise)
Objectify sessions are not by default shared, and definitely shouldn't be. They are not synchronized across requests or instances. You can use memcache by putting @Cache on an entity to enable the write through cache, but this is distinct from the ofy session.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript RegEx, check if string contains * symbol and follows a set of specific rules I haven't found anything regarding this problem yet so I'm asking here.
Our teacher gave us a RegEx exercise in JavaScript, we're supposed to apply these rules to user password creation:

*

*Password begins with the character P

*Password must contain one or more lowercase letters, one or more uppercase letters and one or more numbers

*Password must contain one * symbol
I tried to check whether the star is inside the text or not, by searching for P, then 1 or more symbols in [a-zA-Z0-9], then the * symbol and then 0 or more symbols in [a-zA-Z0-9] OR the other way around.
const pw_check = /P([a-zA-Z0-9]+\*[a-zA-Z0-9]*|[a-zA-Z0-9]*\*[a-zA-Z0-9]+)/;
console.log(pw_check.test("Ppassw1*")); // outputs true, shouldn't (it rather isn't wanted)
The issue with this is that it allows passwords with no capital letters (other than P). I'm guessing the same issue would arise if there weren't any digits or lowercase letters.
This is the closest I've got to solving this problem without the pattern getting too long. I've been pulling my hair out trying to solve this problem for a couple of hours now, reading JS regex documentation wasn't much helpful. Perhaps I'm just a little bit simple for this.
Any help is greatly appreciated, thank you in advance.


text:
Q: Cross origin error when using cloud functions in back4app Getting CORS error when calling cloud function in back4app.

Error:

Access to XMLHttpRequest at
 'https://parseapi.back4app.com/functions/hello' from origin
  'http://localhost:8100' has been blocked by CORS policy: No 'Access-
   Control- Allow-Origin' header is present on the requested resource.
In client code cloud function implemented in home page

 home.page.ts:

 Parse.Cloud.run('hello').then(function (ratings) {

   console.log("updated");

 }).catch((error) => {

   console.log(error);

   console.log("fail");

 });

 Cloud function:

In back4app added main.js file with cloud code implementation

  main.js:

 Parse.Cloud.define('hello', function(req, res) {

   Parse.Cloud.useMasterKey();

   return 'Hi';
 });

A: It can be related to the Parse Server version.
Can you please take a look to check what is the Parse Server version that you are using? Please, find this info following this guide.
If it is 2.X, you must deploy a function with the structure below:
main.js:
Parse.Cloud.define('hello', function(req, res) {
   response.success('Hello')
});

The code Parse.Cloud.useMasterKey(); is deprecated. Read more here.
If it is the 3.X, you can deploy something like:
Parse.Cloud.define('hello', (req) => {
   return 'Hello';
});

*

*Check if you have initialized the correct keys on your frontend side.

If it still doesn't work, please contact the Back4App team in the live chat =D


text:
Q: Bootstrap file not linking My bootstrap files are not linking with my HTML file. Hence, they are unable to give the correct output.I have downloaded the bootstrap 4 files in my machine and using it rather than referring to web. I had downloaded it and extracted it .
npm install bootstrap@4.0.0 --save
npm install jquery@3.3.1 popper.js@1.12.9 --save

I used these to commands to setup bootstrap file in my project directory.
This is the link to my github repo
https://github.com/SMAmmar/bootstrap


text:
Q: Is there an official way to create discrete-valued range widget in GTK? From what I can see, the behavior any Range-based widget is  defined by an Adjustements one.
Since there seems to be no official way to restrict the range to a few discrete values, I have tried a lots of ways  to actually reset the values.
What works, but is not optimal, is simply to take the current value and determine which valid discrete value is the nearest from that continuous value and use that instead.
But what I would like is to visually freeze the slider to its current position until the user grabs it far enough and then change its value at once to the next valid value.
I want the user to understand and feel that these are discrete values. The problem with my working solution above is that the 3 users who tested the program told me that I should put more figures in the number I displayed, thinking the change was continuous.
NB: by "official", I mean either a "hidden" option or subclass of the Adjustements class if at all available. If not, any way that is reasonably efficient to achieve such a requirement (i.e. that don't use 50% of CPU for a simple slider!). In particular, I am not asking for the "ultimate best way" to do this.

A: It seems you can just override the change-value signal:
class DiscreteScale(Gtk.Scale):
    def __init__(self, values, *args, **kwargs):
        super().__init__(*args, **kwargs)

        values.sort()
        self.values= values

        adjustment= self.get_adjustment()
        adjustment.set_lower(values[0])
        adjustment.set_upper(values[-1])

        self.__changed_value_id= self.connect('change-value', self.__change_value)

    def __change_value(self, scale, scroll_type, value):
        # find the closest valid value
        value= self.__closest_value(value)
        # emit a new signal with the new value
        self.handler_block(self.__changed_value_id)
        self.emit('change-value', scroll_type, value)
        self.handler_unblock(self.__changed_value_id)
        return True #prevent the signal from escalating

    def __closest_value(self, value):
        return min(self.values, key=lambda v:abs(value-v))

A little demo:
w= Gtk.Window()
s= DiscreteScale([0, 1, 5, 20, 22])
w.add(s)
w.set_size_request(500, 50)

w.connect('delete-event', Gtk.main_quit)
w.show_all()
Gtk.main()

A: You didn't specify the discrete valued interval you were looking for, but GtkRange (and thus GtkScale) supports rounding:
scale_widget.set_round_digits(1)
scale_widget.set_digits(1)

I suspect this is the solution for discrete valued GtkScale that many users are looking for.
https://developer.gnome.org/pygtk/stable/class-gtkrange.html#method-gtkrange--set-round-digits
https://developer.gnome.org/gtk3/stable/GtkRange.html#gtk-range-set-round-digits


text:
Q: How to join a MYSQL fulltext search with another table? Hello thanks for reading this:
I have a Product Table in which i am carrying out a full text search on but need to combine it with a product image table
    SELECT * FROM product  WHERE Match(productBrand,productTags,ProductDiscription,productCondition,productColour,productCat)  Against('top');

I need to join by product ID.
My productImage table contains a productID and a productURL;

A: You can use query something like below-
SELECT prd.*,pim.productURL FROM product AS prd
JOIN productImage pim ON prd.productID=pim.productID
WHERE MATCH(prd.productBrand, prd.productTags, prd.ProductDiscription, prd.productCondition, prd.productColour, prd.productCat)  AGAINST('top');

Use of Limit:
    SELECT prd.*,pim.productURL FROM product AS prd
    JOIN productImage pim ON prd.productID=pim.productID
    WHERE MATCH(prd.productBrand, prd.productTags, prd.ProductDiscription, prd.productCondition, prd.productColour, prd.productCat)  AGAINST('top')
  LIMIT 1;


text:
Q: Odoo extend website_sale JS function Hello I'd like to inherit on the following function $shippingDifferent.change(function (event) { under website_sale.js in order to add the following piece of code in it:
if (value == 1) {
        value = 0
}

I know how to include or extend a Module but here there is no module, so any ideas?

A: First of all i would suggest you one line:

Never ever use the website_sale.js for the purpose of reference.

As it's contain  raw j query  instead of backbone.js .
You can't use the concept of include and extend Like:
var website_sale = require('website_sale.website_sale');
   website_sale.include({
     include_my_task: function() {
        var self = this;
         // body of  logic to be included ...

        },
    });

   website_sale.extend({
     override_prev_task: function() {
       var self = this;
       this._super();
       // body of  logic to be extended ...

     },
   });

Below i am posting some j query based code snippet, it's may help you.
   $(document).ready(function()
 {
      odoo.define("website_sale.website_sale", function (require)
      {
            "use strict";
            $(".oe_website_sale").each(function () {
             var oe_website_sale = this;
                function do_my_task (event) {
                        // body...
                }

                $(oe_website_sale).on("click", "span.my_class",do_my_task );

           });
      }
});


text:
Q: ActiveRecord .new not working, any ideas why? I know it is broad question but I am really confused.
I have table users and columns :username, :pwd_hash, :first_name, :last_name etc.
When I try to create new instance with
user = User.new(:username => 'Foo', first_name => 'Bar')
puts user.inspect

and I inspect user I get that all properties set to nil. If I do get existing user all is set properly with User.find(1) so DB is setup correctly. Also there are columns with same name in DB. Using ruby 1.9.3 on Windows.
Again I know it is stupid question but I am despreate I am wondering if anybody had similiar problem. Thank you.

A: This can happen if your User model uses attr_protected or attr_accessible to prevent username or first_name from being mass-assigned.


text:
Q: Windows CAL clarification
Possible Duplicate:
Can you help me with my software licensing question?

I'm hoping that someone can clear up a question regarding the ever confusing Microsoft client access licensing.
Reading this page, would suggest that if you bought a client or device CAL and set the licensing mode on the server to 'per client or device' (as opposed to 'per server'), then each CAL would allow that many users or devices to connect to all the Microsoft servers** on the network.
For example, say we have a network with 100 users, 100 clients, and 10 Windows servers, but we only have 50 user CALs (for argument's sake - because I know that isn't enough CALs).
Now suppose I purchased a new server, with a server operating system with another 50 user CALs, does this give all 100 of our users access to all 11 of our Windows servers?
The link above suggests that is the case, however, why is it then, that when I attempt to buy a server with an OEM version of a server operating system, that I can't buy it without CALs?
What I'm actually looking at, is buying a Hyper-V server with Windows Server 2008 enterprise (to allow me to run 4 OS instances), however, I can't seem to purchase Server 2008 enterprise with any less than 25 CALs. Why is this?
** = To the type of server the CALs belong to (e.g. Server 2003 or Server 2008 - but not both)

A: You are reading correctly...  If you choose per user/per device, they will be able to access all 10 of your Windows servers, and you would need as many CALs as you have users or devices (per user makes sense if you have users that may be accessing the servers from several different devices, per device makes sense in an environment where you have many users accessing the servers from a few devices, such as a company with shift work).
I ran over to http://www.cdw.com and typed in "server 2008 enterprise", and the first few results didn't appear to come with CALs (which I believe is what you are looking for).  Your best bet is to directly call a reseller such as CDW (and they can tell you what licenses are available), or call the Microsoft licensing hotline (800) 426-9400, where they have people trained on the ins and outs of licensing.

A: Microsoft's Open License program allows purchase of software without CAL's.  The Box & OEM version's come with CAL's because thats how MS sells them.  If you have more then a couple of a computers its better to go with the Open License program.

A: I think that OEM licenses come with CALs because Microsoft has a HUGE amount of influence over the way that OEM licenses are handled.  They have probably simply dictated that you can't sell an OEM server license without CALs and the OEMs have no choice.  That said, I have found that Volume Licensing is often cheaper then OEM licensing and gives you much more flexibility.  I strongly suggest buying your severs without software and using Volume Licenses for all your Microsoft products.


text:
Q: Toggle info for each product I am using OpenCart v2.2.0. On category page I have Show/Hide link for each product belonging to the category, which is supposed to shor or hide product info. The problem is it toggles only for first product info, no matter which Show/Hide link I click. Others don't toggle their info, they all toggle the first only. So far I have this code:
In category.tpl:

<a style="width:140%;" href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?>

    Show/Hide

About: <?php echo $product['description']; ?>

            <?php if ($product['manufacturer']) { ?>
            <?php echo "Manufacturer:" ?> <a href="<?php echo $product['manufacturers']?>"><?php echo $product['manufacturer']; ?>
            <?php } ?>

    <?php echo "For models:  " . $product['model']; ?>

            <?php echo "Manufacturer code:  " . $product['mpn']; ?>

Also there is:

Does anyone know how do I make others toggle their own info as well? I've been trying to solve this with no luck, obviously. This is all I came up with, but it is not good.

A: Identifiers in HTML must be uniuqe. You can use common class to target the element. I would recommend you to use unobstrsive event handler and bind event using jQuery  .on() method.
You can use various method to traverse DOM.
$(function(){
    $('.toggleDiv').on('click', function(e){
        e.preventDefault();
        $(this) //Current element
           .closest('.caption') //Travese up to get common parent
           .find('.myContent') //Get Element using class
           .toggle();
    })
});

HTML, Here added toggleDiv to anchor element and myContent to content div

<a style="width:140%;" href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?>

    Show/Hide

About: <?php echo $product['description']; ?>

        <?php if ($product['manufacturer']) { ?>
        <?php echo "Manufacturer:" ?> <a href="<?php echo $product['manufacturers']?>"><?php echo $product['manufacturer']; ?>
        <?php } ?>

         <?php echo "For models:  " . $product['model']; ?>

        <?php echo "Manufacturer code:  " . $product['mpn']; ?>

A: First the id should be unique in the same document so replace the duplicate ones by general classes then use those classes for the selection, example give your anchors a a class like toggle in my example then attach the click event to the class :
$('body').on('click','.toggle',function(e){
  e.preventDefault();

  $(this).closest('.caption').find('.myContent').toggle();
  //Or
  $(this).next('.myContent').toggle();
})

I suggest here to avoid the use of the inline-event onclick and to attach the click event from your javascript code.
Hope this helps.

$('body').on('click','.toggle',function(e){
  e.preventDefault();

  $(this).closest('.caption').find('.myContent').toggle();
})

    Name1

  Show/Hide

About: description1

    Manufacturer:

      manufacturer

    For models:  Manufacturer code:

Name2

  Show/Hide

About: description2

    Manufacturer:

      manufacturer

    For models:  Manufacturer code:

A: Your answers were helpful, but my solution was to pass product_id and that way every div would toggle separately when I click Show/Hide link. So, the code is as my original, except for these two lines where I actually pass product_id:
  <a href="javascript:toggleDiv('myContent<?php echo $product['product_id']; ?>');" style="padding: 5px 10px;">Show/Hide
<div id="myContent<?php echo $product['product_id']; ?>" style="display:none;">


text:
Q: Does corona discharge charged insulator? Does corona discharge charged insulator? I draw a diagram to make it simpler to understand.
Electrons form negative side is accelerated due to electric field and accumulate on insulator surface. Gas on the positive side was ionize giving off electrons and flow to positive terminal.

Am I understanding this correctly, When I place plastic sheet between HV terminals and when I remove plastic sheet I got an electric shock, so I think corona discharge might charge plastic sheet.

A: Your answer is correct. Indeed there is surface charge deposited on the surface of the insulator. This configuration is called a Dielectric barrier discharge. Its concept of work is explained in this document. In section 2 it is clearly stated that the charge deposited on the surface of the dielectric play an important role in sustaining the discharge.
The more common configurations of DBD are concentric cylinders or parallel plates configurations. Still, sharp pin electrodes are common, they are not as common as the others because other configurations have certain functionality
When you switch off the discharge and touch the insulator by your hand you get shocked by the deposited surface charge on insulator's surface

A: . . .  Well, anyway, you can get a shock through the insulator when it is under tension from a power supply or  source and the tension exceeds the breakdown threshold of  the insulator.   The conductor inside the insulator shorts through it and can shock you.
The other case, with no breakdown, depends on whether or not the dielectric in the insulator exhibits hysteresis.  The (insulator's) hysteresis is zero if the charge dipole built up within it at maximum applied tension returns to zero linearly as the applied tension returns to zero.  However, if the  built up charge dipole does not return to zero after the applied tension is removed, then the insulator is exhibiting hysteresis and the charge  remaining after the applied  tension is removed  may be available for discharge to an external conductor, such as your finger.  In this case you can get a delayed shock.

A: Also, if a charged, insulated wire with Direct Current applied tension exhibits coronal dischage over a period of time, the insulator must be conducting and shorting to the outside.
Alternatiing applied tension is  much messier to analyze, but involves the dielecctric constants and the total capacitances of both the insulator and of the surrounding air.


text:
Q: Density plot exceeds x-axis interval I am attempting to make some density plots using ggplot2 but the distribution exceeds the bounds of my data. Specifically, I am trying to show the distribution of GPS locations in 2 habitat types over time (hours of the day). As I am only interested in displaying the distribution of locations during daylight (0500 to 2100), I have filtered out hours occurring at night. However when I plot the data, the distribution exceeds both hours 5 and 21 on the x-axis. I have a feeling it has to do with "scale_x_continuous" in ggplot, where I have specified the limits to be (0,24), but that doesn't explain why the distribution exceeds daytime hours when there is not data before or after those hours. FYI, I do want the entire time series to show even though I don't have data for each hour.
But again, I only have data between the hours of 5 and 21.
Can someone explain what might be going on here? Hopefully I am making sense.  Thanks!
Sample code:
locs.19
locs.19 <- subset(locs, hour >= 5 & hour <=21)

> head(locs.19)
     ID         x        y         datetime hour shelfhab
2019_01 -122.9979 37.68930 2019-06-07 05:04    5    inner
2019_01 -122.9977 37.68833 2019-06-07 05:06    5    inner
2019_01 -122.9975 37.68737 2019-06-07 05:08    5    inner
2019_01 -122.9974 37.68644 2019-06-07 05:10    5    inner
2019_01 -122.9974 37.68550 2019-06-07 05:12    5    inner
2019_01 -122.9974 37.68457 2019-06-07 05:14    5    inner

> str(locs.19)
'data.frame' :  6531 obs. of  6 variables:
 $ ID       : chr  "2019_01" "2019_01" "2019_01" "2019_01" ...
 $ x        : num  -123 -123 -123 -123 -123 ...
 $ y        : num  37.7 37.7 37.7 37.7 37.7 ...
 $ datetime : chr  "2019-06-07 05:04" "2019-06-07 05:06" "2019-06-07 05:08" "2019-06-07 05:10" ...
 $ hour     : int  5 5 5 5 5 5 5 5 5 5 ...
 $ shelfhab : chr  "inner" "inner" "inner" "inner" ...

### Plot ###
p19 <- ggplot(locs.19, aes(x = hour))+
  geom_density(aes(fill = shelfhab), alpha = 0.4)+
  xlab("Time of Day (24 h)")+
  theme(legend.position = "right",panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.line = element_line(colour = "black"),
        text = element_text(size = 14,family = "Calibri"))+
  scale_x_continuous(breaks=seq(0,24,2),limits = c(0, 24), expand = c(0,1))

p19

A: The issue is that you set the limits in scale_x_continuous. Thereby you set the range over which the denisty is estimated. To achieve your desired result simply set the limits via coord_cartesian. This way the density is only estimated on your data while you still get a scale ranging from 0 to 24 hours.
Using some random example data:
set.seed(42)

# Example data
locs.19 <- data.frame(hour = sample(5:21, 1000, replace = TRUE),
                      shelfhab = sample(c("inner", "outer"), 1000, replace = TRUE))

library(ggplot2)

ggplot(locs.19, aes(x = hour))+
  geom_density(aes(fill = shelfhab), alpha = 0.4)+
  xlab("Time of Day (24 h)")+
  theme(legend.position = "right",panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.line = element_line(colour = "black"),
        text = element_text(size = 14))+
  scale_x_continuous(breaks=seq(0,24,2), expand = c(0,1)) +
  coord_cartesian(xlim = c(0, 24))


text:
Q: Customize Sharepoint User Interface - List Display I am currently working on site on SharePoint. I created all the lists I needed.
I am trying to make an User Interface. The futur users have an interface requirement but I don't know how to fulfull it :

*

*The editing grid view must be vertical and not horizontal, same for all the list view

I have been looking on the internet for many days for solutions but could not find any that worked on my site. I am not allowed to use neither Sharepoint Designer, nor InfoPath , and any other related softwares.
I tried several Javascript codes that I found online but the final effect is not what the clients are expecting to get and the scripts usually require to write Column Names of the lists in the parameters, but the users will add more columns in the future, and they don't want to modify the code.
Could you help me ?
Thanks in advance


text:
Q: jQuery - Inserting data attribute into variable When you click load more I am trying to load the youtube videos using their data-youtube attribute on the li. The problem is this doesnt seem to be working and it just renders out [Object object]
Anyone know what I'm doing wrong please?
http://jsfiddle.net/qxxq9u21/
var youtubeID = $('.video-list li').each(function () {
    $(this).attr('data-youtube');
});

$('.load').click(function () {
    var video = '';

    $('.video-list li').find('iframe').remove();
    $('.video-list li').append(video);

    return false;
});

A: there are multiple problems/misunderstandings in your code:

*

*your each() function is only executed once on pageload, plus it doesn't return anything so you get nothing in your var youtubeID.

*your append() function is applied to all list elements, so you will get all the videos in every
 (in your example that's two)
what i changed to make it work:
so i put the each() function inside your click event, so that it's executed on every click. inside the each() function i appended the video-iframe to $(this) which in this case is the current
 element each() is iterating. so you got the video just once where you actually wanted it to be.
and with $(this).data("youtube") you can read the value of your data-youtube attribute of your
.

here you got a working example:
$('.load').click(function () {

    $('.video-list li').find('iframe').remove();

    $('.video-list li').each(function () {
        $(this).append('');
    });
    return false;
});

and here is the working JSFiddle

A: jQuery's each returns a jQuery object, which is why you are getting [Object object] in your url. Even if that returned an array of youtube ids, you'd still be having an issue with how you are building the iframe html.
I'd suggest changing your jQuery a bit. In your click event, loop through each list item that has a data attribute of youtube, and build and replace your iframe.
$('.load').on('click', function(){
    $('.video-list > li[data-youtube]').each(function(item, index){
        var video = '';
        $(this).find('iframe').remove();
        $(this).append(video);
    });

    return false;
});


text:
Q: Basic assembly language Get & Display system time i have a code here:
org 100h

mov ah, 2ch
int 21h

mov ah, 2
mov dl, ch
int 21h

mov ah, 2
mov dl, cl
int 21h

ret

and what i want is to display the system time.
But it displays other characters instead. How do i fix that?
EDIT:
how can i add a division operation here? i guess what i want is to divide ch and cl by 10 and print it individually
thanks for answers

A: Hours range from 0 to 23.
Minutes from 0 to 59.
They are two digits numbers and as such must be handled.
There is no built-in service that prints numbers, the Int 21/AH=02h prints characters, you need to transform a two digits number (an 8 bit quantity) into a two characters (two 8 bit quantities)1.
This site has plenty of examples, here is one that use only simple instructions.
ORG 100h

mov ah, 2ch           ;Get time
int 21h

mov dl, ch            ;Show hours
call itoa99

mov ah, 02h           ;Show separator
mov dl, ':'
int 21h

mov dl, cl            ;Show minutes
call itoa99

mov ax, 4c00h         ;Exit
int 21h

;dl = number to display (0..99)
itoa99:
 push bx
 push ax            ;Save registers used

 xor ax, ax         ;AX = 0
 mov al, dl         ;AX = DL

 mov bl, 10d
 div bl             ;AL = AX/10, AH = AX mod 10

 ;AX contains the digits

 add ax, 3030h      ;Transform digit to digitals

 ;ASCII digits starts at 30h, digit X is the char 30h+X

 ;ASCII value: 30h  31h  32h  33h ... 39h
 ;Character:   0    1    2    3   ... 9

 mov bx, ax         ;Save for later

 ;Show the digits
 mov dl, bl
 mov ah, 02h
 int 21h

 mov dl, bh
 int 21h

 pop ax
 pop bx
 ret

1 A two digits number has... two digits.
Base 10 is a positional system, it means that the number representation is composed of weighted quantities called digits.
Each digit is itself a number, but simple enough to have an unique symbol associated, a digital.
For example the digit 4 is represented with various symbols depending on the culture: '4', 'ד', '四', 'IV', '٤', ...

To display a number in base 10, we first need to extract the digits, then convert the digits to their digitals. The final result is a numeral.
To extract the two base 10 digits of a 0-59 range number, we simply use: d0 = n mod 10, d1 = n / 10.
Convince your self that this indeed gives the correct result and that each di is between 0 and 9.

A: This code might be helpful for you. You can find it here and download also: Timer Tick Example of Assembly Language
[org 0x0100]

    jmp start

incTime: dw 0
hrs: dw 0
min: dw 0
sec: dw 0

clearScreen:

   push ax
   push di
   push es

   mov ax , 0xB800
   mov es , ax
   mov di , 0
   nextCls:
      mov word [es:di] , 0x0720
      add di , 2
      cmp di , 4000
      jne nextCls

   pop es
   pop di
   pop ax
   ret

printTime:

   push bp
   mov bp , sp
   push ax
   push bx
   push cx
   push dx
   push si
   push di
   push es

   call clearScreen

   mov si , 0  ;counter to use 3 prints i.e. Hrs, Min, Sec
   mov ax , 0xB800
   mov es , ax
   mov di , 142

nextState:

   mov bx , bp
   sub bx , si
   add bx , 8
   mov ax , [bx]    ;BX=BP-SI+8
   mov bx , 10
   mov cx , 0

   nextDigit:
      mov dx , 0
      div bx
      add dl , 0x30
      push dx
      inc cx
      cmp ax , 0
      jnz nextDigit

   nextPos:
      pop dx
      mov dh , 0x07
      mov [es:di] , dx
      add di , 2
      loop nextPos

      add si , 2
      cmp si , 6
      jz return

      mov dl , ':'
      mov [es:di] , dx
      add di , 2
      jmp nextState

   return:
      pop es
      pop di
      pop si
      pop dx
      pop cx
      pop bx
      pop ax
      pop bp

      ret 6

Clock:
   push ax

   inc word [cs:incTime]
   cmp word [cs:incTime] , 18
   jz Reset

   proceedToCall:
      push word [cs:hrs]
      push word [cs:min]
      push word [cs:sec]
      call printTime

      mov al , 0x20
      out 0x20 , al

      pop ax
      iret

   Reset:
      mov word [cs:incTime] , 0
      inc word [cs:sec]
      cmp word [cs:sec] , 60
      jnz proceedToCall
      mov word [cs:sec] , 0
      inc word [cs:min]
      cmp word [cs:min] , 60
      jnz proceedToCall
      mov word [cs:min] , 0
      inc word [cs:hrs]
      cmp word [cs:hrs] , 24
      jnz proceedToCall
      mov word [cs:hrs] , 0
      jmp proceedToCall

start:
   xor ax , ax
   mov es , ax
   cli
      mov word [es:8*4] , Clock
      mov word [es:8*4+2] , cs
   sti

   mov dx , start
   add dx , 15
   mov cl , 4
   shr dx , cl

   mov ax , 0x3100
   int 0x21

A: i got it!
org 100h

mov ah, 2ch   ;get time
int 21h       ;

mov hour, ch
mov mins, cl

mov ah, 0     ;
mov al, hour  ;divide by 10
mov bl, 10    ;
div bl        ;

mov hour1, al
mov hour2, ah

mov ah, 2     ;
mov dl, hour1 ;
add dl, 30h   ;
int 21h       ;
              ;print hour
mov ah, 2     ;
mov dl, hour2 ;
add dl, 30h   ;
int 21h       ;

mov ah, 2
mov dl, ':'
int 21h

mov ah, 0     ;
mov al, mins  ;divide by 10
mov bl, 10    ;
div bl        ;

mov min1, al
mov min2, ah

mov ah, 2     ;
mov dl, min1  ;
add dl, 30h   ;
int 21h       ;
              ;print minuntes
mov ah, 2     ;
mov dl, min2  ;
add dl, 30h   ;
int 21h       ;

ret

hour db ?  ;
mins db ?  ;
hour1 db ? ;
hour2 db ? ;initialize variables
min1 db ?  ;
min2 db ?  ;


text:
Q: É seguro usar TimThumb? Estou fazendo um site e comecei a fazer o uso da biblioteca TimThumb.php para redimensionar as imagens no tamanho exato que eu quero. No entanto me veio duas dúvidas

*

*Será que é seguro usar? ouvir dizer que versões passadas
apresentaram    vulnerabilidade;

*Fazendo o uso irá implicar em algo na performance do meu site? ex:
mais trabalho para o servidor.

A: O Timthumb tem sim vulnerabilidades de segurança, os próprios desenvolvedores mencionaram isso uma vez (penso que foi no próprio blog/site deles) e vincularam que essa foi a razão pelo qual eles deixaram de continuar o seu desenvolvimento. Eu fiz uma breve pesquisa a ver se encontrava esse artigo mas não encontrei. Entretanto nunca mais segui as suas atualizações de status e de desenvolvimento, então não sei como se encontra a situação no momento e se eles já resolveram estas vulnerabilidades ou não, mas talvez possa haver outros desenvolvedores que possam ter pegado no projeto e tenham fixado este problema.
No entanto existem outros métodos e alternativas para este plugin.
Pesquisando no Google podemos encontrar algumas delas:

*

*Pergunta feita no SOen - What's a good PHP alternative to Timthumb

*Plugin bfi_thumb para o WordPress que agora mudou e está a ser continuado como - OTF Regenerate Thumbnails ou no GitHub - https://github.com/gambitph/WP-OTF-Regenerate-Thumbnails

Artigo em inglês falando de ambos, o TimThumb e do BFIThumb

*

*Entre outros...


text:
Q: SASS compiling a file from an http/s location Is there a way to compile a scss file using the sass command line where the source file resides in a remote location?
i.e.
sass http://example.com/scss-files/style.scss /path/to/static/assets/output.css
when I try to do that (with a real source file, of course) I get this error:
Errno::ENOENT: No such file or directory - http
Is there a way to do that?
Thanks in advance.

A: Sadly there isn't a way to do this. What you could do is mount your site as a folder using Panic's Transmit, compile your SASS and then sync your site with the live site. It isn't ideal, but it's the closest to what you want.


text:
Q: How to check available disk space using SAS How can I check the space left on a drive and if it is less than 1GB to output a message using SAS.
I only have a code that checks the SAS file size.

A: I've basically modified the code available in this link according to your requirement. I've also added a bit of code to fix issues faced due to quotes and the pipe command. Basically you should let SAS deal with quotes  before passing on the code.
%macro windows_bytes_free(sm_path);

%global mv_bytes_free;
%let mv_bytes_free = -1;  /* In case of error */
%let filepath = %sysfunc(quote(%qsysfunc(dequote(&sm_path)))); /* To prevent issues with quotes remove quotes if present and apply it again*/

/* Run the DIR command and retrieve results using an unnamed pipe */
filename tempdir pipe %sysfunc(quote(dir /-c  &filepath  | find "bytes free")) ;

    data _null_;
        infile tempdir length=reclen ;
        input line $varying1024. reclen ;

        re = prxparse('/([0-9]+) bytes/');  /* Parse the output of DIR using a Perl regular expression */

        if prxmatch(re, line) then do;
            bytes_str = prxposn(re, 1, line);
            bytes = input(bytes_str, 20.);
            call symput('mv_bytes_free', bytes);    /* Assign available disk space in bytes to a global macro variable */
            kb = bytes /1024;
            mb = kb / 1024;
            gb = mb / 1024;
            format bytes comma20.0;
            format kb mb gb comma20.1;

            /* Write a note to the SAS log */
            put "NOTE: &sm_path " bytes= kb= mb= gb=;
            if gb<1 then put '** Available space is less than 1 gb';
            else put '** Enough space is available';

        end;

    run;

    %if &mv_bytes_free eq -1 %then %put ERROR: error in windows_bytes_free macro;

%mend;

An example of how to use this macro for the C: drive
%windows_bytes_free(c:);

A: Tazz:
Presuming you are running SAS on a Windows platform -- Piping wmic command output into SAS can deliver vast amounts of information about the system, including the freespace on the disks.
WMIC - Using Windows Management Instrumentation Command-line;
https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx;
%let csvdata = %sysfunc(pathname(work))\wmic_output.csv;

filename wmic_csv "&csvdata" encoding="utf-16";
filename gather pipe "wmic logicaldisk get name,size,freespace /format:csv";

* process the wmic command and strip off blank first row and extraneous CR character at end of line;
data _null_;
  infile gather;
  input;
  if _n_ > 1;
  _infile_ = compress(_infile_, '0d'x);
  file wmic_csv;
  put _infile_;
run;

proc import replace out=diskinfo file=wmic_csv dbms=csv;
run;

data _null_;
  set diskinfo;
  if freespace < 1e9 then put "WARNING: " name "has remaining" freespace=;
run;

wmic can also export it's information in XML format -- the output is more complicated but extremely capable.  This sample code uses SAS' xmlv2 engine and the automap= option:
* WMIC - Using Windows Management Instrumentation Command-line;
* https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx;

%let xmldata = %sysfunc(pathname(work))\wmic_output.xml;
%let xmlautomap  = %sysfunc(pathname(work))\wmic_output-automap.xml;
%let xmlmap =  %sysfunc(pathname(work))\wmic_output-map.xml;

filename wmic "&xmldata" encoding="utf-16";
filename wmicmap "&xmlmap";

filename gather pipe "wmic logicaldisk get name,size,freespace /format:rawxml > ""&xmldata""";

data _null_;
  infile gather;
  input;
  put _infile_;
  rc = sleep(.1,1);
run;

libname wmic xmlv2 automap=replace xmlmap=wmicmap;

proc copy in=wmic out=work;
run;

proc transpose data=work.property out=properties(drop=_name_) suffix=_text;
  by instance_ordinal;
  id property_name;
  var value;
run;

filename gather;
filename wmic;
filename wmicmap;


text:
Q: Dual boot win 10 ubuntu I do not have the option to install Ubuntu along side windows 10.
It only gives the option to format the drive, and install Ubuntu.
However I have partitioned my drive to make space for Ubuntu.

A: There should be an option to do something else, at the bottom of the window. If you pick that one, it will let you pick the partition you want to use for Ubuntu, which ones do you want to format and which you don't, pretty much anything you might possibly want.


text:
Q: How to show $\frac{wH^x +(1-w)(1-H)^x}{wL^x +(1-w)(1-L)^x}$ is convex in $x$? How do I show that the function $f(x) = \frac{wH^x +(1-w)(1-H)^x}{wL^x +(1-w)(1-L)^x}$ is convex in $x$, where $0 <w<1$ and $0.5 \leq L <H<1$?  Visual inspection in Mathematica suggests this conjecture is true, but I have not been able to make headway by signing the second derivative with respect to $x$.

A: This is not an answer, but a counterexample (obtained via Desmos) that shows that the convexity claim for the values
$$L=0.9, H=0.95, w=0.1$$
is not true (though they comply with the given constraints).

Therefore, the asker should restrict the considered range of values.


text:
Q: Update data in database based on order id in Django I am new in Django.
I want to update the value in the database based on the order id. Therefore, every order id has different updates. But, i only can update the last item that i add to the order. And every previous orders that i have, will directly follow the update from the last item.
models.py
 class OrderItem(models.Model):
     Table_No = models.IntegerField(blank=False)
     FoodId = models.TextField()
     Item = models.TextField()
     Qty = models.DecimalField(max_digits=5, decimal_places=0)
     Price = models.DecimalField(max_digits=10, decimal_places=2)
     TotalPrice = models.TextField()
     Note = models.TextField(max_length=100, null=True)
     OrderId = models.TextField(max_length=5, null=True)

     FoodStatus = (
         ('1', 'Has been ordered'),
         ('2', 'cooked'),
         ('3', 'ready to be served'),
         ('4', 'done'),
     )
     food_status = models.CharField(max_length=50, choices=FoodStatus)

views.py
def kitchen_view(request):
    chef_view = OrderItem.objects.all()
    if request.method == "POST":
        order_id = request.POST.get("OrderId")
        status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))
        status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))
    return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})

kitchen_page.html
<form action="#" method="post">

        {% csrf_token %}
        {% for order in chef_view %}

                    Table Number
                    Item
                    Quantity
                    Price
                    Note
                    Order Id
                    Status

                    {{ order.Table_No }}
                    {{ order.Item }}
                    {{ order.Qty }}
                    {{ order.Price }}
                    {{ order.Note }}
                    {{ order.OrderId }}
                    {{ order.food_status }}
                        <input type="text" name="food_status">

        {% endfor %}

<input type="submit" value="Change Status"></button>
    </form>

The result should be able to update the food_status based on the order_id. Therefore, every order_id may have different food_status and show it to the template.
Anyone can help me to solve this problem? I really need the help to solve this issue. Really appreciate.

A: Previously stored filtered objects are not being updated as you have
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))

but when you are updating them, you should be updating the already filtered objects like
status = status.update(food_status=request.POST.get("food_status"))

Hope this helps.

A: Ok so real problem is that your form is incorrect - you are not sending OrderId to view. Here's quickfix to it:
kitchen_page.html:

<form action="#" method="post">

            Table Number
            Item
            Quantity
            Price
            Note
            Order Id
            Status

        {% csrf_token %}
        {% for order in chef_view %}

                {{ order.Table_No }}
                {{ order.Item }}
                {{ order.Qty }}
                {{ order.Price }}
                {{ order.Note }}
                {{ order.OrderId }}
                {{ order.food_status }}
                    <input type="text" name="food_status" value="{{ order.food_status }}">

            <input type="hidden" name="OrderId" value="{{ order.OrderId }}">
        {% endfor %}

<button type="submit" value="Change Status">Change Status</button>
</form>

views.py:
def kitchen_view(request):
    if request.method == "POST":
        order_ids = request.POST.getlist("OrderId")
        food_statuses = request.POST.getlist("food_status")
        for i in range(len(order_ids)):
            OrderItem.objects.filter(OrderId=order_ids[i]).update(food_status=food_statuses[i])
    chef_view = OrderItem.objects.all()
    return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})

A: You can update multiple objects at once including the filter in a single line as:
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId")).update(food_status=request.POST.get("food_status"))

The problem in your code:
status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))

was that you were not using the filter, instead you tried updating the status1 field(Can't see a status1 field in your model) using status.status1.


text:
Q: Refresh page on scroll to top of page I am creating a website in php, in which I want a division to reload by javascript when the user scroll to the top of the page.
Can anyone guide me how to do this with example?

A: With using something like jQuery you can do it like this;
$(window).scroll(function () {

   var offset = 50;

   if( $(window).scrollTop() <= offset ) {

   // Reload your division
   //

   }

 });

Note; the .scroll function is firing each pixel you scroll, for browserload you might want to add a timeout for this

A: You need to watch the scrollTop value. Simple example:
$(window).scroll(function () {
    if ( $(window).scrollTop <= 30 ) {
        window.location.reload();
    }
});


text:
Q: Frequency on doing exercises in learning Calculus & Linear Algebra & Probability and so on When I'm taking courses in Calculus I & II, and Linear Algebra, the lecturers are always telling us to do as many exercises as possible. But when it comes to practical situation, I realize it takes so much time on exercises especially calculation parts.
So I'm thinking about whether it's really necessary, because I found that I love proof exercises mostly, with that, I could think more, and make connections among many theorems, to see how they are related and what it really means. But for many 'calculation' exercises(say 400-500 problems for each chapter totally) I realize for most of them are just substituting the data into the formulas, and doing calculations are somehow less helpful in understanding compared with proof problems or just read & re-read text part and thinking.
So in this case, I want to ensure that whether or not what I'm doing is suitable, because lots of people around told me that it's dangerous.  Thus, I want to know more advices or explanations. (It's somehow impossible to focus both proof and calculation as much as possible, and I've enjoyed and benefited from the former but not latter one.)

A: I would agree that the proof exercises are more interesting. However I would still recommend that you complete a lot of the calculation exercises. If you are really focused, 500 exercises really shouldn't take that long to complete. Unless, that is, they aren't as easy for you as you believe. Understanding an exercise is not the same as solving it quickly.
You might not think that you need the mechanics but if you practice the mechanics, you have more brain power left to do the interesting parts. Exercises are not just about understanding, they are also about execution. You should be able to fill out the details of a calculation without hesitation or even thinking. That only comes from practice.


text:
Q: EBCDIC to ASCII conversion. Out of bound error. In C# I tried creating a EBCDIC to ASCII convector in C# using  this general conversion order(given below).  Basically the program converted from ASCII to the equivalent integer and from there into EDCDIC using the order below.
Now when I try compiling this in C# and try giving a EBCDIC string(got this from another file from another computer) it is showing 'Out of Bound' exception for some of the EBCDIC character. Why is this like this?? Is it about formating?? or C# ?? or windows?
Extra: I tried just printing out all the ASCII and EBCDIC characters using a loop from 0..255 numbers but still its not showing many of the EBCDIC characters. Am I missing any standards?
The whole code is as follows:
public string convertFromEBCDICtoASCII(string inputEBCDICString, int initialPos, int endPos)
    {
        string inputSubString = inputEBCDICString.Substring(initialPos, endPos);
        int[] e2a = new int[256]{
                                    0, 1, 2, 3,156, 9,134,127,151,141,142, 11, 12, 13, 14, 15,
                                    16, 17, 18, 19,157,133, 8,135, 24, 25,146,143, 28, 29, 30, 31,
                                    128,129,130,131,132, 10, 23, 27,136,137,138,139,140, 5, 6, 7,
                                    144,145, 22,147,148,149,150, 4,152,153,154,155, 20, 21,158, 26,
                                    32,160,161,162,163,164,165,166,167,168, 91, 46, 60, 40, 43, 33,
                                    38,169,170,171,172,173,174,175,176,177, 93, 36, 42, 41, 59, 94,
                                    45, 47,178,179,180,181,182,183,184,185,124, 44, 37, 95, 62, 63,
                                    186,187,188,189,190,191,192,193,194, 96, 58, 35, 64, 39, 61, 34,
                                    195, 97, 98, 99,100,101,102,103,104,105,196,197,198,199,200,201,
                                    202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208,
                                    209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215,
                                    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,
                                    123, 65, 66, 67, 68, 69, 70, 71, 72, 73,232,233,234,235,236,237,
                                    125, 74, 75, 76, 77, 78, 79, 80, 81, 82,238,239,240,241,242,243,
                                    92,159, 83, 84, 85, 86, 87, 88, 89, 90,244,245,246,247,248,249,
                                    48, 49, 50, 51, 52, 53, 54, 55, 56, 57,250,251,252,253,254,255
                            };
        char chrItem = Convert.ToChar("0");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < inputSubString.Length; i++)
        {
            try
            {
                chrItem = Convert.ToChar(inputSubString.Substring(i, 1));
                sb.Append(Convert.ToChar(e2a[(int)chrItem]));
                sb.Append((int)chrItem);
                sb.Append((int)00);
            }
            catch (Exception ex)
            {
                Console.WriteLine("//" + ex.Message);
                return string.Empty;
            }
        }
        string result = sb.ToString();
        sb = null;
        return result;
    }

A: You didn't show your code that generates the error but if you are using the character as the index into the array, you should know that C# uses Unicode (2-byte) characters. The character code could go all the way up to 64k. That would definitely be out of bounds for your array.

A: It's entirely unclear what you're doing, as all you've posted is the array.
However, I have an EBCDIC encoding implementation you might want to use. It doesn't cope with "shifting" but it is a subclass of the normal System.Text.Encoding class, so you can use it with things like StreamReader. Oh, and there are various different flavours - everything listed in this directory, basically. You'll need to find the one that suits you.

A:   string convertFromEBCDICtoASCII(string inputEBCDICString, ...)

You started off on the wrong foot.  There is no way that you can read an file that contains EBCDIC into a string.  A .NET text file reader is going to assume the text in the file is encoded in some way.  Like StreamReader, it will use utf-8 by default.  That cannot work properly on a EBCDIC file, it will mis-interpret some of the characters and turn them into Unicode codepoints that are >= 256.  Which will then blow up your array indexing code.
You have to change the input argument to byte[].  Read the file with FileStream or File.ReadAllBytes().
The next problem is that your table isn't valid for .NET strings, they are encoded in utf-16.  For example, 128 isn't an ASCII code and doesn't encode a valid Unicode code point.  Not sure what code page was used to construct the table, code page 1252 perhaps.  After replacing the byte, you'd then next have to use Encoding.GetString() to convert that code page to Unicode.
To slay this dragon another way, note that the Encoding class already supports EBCDIC code pages.  Review the docs of the Encoding.GetEncodings() method.  You'll have to know the IBM code page.  You can pass the proper encoding to the StreamReader(String, Encoding) constructor and won't have to write any of this code.

A: This is how I did it
    #region public static byte[] ConvertAsciiToEbcdic(byte[] asciiData)
    public static byte[] ConvertAsciiToEbcdic(byte[] asciiData)
    {

        // Create two different encodings.
        Encoding ascii = Encoding.ASCII;
        Encoding ebcdic = Encoding.GetEncoding("IBM037");

        //Retutn Ebcdic Data
        return Encoding.Convert(ascii, ebcdic, asciiData);

    }
    #endregion

    #region public static byte[] ConvertEbcdicToAscii(byte[] ebcdicData)
    public static byte[] ConvertEbcdicToAscii(byte[] ebcdicData)
    {
        // Create two different encodings.
        Encoding ascii = Encoding.ASCII;
        Encoding ebcdic = Encoding.GetEncoding("IBM037");

        //Retutn Ascii Data
        return Encoding.Convert(ebcdic, ascii, ebcdicData);
    }
    #endregion


text:
Q: module 'sample_project' has no attribute 'data' I thought I understand python import system, but it looks like I was wrong.
For some reason, I cannot use modules from my package unless I explicitly import them in the __init__.py or in the script code. This is not what the documentation says and I have other projects (e.g., this one) that don't have this kind of issue.
To illustrate it, I created a super simple example. A project with a following structure:
sample_project
├── sample_project
│   ├── __init__.py
│   └── data.py
└── setup.py

setup.py looks like this
import setuptools

setuptools.setup(name='sample_project', packages=setuptools.find_packages())

and data.py like this
class Data:
    pass

__init__.py is empty.
After pip install -e . I can import sample_project, but sample_project.data throws
AttributeError: module 'sample_project' has no attribute 'data'

Note that data.py is not inside the submodule, so the issue is different from this one.
This happens either if I am in the project directory or outside it.
I can fix it via import sample_project.data either in my script or in the __init__.py, but I don't understand why it does not work. It feels like the default __all__ does not work for some reason.
In the project I mentioned above I have multiple python files inside new_semantic_parsing directory. Some of them are imported in the __init__.py, some are not, but I don't have this problem with either of them.
E.g.
import new_semantic_parsing
new_semantic_parsing.utils

works fine even though utils is not explicitly imported in the __init__.py.
Clearly, there is an issue somewhere, but I can't see it.


text:
Q: Link/connect Google oidc external provider with aws cognito Recently I faced a new requirement to link or connect Google oidc external provider with aws cognito.
Background: my frontend application is running in aws and integrated with cognito for users and groups. Due to new requirements I have to connect client web application (jupyterhub) which is running on GCP vm instances.
My question is here : is this compatible or possible to use Google IAP with external oidc provider which could link to aws cognito app client and provide cognito UI to login?
Has someone faced such situation?
I would appreciate any comments or thought on this scanerio.
Many thanks
Adam

A: You can authenticate users with a wide range of identity providers such as OIDC and more by combining IAP and Identity Platform.
Identity Platform can be used to sign in users with an OpenID Connect (OIDC) provider.


text:
Q: Problema com paginação wordpress (retorna 404) Estou fazendo o index de um site e nele eu faço uma pesquisa dos posts, alias várias pesquisas, e a ultima delas tem paginação que é os últimos posts cadastrados.
Estou fazendo a consulta do seguinte modo:
<?php query_posts(array('posts_per_page' => 2, 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), 'meta_query' => array(array('key' => 'destaque', 'value' => 'on', 'compare' => 'NOT EXISTS')))); ?>

Ai depois do while eu coloco:
<?php echo paginate_links(); ?>

ele mostra os dois posts da pagina e os links da paginação, mas ele vai pra 404. O que pode ser?

A: Se você faz várias consultas, não se esqueça de zerar a query do WP, desta maneira:
<?php wp_reset_query(); ?>

De acordo com a documentação do WP, este método deve ser chamado sempre que você invoca o query_posts().
Caso você esteja trabalhando com Custom Posts, recomendo também que faça um flush nas suas regras de permalinks (basta alterar para algum outro e depois voltar para o que estava). Em vezes, o 404 pode ocorrer por algum conflito nessas regras.

A: Acredito que através do próprio painel de administração do Wordpress você pode corrigir este problema.
Primeiro vá em Configurações > Leitura, e altere o valor do campo "As páginas do blog mostram no máximo" para 2, em seguida salve as alterações.

Depois vá em Configurações > Links Permanentes, nesta página somente clique em Salvar Alterações para que o Wordpress "refaça" toda a estrutura de links.


text:
Q: Java ArrayList of Strings Throwing ArrayIndexOutOfBoundException Here is my problem:

*

*I have a Java String returned from my Web service in the below form:
21,6.417,0.3055714,27,0.7778,0.04761905

*Now I have splitted this string into separate Strings by using split function by comma delimiter.
dataList = Arrays.asList(data.split(","));

*I need to loop through this list and assign these Values into separate Strings like below:
int playsCount = Integer.parseInt(dataList.get(0));
float sumTimeViewed = Float.valueOf(dataList.get(1));
float avgTimeViewed = Float.valueOf(dataList.get(2));
int loadsCount = Integer.parseInt(dataList.get(3));
float loadPlayRatio = Float.valueOf(dataList.get(4));
float avgViewDropOff = Float.valueOf(dataList.get(5));

*Now While getting the values and assigning to the Individual int and floats, getting ArrayIndexOutofBoundsException. This is because some times the list is returning the size as 4 than 6. Here is the code:
reportDataList = getReportData(entry.id);
    //System.out.println("reportDataList.size()"+reportDataList.size());
    if(reportDataList.size() >= 1) {
        for(int i=0;i<reportDataList.size();i++) {
            if(!reportDataList.get(0).equals("")) {
                playsCount = Integer.parseInt(reportDataList.get(0));
                }
            if(!reportDataList.get(1).equals("")) {
                sumTimeViewed = Float.valueOf(reportDataList.get(1));
                }
            if(!reportDataList.get(2).equals("")) {
                avgTimeViewed = Float.valueOf(reportDataList.get(2));
                }
            if(!reportDataList.get(3).equals("")) {
                loadsCount = Integer.parseInt(reportDataList.get(3));
                }
            if(!reportDataList.get(4).equals("")) {
                loadPlayRatio =Float.valueOf(reportDataList.get(4));
                }
            if(!reportDataList.get(5).equals("")) {
                avgViewDropOff = Float.valueOf(reportDataList.get(5));
        }
        }
    }

And here is the getReportData method:
private List<String> getReportData(String id) throws KalturaApiException {
    List<String> headerList = null;
    List<String> dataList = new ArrayList<String>();
    ReportService reportService = client.getReportService();
    ReportType reportType = ReportType.TOP_CONTENT;
    ReportInputFilter reportInputFilter = new ReportInputFilter();
    reportInputFilter.fromDate = 1390156200;
    reportInputFilter.toDate = 1453660200;
    ReportTotal reportTotal = reportService.getTotal(reportType, reportInputFilter, id);
    String data = reportTotal.data;
    if(data != null) {
        dataList = Arrays.asList(data.split(","));
    }
    if(dataList.size() >= 1) {
        System.out.println("dataList.size() ------->"+dataList.size());
    }
    return dataList;
    }

How to resolve this problem for any List size acceptable?
Thanks in Advance
Raji

A: I think your problem is due to the unpredictable length of the returned string from the internet.
If you string can have i.e. 4 numbers separated with ',', you'll get 4 strings, with indexes from 0 to 3.
But if you have 6 numbers separated by comma, you'll get 6 strings with index from 0 to 5.
Due to this, I think you'll have to detect the size of the list (using dataList.size() ) and then handle different part of code if, for example, size=4 or size=6.
Also, if your input string from the internet will always have "fixed" different possible sizes (i.e. siez=4 or size=6 and no other sizes) you'll can overcome the problem using a switch(dataList.size()) , but if your length is unpredictable, so you can have sizes always different, I'll suggest you to revise your code in a semantically way that can led you to write better code, because I think your code is much "fixed" for a particulare case. If this is the case, so just continue with your coding. But if it is not, i'll suggest to think of more adaptive solutions.

A: This is how I fixed as of now:
if(reportDataList.size() == 4) {
            //System.out.println("Size is 4");
            for(int i=0;i<reportDataList.size();i++) {
                if(!reportDataList.get(0).equals("")) {
                    playsCount = Integer.parseInt(reportDataList.get(0));
                    //System.out.println("playsCount :"+playsCount);
                    accountVO.setMediaPlays(playsCount);
                }
                if(!reportDataList.get(1).equals("")) {
                    sumTimeViewed = Float.valueOf(reportDataList.get(1));
                    //System.out.println("sumTimeViewed :"+sumTimeViewed);
                    accountVO.setSumTimeViewed(sumTimeViewed);
                }
                if(!reportDataList.get(2).equals("")) {
                    avgTimeViewed = Float.valueOf(reportDataList.get(2));
                    //System.out.println("avgTimeViewed :"+avgTimeViewed);
                    accountVO.setAvgViewTime(avgTimeViewed);
                }
                if(!reportDataList.get(3).equals("")) {
                    loadsCount = Integer.parseInt(reportDataList.get(3));
                    //System.out.println("loadsCount :"+loadsCount);

                }
            }
        }
        else {
            //System.out.println("Size is not 4");
            for(int i=0;i<reportDataList.size();i++) {
                if(!reportDataList.get(0).equals("")) {
                    playsCount = Integer.parseInt(reportDataList.get(0));
                    accountVO.setMediaPlays(playsCount);
                    //System.out.println("playsCount :"+playsCount);
                }
                if(!reportDataList.get(1).equals("")) {
                    sumTimeViewed = Float.valueOf(reportDataList.get(1));
                    //System.out.println("sumTimeViewed :"+sumTimeViewed);
                    accountVO.setSumTimeViewed(sumTimeViewed);
                }
                if(!reportDataList.get(2).equals("")) {
                    avgTimeViewed = Float.valueOf(reportDataList.get(2));
                    //System.out.println("avgTimeViewed :"+avgTimeViewed);
                    accountVO.setSumTimeViewed(sumTimeViewed);
                }
                if(!reportDataList.get(3).equals("")) {
                    loadsCount = Integer.parseInt(reportDataList.get(3));
                    //System.out.println("loadsCount :"+loadsCount);
                }
                if(!reportDataList.get(4).equals("")) {
                    loadPlayRatio =Float.valueOf(reportDataList.get(4));
                    //System.out.println("loadPlayRatio :"+loadPlayRatio);
                    accountVO.setPlayToImpressionRatio(loadPlayRatio);
                }
                if(!reportDataList.get(5).equals("")) {
                    avgViewDropOff = Float.valueOf(reportDataList.get(5));
                    //System.out.println("avgViewDropOff :"+avgViewDropOff);
                    accountVO.setAvgViewDropOff(avgViewDropOff);
                }
            }

        }


text:
Q: UPDATE one column of multiple tables at once Here is my code:
UPDATE
tb_character_name t1, tb_character_area_crime t2, tb_character_friend t3,
tb_character_addr t4, tb_character_parents t5, tb_character_gps t6,
tb_character_image t7, tb_character_info t8, tb_character_data t9
SET
t1.item_deleted = 1, t2.item_deleted = 1, t3.item_deleted = 1,
t4.item_deleted = 1, t5.item_deleted = 1, t6.item_deleted = 1,
t7.item_deleted = 1, t8.item_deleted = 1, t9.item_deleted = 1
WHERE
t1.id_character = '123456' AND t2.id_character = t1.id_character AND t3.id_character = t2.id_character AND
t4.id_character = t3.id_character AND t5.id_character = t4.id_character AND t6.id_character = t5.id_character AND
t7.id_character = t6.id_character AND t8.id_character = t7.id_character AND t9.id_character = t8.id_character;

This code runs normally but the columns (item_deleted) didn't change to 1. I don't want to call 9 mysql queries because I know its CPU expensive. Whats wrong with this code?

A: You can update columns across multiple tables using various JOIN methods, and those columns can have matching names as long as you specify which table for each such field (in fact you are required to in the case of such ambiguities. However, for large numbers of tables all using identical criteria separate queries are likely faster, more stable/predictable, and more coherent.


text:
Q: Accessing the script for a Google Sheets spreadsheet I have a bunch of custom functions for a Google Sheets spreadsheet (access via Tools -> Script Editor...) that were working fine. At some point I decided to back up my functions by saving a copy of the script.
Now when I click Tools -> Script Editor... I get:
Select a project to open
Copy of myspreadsheet
myspreadsheet
Create a new project
The spreadsheet now alternates between the two scripts in an unpredictable fashion, using an old version of the same functions, then switching. How can I designate which one it should use? I can't even work out how to delete one of them.

A: From https://developers.google.com/apps-script/guides/projects

Deleting a container-bound project

*

*Open your container-bound project using the appropriate method above.

*Select File > Delete.

*Click Yes to delete the project.


text:
Q: AngularJS check box upon clicking on input field I have the following piece of code in my HTML page, with a very standard controller.

        Item ID
        1st Value
        2nd Value

         <input type="checkbox" ng-model="selected[id]">  {{id}}
         <input type="number" ng-model="values.first">
         <input type="number" ng-model="values.second">

In the above code an item is selected only when the checkbox is clicked. However, I would like that when the user clicks on either of the two numerical input fields of any particular row, the associated checkbox is checked.
I have not found anywhere a similar problem. Usually the problem that developer face is to make something happen when a checkbox is checked. However, this case is different.
I don't know how AngularJS can help me with this problem, considering that the rows are displayed through in a ng-repeat loop. Any suggestion?

A: You can achieve it this way :
HTML :

            Item ID
            1st Value
            2nd Value

             <input type="checkbox" ng-model="selected[id]">  {{id}}
             <input type="number" ng-click="selectRow(id);" ng-model="values.first">
             <input type="number" ng-click="selectRow(id);" ng-model="values.second">

Controller code :
var app = angular.module('testApp', []);
app.controller('testController', function ($scope) {
    $scope.myItemList = [{ first: 'aaa', second: 'bbbb' }, { first: 'aa1', second: 'bbb1' }, { first: 'aa2', second: 'bbb2' }];
    $scope.selected = [false, false, false];
    $scope.selectRow = function (id) {
        $scope.selected[id] = true;
    }
});

JSFiddle : https://jsfiddle.net/ffxddsre/
As you can see, all I did is adding a selectRow function and bind it to the click event of the inputs, when the input is clicked it sets the corresponding selected flag and Angular's two way binding mechanism take care of updating the UI.


text:
Q: nextDay, nextWeek, nextMonth Javascript changing date shown in textfield Im pretty sure there is an answer somewhere, found many of them, but somehow couldnt implement it in my code. I'm aware of mistakes in my code, however Im not sure how javascript works in that case, therefore there is my question. I'd like to know the reason why my function does not work correctly (why months are added?) and how to make it work. Thanks for any kind of answer.
<input type='text' id='calendar_form' />
<input type='button' onclick="nextDay()" value='NextDAY' />
<script>
    function nextDay() {
        var example = document.getElementById('calendar_form').value;
        var date = new Date();
        var parts = example.split('.');
        date.setFullYear(parts[2], parts[0], parts[1]);
        date.setTime(date.getTime() + 86400000);
        var dateDay = date.getDate();

        var dateMonth = date.getMonth();

        var dateYear = date.getFullYear();

        document.getElementById("calendar_form").value = dateDay + "." + dateMonth + "." + dateYear;

    }
</script>

What Im trying to achive is a set of functions which allow me to change date (dd.MM.yyyy) shown in textfield (as next/prev day, next/prev week, next/prev month). If you can point me in any good direction to look for an answer, Id be grateful.

A: You swapped month/year because the order is year-month-date. I'd recommend new Date rather than setFullYear as well. You could do: http://jsfiddle.net/nQtQP/.
var date = new Date(parts[2], parts[1], parts[0]);


text:
Q: using javascript in included views in jsp What is the best practice for using or not using javascript in a partial view (a helper jsp included by parent jsp)?
In general, I want to use partial views for listing results in a parent view and there should be some listeners on items of result list, so I want to bind js events like click on these items created by partial view.
What are advantages/disadvantages of binding these listeners on included jsp or parent jsp?

A: It depends on ! What work you want to do on your listeners ? If you want to do works like showing a popup or ui elements , this is may be good , but you should not do your business logic in js . In general the js itself has some disadvantage like security issues and  rendering varies(Different layout engines may render Javascript differently resulting in inconsistency in terms of functionality and interface). So I prefer you use js if you really need it !


text:
Q: PHP Links Regex How to modify this function so it could add target="_blank" attribute to external links?
Take the default domain as example.com
function makeLinks($text){
 if(eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1', $text) != $text){
  $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1', $text);
  return $text;
 }
 $text = eregi_replace('(www\.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1', $text); // ([[:space:]()[{}]) deleted from beginnig of regex
 $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '\\1', $text);
 return $text;
}

A: Parsing HTML is unestable, expensive and, in a word, a hell. You should use Simple HTML DOM Parser.

A: <?php
    class HtmlLinkUtility
    {
        public static $BaseDomain = null;
        public static function ReplaceEmailToHtmlLink($source)
        {
            return preg_replace('/([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i',
                '\1', $source);
        }

        public static function ReplaceUrlToHtmlLink($source)
        {
            function replaceUrl($groups) {
                $url = $groups[1];
                return '' . $url . '';
            }

            return preg_replace_callback('!(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)!i',
                replaceUrl, $source);
        }

        public static function ReplaceTextDataToLinks($source, $baseDomain)
        {
            self::$BaseDomain = $baseDomain;
            return self::ReplaceUrlToHtmlLink(self::ReplaceEmailToHtmlLink($source));
        }
    }

    echo HtmlLinkUtility::ReplaceTextDataToLinks(
        "test@test.com
http://www.google.com/
http://www.test.com/",
        "google.com"
    );
?>

Could not see why you would use two expressions that basically matched/replaced the same thing. Simplified your method a little.
Also, for the record. HTML is not regular in that way that it in any form could be parsed by a regular expression. Though, for simple cases like the one above, it works well.


text:
Q: SonarQube replying with NO_MIGRATION although db migration is required We have automated the SonarQube server installation using Ansible. As part of this procedure, Ansible polls the URL sonar/api/server/index to check whether the server is up-and-running. As soon as an HTTP 200 is returned and the server status is equal to SETUP...
<server>
    <id>20170131094026</id>
    <version>5.6.2</version>
    <status>SETUP</status>
</server>

... the script triggers a database upgrade by sending a POST to sonar/api/server/setup and waiting for MIGRATION_SUCCEEDED to be returned.
This has worked well until now that I tried to upgrade SonarQube from version 5.6.2 to 5.6.5. For some reason sonar/api/server/index now always returns the status UP (even though the GUI clearly indicates that it's still under maintenance) and a POST to sonar/api/server/setup indicates that the database is up-to-date and no migration is needed (NO_MIGRATION).
However, the server is still in maintenance mode and the nexus.log keeps repeating the same line:
09:41:05 INFO  ce[o.s.c.a.WebServerWatcherImpl] Still waiting for WebServer...
09:41:39 INFO  ce[o.s.c.a.WebServerWatcherImpl] Still waiting for WebServer...
09:43:13 INFO  ce[o.s.c.a.WebServerWatcherImpl] Still waiting for WebServer...
09:47:28 INFO  ce[o.s.c.a.WebServerWatcherImpl] Still waiting for WebServer...

When I manually navigate to sonar/setup and click on the Update button, then a database migration starts... Has there been any changes in the API? Am I calling the wrong REST endpoints?

A: You're using internal web services (api/server/index and api/server/upgrade). Responses and behavior can change between versions without any notification.
You should use instead :

*

*GET api/system/db_migration_status : to get the database migration status

*POST api/system/migrate_db : to execute the migration

I encourage you to go to http:///web_api to see documentation of available web services for the version of SonarQube your using.


text:
Q: Specifying within Xcode dart main entry point Supporting multiple environments my Flutter app contains multiple main entry point files:
main_prod.dart
main_dev.dart
main_staging.dart

Within each file importing the appropriate config file:
void main() => runApp(
    new ConfigWrapper(config: Config.fromJson(config), child: new PlatterzApp()));

Building android APK, I can specify the main entry point using command:
flutter build apk --split-per-abi -t lib/config/main_prod.dart

I am searching for a way of archiving this using Xcode for iOS app (multiple targets)

A: You can use custom xcconfig (like Release.xcconfig or Debug.xcconfig) and override FLUTTER_TARGET property from Generated.xcconfig. E.g. dev.xcconfig:
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
app_name_prefix=DEV.
bundle_id_suffix=.dev
FLUTTER_TARGET=/path/to/your/main_dev.dart

A: In addition to roman's answer, you can also configure the entry points directly from Xcode. Just open your Runner.xcworkspace with XCode, select the 'Runner' project, go to Build Settings and make sure the all option is selected (see image in the link below). Then, just type FLUTTER_TARGET at search bar (upper right corner) and edit the dart's entry points.


text:
Q: Rand() Conversion Warning I have :
r = ((float)(rand()/(float)(RAND_MAX)) *  BOUND);

this also gives the same warning:
r = ((rand()/(float)(RAND_MAX)) *  BOUND);

And the warning:
 conversion to 'float' from 'int' may alter its value

Any possible fixes?

A: You get this warning because float variables do not have enough precision to hold any possible value an int can take. That means the cast can produce a wrong result if the integer you're casting from is too large. For example, an integer like 1 000 000 451 would be cast to 1.000000E9, making it wrong by 451. Depending on the value of your RAND_MAX this may or may not actually be a problem in your specific case.
It would be safer to use double instead, where you should not have this issue.

A: Both RAND_MAX and the return value of rand() itself are of type int.
A 32bit int can have a maximum value (INT_MAX) of up to ten digits.
A float -- commonly implemented as 32 bit FP -- has about 6 digits of precision.
This means that there is not enough precision to distinguish e.g. 2,147,483,647 from 2,147,483,646. This is why the compiler generates that warning: Your conversion is not safe for all cases.
The quick fix is to use double, which is commonly implemented as 64 bit FP, having about 15 digits of precision. That's enough to hold a 32bit int (but not enough for a 64bit one).
All in all, rand() is a terrible function, and the standard allows it to be quite bad on the "randomness" as well. If you need good random numbers, you shouldn't rely on the standard library, but use a dedicated third-party solution (which usually includes functions that return floating point right away).


text:
Q: Finding only path through directed graph which visits all nodes exactly once Suppose I have a directed graph that only has exactly one path which visits all the nodes exactly once.
Since there is only one possible path, a start (no arrows pointing to it) and end node (no arrows pointing from it) - marked in red - can be easily identified. Thereafter, I can use brute force to determine the path.
I'd like to learn a better way of doing this, assuming the conditions given in paragraph 1 are always true for the graph.

A: Sounds like you should do a breadth-first search, start at your starting node, add all neighbours to a Queue, look at the first item from the Queue, add all its neighbours to the Queue, repeat.
https://nl.wikipedia.org/wiki/Breadth-first_search


text:
Q: Animation-play-state lines not working and disabling another function? Warning: I'm a noobie. I have these 2 functions in my J/S:
function please()
{
    document.getElementById("test3").innerHTML = "mercy";
}

function displayAnimation()
{

    document.getElementById('myfirst').style.animation-play-state = 'running';
    document.getElementById('myfirst').style.-moz-animation-play-state = 'running';
    document.getElementById('myfirst').style.-webkit-animation-play-state = 'running';

}

They do not interact whatsoever, from what I know. But when I have the 3 lines in displayAnimation(), please() does not work, even though my other J/S functions will work.
In addition to that, the animation isn't changing from 'pause' to 'running' when I active displayAnimation().

A: If you take a good look at your style properties you'll notice their syntax is invalid(JavaScript syntax)
The naming conventions for multiple word properties separated by a - is first-second --> firstSecond eg
style.animationPlayState

for vendor prefixes -prefix-other --> PrefixOther
eg
style.MozAnimationPlayState


text:
Q: Using RegEx in a CodeIgniter route I'm in the progress of converting an old site over to CodeIgniter which involves preserving some old URLS. I need to be able to pass a single character, either #, A-Z or a-z. Here is my pattern:
/^[a-zA-Z#]$/

It seems to work out just fine in all of my tests by passing it to preg_match(). I simply added it to a CI route like this:
$route['(:any)/(/^[a-zA-Z#]$/)'] = "collection/view/$1/alpha/$2";

and it is giving me this error:
Message: preg_match(): Unknown modifier '/'

I can't for the life of me massage this pattern to allow CI to accept it. I think it's being escaped strangely. Any help would be appreciated.
UPDATE:
I dove in to /core/Router.php just to see what CI was doing with the pattern. Here is what CI is using:
#^(.+)/(/^[a-zA-Z\#]$/)$#

It is converting the entire passed string into one big pattern.
SOLVED:
After figuring out that CI attempts to create one big pattern I rewrote the pattern from scratch and removed the (:any). I have also replaced the # with a +. Here is my final solution:
 $route['(^(.+)/([a-zA-Z\+]$))'] = "collection/view/$2/alpha/$3";

If anyone has a more elegant pattern, please feel free to post it. Thanks!

A: $route['(:any)/(^([a-zA-Z]|\#))'] = "collection/view/$1/alpha/$2";

A: I don't think you need to escape # in regex. Try using
/^([a-zA-Z#])$/
instead of
(/^([a-zA-Z]|#)$/)


text:
Q: how to delete an item in array I've a question about removing items from an meteor document.
First of all, my database schema:
{
    _id: "kun1",
    job_x ["20080101","20131204"],
}

Well, I want to delete the last item of the array job_x and
I tried:
Box.update( {_id: this._id} , {$pull: { job: -1 } } );

A: You can use mongodb's $pop to remove an item from an array.  The value 1 will specify it is the last item to be removed.
Box.update( {_id: this._id} , {$pop: { job_x: 1 } } );


text:
Q: AS sentence differences
*

*What was the most painful experience you have ever experienced as mother?

*What was the post painful experience you have ever experienced as a wife?

*What was the most painful experience?
What are the differences between these 3 questions?
What does change when we use "as a someone" and what does change if we change that "someone"?

A: The literal difference between these sentences is simply one of time limiting. "What was the most painful experience you have ever experienced as a mother" would be "from the time you became a mother until now, what was your most painful experience?" — if you choose to interpret the questions completely literally.
However, when people ask these questions, there is more than likely an extra nuance implied with these "as" clauses. "What was the most painful experience you have ever experienced as a mother" has the implied limitation that the painful experiences you're interested in are ones that have to do in some way with motherhood (or, for the "as a wife" example, married life). For instance, they might be looking specifically for conflicts with your children or partner, or times when your children or partner were seriously ill or upset; and even if you, for instance, lost your arm in an accident during your day job during that time, the asker probably isn't interested in that unless it specifically has to do with motherhood (or married life).


text:
Q: Joomla Invalid token / Session timeout issue I have a site that is implemented in Joomla 3.1.5 on which the following are installed

*

*http://www.joomlart.com/joomla/templates/ja-muzic --> This is the theme

*http://www.jomsocial.com/ --> Used as the community plugin

*http://www.kunena.org/ --> The forums plugin

*http://getk2.org/blog --> The Blog plugin

Of course there are some custom components and modules that are implemented.
The issue i am facing is that there is some kind of conflict happening between the sessions i think. What happens is that the session times out randomly or i get a error message as "Invalid Token". All this even when the pages is being used continuously.
I have checked the value in the back-end config , Session Lifetime is set to 60 and Session Handler is set to Database
Let me know if you need more info.
Any help or direction would be appreciated.
Thanks

A: The problem is actually caused by JomSocial and the cache plugin. Try disabling caching or changing the order of the cache plugin.
Worst case scenario, you can disable the "Invalid Token" issue in the code - but that solution would be a bit extreme (but, if all else fails, it's the only solution).
PS: For an in-depth about the "Invalid Token" error, you can check here: http://www.itoctopus.com/invalid-token-on-joomla-login


text:
Q: JBoss Deployment error: Caused by: java.lang.RuntimeException: .war module listed in application.xml does not exist within .ear I am using jboss-5.1.0.GA and jdk1.6. I have my stock.ear in C:\atgcertenv20120601\jboss-5.1.0.GA\server\AllStocks\deploy\stock.ear.While running getting deployment error.Find the following error trace.
15:41:17,518 ERROR [ProfileDeployAction] Failed to add deployment: stock.ear
org.jboss.deployers.spi.DeploymentException: Exception determining structure: Ab
stractVFSDeployment(stock.ear)
        at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentExcept
ion(DeploymentException.java:49)
        at org.jboss.deployers.structure.spi.helpers.AbstractStructuralDeployers
.determineStructure(AbstractStructuralDeployers.java:85)
        at org.jboss.deployers.plugins.main.MainDeployerImpl.determineStructure(
MainDeployerImpl.java:1004)
        at org.jboss.deployers.plugins.main.MainDeployerImpl.determineDeployment
Context(MainDeployerImpl.java:440)
        at org.jboss.deployers.plugins.main.MainDeployerImpl.addDeployment(MainD
eployerImpl.java:390)
        at org.jboss.deployers.plugins.main.MainDeployerImpl.addDeployment(MainD
eployerImpl.java:300)
        at org.jboss.system.server.profileservice.repository.MainDeployerAdapter
.addDeployment(MainDeployerAdapter.java:86)
        at org.jboss.system.server.profileservice.repository.ProfileDeployAction
.install(ProfileDeployAction.java:61)
        at org.jboss.system.server.profileservice.repository.AbstractProfileActi
on.install(AbstractProfileAction.java:53)
        at org.jboss.system.server.profileservice.repository.AbstractProfileServ
ice.install(AbstractProfileService.java:361)
        at org.jboss.dependency.plugins.AbstractControllerContext.install(Abstra
ctControllerContext.java:348)
        at org.jboss.dependency.plugins.AbstractController.install(AbstractContr
oller.java:1631)
        at org.jboss.dependency.plugins.AbstractController.incrementState(Abstra
ctController.java:934)
        at org.jboss.dependency.plugins.AbstractController.resolveContexts(Abstr
actController.java:1082)
        at org.jboss.dependency.plugins.AbstractController.resolveContexts(Abstr
actController.java:984)
        at org.jboss.dependency.plugins.AbstractController.change(AbstractContro
ller.java:822)
        at org.jboss.dependency.plugins.AbstractController.change(AbstractContro
ller.java:553)
        at org.jboss.system.server.profileservice.repository.AbstractProfileServ
ice.activateProfile(AbstractProfileService.java:306)
        at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(
ProfileServiceBootstrap.java:271)
        at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:
461)
        at org.jboss.Main.boot(Main.java:221)
        at org.jboss.Main$1.run(Main.java:556)
        at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.RuntimeException: Error determining structure: stock.ear
        at org.jboss.deployment.EARStructure.determineStructure(EARStructure.jav
a:293)
        at org.jboss.deployers.vfs.plugins.structure.StructureDeployerWrapper.de
termineStructure(StructureDeployerWrapper.java:73)
        at org.jboss.deployers.vfs.plugins.structure.VFSStructuralDeployersImpl.
doDetermineStructure(VFSStructuralDeployersImpl.java:196)
        at org.jboss.deployers.vfs.plugins.structure.VFSStructuralDeployersImpl.
determineStructure(VFSStructuralDeployersImpl.java:221)
        at org.jboss.deployers.structure.spi.helpers.AbstractStructuralDeployers
.determineStructure(AbstractStructuralDeployers.java:77)
        ... 21 more
Caused by: java.lang.RuntimeException: stk_bootstrap.war module listed in applic
ation.xml does not exist within .ear vfsfile:/C:/jboss-5.1.0.GA/server/AllStocks/deploy/ stock.ear/
        at org.jboss.deployment.EARStructure.determineStructure(EARStructure.jav
a:272)
        ... 25 more

A: The war is really inside the ear? You can open the .ear with WinRAR or something similar and check.
Are you using Eclipse? If you turn off automatic build in Eclipse it doesn't create the war or ejb.jar before the packaging of the ear.
You could do it manually or enable it under Project -> Build Automatically.
Have you included the .war in the .ear project? Right click on the project, properties and check under 'Deployment Assembly'.


text:
Q: I need to change the entire row colour in Excel when a cell value =1 I need to change the entire row colour in Excel when a cell value has a "1"
Can this be done?
For example the column G will contain either a 1 or a 0. If the cell has the value  1 then I want the entire row to change colour
Appreciate any help

A: The formula is:
=$G1 = 1

And the Applies to is:
=$1:$1048576


text:
Q: Cron to send email if file doesn't exist I have a cron job that executes a shell script like following
00 01 * * * sh /backup/script.sh

Now I need to add a functionality in cron so that if this script doesn't exist then it generates an alert to me through email using sendmail utility.
Something like
00 01 * * * find script and execute script or if find no result then email.

A: I see two general solutions. One is to make cron notify you of the results of commands it runs. Specifically, the crontab(5) man page states that

cron(8) will look at MAILTO if it has any reason to send mail as a
  result of running  commands  in  ``this''  crontab.  If MAILTO is
  defined (and non-empty), mail is sent to the user so named.

Just put a line like the following in the head of your crontab file:
MAILTO=username@domain.com

Alternatively, if you want a more specialized solution, you can create a script and put it in place where it is guaranteed to be found (like /bin). The script itself would check whether the actual script is present, if yes, run it, if not, send you a notification. Something along the following lines:
#!/bin/bash

myscript=/path/to/your/script
myemail=username@server.org

if [ -f "$myscript" ] ; then
    exec "$myscript"
else
    mail -s "Error running $myscript" $myemail <<EOF
There was an error running the script
$myscript
The script could not be found
EOF
fi

You could even make it generic:
#!/bin/bash

myscript=$1
shift 1
params=$*
myemail=username@server.org

if [ -f "$myscript" ] ; then
    exec "$myscript $*"
else
    mail -s "Error running $myscript" $myemail <<EOF
There was an error running the script
$myscript
The script could not be found
EOF
fi

A: cron does this for you already. Your crontab entry says:
00 01 * * * sh /backup/script.sh

At the scheduled time, cron will execute the command you specified and email you its output.
The output of sh /does/not/exist is: sh: 0: Can't open /does/not/exist. So this is what cron will email you if the file does not exist.
You may need to make sure your system is configured correctly for email, so that cron is able to email you successfully. You mentioned sendmail; if sendmail is configured correctly, and emailing your user works, then cron will work, too.
The MAILTO variable can also help if you need to email a different address, or if emailing your user does not work, but emailing a specific Internet email address does. Just add the line MAILTO=foo@example.com above the existing line.

A: Well, you will need another script. Something like this:
#!/bin/bash

file="/path/to/script.sh"

# if script.sh exists and is executable.
if [ -x $file ]; then
    # execute script.sh
    sh /path/to/script.sh
else
    #send mail
    echo "script.sh doesn't exists or is not executable" | sendmail me@example.com
fi


text:
Q: using sinonjs to test a function that calls new on a dependency I'm terribly confused and would love some help.
I don't think this code is poorly designed, but correct me if you see a flaw.
I can't seem to figure out how to test a function that calls new on a dependency.  Here are my boiled down classes....with irrelevant business logic stripped.
MyWrapper.js
const SomeLib = require('SomeLib');

module.exports.MyWrapper = class MyWrapper {
    constructor(username, password) {
        this._someLib = new SomeLib(username, password);
    }

    async getFoo(id) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.findById(id)
    }

    async saveFoo(object) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.save(object)
    }
}

MyApp.js
const MyWrapper = require('MyWrapper');

const process = async (message) => {
    const wrapper = new MyWrapper(process.env.username, process.env.password)
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }

MyApp.spec.js
const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        it('should call save when data is found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return some JSON
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was called
        });
    });
});

A: from looking at your code with the way it is currently structured, you won't be able to not call new MyWrapper because that call is made inside the function that you are calling. What you likely would want to do is use dependency injection to pass in an instance of MyWrapper. Using DI would also allow you to pass in a mocked version of your Wrapper class for more control over testing. This would look something like this:
// MyApp.js

const MyWrapper = require('MyWrapper');

const wrapper = new MyWrapper(process.env.username, process.env.password);

const process = async (message, wrapper) => {
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }

You may want to instantiate the wrapper somewhere else that makes sense for your application, but based on the code you have presented this would now allow you to pass in your own test version of the Wrapper class when testing, like so:
// MyApp.spec.js

const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             const wrapper = new MyWrapper();
             await sut.process(msg, wrapper);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        ...
});

the second part of your question involves creating a stub of a class using sinon. The documentation for sinon, found here, is probably going to give you the best example of how to make a stub and return your own value from the stubbed class.
Hope this helps!

A: We probably need to install and include proxyquire library to stub MyWrapper implementation.
MyApp.spec.js
const proxyquire = require("proxyquire"); // include the library here
const sinon = require("sinon");
const chai = require("chai");
const sinonChai = require("sinon-chai");
chai.should();
chai.use(sinonChai);

describe("MyApp", function() {
  describe("process", function() {
    beforeEach(() => {
      sinon.restore(); // best practice to always restore stub
    });

    it("should not call save when no data found", async function() {
      // stub getFoo to return undefined
      const getFooStub = sinon.stub().returns(undefined);
      const saveFooStub = sinon.stub();

      // create wrapper function to return stub
      function MyWrapperStub() {
        return {
          getFoo: getFooStub,
          saveFoo: saveFooStub
        };
      }

      // I don't know why your code use require('MyWrapper'), it should be prefixed with `./`
      // Here is basically we override `./MyWrapper` in our `MyApp.js` with the stub
      const sut = proxyquire("./MyApp", { "./MyWrapper": MyWrapperStub });

      const msg = { id: "123" };
      await sut.process(msg);

      getFooStub.should.have.been.calledWith("123");
      saveFooStub.should.not.have.been.called;
    });

    it("should call save when data is found", async function() {
      // stub getFoo to return json data
      const data = { name: "something" };
      const getFooStub = sinon.stub().returns(data);
      const saveFooStub = sinon.stub();

      function MyWrapperStub() {
        return {
          getFoo: getFooStub,
          saveFoo: saveFooStub
        };
      }
      const sut = proxyquire("./MyApp", { "./MyWrapper": MyWrapperStub });

      const msg = { id: "123" };
      await sut.process(msg);

      getFooStub.should.have.been.calledWith("123");
      saveFooStub.should.have.been.calledWith(data);
    });
  });
});

In MyApp.js, I changed the implementation of require to be
const MyWrapper = require('./MyWrapper');

If you keep insisting to use require('MyWrapper') then in the test file, proxyquire must be set to proxyquire("./MyApp", { "MyWrapper": MyWrapperStub });
Screenshot:

Hope it helps
Ref:

*

*https://www.npmjs.com/package/proxyquire