text:
Q: Airflow: How to only send email alerts when it is not a consecutive failure? I've an airflow dag that executes 10 tasks (exporting different data from the same source) in parallel, every 15min. I've also enabled 'email_on_failure' to get notified on failures.
Once every month or so, the tasks start failing for a couple of hours due to the data source not being available. Causing airflow to generate hundreds of emails (10 emails every 15min.), until the raw data source is available again.
Is there a better way to avoid being spammed with emails once consecutive runs fail to succeed?
For example, is it possible to only send an email on failure once it is the first run that start failing (i.e. previous run was successful)?

A: To customise the logic in callbacks you can use on_failure_callback and define a python function to call on failure/success. in this function you can access the task instance.
A property on this task instance is try_number - which you can check before sending an alert. An example could be:
some_operator = BashOperator(
    task_id="some_operator",
    bash_command="""
        echo "something"
    """,
    on_failure_callback=task_fail_email_alert,
    dag=dag,

def task_fail_email_alert(context):
    try_number = context["ti"].try_number
    if try_number == 1:
        # send alert
    else:
        # do nothing

You can them implement the code to send an email in this function, rather than use the builtin email_on_failure. The EmailOperator is available by importing from airflow.operators.email import EmailOperator.

A: Giving consideration that your tasks are running concurrently and one or multiple failures could occur, I would suggest to treat the dispatch of failure messages as one would a shared resource.
You need to implement a lock that is "dagrun-aware" –– one that knows about the DagRun.
You can back this lock using an in-memory database like Redis, an object store like S3, system file, or a database. How you choose to implement this up to you.
In your on_failure_callback implementation, you must acquire said Lock. If acquisition of said Lock is successful, carry on to dispatch the email. Otherwise, pass.
from airflow.providers.amazon.aws.hooks.s3 import S3Hook

class OnlyOnceLock:

    def __init__(self, run_id):
        self.run_id = run_id

    def acquire(self):
        # Returns False if run_id already exists in a backing store.
        # S3 example
        hook = S3Hook()
        key = self.run_id
        bucket_name = 'coordinated-email-alerts'
        try:
            hook.head_object(key, bucket_name)
            return False
        except:
            # This is the first time lock is acquired
            hook.load_string('fakie', key, bucket_name)
            return True

    def __enter__(self):
        return self.acquire()

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

def on_failure_callback(context):
    error = context['exception']
    task = context['task']
    run_id = context['run_id']
    ti = context['ti']
    with OnlyOnceLock(run_id) as lock:
        if lock:
            ti.email_alert(error, task)


text:
Q: Google chrome dev tools says 404 error, but the file is present and can be clicked right in dev tools! I've got this script installed on two sites. In my localhost site, it operates fine. However, on my 2nd test site, the script below is returning a 404 error (in Chrome's developer console) on the color.php file.
Although, I can then click on color.php in the console and it loads fine and echo's out the correct value I'm expecting. I'm at a loss for what's causing the 404, but its preventing the script from getting to the alert() in the doColor() function. Any ideas?
$('#my_theme').change
(
    function()
    {
    $("#largePreview").hide();
    var myImage = $('#my_theme :selected').text();
    $('.selectedImage img').attr('src','<?php echo get_bloginfo('template_directory') ?>/styles/'+myImage+'/screenshot.jpg');
    $('.selectedImage img').attr('title',myImage);
    $.get('<?php echo get_bloginfo('template_directory') ?>/color.php', {theme: myImage, spot: '1'}, function(data){doColor('#my_theme_header_color', data);});
    $.get('<?php echo get_bloginfo('template_directory') ?>/color.php', {theme: myImage, spot: '2'}, function(data){doColor('#my_theme_sidebar_color', data);});
    $.get('<?php echo get_bloginfo('template_directory') ?>/color.php', {theme: myImage, spot: '3'}, function(data){doColor('#my_theme_spot_color_alt', data);});
    $.get('<?php echo get_bloginfo('template_directory') ?>/color.php', {theme: myImage, spot: '4'}, function(data){doColor('#my_theme_spot_color_alt2', data);});
    }
);

function doColor(el, color)
    {
    alert('in function docolor');
    $(el).val(color).trigger('keyup');
    $(el).attr('value', color);
    $(el).val(color);
}

Contents of color.php is below...
<?php
require_once('../../../wp-blog-header.php');

$myTheme = $_REQUEST['theme'];
$spot = $_REQUEST['spot'];
$myThemeColor = $myTheme."_color".$spot;
$myColor = get_option($myThemeColor);
$file = "styles/".$myTheme."/template.ini";
if ($myColor == "")
{
    if (file_exists($file) && is_readable($file))
    {
    $ini_array = parse_ini_file($file);
     if($spot == 1){$myColor = $ini_array['color1'];}
     if($spot == 2){$myColor = $ini_array['color2'];}
     if($spot == 3){$myColor = $ini_array['color3'];}
     if($spot == 4){$myColor = $ini_array['color4'];}
    }
    else
    {
     if($spot == 1){$myColor = get_option('cb2_theme_header_color');}
     if($spot == 2){$myColor = get_option('cb2_theme_sidebar_color');}
     if($spot == 3){$myColor = get_option('cb2_theme_spot_color_alt');}
     if($spot == 4){$myColor = get_option('cb2_theme_spot_color_alt2');}
    }
}
echo $myColor;
?>

A: Sounds like your web server doesn't know about the file on the second test server.
Could be a permissions setting.
What platform and web server are you using?

redpajama_set_name: RedPajamaStackExchange


text:
Q: URLRequest equality doesn't include httpBody Overview
There are 2 URLRequests, one with httpBody and one with no httpBody.
However when compared, it shows both are equal.
Question
Is this expected behaviour or am I missing something ?
Code
let url = URL(string: "www.somevalidURL.com")!

var r1 = URLRequest(url: url)
r1.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")
r1.httpBody = makeBody(withParameters: ["email" : "a@b.com"])

var r2 = URLRequest(url: url)
r2.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")

if r1 == r2 {
    print("requests are equal")
}
else {
    print("requests are not equal")
}

if r1.httpBody == r2.httpBody {
    print("body is equal")
}
else {
    print("body is not equal")
}

func makeBody(withParameters bodyParameters: [String : Any]?) -> Data? {
    guard let bodyParameters = bodyParameters,
        !bodyParameters.isEmpty else {
            return nil
    }
    let body : Data?
    do {
        body = try JSONSerialization.data(withJSONObject: bodyParameters,
                                          options: .prettyPrinted)
    }
    catch {
        print("Error in creating Web Service Body = \(error)")
        body = nil
    }
    return body
}

Output
requests are equal
body is not equal

Xcode 10
Swift Version: 4.2

A: URLRequest is the Swift overlay type for the Foundation type NSURLRequest, so that that == ultimately calls the isEqual() method of
the NSURLRequest.
The Foundation library is open source for non-Apple platforms, and at
NSURLRequest.swift#L252 we find:
open override func isEqual(_ object: Any?) -> Bool {
    //On macOS this fields do not determine the result:
    //allHTTPHeaderFields
    //timeoutInterval
    //httBody
    //networkServiceType
    //httpShouldUsePipelining
    guard let other = object as? NSURLRequest else { return false }
    return other === self
        || (other.url == self.url
            && other.mainDocumentURL == self.mainDocumentURL
            && other.httpMethod == self.httpMethod
            && other.cachePolicy == self.cachePolicy
            && other.httpBodyStream == self.httpBodyStream
            && other.allowsCellularAccess == self.allowsCellularAccess
            && other.httpShouldHandleCookies == self.httpShouldHandleCookies)

So that seems to be intentional.

A: If you've come here wondering why your identical URLRequests aren't equal to each other like I did I found the reason to be that URLRequest's equatable implementation differentiates between httpBody being set to nil or being defaulting to nil.
If we do the following:
let request = URLRequest(url: URL(string: "test.com"))
var expectedRequest = URLRequest(url: URL(string: "test.com"))
expectedRequest.httpBody = nil

Then:
request == expectedRequest //false
print(request.httpBody) // nil
request.httpBody = nil
request == expectedRequest //true

Explicitly settings the httpBody to nil will fix this issue. In fact what the body is doesn't matter, only that it has been explicitly set.
request.httpBody = Data()
request == expectedRequest //true

Potential explanation
As Martin rightly points out Swift's source code does not include httpBody. However all of the properties (in the link) being equal (and both being castable as NSURLRequests) does not return true (see lldb output below). I can only presume the linked code is overridden to include another property and this is modified when didSet or willSet is called on httpBody


text:
Q: Reac component is not beeing exported I'm new to react and I'm just trying to start a new website but not being successful at it. For some reason, I get this error Module not found: Can't resolve './pages' in '/Users/joanaleitaooliveira/repos/web-project/src'. Here you can see the App.js file and the about page file. All the other pages are the same.
I've also tried ./src/pages/About/index.jsx but got the same result. Can anyone tell me why is this happening?
[![enter image description here][1]][1]

A: The cause of the problem is due to the path mentioned in import statement not getting resolved.
Problem can be fixed by using the complete path to the component in the import statement.
Working example:
import Home from "./pages/Home"
import About from "./pages/About"
import Contact from "./pages/Contact"

A: You would need to create an index.js file in pages that exports all these components if you want to import through ./pages.


text:
Q: Find the Algorithm that generates the checksum I have a sensing device that transmits a 6-byte message along with an 1-byte counter and supposedly a checksum.
The data looks something like this:
------DATA----------- -Counter- --Checksum?--

55 FF 00 00 EC FF ---- 60---------- 1F

The last four bits in the counter are always set 0, i.e those bits are probably not used. The last byte is assumed to be the checksum since it has a quite peculiar nature. It tends to randomly change as data changes.
Now what I need is to find the algorithm to compute this checksum based on --DATA--.
what I have tried is all possible CRC-8 polynomials, for each polynomial i have tried to reflect data, toggle it, initiate it with non-zeroes etc. I've come to the conclusion that i am not dealing with a normal crc-algorithm. I have also tried some flether and adler methods without success, xor stuff back and forth but still i have no clue how to generate the checksum.
My biggest concern is, how is the counter used??? Same data but with different countervalue generates different checksums.
I have tried to include the counter in my computations but without any luck.
Here are some other datasamples:
55 FF 00 00 F0 FF A0 38
66 0B EA FF BF FF C0 CA
5E 18 EA FF B7 FF 60 BD
F6 30 16 00 FC FE 10 81

One more thing that might be worth mentioning is that the last byte in the data only takes on the values FF or FE
Please, if you have any tips or tricks that i may try post them here, I am truly desperate.
Thanks

A: Some random ideas:

*

*Bit ordering: you are currently representing the data as octets, but this is not how the CRC algorthm sees it. CRCs operate on polynomials represented as arrays of bits, not arrays of octets. Because of this, it is possible that the device performs the CRC using different bit ordering scheme than the one you are using.

*Depending on the device, I would say it is rather likely that the counter is included in the CRC calculation.

*If this is an embedded device, it might be use some other code, such as a BCH.

Is there any other information that can be given about the device in question?
This might give some indication as to how strong coding has been used. As an example, certain CRC-12 (0x8F8) provides Hamming distance of 5 up to data word lengths of 53 bits (in your data the data word could be 52 bits, assuming CRC size of 12 bits).
Edit:
See the answer in How could I guess a checksum algorithm? for some additional ideas.


text:
Q: Rails 5 search ActiveRecords with many to many relationship for matching fields I have two models with a many-to-many relationship defined through another model.  In this case A user belongs to many groups.   And each group can have many users.
There relationship is defined through a Membership model, which also has the status of their membership i.e.
user.rb
class User < ApplicationRecord
  has_many :memberships
  has_many :groups, through: :memberships
end

group.rb
class Group < ApplicationRecord
  has_many :memberships
  has_many :users, through: :memberships
end

membership.rb
class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :group

  enum status: [ :non_member, :pending, :member ]
end

When I create a new group, It always creates a membership for the user who created it.   At a later date other users create memberships for a group.
Within one of my views, I want to show all groups that the current user belongs to. So I can do something like this:
<% @user.groups.each do |group| %>
   <p><%= group.name %>
<% end %>

I then want to show all the groups that a user does not belong to, so that they can request to join.  I tried this, but it returns all records, even though my user is a member of one group.
<% Group.joins(:users).where.not(:users => { :id => current_user.id }).each do |group| %>

Is there a better way to achieve this?

A: class User < ApplicationRecord

   has_many :memberships
   has_many :groups, through: :memberships

   def unjoined_groups
      Group.where.not(id: group_ids)
   end

   def unjoined_groups_by_membership_status(status)
      Group.includes(:memberships)
        .where.not(id: group_ids)
        .where(memberships: { status: status })
   end

end

Try this instead...


text:
Q: jQuery Mobile - Intellisense for Visual Studio 2010 I have been unable to get Visual Studio to present intellisense when working with jQuery-Mobil.
How do I enable this in Visual Studio 2010

A: You can use intellisense-jquery-mobile that adds Intellisense support to Visual Studio 2010 SP1 for the jQuery Mobile data-* attributes.
To install, copy the html_5_jqm.xsd to the appropriate Visual Studio schema directory (e.g. C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Packages\schemas\html) and execute the corresponding .reg file for your environment.

A: So I did everything except "running the corresponding .reg for my environment".
I cannot understand how to do this.Inside of Windows or in VS.I am using VS 2010 SP1.


text:
Q: OpenGL GL_RGB texture format isn't working on iOS (GL_RGBA works great) Hello people of the wasteland :),
Brief: There is a problem with GL_RGB internal texture format on iOS platform.
In my application I try to save some memory by using GL_RGB instead of GL_RGBA as an internal format.
I'm using the next code piece to achieve this. Nothing else is changed.
glTexImage2D(_textureTargetType,
     0,
     GL_RGB,            // pixel internalFormat
     texWidth,          // image width
     texHeight,         // image height
     0,             // border
     GL_RGBA,           // pixel format
     GL_UNSIGNED_BYTE,      // pixel data type
     bitmapData);

On MacOS these changes went fluently, no problems. But on iOS, particularly 4.3 (OpenGL ES2.0) it gives me GL_INVALID_OPERATION everytime I try to render textured polgons with this texture. As nothing except this format is changed I think the problem is in incompatibility of GL_RGB internal format with OpenGL ES2.0. This is just my guess, I'm no guru.
This doesn't work in simulator nor iPod touch 4th gen.
Thank you for any reasonable suggestion.

A: According to the documentation, "internalformat must match format. No conversion between formats is supported during texture image processing." See the Khronos website. OpenGL does not have this limitation, so this code will work on Mac OS, but not the more limited OpenGL ES on iOS devices.


text:
Q: web app apparently mixing up authentication credentials I built this in-house web app (built on Flask and served with Gunicorn) and for ages it's never stored any sort of user data or session data and it worked fine. Now I added an authentication page, using my organization's LDAP - user inputs username and password (same they use to log in on their machines), app verifies the credentials on the LDAP server and lets the user through if everything matches.
When I serve the app with only one process (gunicorn -w 1) it works fine. But when I serve the app with multiple processes I get erratic behavior! Sometimes authentication fails even though username and password are correct. Sometimes if one user authenticates then others are treated as authenticated. And sometimes the user authenticates and gets to use the app for a while but then clicks something and gets redirected to the login page (all functions are decorated to check that the user is authenticated).
My guess is that I'm failing to properly isolate the users - user X enters correct username and password but when clicks "submit" the app thinks that's user Y, who hasn't authenticated, and therefore denies access (here's the logic of the authentication: I check if flask.session has the key user; if it does, the user gets through; if not, user is redirected to the login page and if authentication is successful I store the username in flask.session["user"]).
How can I debug this? If my guess is correct then how can I make sure that users' credentials don't get mixed up?

A: I noticed that the session object was not persisting (it kept getting empty for no apparent reason). I googled around and found this answer. Turns out my app's secret key shouldn't be random (it was os.urandom(24)), it should be a constant string instead. Once I fixed that the authentication worked correctly.


text:
Q: Calculate sum of N preceding values I am write a SQL query to replicate below Excel result.
In Column A I have 252 values in ASC order from 10/30/2018 to 10/29/2019
In Column BV I have respective PL Number
I want to calculate TestPL column having value as Ignore first 3 PL Values and 4th Cell would be addition of B2:B5, 5th Cell would be B3:B6 and so on for all 251 values
TestPL should start from row 4 and should have sum of cells B2:B5, and row 5 would be  B3:B6 and so on in a stream till row 252 which would B249:B252

A: Use a window function
...sum(PL) over(order by [Date] range between 3 preceding and current row)


text:
Q: Image sliding while using a slice effect I'm trying to make a slideshow with some great effects. Im trying to make the image slide while making a slice function. The slice function of the image slideshow works fine, but i can't seem to figure out how to make the image change while im using my slice function.
HTML:

CSS:
.sliced {
position: relative;
width: 640px;
height: 400px;
}
.sliced img {
position: absolute;
width: 640px;
height: 400px;
}
.tile {
float: left;
opacity: 1;
-webkit-transition: all .3s ease-in-out;
-moz-transition: all .3s ease-in-out;
-ms-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
}
.tile-animated {
    opacity: 0;
}
.css3-preload .sliced * {
-webkit-transition: none !important;
-moz-transition: none !important;
-ms-transition: none !important;
-o-transition: none !important;
transition: none !important;
}

AND JAVASRIPT:
;(function( $, window ) {
var _defaults = {
x      : 2, // number of tiles in x axis
y      : 2, // number of tiles in y axis
random : true, // animate tiles in random order
speed  : 2000 // time to clear all times
  };
* range Get an array of numbers within a range
* @param min {number} Lowest number in array
 * @param max {number} Highest number in array
 * @param rand {bool} Shuffle array
* @return {array}
  */

function range( min, max, rand ) {
var arr = ( new Array( ++max - min ) )
  .join('.').split('.')
  .map(function( v,i ){ return min + i})
return rand
  ? arr.map(function( v ) { return [ Math.random(), v ] })
     .sort().map(function( v ) { return v[ 1 ] })
  : arr
  }
// Prevent css3 transitions on load
$('body').addClass('css3-preload')
$( window ).load(function(){ $('body').removeClass('css3-preload') })
  $.fn.sliced = function( options ) {

var o = $.extend( {}, _defaults, options );

return this.each(function() {

  var $container = $(this);
  /*---------------------------------
   * Make the tiles:
   ---------------------------------*/

  var width = $container.width(),
      height = $container.height(),
      $img = $container.find('img'),
      n_tiles = o.x * o.y,
      tiles = [], $tiles;

  for ( var i = 0; i < n_tiles; i++ ) {
    tiles.push('
');
  }
  $tiles = $( tiles.join('') );

  // Hide original image and insert tiles in DOM
  $img.hide().after( $tiles );

  // Set background

  $tiles.css({
    width: width / o.x,
    height: height / o.y,
    backgroundImage: 'url('+ $img.attr('src') +')'
  });

  // Adjust position
  $tiles.each(function() {
    var pos = $(this).position();
    $(this).css( 'backgroundPosition', -pos.left +'px '+ -pos.top +'px' );
  });

  /*---------------------------------
   * Animate the tiles:
   ---------------------------------*/

  var tilesArr = range( 0, n_tiles, o.random ),
      tileSpeed = o.speed / n_tiles; // time to clear a single tile

  // Public method
  $container.on( 'animate', function() {

    tilesArr.forEach(function( tile, i ) {
      setTimeout(function(){
        $tiles.eq( tile ).toggleClass( 'tile-animated' );
      }, i * tileSpeed );
    });

  });

});

  };

}( jQuery, window ));
$('.sliced').sliced({ x: 20, y: 15, speed: 1000 });

var timeCounter = 0;
var timeOut = window.setInterval(function(){
        if(timeCounter==0){
            $('.sliced').trigger('animate');
            timeCounter = 1100;
        }
        if(timeCounter==1100) {
            window.setTimeout(function(){
                $('.sliced').trigger('animate');
            }, timeCounter);
            timeCounter = 0;
        }
}, 5000);

Note that this image slide-slice effect is found on http://jsfiddle.net/elclanrs/4nsJE/ .
I have changed the code a bit, so it loops every 5 second.
What gives me my problem is, that the Tiles seem to use the background of the image when loaded, and then the real image is hidden. I cannot find a way to change the background of the tiles, so that they will use the background of the other image.
//Please look at the jsfiddle to see how it works with a "click-button" to understand it more.
If you've got an answar on how i can solve my problem please feel free to tell me, and give me the code. However i would appreciate if you'd give a reasoning of why it works with your code.
It's important for the scripter that the code works, but more importantly is to know why it works.! :-)


text:
Q: Android Parse: Can't update local user I have a custom boolean field called Approved in my custom ParseUser object. We change this field from false to true via a web app. According to the documentation, I should be able to update currentUser after changing the flag with fetchInBackground(), like this:
ParseUser.getCurrentUser().fetchInBackground(new GetCallback<ParseObject>() {
    @Override
    public void done(ParseObject parseObject, ParseException e) {
        Log.v("qwer", "fetched User: " + ((CustomUser)parseObject).isApproved());
    }
});

But even though the approved flag has been set to true, the result coming back from the server is always false. Unless I logout and login again, at which point currentUser and the respective field is synced with the server.
Why doesn't fetchInBackground() work for the local user, and if I'm using it incorrectly, how do I update the currentUser.

A: Please see this link, the point is to use pinInBackground and also enable local datastore with Parse.enableLocalDatastore(yourContext); in your Application class.

Update:
Not sure if this will help you, but I do have a similar situation with you:
I do a typical user.put("userVerified", true); then user.saveInBackground to save a boolean that indicates whether user has been verified, then in the next activity I use user.getBoolean("userVerified") to retrieve the flag...Would this be something you might consider?


text:
Q: How to connect two docker containers into one python app? I have a python (Streamlit) app, which after the installment of all of the packages, is more than 2GB, when 1.8 of its is only the enviroment.
I want to split it into 2 containers.
First container for the Enviroment, which will include of all of the libraries and so on.
The second one will contain only the python app.
Is there any place I can see how can I do that? Can I "inject" the app files into the enviroment somehow alternatively? Or to link the Containers somehow?
Not sure how to start doing this.


text:
Q: Can we manage the deployment of each django app within a single Django project independently? Lets say we have one django project that has two apps - FooApp & BarApp.
Each app talks to its own database. Meaning they both manage their own set of models. Is it possible to manage the deployments of these apps independently? It's okay for them to be deployed on same server within the same nginx process as long as I am able to make changes to the apps without bringing down the other as well.
I understand that these can very well be separate projects and they can communicate with each other using RESTful APIs. For my needs, I want to avoid that REST interaction for the time being.
The django documentation [here][1] describes a django project and django app as follows
Django project:

The term project describes a Django web application.

Django App:

The term application describes a Python package that provides some set
of features.

So if the app is simply a python package, and the django project is really the one that defines how these apps are managed via the settings module, then I suppose there is no straight forward way of accomplishing what I want. Or is there anything I can do?
TIA
[1]: https://docs.djangoproject.com/en/dev/ref/applications/


text:
Q: Opening existing project from source control I've been pushing my source to a Mercurial repository.  Today I needed to delete my local copy and re-clone.  I did this by simply moving my local copy somewhere else (just in case) and typing "hg clone url".
This part has worked just fine.
However, when I try to pull the newly cloned local copy into Eclipse, I get the following error:
/Users/Andrew/Dev/Workspace/Android/MyProject overlaps the location of another project: 'MyProject'

My guess is that I have been committing some meta file or something that I shouldn't have.  Does anyone have any ideas?  Here is my .hgignore:
syntax: regexp
\.DS_Store
.swo
.swp
.metadata/
/bin/

Note: Looks like my hgignore is not blocking the gen folder.  Could this be part of the problem?

A: Ok, I'll try to sum it up, after I faced similar problems and wasted some time:
Eclipse Juno /4.2 SR1
(however I think it is a general misunderstanding of how eclipse imports projects)

*

*If you want your new project "connected" to git/mercurial, you'll have to clone and import via "Import/Git/Import from Git"

*It will fail if your "workspace dir" equals the "local destination dir".
A git clone via egit MUST NOT be placed! in the "eclipse workspace dir"!

The project import will fail because the projectname in the cloned ".project file" already exists in the eclipse workspace dir when the import occurs.

A: There is a bug in Eclipse what won't let you create an Android project from existing sources:
http://code.google.com/p/android/issues/detail?id=8431
You have to move MyProject to a folder that doesn't have any other projects in its sub-directories.  You can then make a new project from existing source with MyProject.  Remove the new project from the workspace without deleting the contents on disk and move it back to your Android folder.  Now do an Import -> General -> Existing Project into Workspace, and MyProject should be available to import.
This is the only way I've been able to do it.

A: I think the problem is that you moved your local copy away and then you try to add another project into Eclipse at the same location as what you had before and you are just confusing Eclipse...
I would recommend to try to use command line commands for Mercurial and when you get into Eclipse, first clean up existing projects before adding another one.

A: My sollution was just to import as general project not an android one.

A: I ran into this problem when trying to import a git repo project and it's submodules.  I ended up using import -> git -> Projects from Git (git plugin).  This understood the concept of a project within a project just fine. The project is now monitored by that plugin.  It's a good enough tradeoff for me.


text:
Q: divide (split) the line into segments of arbitrary length each. (short at begining wide at the end) Assume there is a line (1, 30) (float x = 30)
I need to split it into segments, each next segment should be wider than previous one, and the last segment should be X times wider than first one.
I have idea first split line into equal parts and than increase next and decrease previous until two conditions reached:
- first segment is shorter than last X times
- each segment (except first) is wider than previous for the same multiplier
    //input:
    int lineDimension = 30;
    int numberOfSegments = 5;
    int step = 1;

    float[] splitLineIntoSegments(float lineDimension, int numberOfSegments, float differenceBetweenFirstAndLastSegmentMultiplicator, float step) {
      float[] result = new float[numberOfSegments];
      //first split into equal segments
      for (int i = 0; i < numberOfSegments; i++) {
        result[i] = lineDimension / numberOfSegments;
      }
      //increase each next value untill difference reached
      do {
        for (int ii = 0; ii < numberOfSegments; ii++) {
          if (result[ii]-step<=0)
            return result;
            if (ii>numberOfSegments/2){
              result[ii] += step;
            }
            else result[ii] -= step;
        }
      }
      while ((float)result[numberOfSegments] / (float)result[0] > differenceBetweenFirstAndLastSegmentMultiplicator);

      return result;
    }

float [] res = splitLineIntoSegments(lineDimension,numberOfSegments,2,step);

as the result it should be 4,5,6,7,8
There is a better way to do it ?

A: If the ratios must be constant, let r, the relative lengths of the segments are 1, r, r², r³, … r^(n-1) for n parts and this sums to (r^n-1) / (r-1). We also have X = r^(n-1), giving r = X^(1/(n-1)).
If the length of the line segment is L, the parts are
L.r^k.(r-1) / (r^n-1)

E.g. for 4 parts and X=27/8, we have r=3/2 and the parts are 8/65, 12/65, 18/65, and 27/65 of L.

If the ratios needn't be constant and the parts are proportional to some given numbers Rk (such that X=R[n-1]/R0), take the sum R and use
L.Rk / R

A: You can force a simple arithmetic sequence for this.
Start with the problem parameters:
N = quantity of segments
X = scale factor: segment[N-1] / segment[0]
L = length of line

First, find the required mean:
mean = L / N

Now, we need the first and last terms to average to the mean.  Let a be the length of the first segment, currently unknown.  Solve for a
(a + X*a) / 2 = mean
 a = 2*mean / (1+X)

You now have the first (a) and last (X*a) terms, and the quantity of terms.  Now it's trivial to find the common difference:
d = (X*a - a) / (N-1)

Your sequence of segments is now
[ a + i*d for 0 <= i < N ]    // i being a sequence of integers


text:
Q: My $(document).ajaxComplete() doesn't work I'm messing with jQuery an AJAX for few days and I've come to a dead end. I'm trying to load some content with AJAX -this part works just fine - and after that I want to execute other script. However, my content loaded with first script doesn't show up till the second script is finished. Code looks like this:
$.ajax({
            url : folder,
            success: function (data) {
                $(data).find("a").attr("href", function (i, val) {
                    if( val.match(/\.(jpe?g|png|gif)$/) ) {
                        var $codeText = "

";
                        $("ul[id=sortable]").append($codeText);
                        $("li").featherlight(folder + val);
                    };
                });
            }
        })

$(window).ajaxComplete(function(){
    console.log("Haba");
    var x = 0;
    while( x < 50000 )
        {
        console.log("Haba nr "+x);
        x++;
        }

The whole code is triggered, but images are showing up on website after all the console messages. Does anyone have any suggestion what to do to show up pictures first? I've also tried with done(). and ajaxStop(), still no effect.

A: Why not just move the code you want to run after the pictures are loaded into the success function of the ajax call and do that after the code to load pictures?
$.ajax({
    url : folder,
    success: function (data) {
        //Code to load pictures

        console.log("Haba");
        var x = 0;
        while( x < 50000 ) {
            console.log("Haba nr "+x);
            x++;
        }
    });

I think the reason it's not behaving the way you want it to is because the ajax call is complete after it gets a response back. That response triggers the ajax complete function that runs before your logic in the success function of the ajax call. Also, the way you have it written, the ajax complete logic will fire even if your ajax call fails. Which I don't think you want.

A: you have to use the .done() function of ajax to get the asynchrone result :

var jqxhr = $.ajax( "example.php" )
  .done(function(data) {
    alert( "success : " + data  );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });

A: try to use setTimeout()
function ajaxDone(){
    console.log("Haba");
    var x = 0;
    while( x < 50000 )
    {
      console.log("Haba nr "+x);
      x++;
    }
}
$(window).ajaxComplete(function(){
  window.setTimeout(ajaxDone,1);
});


text:
Q: Xcode 4 + 5 compatible code using tabBar setTranslucent I'm trying to use [tabBarController.tabBar setTranslucent:NO]; in my app for iOS7.
However, I want the code to compile using xcode 4.
So I check the iOS version at runtime
float ver = [[[UIDevice currentDevice] systemVersion] floatValue];
if (ver >= 7.0) {

using [tabBarController.tabBar setTranslucent:NO]; in Xcode 4 produces the error..
No visible @interface for 'UITabBar' declares the selector 'setTranslucent:'
Because setTanslucent isn't available in iOS6.
I've had many attempts but either the code doesn't run or causes an error...
  //UITabBar *tabBarr = [tabBarController tabBar];
    //if ([tabBarr respondsToSelector:NSSelectorFromString(@"setTranslucent")]) {
    //    [tabBarr setValue:NO forKey:@"setTranslucent"];
    //}

    //if ([tabBarr respondsToSelector:@selector(setTranslucent:)]) {
    //    [tabBarr setTranslucent:NO];
    //}

   // tabBarController.tabBar.superview.backgroundColor = [UIColor clearColor];

    //if ([tabBarr respondsToSelector:@selector(setTranslucent:)]) {
    //if ([[tabBarController.tabBar class] instancesRespondToSelector:@selector(setTranslucent:)]) {
        //[tabBarController.tabBar setTranslucent:NO];
        //[tabBarController.tabBar setBool:NO forKey:@"setTranslucent"];
     //   [tabBarController.tabBar setValue:NO forKey:@"setTranslucent:"];
    //}

I'm not sure what else to try ?

A: I define macros instead an use these:
#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

Use like:
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) { ... )

See if the issue is with your version check.

A: You could create a category and define the property again
@interface UITabBar (OldSDKCompatibility)
@property(nonatomic,getter=isTranslucent) BOOL translucent;
@end

A: Correction: This problem is you can't use functionality not in the sdk. Therefore use Xcode 4 and don't use that code or use Xcode 5.


text:
Q: How does Angular modify the DOM? Imagine this template...

...and a MutationObserver "listening" to its changes:
observer.observe(this.el, { characterData: true, subtree: true });

Now every time this template renders, the observer reacts correctly.
But it does not, when I modify the content "by hand":
this.el.innerHTML = "
Another item
";

This is probably because Angular has much more clever ways to modify the DOM.
But just how exactly does Angular do it - in one line of code? Especially that "characterData" changes are getting triggered?

A: As @wOxxOm said if you use characterData: true option then the changes will be only triggered if you assign to an element's text node's nodeValue
Angular uses #comment node for embedded views.

And angular assigns some meta information to this node

which causes the changes in MutationObserver  to be triggered.


text:
Q: Multi-Class GUI I have been taking the basic 'guess my number' game in Java utilizing the Random class, but I was attempting to make my first GUI to have more than one window.  I was having some issues that I can't see, to figure out on my own, so I have come here for help.
Here is he main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class GuessMyNumber extends JFrame
{
    private JLabel lblIntro;
    private JLabel lblPrompt;
    private JTextField txtInput;
    private JButton btnSend;
    private JButton btnCustomize;
    private JTextField txtMin;
    private JTextField txtMax;
    private JButton btnSet;
    private ButtonListener btnListener;
    private boolean customize;
    private boolean game;
    private int min;
    private int max;
    private int dif;
    private int magicNum;
    private int num;
    private int guesses = 1;

    public GuessMyNumber()
    {
        super("Guess My Number");
        Container cp = getContentPane();
        setLayout(new FlowLayout());

        lblIntro = new JLabel("Welcome to Guess My Number");
        lblPrompt = new JLabel("Please enter your guess:");
        txtInput = new JTextField(15);
        btnSend = new JButton("Send");
        btnSend.addActionListener(new ButtonListener());

        btnCustomize = new JButton("Customize Range");
        btnCustomize.addActionListener(new ButtonListener());

        cp.add(lblIntro);
        cp.add(lblPrompt);
        cp.add(txtInput);
        cp.add(btnSend);
        cp.add(btnCustomize);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 100);
        setVisible(true);
    }
    public static void main(String[]args)
    {
        GuessMyNumber foo = new GuessMyNumber();
    }
    public int getMagicNum(int min, int max)
    {
        Random g = new Random();
        if(customize)
        {
            dif = max - min;
            magicNum = g.nextInt(dif) + min + 1;
        }
        else
        {
            magicNum = g.nextInt(100) + 1;
        }
        return magicNum;
    }
    public String getFeedback(int guesses)
    {
        String feedback;
        if(guesses < 4 && guesses > 0)
            feedback = "Superstar";
        else if(guesses < 7 && guesses > 3)
            feedback = "Pretty Good";
        else if(guesses < 10 && guesses > 6)
            feedback = "Mediocre";
        else
            feedback = "Pathetic";
        return feedback;
    }
    private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            Object clicked = e.getSource();
            if(clicked == btnCustomize)
            {
                customize = true;
                game = false;
                GUIUtil gui = new GUIUtil();
                min = gui.getMin();
                max = gui.getMax();
            }
            if(clicked == btnSend)
            {
                String feedback;
                if(!(customize))
                {
                    min = 1;
                    max = 100;
                    if(!(game))
                        magicNum = getMagicNum(min, max);
                    game = true;
                    num = Integer.parseInt(txtInput.getText());
                    if(num < magicNum)
                        JOptionPane.showMessageDialog(null, "Too low!");
                    else if(num > magicNum)
                        JOptionPane.showMessageDialog(null, "Too high!");
                    else
                    {
                        feedback = getFeedback(guesses);
                        JOptionPane.showMessageDialog(null, "Correct!!!\nYou guessed my number in " + guesses + " guesses!\n" + feedback);
                        guesses = 0;
                        game = false;
                    }
                    guesses++;
                }
                else
                {
                    if(!(game))
                        magicNum = getMagicNum(min, max);
                    game = true;
                    num = Integer.parseInt(txtInput.getText());;
                    if(num < magicNum)
                        JOptionPane.showMessageDialog(null, "Too low!");
                    else if(num > magicNum)
                        JOptionPane.showMessageDialog(null, "Too high!");
                    else
                    {
                        feedback = getFeedback(guesses);
                        JOptionPane.showMessageDialog(null, "Correct!!!\nYou guessed my number in " + guesses + " guesses!\n" + feedback);
                        guesses = 0;
                        game = false;
                    }
                    guesses++;
                }
            }

        }
    }
}

And here is the second class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUIUtil extends JFrame
{
    private JTextField txtMin;
    private JTextField txtMax;
    private JButton btnSet;
    private ButtonListener btnListener;
    private int min;
    private int max;
    private boolean set = false;

    public GUIUtil()
    {
        super("Customization");
        Container cp = getContentPane();
        setLayout(new FlowLayout());

        txtMin = new JTextField("Min", 15);
        txtMax = new JTextField("Max", 15);
        btnSet = new JButton("Set");
        btnSet.addActionListener(new ButtonListener());
        cp.add(txtMin);
        cp.add(txtMax);
        cp.add(btnSet);
        setSize(190,125);
        setVisible(true);
    }
    public int getMin()
    {
        if(set = true)
        {
            set = false;
            return min;
        }
        else
        {
            min = 0;
            return min;
        }
    }
    public int getMax()
    {
        if(set = true)
        {
            set = false;
            return max;
        }
        else
        {
            max = 100;
            return max;
        }
    }
    private class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            min = Integer.parseInt(txtMin.getText());
            max = Integer.parseInt(txtMax.getText());
            set = true;
        }
    }
}

Errors when I attempt to customize range and then guess while leaving the second window open so the object remains active are as follows:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: n mus
t be positive
        at java.util.Random.nextInt(Unknown Source)
        at GuessMyNumber.getMagicNum(GuessMyNumber.java:66)
        at GuessMyNumber$ButtonListener.actionPerformed(GuessMyNumber.java:127)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)
        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
        at java.awt.EventQueue.access$200(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
        at java.awt.EventQueue$4.run(Unknown Source)
        at java.awt.EventQueue$4.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)

A: Try declaring GUIUtils as a class member of the GuessNumber class. and instantiate it in the constructor
public class GuessNumber {
    GUIUtil utils;

    public GuessNumber(){
        utils = new GUIUtils();
    }
}

And delete it from your actionPerformed(). I think what's happening is that when you create the GUIUtilsobject in the actionPerformed(), there is no initial data in the text fields. Right after the GUIUtil object is created, the program immediately tries to get the input from the textFields which has no value.


text:
Q: copy+paste from eclipse to flash does not work When I try to copy code from eclipse and paste it in the actionscript editor within Flash (CS3 or CS4) nothing gets pasted. Flash does detect there is something on the clipboard and does try to paste, but no content is added.
I can copy paste from eclipse to all other pieces of software running on my computer that have some form of input field.
Both eclipse and flash are set to utf-8.
This annoyance occurs on my macbook with snow leopard installed.
update:
I made an interesting discovery just now, when I copy in Eclipse, then paste somewhere else (so just paste) I then can also paste in Flash.
update 2
I've exhausted anything I can try and have given up by blaming Adobe.
one extra thing I noticed was when I copy in Eclipse, select text in flash and paste, the text selected gets replaced by nothing. It's like with flash stopping after encountering a badly encoded character.

A: I'm guessing the bug is within Flash's editor; it's had a long history of gripes from users.
For my projects, I usually create an external .as file and then just load it into my FLA. In your case, it's as easy as:

*

*Copy your current code into an external .as file and save it in the same directory as your .fla.

*Let's assume you save it as main.as. In the place where the code used to be, put in:
include "main.as"
This will solve your problem without having to go through your workaround. External .as files are also generally a good practice if your code is any significant length or there's a chance that someone besides you will be looking at it :)

A: Seems like a bug in your editor. But yeah, try your own solution.

update: I made an interesting
  discovery just now, when I copy in
  Eclipse, then paste somewhere else (so
  just paste) I then can also paste in
  Flash.

A: I've seen similar problems in Eclipse on Windows; in certain Eclipse file-type editors the copy and paste don't work properly.  If you are using the HTML or JSP editor in Eclipse try using the text editor and see if your problem goes away.  On Windows copy/paste are CTRL-C/CTRL-V, but they are also CTRL-INS/SHIFT-INS.  The latter keystrokes sometimes work for me when the others do not.


text:
Q: Basic Sharepoint Question re: Read-Only Files My organization stores "template" files in a directory on sharepoint.
Since these files are "templates", the need is to prevent anyone from changing these versions that are on the Sharepoint site, but allow a local download so the user can update within their own context.
However, the "administrator" is saying that sharepoint allows the checking out of these files, and therefore there is a risk that a user may change the "template".
How can I prevent the user from updating the files on Sharepoint, but allow them to download a local copy so they can update it for their purposes?

A: Another option for your situation is a bit more complex but results in a much better solution for end users :

*

*create a document library on the site and make it read-only to everyone but the people who should have permission to edit the templates themselves

*upload all templates to that library

*For each template, create a new Content Type based on the Document type and name it the proper user friendly name and description for the template (i.e. "Expenses Worksheet" instead of '2013compexp.xlsx').  Go to Advanced settings for the content type and enter the URL to the template for that type.

*For each library that accepts one or more of these documents, go to Advanced, Enable Content Types, then add the proper content types for the templates that should be in the library

Now, instead of users having to figure out which file to use as a template and then manually downloading and then navigating back to the library, they simply go to the Ribbon - Documents - New document and then select the proper type from the dropdown.  This will automatically open the proper template for that type.  They than simply save it back into the library when they are done.  In SharePoint 2013, it even defaults the location for saving documents right back to the library where they started so it even skips the manual upload step.
This keeps the templates protected and lets the end users focus on what they are trying to do rather than where all the files are.  Best of all, since the template is specified in the Content Type, you can easily point it to a different template should the need arise (i.e. 2014 Expenses have a different template but the 2013 template needs to still be available in special cases)

A: You should be able to break the permissions inheritance, remove existing permissions and add read only / visitor permissions to the library. Users should no longer have access to edit documents but still be able to download or open and save as...


text:
Q: ModuleNotFoundError: No module named 'usb' in python To read a file from usb device used 'usb' package but im not able to import that package.
**But in my python and virtual environment there is usb module installed and it present there but still im getting this error **
Im trying to read file from my usb storage using 'usb' package
Simple i need to read the file inside my usb using python (the file located inside the usb)and i don't understand abot this error"
These are the installed packages
~/PycharmProjects/pythonProject$ pip freeze
asciitable==0.8.0
monitoring==0.9.12
psutil==5.9.0
pyudev==0.23.2
pyusb==1.2.1
six==1.16.0
usb==0.0.83.dev0

the blow attached link that im refered now so access the usb device https://github.com/pyusb/pyusb/blob/master/docs/tutorial.rst
If any one know how to read a file that located  inside the USB storage using python .kindly please help

A: 1 .First make sure that you are installed this package under the right ven if not please install on that environment
2. sometimes its happens like this so just restart the pycharm and re-run the code

A: Make sure to install pyusb (see https://pypi.org/project/pyusb/) with pip install pyusb and not usb.
Then you should be able to import usb and use it as expected.


text:
Q: Fully Working iPhone Project Fails When Transioned To iPad I have a working app that I have ran on the iPhone countless times. Everything has worked and the app will run on the iPad in compatibility mode. The problem came when I duplicated my iPhone target and hit "Transion to iPad" When building to my iPad device I get 1 error - Apple Mach-O Linker Error.Does anyone have any advice on a fix for this?

Thanks
Tanner

A: Did you read the output you posted? The linker can't find the OAuth library you're using. Verify Xcode knows where the library is.


text:
Q: UIBarButtonItem not reacting to click
Possible Duplicate:
UIBarButtonItem not reacting after click

So I have done a lot of views with UIBarbuttonitem with it's selector methods and navigate through a lot of views.
This is by far the most confusing one, and I have searched stack overflow and a lot of links, but no proper answer as yet.
My exact question is asked by some other person. Please visit THIS  link.
I started a UIViewController, hooked up the the Navigation Bar and the UIbarbuttonitem through the interface builder and setup an IBAction with the First Responder when the barButtonITem is clicked.
Could someone please tell me why the BarButtonItem does not work ?
Thanks !


text:
Q: Wrap text in a circle with angular and limit the string length I'm quite new to angular and I'm trying to get the text from the input field to wrap in the circular div so that the text does not go outside the border. Any help would be greatly appreciated here is my code - thanks!
HTML:

    Add Information <textarea ng-model ="input" maxlength = "120" class = "textinput" </textarea>

        {{input}}

CSS:
    .textinput{
    height: 15%;
    width: 40%;
    margin-left: 5px;
}
.textcircle{
    width:200px;
    height: 200px;
    border-radius: 1000px;
    border: 1px solid #888080;
    box-shadow: 1px 1px 1px 1px;
    text-align: center;
    font-size: 18px;
    font-family: Museo-Sans;
    font-weight: 300;
}
#text{
    padding: 1em;
    text-align: center;
    margin-left: 10px;
    margin-right: 10px;
    display: block;
}

UPDATE - I have changed the HTML/CSS and gotten the text to wrap well around the circle, but if a word is too long it moves outside the circle. Is there a way to limit the length of a word inside the div?
See an example with this fiddle:
http://jsfiddle.net/Gj7tL/16/

A: This should work!
http://jsfiddle.net/D2TL3/
Basically needed to change  to a
 for text wrapping purposes.  Created an inner circle for #text to wrap with.
Good Luck!

A: this has nothing to do with angular itself, it can be done by css:
.textcircle{
        width:200px;
        height: 200px;
        border-radius: 1000px;
        border: 1px solid #888080;
        box-shadow: 1px 1px 1px 1px;
        text-align: center;
        font-size: 18px;
        font-family: Museo-Sans;
        font-weight: 300;
        overflow: hidden;
    }

I´ve just added the "overflow: hidden" in your css class.
http://jsfiddle.net/gztR6/

A: Not really an angular question (as that part seems to be working fine), more about CSS.
try this:
#text {
    display: block;
    padding: 0 30px
}

Filling text in a circular area with CSS is definitely an inexact science.


text:
Q: Присваивание результата запроса MS SQL 2005 Добрый день.
Требуется присвоить переменной А (тип int) результат запроса (тоже int)
Код:
DECLARE @A  int;
Set @A =
SELECT ДокументПоступлениеТоваровИДН FROM ДокументПоступлениеТоваров WHERE
Дата = '05.05.2005 0:00:00'
AND Склад = 'Склад'
AND Поставщик = 'Поставщик'

Получаю ошибку:

Неправильный синтаксис около ключевого
слова "SELECT"

в третьей строке. Как ни пробовал, не получается :( Сам запрос (!) выполняется правильно, мне кажется  что-то нужно дописать где-то в раене присваивания, но вот  что именно:(
Подскажите пожалуйста, как выйти из ситуаци. Заранее спасибо.
A: SELECT @A = ДокументПоступлениеТоваровИДН FROM ДокументПоступлениеТоваров WHERE
Дата = '05.05.2005 0:00:00'
AND Склад = 'Склад'
AND Поставщик = 'Поставщик'


text:
Q: Use one table for different resource in Laravel Nova I'm trying to create something like a blogging system inside the Laravel Nova.
I have a table named articles as well as abstract model AbstractArctile.
I also have 3 categories:

*

*News - App\Models\News\Article extending the App\Models\Abstract\AbstractArticle

*Digests - App\Models\Digests\Article extending the App\Models\Abstract\AbstractArticle

*Offtopic - App\Models\Offtopic\Article extending the App\Models\Abstract\AbstractArticle
The table articles has a field named category, and there are 3 types of categories: news, digests, offtopic.
Besides the extending the abstract model, each resource model also has one attribute defined, which is it's category in the following manner:
/**
 * To which category this article belongs to
 * @var array
 */
protected $attributes = [
    'category'  =>  'news'
];

I have no problem creating the articles under the specified categories in the Nova, however, instead of showing the articles from specified category, it displays articles from all categories on all resources.
Is there a way to display articles only from certain category on a given resource?
Summary
One abstract model -> 3 resources extending that model (with category attribute defined) -> how to display only items from that category inside the nova resource?

A: You can make use of Laravel eloquent query scope.
Add global scope like below to all 3 models (App\Models\News\Article, App\Models\Digests\Article, App\Models\Offtopic\Article),  which is a easy way to make sure every query for a given model receives category constrains.
protected static function boot()
{
    parent::boot();

    static::addGlobalScope('category', function (Builder $builder) {
        $builder->where('category', 'news'); // Change the value depends on the model
    });
}

Hope this will help you.

A: In Nova, you can use indexQuery,detailQuery and editQuery as well and customize your resource results.
https://nova.laravel.com/docs/4.0/resources/authorization.html#index-filtering


text:
Q: Can every number be realised as the chromatic number of a countable hypergraph? If $H=(V,E)$ is a hypergraph and $\kappa$ is a cardinal,we say a map $c:V\to\kappa$ is a coloring if the restriction $c\restriction_e$ of $c$ to $e$ is non-constant whenever $e\in E$ and $|e|>1$. The smallest cardinal such that there is a coloring from $V$ to that cardinal is denoted by $\chi(H)$.
By $[\omega]^\omega$ we denote the set of infinite subsets of $\omega$.
Given $n\in\omega,n>1$ is there $E\subseteq[\omega]^\omega$ such that $\chi(\omega,E)=n$?

A: Yes. Partition $\omega$ into $n$ infinite sets $V_1,\dots,V_n$. Let $H=(\omega,E)$ where $E=\{e\in[\omega]^\omega:|\{i:e\cap V_i\ne\emptyset\}|\ge2\}$. Plainly $\chi(H)\le n$. Suppose the vertices of $H$ are colored with $m$ colors, $m\lt n$. For each $i$ choose an infinite monochromatic set $W_i\subseteq V_i$. By the pigeonhole principle, since $m\lt n$, for some $i\ne j$ the sets $W_i,W_j$ have the same color. Then $W_i\cup W_j\in E$ is monochromatic, showing that the coloring is not proper.


text:
Q: Can we force our Office task pane add-in to use IE11 rather than Edge? My company has an internally developed Office task pane add-in that we host internally in a SharePoint 2013 add-in catalog, that is only used by employees on our network.
We noticed that recently the add-in began prompting users for a login, which has never happened in the past:

After doing some research, it seems that the combination of Windows and Office version we've recently upgraded to has resulted in Microsoft Edge being used to render the add-in from desktop Office programs (the only way our users consume the add-in). Previously, IE11 was used to render the add-in, and we had no problems with the users being prompted for a login.
The Microsoft documentation linked above has a note:

If your add-in includes the Runtimes element in the manifest, it uses
Internet Explorer 11 regardless of the Windows or Microsoft 365
version. For more information, see Runtimes.

We have tried using the Runtimes element in our add-in manifest, but it has not worked. The task pane continues to render with Edge, prompts for a login, and shows a message like so:

Is there anything we can do within the manifest to force Word & Excel to use IE11 instead of Edge to render our add-in?
If we're forced to live with Edge, is there anything we can do to make it stop prompting for login each time the add-in is loaded?
Is there anything policy-wise our IT team can do to either force IE11 or get Edge to stop prompting for login? From my research, it seems that Edge has no concept of Trusted Sites.

A: I can give you a partial answer, but maybe not a solution:
There is no way that you can control what browser is used on the user's computer.
SharePoint add-in catalogs cannot be used for add-ins that use certain manifest XML that has been developed in the last few years. (I don't know why.) It looks like <Runtimes> is one of those.
As for getting rid of the login prompt, If you don't get an answer here in the next few days, you could try raising an issue on the office-js repo.


text:
Q: Unable to create a management zone in dynatrace using uri module ansible I am having hard time to create a management zone in dynatrace using ansible playbook on rhel 7 below is my code, and expected output and actual output
uri:
        url: "https://{{ xxxxxxx }}/e/{{ xxxxxxx }}/api/config/v1/managementZones"
        method: POST
        return_content: yes
        validate_certs: no
        status_code: 201,400
        headers:
           Accept: 'application/json'
           Authorization: 'Api-Token {{ xxxxxxxx }}'
        body_format: json
        body: "{{ somejsonoutput }}"
      register: managzone
      run_once: true

I am expecting above code to create management zone if it is not available but it is not working as it is expected.
expected output:
dynatrace_response_source": "Cluster",
        "elapsed": 0,
        "failed": false,
        "frame_options": "xxxxxxx",
        "json": {
            id: "xxxxx"
            name: "xxxxx"
                    }
            }
        },
        "msg": "HTTP Error 400: Bad Request",
        "pragma": "no-cache",
        "redirected": false,
        "status": 400,

but below is actual output
Output
"dynatrace_response_source": "Cluster",
        "elapsed": 0,
        "failed": false,
        "frame_options": "xxxxxxx",
        "json": {
            "error": {
                "code": 400,
                "constraintViolations": [
                    {
                        "location": null,
                        "message": "must not be blank",
                        "parameterLocation": "PAYLOAD_BODY",
                        "path": "name"
                    }
                ],
                "message": "Constraints violated."
            }
        },
        "msg": "HTTP Error 400: Bad Request",
        "pragma": "no-cache",
        "redirected": false,
        "status": 400,

A: Looks like you are missing one of parametrs in payload body(json format) or your stucture of json is invalid. Check it in documentation.
One of the required is the name of the MZ, other parameters is optional.
Try to create MZ without rules first.


text:
Q: Is setting up a backup domain controller as simple as adding AD DS to an existing server on the network? I've recently been tasked with setting up a "backup DC" for our business. Currently we have a physical machine running DC and two ESXi hosts running various VMs for our email and file server etc.
After doing some research, it seems all I have to do is spin up a new machine OR use an existing server and just add AD DS then promote it to domain controller just like a migration.
The issue i'm worried about is I've read conflicting information about the FSMO roles and global catalog. I was under the impression only one DC can be a global catalog and host certain FSMO roles. If my main DC goes down, I assume my network is going to have issues since its hosting all those FSMO roles.
My main question is: Is it truly as simple as setting up a second domain controller and thats it or is there extra setup to have a true failover DC? I don't necessarily even need this second DC running other than if the main DC were to go down then we want the second one to take over the entire load.

A: Yes, it is that simple to set up. Promote your server to domain controller.
< The issue i'm worried about is I've read conflicting information about the FSMO roles and global catalog. I was under the impression only one DC can be a global catalog and host certain FSMO roles.
You can have any number of DCs that have the global catlog. In fact you should have the GC on every DC so accounts can authenticate against the backup DC when the primary DC is down. (You need to do this step manually after promoting).
The FSMO roles can only be assigned to one DC at a time. If your backup DC is not going to be online all the time, you would want to leave all FSMO roles on your primary DC. But you don't have anything to do for that since your single DC now has the FSMO roles.
Having an FSMO outage usually doesn't affect the day to day operations of your Active Directory. For instance you would not be able not update the domain or forest schema. If need be, i.e. the primary DC dies for good, you can transfer the FSMO roles to the backup DC without having the actual FSMO online.

A: Non-expert answer:
All the FSMO roles are only necessary for low-level domain management – you need the corresponding master to edit schema; create domains within a forest; add new DCs (specifically to allocate them RID ranges); and so on.
Everyday tasks such as authentication, Global Catalog lookup, or regular editing of directory objects can be done on any writable DC. All writes to any DC will be replicated to all other DCs, including the ones currently down.
(Not all DCs are automatically GC servers – it's an option you select when promoting the server – but it's not a single-master role.)
If the current FSMO master dies entirely, another DC can be told to seize those roles forcefully and the domain continues operating at full capacity.


text:
Q: Why aren't these JSX
* items rendering? I have this nested object:
 const data = {
    username: "username",
    date: "16/01/2021",
    time: "10:30",
    end: "11:30",
    equipment: {
        thing1: 0,
        thing2: 0,
        thing3: 0,
    },
    cost: 25.00
}

I want to create a li item for each key/value pair as part of a functional React component using JSX.
The rest of the code looks like this:
const entries = Object.entries(data)

return (

Please review your booking

       {
         entries && typeof entries === 'object' ?
         entries.map(entry => {
           if (typeof entry[1] ==='object') {
             let nestedObj = Object.entries(entry[1])
              nestedObj.map(entry => {
                return
{entry[0]}: {entry[1]}
)
              }
            } else {
{entry[0]}: {entry[1]}
}
         })
         :

       }

)

It looks to me like it should work. Tested the logic with console logs instead of li's and it was fine. Any ideas?

A: You have two errors: you're not returning from the else, and you have an extra closing paren.
 return (

Please review your booking

        {
          entries && typeof entries === 'object' ?
            entries.map(entry => {
              if (typeof entry[1] ==='object') {
                let nestedObj = Object.entries(entry[1])
                nestedObj.map(entry => {
                  // removed extra paren here
                  return
{entry[0]}: {entry[1]}

                })
              } else {
                // added return here
                return
{entry[0]}: {entry[1]}

              }
            })
            :

        }

  )

A: It seems you don't return the value in the map function.
if (typeof entry[1] ==='object') {
   let nestedObj = Object.entries(entry[1])
      return nestedObj.map(entry => {
         return
{entry[0]}: {entry[1]}
)
      }
} else {
  return (
{entry[0]}: {entry[1]}
)
}


text:
Q: adding all elements within division and append it jquery without touching html I'm super new to coding and I'm not allowed to touch the html given.
I added the codes in js file and the ones that i comment out is the one that I added to append. But it is not working. The background does not follow the ones b4.
Is there another way for it be be simpler? I feel that it is the wrong way as the code is too bulky.this is what i have after i added the codes in js, the ones not commented
this is what happen when i added the commented code in js
this is the expected output
what am I doing wrong or how can i better my codes?

#contentimages
{
    background-color: grey;
}

.col
{
    float: left;
    text-align: center;
    width: 250px;
    background-color: #d7dadb;
    border-radius: 10px;
    padding:10px;
    margin: 10px;
}

.col p
{
    text-align: left;
}
.imageCS{
    width: 150px;
    height: 150px;
    opacity: 1;
}

.imageCS:hover {
    opacity: 0.5;
    -webkit-transition: opacity 0.5s;
    transition: opacity 0.5s;
}

var _img3 = document.getElementById('img3');
var newImg3 = new Image;
newImg3.onload = function() {
    _img3.src = this.src;
}
newImg3.src = 'https://www.suss.edu.sg/images/default-source/card/home_grad2-optimize.tmb-373_373.jpg?sfvrsn=413c2ef7_1';

 var para = document.createElement("H3");
var node = document.createTextNode("Graduate Programmes");
para.appendChild(node);

var element = document.getElementById("image3");
element.appendChild(para);
 var para = document.createElement("p");
var node = document.createTextNode("SUSS graduate programmes are structured to hone graduates, giving them a competitive edge as they progress in their careers");
para.appendChild(node);

var element = document.getElementById("image3");
element.appendChild(para);

/*
var newHeading = "
Law Programmes
";
    var newParagraph = document.createElement("p");
    newParagraph.innerHTML = "Our primary focus is to train and produce lawyers for the practice of law in Singapore, particularly in the areas of Criminal Law and Family Law";
    var newImage4 = new Image;
    newImage4.class="imageCS";
    newImage4.src='https://www.suss.edu.sg/images/default-source/card/home_law2-optimize.tmb-373_373.jpg?sfvrsn=80b4ca55_1 ';
    $("#contentimages").append(newHeading, newParagraph, newImage4);

    */
div id="contentimages">

A: I have created a function for you to create a profile card. Call the function createProfileCard(imageurl,image4Heading,image4Desc)
with the required parameters to create a new card.
function createProfileCard(imageurl,image4Heading,image4Desc){
 let parentNode = document.getElementById("contentimages");
 let element = document.createElement("div");
 element.classList.add('col');
 element.innerHTML = `<img src='${imageurl}' class="imageCS"/><h3>${image4Heading}</h3><p>${image4Desc}</p>`;
 parentNode.appendChild(element);
}
let image4url = "https://www.suss.edu.sg/images/default-source/card/home_law2-optimize.tmb-373_373.jpg?sfvrsn=80b4ca55_1";
let image4Heading = "Graduate Programmes";
let image4Desc = "Our primary focus is to train and produce lawyers for the practice of law in Singapore, particularly in the areas of Criminal Law and Family Law";

createProfileCard(image4url,image4Heading,image4Desc);

Refer to the expected output here -> https://codepen.io/askannan/pen/RwoZyyK


text:
Q: How to create thumbnail image from .flv video by using ffmpeg ? I am using following command to create thumbnail image from flv video , image is created but with error (image doesn't open)
ffmpeg -ss 00:00:10 -i output.mp4 -f image2  -s 150x150 -vframes 1  -c:v libx264  assetPathNew.jpg

ffmpeg version 0.9.2, Copyright (c) 2000-2012 the FFmpeg developers
  built on Oct 22 2012 11:15:53 with gcc 4.4.4 20100630 (Red Hat 4.4.4-10)
  configuration: --enable-libx264 --enable-gpl
  libavutil    51. 32. 0 / 51. 32. 0
  libavcodec   53. 42. 4 / 53. 42. 4
  libavformat  53. 24. 2 / 53. 24. 2
  libavdevice  53.  4. 0 / 53.  4. 0
  libavfilter   2. 53. 0 /  2. 53. 0
  libswscale    2.  1. 0 /  2.  1. 0
  libpostproc  51.  2. 0 / 51.  2. 0
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'output.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 1970-01-01 00:00:00
    encoder         : Lavf52.64.2
  Duration: 00:00:16.96, start: 0.000000, bitrate: 873 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 320x240, 825 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: mp3 (mp4a / 0x6134706D), 22050 Hz, stereo, s16, 40 kb/s
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    :
[buffer @ 0xa1c7620] w:320 h:240 pixfmt:yuv420p tb:1/1000000 sar:0/1 sws_param:
[scale @ 0xa1befa0] w:320 h:240 fmt:yuv420p -> w:150 h:150 fmt:yuv420p flags:0x4
[libx264 @ 0xa1bc540] using cpu capabilities: none!
[libx264 @ 0xa1bc540] profile High, level 1.1
Output #0, image2, to 'assetPathNew.jpg':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 1970-01-01 00:00:00
    encoder         : Lavf53.24.2
    Stream #0:0(und): Video: h264, yuv420p, 150x150, q=-1--1, 90k tbn, 25 tbc
    Metadata:
      creation_time   : 1970-01-01 00:00:00
      handler_name    : VideoHandler
Stream mapping:
  Stream #0:0 -> #0:0 (h264 -> libx264)
Press [q] to stop, [?] for help
frame=    1 fps=  0 q=28.0 Lsize=       0kB time=00:00:00.-4 bitrate=  -0.0kbits/s dup=0 drop=41
video:5kB audio:0kB global headers:0kB muxing overhead -100.000000%
[libx264 @ 0xa1bc540] frame I:1     Avg QP:32.24  size:  4707
[libx264 @ 0xa1bc540] mb I  I16..4:  0.0% 43.0% 57.0%
[libx264 @ 0xa1bc540] 8x8 transform intra:43.0%
[libx264 @ 0xa1bc540] coded y,uvDC,uvAC intra: 94.8% 97.0% 74.0%
[libx264 @ 0xa1bc540] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 35% 10%  9% 12%  8%  7%  3% 10%  5%
[libx264 @ 0xa1bc540] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 22% 17% 13% 10%  7%  8%  6% 10%  8%
[libx264 @ 0xa1bc540] i8c dc,h,v,p: 49% 19% 19% 13%
[libx264 @ 0xa1bc540] kb/s:941.40

A: When you pass -c:v libx264 after -i, you're telling FFmpeg to encode the input video stream to x264 video. However, you're telling it to write the video to an image2 format, within a JPEG file. This, naturally, won't work. You can actually see this in the stream mapping:
Stream mapping:
Stream #0:0 -> #0:0 (h264 -> libx264)

So let's make FFmpeg write a JPEG image. Use a simple command instead:
ffmpeg -ss 00:00:10 -i output.mp4 -s 150x150 -vframes 1 assetPathNew.jpg

This time, we get the correct stream mapping:
Stream mapping:
Stream #0:0 -> #0:0 (h264 -> mjpeg)

Note that FFmpeg will automatically choose the right container. You therefore don't need the -f image2.
Using 150x150 will probably create a stretched image and will not keep the original aspect ratio of the input. You can use the scale filter to automatically resize while keeping the aspect ratio:
ffmpeg -ss 00:00:10 -i output.mp4 -filter:v scale=150:-1 -vframes 1 assetPathNew.jpg

This will most likely give you an output of 150x113. If you must have a size of 150x150, then you can add the pad filter to fill in the extra:
ffmpeg -ss 00:00:10 -i output.mp4 -filter:v "scale=150:-1,pad=iw:150:0:(ow-ih)/2" -vframes 1 assetPathNew.jpg


text:
Q: What is the difference between passing deep copy vs shallow copy of a list in a recursion problem? I have encountered several places while solving problems using recursion and lists that the results change drastically, when a deep copy of list is passed vs shallow copy. For example, in the code snippet below (to print all root to leaf paths in a binary tree), passing the shallow copy of the list in the left and right subtree recursive calls, gives incorrect results. While passing a deep copy works as expected.
Can anyone explain what's the difference between the two and specifically, how it makes a difference in recursion.
Thanks in advance !
List<List<Integer>> result = new ArrayList();
public void getPath(TreeNode root, List<Integer> path) {
if(root == null)
   return;
path.add(root.val);
if(root.left == null && root.right == null) {
   this.result.add(path);
   return;
}
else {
   getPath(root.left, new ArrayList(path));
   getPath(root.right, new ArrayList(path));

   //getPath(root.left, path);
   //getPath(root.right, path);
}

}


text:
Q: Supplying elements to a 2 dimensional array in Java, why not working? I want to fill a 2 dimensional array in Java with a specific set of numbers.
My sample array set: {{7,-4},{8,-2},{9,-1}}
How can I load the array without doing this?
int[][] x = new int[3][2];
x[0][0] = 7;
x[0][1] = -4;
x[1][0] = 8;
x[1][1] = -2;
x[2][0] = 9;
x[2][1] = -1;

Further, I thought I could do this, but I get "error: illegal start of expression."
class Alpha {
    int[][] x;

    public Alpha () {
        x = new int[3][];
        x[0] = {7,-4};    <== line where error is located
    }
}

A: Try this.
You can initialize the two dimensional array like this.
int x[][] = {
                {7, -4},
                {8, -2},
                {9, -1}
            };

OR
x[0] = new int[] {7,-4};
x[1] = new int[] {8,-2};
x[2] = new int[] {9,-1};

A: As each element of the outer array effectively points to a 1D array, you could do:
x[0] = new int[] {7,-4};


text:
Q: Implementing swipe gesture in xCode obj. C I am fairly new at programming in objective c and am trying to implement swipe gestures to swipe between view controllers on an app I am creating in xcode. I'm trying to make it so when I swipe left, it switches to another view controller that I have named "SecondViewController". I have created the outlet and action for my gesture in my .h file, and in my .m file I have added the following code:
- (IBAction)swipeLeft:(id)sender {

ViewController *SecondViewController = [[ViewController alloc] init];
[self presentViewController:SecondViewController animated:YES
    completion:nil];

Whenever I run the app, nothing happens when I swipe. Is there something that I have not yet done that I need to do to make this work?

A: There are basically four Swipe Gesture is available:
UISwipeGestureRecognizerDirectionRight
UISwipeGestureRecognizerDirectionLeft
UISwipeGestureRecognizerDirectionUp
UISwipeGestureRecognizerDirectionDown

You can use any of it as per your requirement. To adding any of above gesture, you can alloc Gesture and then add it to your particular view. So as soon as you swipe detected, it will call relevant method.
For Example for Right and Left gesture:
 UISwipeGestureRecognizer *gestureRecognizerRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeHandlerRight:)];
    [gestureRecognizerRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [self.view addGestureRecognizer:gestureRecognizerRight];

    UISwipeGestureRecognizer *gestureRecognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeHandlerLeft:)];
    [gestureRecognizerLeft setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [self.view addGestureRecognizer:gestureRecognizerLeft];

-(void)swipeHandlerRight:(id)sender
{
}

-(void)swipeHandlerLeft:(id)sender
{
}


text: Q: Why is Easy PHP, when changing Listening port to 8080 in httpd.conf, it reverts back to port 80? In the httpd.conf file on Easy PHP 17.0, I need to be using port 8080.  After I change it and restart the services, it reverts back to port 80.  What am I missing?


text:
Q: Integrating PayPal .NET SDK into website without using PayPal button We've implemented the above as follows:
We're integrating PayPal .NET SDK with a public website without using PayPal's built-in Buttons (Buy Now etc.). The process flow is as follows:

*

*User clicks on a regular ASP.NET MVC button that calls an Action method that creates a payment object with all necessary properties set (transactions, urls, amount, quantity etc.).

*The above action method calls necessary PayPal .NET SDK APIs, connects to PayPal that displays its own page where user logs in, verifies the amount displayed, approves it by clicking their submit button

*PayPal - after approving it- sends a response back where we perform our some back-office tasks and if everything goes OK our "Payment Successful" pages gets displayed.

Note: Our code is using PayPal's Webhook  functionality as well.
Question: We've tested the above process on PayPal's SandBox and it works fine. Are we missing something and/or PayPal's Built-in button ("Buy Now" etc.) is necessary? The application is for selling one single item (a digital download) at a time.

A: According to the PayPal documentation  the buttons are just default and the most stable flow.

PayPal Checkout gives your buyers a simplified and secure checkout experience that keeps them local to your website or mobile app throughout the payment process.

But in real world 'PayPal Smart Payment Buttons' seems to be just the most straightforward way to implement PayPal behavior in your website. Furthermore, most of the greatest PayPals clients (like Netflix, Google play or Spotify) don't use them. Mostly they provide their own buttons with additional logic.
So, I guess that there is nothing wrong in avoiding PayPal default "recommended" buttons. Just make sure your end-2-end payment flow is working correctly.


text:
Q: What is an "XY" rated safety capacitor, exactly?
Please help me understand this. In a prominent, 480v, 6kW AC servo drive, across three input phases, three 22mm "XY" class 10nF caps are placed for EMI suppression. Also, from these three phases, three of the exact same "XY" caps go to chassis ground:

simulate this circuit – Schematic created using CircuitLab
Now it is my understanding that "X" rated caps are designed to fail shorted to take out a fuse. So "X" should be used in the phases. And "Y" rated caps are designed to fail open so as to not electrocute anybody.  So "Y" should be used from the phases to ground.  Obviously, we cannot be doing both here... so what is an "XY" rated safety capacitor, exactly?
The usage of 400/500v-rated safety caps on a 480v bus:

A: No, X caps should fail open to prevent the risk of fire.  However, there have been some parts that have caught fire after a number of years in the field.  It's common wisdom that paper dielectric caps are more reliable because paper soaked with epoxy self-heals better than polypropylene.  In some cases the epoxy has undergone some sort of fatal change.  Became brittle and cracked maybe.
An XY is just one that passed the IEC60384 standard in both an X and a Y subclass...both X1 and Y1 for example.

A: Safety capacitors are classified by X and Y ratings.  Let's properly define everything, and then it should become clear how those capacitors can be rated for both X and Y at the same time.
Class X Capacitors:  These are capacitors are only for use in situations where their failure would not present an electric shock risk, but could result in a fire.  That is all.  There is no specification as to its failure mode, if it fails open or closed, or if it is across-the-line or not.
However, this ultimately amounts to these capacitors being used in across-the-line situations, as line-to-ground situations carry the potential for electric shock risk if those capacitors fail shorted.
Now, no one wants a capacitor to fail shorted, as this is rarely a sure-fire way to blow a fuse before the capacitor explodes or catches fire.  When they fail closed, they often still present several ohms of resistance, rather than being a dead-short.  So, X capacitors aren't really designed to fail open or closed circuit per se, but are designed to withstand a great deal of surge without failing at all.
There are 3 subclasses of X capacitors, X1, X2, and X3. These correspond to peak service voltages, which are generally much higher than the continuous rated voltage.  They are as follows:
$$\begin{array}{|c|c|c|}
\hline Class & Service \, Voltage & Peak \, Voltage \\\hline
  X1 & >2500V ≤ 4000V & 4kV \, (C<1.0µF) \quad \frac{4}{\sqrt{C}}kV \, (C > 1.0µF)\\\hline
  X2 & ≤2500V & 2.5kV \, (C<1.0µF) \quad \frac{2.5}{\sqrt{C}}kV \, (C > 1.0µF)\\\hline
  X3 & ≤1200V & Not \, rated\\\hline
\end{array}$$
Class Y Capacitors: These capacitors are rated for use in situations where failure would present an electric shock risk. What this means is, Y class capacitors are designed to simply not fail at all, or be self-healing, allowing them to recover from an arc-over event.  Basically, the requirements for a class Y capacitor are stricter and higher than that of an X Capacitor.  And Y capacitors are the only capacitors rated to be safely used in 'line-to-ground' situations.  However, again, there is not any mention about their failure mode, the Y rating only implies certain minimum requirements are met.  This amounts to not failing at all generally, or, as mentioned, being self-healing.
Only Y class capacitors are sufficient for use in 'line-to-ground' applications.  Because of the stricter safety ratings, it is acceptable to use Y-rated capacitors in place of X-rated capacitors, but not vise versa.  Capacitors explicitly rated for both are not uncommon, and there is nothing preventing a capacitor from being both classes at once.
There are 4 subclasses of Y capacitors, Y1, Y2, Y3, and Y4.  Here are the differences:
$$\begin{array}{|c|c|c|}
\hline Class & Service \, Voltage & Peak \, Voltage \\\hline
  Y1 & ≤500V & 8kV\\\hline
  Y2 & ≥150V < 300V & 5kV \\\hline
  Y3 & ≤250V & Not \, rated\\\hline
  Y4 & ≤150V & 2.5kV\\\hline
\end{array}$$
Both these tables are generalizations, and depending on which standard was used when designating a capacitor as an X or Y class, the specifics may vary slightly.  If you really want to get into the nitty gritty details, it's best to read the specific standard for a given capacitor.  Here is the list of the various standards, though this may not be a complete list.

*

*UL 1414 American standard

*Ul 1283 American standard

*CSA C22.2 No.1 Canadian standard

*CSA C22.2 No.8 Canadian standard

*EN 132400 European standard

*IEC 60384-14 International standard

Finally, while not mentioned in your question, I would like to add the actual purpose of these capacitors.  They are used for EMI filtering.  They not only block a good deal of garbage from mains getting into your device, but likewise prevent your device from dumping garbage into the mains.  In general, these will be present on switch mode power supplies out of necessity to pass FCC/CE/whatever, but will usually be absent on old-school linear supplies (a mains transformer alone is performing the voltage step-up or step-down).  This is due to the significant switching harmonics that is an inevitable side-effect of fast rise and fall times seen in switchers, while a linear transformer is comparatively low-noise/low-harmonic. The bridge rectifier causes some harmonics, but the iron-laminate core dissipates virtually all of those well before they can make it back into the primary winding.


text:
Q: Mercurial on share host without SSH I am trying to get mercurial to work on a shared host without SSH access.
I have looked through https://www.mercurial-scm.org/wiki/PublishingRepositories and seen different means to publish my repository to the web but not been able to get any method to work because of certain dependencies.
For example, I looked at hgweb, it says
"First of all, you need to have a Python installation that can access the mercurial package. Verify this by running python and typing the following:
import mercurial"
I havent worked with python before and as such not sure where to run the "import mercurial" command. i am guessing via ssh for which i do not have access.
Also came across SCM-Manager, the quick guide just talks about downloading the source and extracting the content to your server, SCM manager depends on java and also not sure how to get that to work over the web.
Which of hgweb, SCM-Manager and RhodeCode is possible to set up without ssh access?

A: Short Answer: NONE
But you can at least try, if you have Java Application Server running (Tomcat, GlassFish etc), run SCM-manager as Web application (*.war)


text:
Q: linux: unable to kill non-zombie process On ubuntu 14.04, I ran an grep command on all the logs, that started to take all memory (~48 Gb).
I tried to kill it, with kill -9, sudo kill -9, killall, pkill, whatever, but the process is still running and taking all memory.
%ps -f -p 28250
UID        PID  PPID  C STIME TTY          TIME CMD
karl     28250     1  6 11:07 ?        00:02:46 grep --color=auto cron alternatives.log alternatives.log.1 ...

%sudo cat /proc/28250/syscall
running

%cat /proc/28250/status
Name:   grep
State:  R (running)
Tgid:   28250
Ngid:   0
Pid:    28250
PPid:   1
TracerPid:  0
Uid:    134000025   134000025   134000025   134000025
Gid:    134000017   134000017   134000017   134000017
FDSize: 256
Groups: 4 997 999 1004 134000000 134000002 134000017 134000028
VmPeak: 71777208 kB
VmSize: 71777208 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:  42003200 kB
VmRSS:  41993348 kB
VmData: 71765652 kB
VmStk:       140 kB
VmExe:       180 kB
VmLib:      2168 kB
VmPTE:     91864 kB
VmSwap:  5013564 kB
Threads:    1
SigQ:   5/386055
SigPnd: 0000000000000100
ShdPnd: 0000000000044103
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000001fffffffff
Seccomp:    0
Cpus_allowed:   ffffffff
Cpus_allowed_list:  0-31
Mems_allowed:   00000000,00000003
Mems_allowed_list:  0-1
voluntary_ctxt_switches:    28419
nonvoluntary_ctxt_switches: 948133

I have the feeling that it is somewhat related with the fact that the lastlog is very huge because of very high user ids (because of freeIPA).
How to kill this process ?!?!?

A: The process died eventually, at least 15 minutes after the kill -9.


text:
Q: Upload big file on Rails-API I wonder how manage on a rails-api the upload of a "big" file (arround 100m). Is it possible to stream to s3 the rack tempfile during the upload?
I'm creating a new service how just need to receive post request with parameters and files ask the original app if it's everything is ok, and process them. Lot's people over blogs tell that ruby is not the best language for that, it's not a problem to change.
So I would like to know if making a rails api who will received post, return status, and communicate with the other rails app is a good thing.
Thanks in advance

A: Yes it's possible.  Amazon has their own AWS SDK Gem which provides the s3 functionality.
s3 = Aws::S3::Client.new

Here's how to get started using it.
This question however is a little off-topic because you show no proof of trial and error.


text:
Q: Rails: Controller not seeing time travel in capybara test I'm attempting to use the travel_to method in ActiveSupport::Testing::TimeHelpers. I want to be able to use visit_page as if it were another day. I can call Date.today from within the block defined by the call to travel_to, and it gives me the date I'm trying to test for. However, when Date.today is called from within the controller of the page I'm visiting with capybara, it always gives me today's date.
Here's the test:
    it 'shows the date' do
      new_time = Time.local(2017, 11, 16, 10, 0, 0)
      travel_to(new_time) do
          puts Date.today
          visit root_path
          expect(page).to have_content '2017-11-16'
      end
    end

And the controller:
class RootPageController < ApplicationController

  def index
     @this_date = Date.today
  end
end

And the test failure:
2017-11-16
    ...
     Failure/Error: expect(page).to have_content '2017-11-16'
       expected to find text "2017-11-16" in "2017-11-27"

I have a suspicion that somehow capybara causes the call to Date.today in the controller to happen before my travel_to block in the test. Is there a way to make sure that doesn't happen? Or, could something else be going on?


text:
Q: pygame, how do you get coordinates of a graphic? I am trying to get my green square to detect the collision with the blue
square, however, I don't know how to construct the if statement that makes it so that it collides as soon as it comes in contact.
If I make it so that the position of rect1 is >= 200,100
it would detect the collision if crossed beyond the blue square too

Here's my code:
import pygame, sys
import time
import random

pygame.init()

screen = pygame.display.set_mode((640,480)) #Display

running = True
randomList = ("Hello", "Hi", "Why", "Die", "Billy Nye")
#Colors
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
blue = (0,0,255)
green = (0,255,0)

#Time variables
time = pygame.time.Clock()
FPS = 60

#Movement Variables
lead_x = 300
lead_y = 200
lead_x1 = 200
lead_y1 = 100
x_change = 0
y_change = 0
position = (200,100)

#Running MAIN Loop
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill(white)
    rect2 = pygame.draw.rect(screen, green, [lead_x,lead_y, 50, 50])
    rect1 = pygame.draw.rect(screen, blue, [lead_x1,lead_y1, 50 ,50])
    pygame.display.update()

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            x_change = -10
        if event.key == pygame.K_RIGHT:
            x_change = 10
        if event.key == pygame.K_UP:
            y_change = -10
        if event.key == pygame.K_DOWN:
            y_change = 10

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT:
            x_change = 0
        if event.key == pygame.K_RIGHT:
            x_change = 0
        if event.key == pygame.K_UP:
            y_change = 0
        if event.key == pygame.K_DOWN:
            y_change = 0

    if lead_x == lead_x1 and lead_y == lead_y1:
        print (random.choice(randomList))

    lead_x += x_change
    lead_y += y_change
    time.tick(FPS)

pygame.quit()
quit()

A: You can use collision response
    rect2 = pygame.draw.rect(screen, green, [lead_x,lead_y, 50, 50])
    rect1 = pygame.draw.rect(screen, blue, [lead_x1,lead_y1, 50 ,50])
    if rect2.colliderect(rect1):
        print("BOOM!")

If you want the coordinates:
print(rect2.left,rect2.right,rect2.top,rect2.bottom)

These are the attributes you can use taken from here:

x,y
  top, left, bottom, right
  topleft, bottomleft, topright, bottomright
  midtop, midleft, midbottom, midright
  center, centerx, centery
  size, width, height
  w,h