text:
Q: Why the Arduino Servo can't be reset in the middle after loop stage? (excuse my poor english as a chinese high school student)
I don't really know that what's the reason of this problem.
When I set an angle in the "setup" section using "Servo.h" in Arduino IDE, I find that it will go back to last angle. However, I didn't set anything for this.
The following is my programme. Can you help me?
The following is main.ino :
#include <Arduino.h>
#include "HC_SR04.h"
#include "DCMotor.h"
#include "MyServo.h"
#include "Husky.h"

int servoPin = 2;
MyServo servo;
int left_ang = 60, right_ang = 175, def_ang = 120;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  // disleft.init(disPin[0], disPin[1]);
  // disright.init(disPin[2], disPin[3]);
  // mot.init(motPin);
  servo.init(servoPin);
  Serial.println("Init successfully! ");
  // cam.init(camPin);
  // prepare();
}

void loop() {
  // put your main code here, to run repeatedly:
  servo.set_ang(def_ang); // only this line matters that the servo changed back into angle:175 after a while, but I didn't set this at all.
  /*mot.on();
  while (disleft.read_dis() < 150 || disright.read_dis() < 150) {
    warn();
    if (disleft.read_dis() < 150) servo.set_ang(right_ang);
    else if (disright.read_dis() < 150) servo.set_ang(left_ang);
  }
  if (cam.fd_tra()) {
    if (cam.tra_posx() < 150) servo.set_ang(left_ang);
    else if (cam.tra_posx() > 170) servo.set_ang(right_ang);
    else servo.set_ang(def_ang);
  } else {
    servo.set_ang(def_ang);
  }*/
}

This is my MyServo.h :

#ifndef _MyServo_H_
#define _MyServo_H_

#include <Arduino.h>
#include "Servo.h"

class MyServo {
  public:
    void reset();
    void init(int pin);
    void set_ang(int ang);
  private:
    Servo mys;
};

#endif

This is my MyServo.cpp :
#include <Arduino.h>
#include "MyServo.h"

void MyServo::reset() {
  mys.write(120);
}

void MyServo::init(int pin) {
  pinMode(pin, OUTPUT);
  mys.attach(pin, 500, 2500);
  mys.write(60);
  delay(1000);
  mys.write(175);
  delay(1000);
  mys.write(120);
}

void MyServo::set_ang(int ang) {
  mys.write(ang);
}

However, this won't happen when I customize it in seperate program.
test.ino :
#include <Servo.h>

Servo mys;
int ang;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  mys.attach(2);
  Serial.println("Initialize successfully! ");
}

void loop() {
  // put your main code here, to run repeatedly:
    mys.write(60);
    delay(1000);
    // mys.write(120);
    // delay(00);
    mys.write(175);
    delay(1000);
    mys.write(120);
    delay(1000);
    exit(0);
}


text: Q: Eclipse IDE no view at all - how to get it back When I start Eclipse I get nothing. Not a single view. Similar to my previous question here except that now I have absolutely nothing at all. I don't have a menu to be able to even select window -> New Window or window -> reset perspective. The screen is completely other then the application running in my taskbar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP file not pulling in .txt files anymore I have a func.php file that grabs three .txt files from my server and inputs the data into a table in a MySQL database. I recently upgraded my PHP to 5.4 from 5.3 and this has caused an issue where it doesn't pull in the .txt files anymore but just deletes the table. In the update_training_db function, it runs empty_table but not move_file and load_csv. This code was working in 5.3 but I am not sure why it isn't grabbing the text files anymore. Can anyone help?
The whole PHP script consists of 4 functions as seen in the whole code. empty_table, move_file, load_csv, and update_training_db to execute everything.

The Problem:
function update_training_db($dbt){
    empty_table($dbt, 'customers');
    move_file('/training/TrainingCustomerList.txt');
    load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}

Whole file:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);

// Use PDO to connect to the DB
$dsn_training = 'mysql:dbname=training;host=127.0.0.1';
$user = 'training';
$password = 'training';

try {
    $dbt = new PDO($dsn_training, $user, $password);
    $dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo 'Connected to SQL Server';
}

function empty_table($dbconn, $tablename){
    try{
        $sql = "TRUNCATE TABLE " . $tablename;
        $sth = $dbconn->prepare($sql);
        //$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);

        // The row is actually inserted here
        $sth->execute();
        //echo " [+]Table '" . $tablename . "' has been emptied.
";
        $sth->closeCursor();
    }
    catch(PDOException $e) {
        die_with_error($e->getMessage());
    }
}

function move_file($filename){
    $source ="/public_html/b3/" . $filename;
    $dest = "/public_html/includes/sfupdate/" .   $filename;
    if(!copy($source, $dest)){
        throw new Exception("Failed to copy file: " . $filename);
    }
    else{
        //echo "Successfully moved $filename.
";
    }
}

function move_files(){
    try {
        move_file('training/TrainingCustomerList.txt');
    }
    catch(Exception $e){
        die_with_error($e->getMessage());
    }

    //sleep(1);
    //Return JSON
    $return["json"] = json_encode($return);
    //echo json_encode($return);
}

function load_csv($dbconn, $filename, $tablename){
    try{
        $sql = "LOAD DATA LOCAL INFILE '/includes/sfupdate/" . $filename . "' INTO TABLE  " . $tablename . " FIELDS TERMINATED BY  '\\t' ENCLOSED BY  '\"' ESCAPED BY  '\\\' LINES TERMINATED BY  '\\n'";
        $sth = $dbconn->prepare($sql);

        // The row is actually inserted here
        $sth->execute();
        //echo " [+]CSV File for '" . $tablename . "' Table Imported.
";
        $sth->closeCursor();
    }
    catch(PDOException $e) {
        die_with_error($e->getMessage());
    }
}

function update_training_db($dbt){
    empty_table($dbt, 'customers');
    move_file('/training/TrainingCustomerList.txt');
    load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}


text:
Q: Getting started in iOS I have an Android App that I have developed and I have been tasked with recreating it for the iOS platform that will work back to iOS 4.
I have purchased the Apple Developer License and I have purchased a Mac Mini and installed XCode 4.4.1 on it. I have been trying to work through some various tutorials on switching views that I have found, and I am not able to get any of them to work. Most of them talk about creating a window application or navigation application in the IDE, but apparently 4.4.1 does things in a different manner because I don't see those options in the places the tutorials show them. Then when opening referenced files there are many more entries in the files than what the tutorials show as the start. I have been fiddling with this for two days and still do not have a simple do-nothing app that just switches back and forth between views which is rather frustrating.
I looked at some of the 4.4.1 tutorials, but they have all seemed to use the storyboards which are not compatible with iOS 4.
Does anyone have any suggestions on tutorials for iOS 4 development that will work with how XCode 4.4.1 creates the project files?

A: You should probably start with the Stanford classes on iTunes U.  They're free and they give you a great, basic understanding of the latest and greatest iOS.
From there I would look into tutorials on  treehouse.com and www.raywenderlich.com.
Good luck.

A: Try Kirby Turner and Tom Harrington's Learning iPad Programming -- it will walk you through a full app.

A: This is the book I used and I found it great. Beginning iPhone 4 Development (Apress).
Of course this won't show you the iOS 5 way of doing things, storyboards, which cannot be used in a iOS 4 app.
Other than that I noticed on google apple docs dont always come up first when you search for something so I would add google site param so like: "UIDocumentInteractionController site:developer.apple.com"

A: You have several problems to overcome and I think you should handle one at a time:

*

*Learn Objective-C

*Learn to get along with XCode in the current version with storyboards

*Learn to get along with XCode in the current version and still use old NIB files rather than storyboards.

So here is my suggestion

*

*Work through the newer tutorials with storyboards. I like the ones from Ray Wenderlich. That way you get familiar with the general concepts and learn Objective-C

*Build an app with NIB files instead of storyboard in the new XCode version and then work through the old tutorials as needed. Better if you download old full projects.

What I do not recommend is to use an old Xcode version to be found here https://developer.apple.com/downloads/index.action


text:
Q: Apply MinMaxScaler() to RFECV() with a pipeline I'm trying to do feature selection and I'm using RFECV for it and LogisticRegression. To do this, I need to scale the data because the regression will not converge otherwise.
However, I think if I scaled the full data first it would be biased (basically data is leaking to the test set).
This is my code so far:
from sklearn.feature_selection import RFECV
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import MinMaxScaler
from sklearn.pipeline import Pipeline
cv = StratifiedKFold(5)
scaler = MinMaxScaler()
reg = LogisticRegression(max_iter=1000, solver="newton-cg")
pipeline = Pipeline(steps=[("scale",scaler),("lr",reg)])
visualizer = RFECV(pipeline, cv=cv, scoring='f1_weighted')

but it gives me this error:
Traceback (most recent call last):
  File "<ipython-input-267-0073ead26d52>", line 1, in <module>
    visualizer.fit(x_6, y_6)        # Fit the data to the visualizer
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 550, in fit
    scores = parallel(
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 551, in <genexpr>
    func(rfe, self.estimator, X, y, train, test, scorer)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 33, in _rfe_single_fit
    return rfe._fit(
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\feature_selection\_rfe.py", line 204, in _fit
    raise RuntimeError('The classifier does not expose '
RuntimeError: The classifier does not expose "coef_" or "feature_importances_" attributes

And I haven't even fit it to the data yet.
I tried searching but I couldn't find anything useful. Any ideas what might be failing?

A: This is a quite frequent issue with Pipeline objects. They do not expose intrinsic feature importance measures and other attributes of fitted estimators by default. So you have to define a custom pipeline object that does.
This answer here has already provided a solution that exposes feature importance measures:
class MyPipeline(Pipeline):
    @property
    def coef_(self):
        return self._final_estimator.coef_
    @property
    def feature_importances_(self):
        return self._final_estimator.feature_importances_

Using this, you would create your pipeline object like:
pipeline = MyPipeline(steps=[("scale",scaler),("lr",reg)])

Now the RFECV object can access the coefficients of the fitted LogisticRegression model with no issues.


text:
Q: javascript $(document).on('click') doesn't work in html Here is my .html code file below, it doesn't seem toload the click function at all..have I missed anything?
I am new to this, any help for this would be great!!

 hello

    <audio id="audio">
    <source src="http://dl.dropbox.com/u/1538714/article_resources/song.ogg"     type="audio/aac">
    </audio>

A: You need to add jQuery library first

 hello

    <audio id="audio">
    <source src="https://dl.dropboxusercontent.com/u/40410302/rainbowride.aac"     type="audio/aac">
    </audio>


text:
Q: Determine if on product page programmatically in Magento I want to insert tracking codes on all of the pages of a Magento site, and need to use a different syntax if the page is a CMS page, a category browsing page, or a product view page. I have a custom module set up with a block that inserts a generic tracking code on each page for now. From within the block, how can I distinguish between CMS pages, category pages, and product pages?
I started with:
Mage::app()->getRequest();

I can see that
Mage::app()->getRequest()->getParam('id');

returns the product or category ID on product and category pages, but doesn't distinguish between those page types.
Mage::app()->getRequest()->getRouteName();

return "cms" for CMS pages, but returns "catalog" for both category browsing and product view pages, so I can't use that to tell category and product pages apart.
Is there some indicator in the request I can use safely? Or is there a better way to accomplish my goal of different tracking codes for different page types?

A: You could have a parameter to the block being used to indicate what type of tracking code is needed. Then you just use the layout XML to solve the problem.  You can use the following layout handles to have your block updated with the proper parameter:
CMS Pages = 'cms_page'
Category browsing = 'catalog_category_view'
Product viewing = 'catalog_product_view'
Something like this:
<layout>
    <default>
        <reference name="before_body_end">
            <block type="mymodule/myblock" name="myblock" />
        </reference>
    </default>
    <cms_page>
        <reference name="myblock">
            <action method="setTrackingType">
                <type>cms</type>
            </action>
        </reference>
    </cms_page>
    <catalog_category_view>
        <reference name="myblock">
            <action method="setTrackingType">
                <type>category</type>
            </action>
        </reference>
    </catalog_category_view>
    <catalog_product_view>
        <reference name="myblock">
            <action method="setTrackingType">
                <type>product</type>
            </action>
        </reference>
    </catalog_product_view>
</layout>

A: The easest answer is the following:
<?php
echo $this->getRequest()->getControllerName();
if($this->getRequest()->getControllerName()=='product') //do something
if($this->getRequest()->getControllerName()=='category') //do others
?>

this is 100% the right way to do according to the MVC model, please look into the core code really understand it, and do not give the method with loading or depends on the registry method. Support mytraining.net even though I am not there.

A: There may be an even better way to do this using routers, but one fast way is to check the registry to see if we have a single product that we are looking at:
<?php

$onCatalog = false;
if(Mage::registry('current_product')) {
    $onCatalog = true;
}

Hope that helps!
Thanks,
Joe

A: I thought it would be worth mentioning there is a flaw to checking
Mage::registry('current_product')

This does indeed check if a product exists, but when on a review page for example, the product is also set, therefore you may need to be more specific to determine the page location.
The following check ensures we are on a product page, by checking it is using the "catalog" module, and the controller is a "product" request. When viewing a products list of reviews it's values would be "review" (module) and "list" (controller).
if($this->getRequest()->getModuleName()=='catalog' &&
$this->getRequest()->getControllerName()=='product'){
    Mage::registry('current_product');
}

I hope this helps.


text:
Q: Hippo CMS SpringBridgeHstComponent Breaks Editing Component Item Parameters I'm currently migrating existing components to use the HST-2 Spring Bean Bridge to integrate better with the Spring IOC container.
I followed the Hippo documentation and everything works as advertised, at least in the running site.  I can now define my component beans in my spring configuration and use DI for my component dependencies.
However, I learned that now I cannot modify the parameters on those component's in the Channel Manager's Template Composer.  Before migrating those catalog components to use the SpringBridgeHstComponent I could click in the component item area in the Template Composer and get the pop up dialog which let me view and edit all the parameters to that component item
(hst:parameternames, hst:parametervalues).

Now the pop up dialog just shows a message that
 "No editable properties found for this component."

I should mention that the component parameter values that were already set on the components are still available during request processing/execution.  But those values are now effectively "hard-coded" because the webmaster cannot view/change them in the Template Composer.
Is this a known issue with the SpringBridgeHstComponent?  Or is there a workaround configuration or something to make those component parameters available again in the Channel's Template Composer?

A: The Hippo CMS Channel manager can only scan annotations in the component class configured by the hst:componentclassname property.
SpringBridgeHstComponent class itself, which is used in your component
configuration now, cannot be annotated by a domain-specific parameters
info annotation. As a result, it's not shown in the channel manager
properly.
If you want to enable the parameters setting window for the
SpringBridgeHstComponent-bridged component, then you should extend the
class only for the annotation. e.g, ContactSpringBridgeHstComponent
extends SpringBridgeHstComponent with a specific annotation in that
extending class for contact component for instance. See the docs for detail.
This is needed at the moment because channel manager recognizes the
parameters information only by class annotation, which makes you extend
a new class for each component.


text:
Q: LINQ: check whether two list are the same This should be easy.
I want to check whether two list are the same in that they contain all the same elements or not, orders not important.
Duplicated elements are considered equal, i.e.e, new[]{1,2,2} is the same with new[]{2,1}

A: Edit: This was written before the OP added that { 1, 2, 2 } equals { 1, 1, 2 } (regarding handling of duplicate entries).
This will work as long as the elements are comparable for order.
bool equal = list1.OrderBy(x => x).SequenceEqual(list2.OrderBy(x => x));

A: var same = list1.Except(list2).Count() == 0 &&
           list2.Except(list1).Count() == 0;

A: The SetEquals of HashSet is best suited for checking whether two sets are equal as defined in this question
        string stringA = "1,2,2";
        string stringB = "2,1";

        HashSet<string> setA = new HashSet<string>((stringA.Trim()).Split(',').Select(t => t.Trim()));
        HashSet<string> setB = new HashSet<string>((stringB.Trim()).Split(',').Select(t => t.Trim()));

        bool isSetsEqual = setA.SetEquals(setB);

REFERENCE:

*

*Check whether two comma separated strings are equal (for Content set)

A: You need to get the intersection of the two lists:
bool areIntersected = t1.Intersect(t2).Count() > 0;

In response to you're modified question:
bool areSameIntersection = t1.Except(t2).Count() == 0 && t2.Except(t1).Count() == 0;

A: If the count of list1 elements in list2 equals the count of list2 elements in list1, then the lists both contain the same number of elements, are both subsets of each other - in other words, they both contain the same elements.
if (list1.Count(l => list2.Contains(l)) == list2.Count(l => list1.Contains(l)))
    return true;
else
    return false;


text:
Q: Apache - Redirection - Paths I have a problem with redirect. Right now I have one page on address like:
http://localhost/Stella/Wiki/index.php

Also in the same directory I have my .htaccess file, which should redirect all requests to the index.php.
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/Stella/Wiki/index.php
RewriteRule (.*)$ /Stella/Wiki/index.php?id=$1 [L,QSA]

This redirection works really good, but I want to use it in relative way, like:
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule (.*)$ /index.php?id=$1 [L,QSA]

Like without absolute path, because I am going to have many subfolders, and I don't want to have long rules like: /xxx/xxx/xxx/xxx/index.php.
Can you help me to solve this problem? I don't know what to do, or if is it even possible?

A:
RewriteCond %{REQUEST_URI} !^/Stella/Wiki/index.php
RewriteRule (.*)$ /Stella/Wiki/index.php?id=$1 [L,QSA]

If the .htaccess is located at /Stella/Wiki/.htaccess then you can write these directives like:
RewriteRule ^index\.php$ - [L]
RewriteRule (.*) index.php?id=$1 [L,QSA]

As you suggested, this now uses relative paths. Note that relative paths don't start with a slash. If you use a slash prefix then that will be root-relative (ie. relative to the document root of the site).
When you use a relative path in per-directory .htaccess files then the directory-prefix (the filesystem path of where the .htaccess file is located) is added back at the end. So, index.php is in the directory where the .htaccess file is located. You can override this with the RewriteBase directive.
However, this a little different to your directives. Instead of a condition that only processes the directive if we are not already requesting the target URL. We have an exception that prevents any further directives being processed if that URL is already being requested.
Note, however, that this directs all requests to index.php (as your original directive does). Including requests for existing files and directories - if that is a concern?


text:
Q: I am not able to get response from web service using Angular javascript var msg = document.getElementById('inputXML').innerHTML;How to pass input xml as a parameter to web service and displaying response from web service using angular javascript in html.
Here is my code, please help, i m not able to get reponse from web service.

        HI

{{x}}

    <ACORD> <SignonRq> <UserId>CUser</UserId> <Password>XuViDgegi/KtGyJuXfuMrw==</Password>
    <SignonPswd> <CustId> < </ACORD>

A: I am not sure about xml but you are not posting it, use innerHTML to get actual xml from
.
inputXML : msg.innerHTML // use innerHTML to get the actual xml

A: Because you are not retriving the content of the div. You are simply extracting #inputXML node from the DOM tree. You can try is
var msg = document.getElementById('inputXML').innerHTML;

A: in var msg you are getting a javascript object though you need complete html to process so it should be
var = document.getElementById('inputXML').innerHTML;

Also default tranformRequest of $http in angular js is json you will have to change it to text/xml i wrote an article on how you could change it tranformRequest example angularjs
complete example, filename is test.php placed at root
<?php
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
    $xmlData = file_get_contents('php://input');
    header("Content-type: text/xml; charset=utf-8");
    echo '<?xml version="1.0" encoding="utf-8"?>' . $xmlData;
    exit;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Simple xml post in angularjs Web Application</title>
<meta name="Description" content="Simple xml post in angularjs Web Application">

{{x}}

    <ACORD>
        <SignonRq><UserId>CUser1</UserId><Password>XuViDgegi/KtGyJuXfuMrw==</Password></SignonRq>
        <SignonRq><UserId>CUser2</UserId><Password>XuViDgegi/KtGyJuXfuMrw==1</Password></SignonRq>
    </ACORD>

A: Have you checked if your controller is executing correctly, I think the standard controller declaration would be something like this:
.controller('customersController', ['$scope', '$http', 'setAsXMLPost',function($scope, $http, setAsXMLPost){
    var msg = document.getElementById('inputXML').innerHTML;
    $http.post("http://nordevd208wa1x.csc-fsg.com/TPOServiceEnh7/TPOService/TPOService.asmx", msg, {transformRequest: setAsXMLPost}).success(function(response) {
        $scope.names = response;
    });
}]);


text:
Q: Restrict focus of talkback on notification bar in android I have an android device in which I set the talkback turned on. Now whenever I restart/reboot the device at that time talkback directly gets focus on notification bar and starts speech out of "syncing sim contacts", "USB debugging connected" etc. Is there any way to either stop focusing on notification bar when device gets restarted/rebooted or keep talkback silent during this specific speech out. Any help will be appreciable.

A: There are questionable usages for what you want to do.
Perhaps you should post your UI/UX and why you'd want to restrict this default TalkBack behavior. TalkBack users are generally (but not limited to) visually-impaired people, and they greatly rely on the audio cues provided by the service. Attempting to out smart it is generally a bad idea. This doesn't mean there aren't valid use-cases, hence why the next paragraph shows you how to move the focus where you may want it.
If you still want to ensure the accessibility service focuses a specific portion of your UI when you open a fragment or activity, then add some helper functions like:
fun View.requestAccessibilityFocus() {
    performAccessibilityAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null)
    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED)
}

And then in onCreate or onViewCreated request it:
import androidx.core.view.doOnLayout

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
   super.onViewCreated(view, savedInstanceState)

   val theViewYouWantToFocus = ... //findViewById or use ViewBinding

   theViewYouWantToFocus.doOnLayout {
       it.requestAccessibilityFocus()
   }
}

The reason for doOnLayout is to let the android layout system to finish the layout pass and to make sure that the accessibility system gets a finalized picture of your layout hierarchy before it attempts to focus a particular view for the purposes of talkback. Your mileage may vary.


text:
Q: Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\test.loc\auth.php on line 13 Помогите понять что я сделал не так? Мучаюсь уже 3 часа. Пересмотрел кучу ответов, ничего пока не подходит.

$result = $mysql->query("SELECT * FROM `users` WHERE `Login` = '$login' AND `Pasword` = '$pass'");
$users = $result->fetch_assoc();
if(count($users)== 0) {
  echo "Такой пользователь не найден";
  exit();
};

print_r($users);
exit();```


text:
Q: Evaluation Board DP83TD510E I'm trying to create a demo based on 2 evaluation boards DP83TD510E-EVM using 10Base-T1L technology. Both boards are connected together via a 10 meter SPE cable and each board is connected to a laptop via Ethernet cable. Both Boards are also powered through USB (No external power supply).
The idea is to try to send a packet from laptop A to B.
But I am strugling to understand how the boards are supposed to work.
What i managed until now is to install the drivers for windows, use USB-2-MDIO to open Board's port. I also read 0 in each register so i don't know if that's even a problem.
So could anyone tell me what are the right steps to do in order to send a packet?
Thanks!


text:
Q: Roots of the equation? If $p,q,r$ are real numbers satisfying the condition $p + q + r =0$, then the roots of the quadratic equation $3px^2 +5qx +7r=0$ are
(A)Positive
(B)Negative
(C)Real and distinct
(d)Imaginary
Actually im a 10 class student i don't know any of it, but my elder brother (IIT Coaching) cannot solve them, he told me post these questions on this site someone might know the answers and for now he is not in the town. So can you please help me. Thank you.

A: Hint :
$$ p+q+r = 0 $$
This, implies that at least one of three must be of different sign than rest two.
There is 3 possible cases for this
$$ (p,q) \space |\space  r $$
$$ (q,r) \space | \space p $$
$$ (p,r) \space | \space q $$
Now, we know that Nature of root can be known by value of D
$$ D = \sqrt{b^2-4ac} $$
Check for all possible combination. My answer is option (c)

A: HINT:
Putting $r=-p-q,$
$$3px^2+5qx-7(p+q)=0$$
So, the discriminant is $$(5q)^2-4(3p)\{-7(p+q)\}=(5q)^2+84pq+84p^2=\left(5q+\frac{42}5p\right)^2+\{84-\left(\frac{42}5\right)^2\}p^2$$
$$=\left(5q+\frac{42}5p\right)^2+\frac{p^2(84\cdot25-42^2)}{25}$$
$$=\left(5q+\frac{42}5p\right)^2+\frac{42p^2(2\cdot25-42)}{25}>0$$
What can we make of it?

A: I will take a different tack, which might be called the "Vi$\grave{e}$te approach".  I will note that for resolving the choices in this problem, the numbers 3, 5, and 7 appearing in the coefficients have no special significance, other than that they do not change the signs of the coefficients from what is given by $ \ p \ , \ q \ , \ \text{and} \ r \ . $  (They do have the effect of making the discriminant of the quadratic polynomial look more intimidating to analyze.)
Since $ \ p \ , \ q \ , \ \text{and} \ r \  $ are real, the coefficients of our polynomial are real; as the door has been "left open" to consider imaginary zeroes, this means that such roots must form a "conjugate pair".  If we call the zeroes $ \ \alpha \ \text{and} \ \beta \ , $ then the factored form of this polynomial is $ \ 3p \ (x - \alpha) \ (x- \beta) \ , $ which "multiplies out" as
$$ 3p x^2 \ - \ 3p \ [\alpha + \beta] x \ + \ 3p \alpha \beta \ = \ 3px^2 + 5qx + 7r \ \ . $$
We can eliminate choice (D) immediately.  If the roots were pure imaginary, the real coefficients require that $ \ \alpha = b i \ \text{and} \ \beta = - b i \ . $  This would force their sum to be zero and, consequently $ \ q = 0 \  ;  $ further, their product would be positive, requiring that $ \ p \ \text{and} \ r \ $ have the same sign.  But under the condition $ \ p + q + r = 0 \ , \ q \ $ being zero forces $ \ p = -r \ . $  So we have an outright contradiction in this case.
If both $ \ \alpha \ \text{and} \ \beta \  $ are positive, then their sum and product are positive, requiring that $ \ p \ \text{and} \ r \ $ have the same sign and $ \ p \ \text{and} \ q \ $ have opposite signs.  Under the specified condition, we can write $ \ p + r = -q \ , $ but this by itself can be satisfied by values of $ \ p \ \text{and} \ r \ $ of opposite sign as well.  This is to say that the specified condition,  $ \ p + q + r = 0 \ , $ does not impose a strong enough constraint to require that the two roots both be positive.  (That is to say, they could be, but don't have to be.)
A stronger  argument follows for having both  $ \ \alpha \ \text{and} \ \beta \  $ negative:  here the sum of the roots is negative and their product is positive, causing $ \ p \ , \ q \ , \ \text{and} \ r \  $ all to have the same sign, which is impossible under the imposed condition.
Finally, we show that choice (C) is correct, also by contradiction.  Were the two roots equal  $ ( \ \alpha = \beta \ ) , $ our polynomial would be
$$ \ 3p \ (x - \alpha)^2 \ = 3p x^2 \ - \ 6p \alpha  x \ + \ 3p \alpha^2 \ .  $$
We would thus have $ \ 5q = -6p \alpha \ \Rightarrow \ q = -\frac{6 \alpha}{5} p \ \ $ and $ \ 7r = 3p \alpha^2 \ \Rightarrow \ r = \frac{3 \alpha^2}{7} p \ . $  The specified condition implies that $ \ p \ (1 - \frac{6}{5} \alpha + \frac{3}{7} \alpha^2 ) \ = \ 0 . \ $  It is impermissible to have $ \ p = 0 \ . $ But the discriminant of the quadratic equation for $ \ \alpha \ $ is $ \ (-\frac{6}{5})^2 - 4 \cdot \frac{3}{7} \cdot 1 \ = \ \frac{36}{25} - \frac{12}{7} \ < \ 0 . $  So the roots cannot be equal and real. [This is the only place in the entire discussion where the numbers 3 , 5 , and 7 have much importance.]


text:
Q: Angular: http RxJS dependant http requests I am developing a small app with Angular 14.1. I need to create a service that get information from N endpoint and is
dependant of an endpoint. I need a solution that could retrieve previous information fast as possible. This data will be
consumed by a component.
Extended information:
Current service is required to request information from HTTP endpoint that return some data like this:
{
  "name": "test",
  "documents":[
    {
      "id": 1,
      "name": "document 1",
      "type": "a"
    }, {
      "id": 2,
      "name": "document 2"
      "type": "b"
    },
    {
      "id": 3,
      "name": "document 3"
      "type": "a"
    }
  ]
}

With previous response:

*

*I need to filter all documents that their type are "a"

*I need for each "id" create a new HTTP request to another endpoint to get more information. Return some data like this:
{
    "name": "document 1",
    "type": "a",
    "start": "2022-10-10"
}

*I need to get a class instance for previous data.
I tried different ways that I think that are too dirty. Could you help me?
Thanks!

A: That's just a combination of concatMap and a forkJoin() that will make all the inner requests concurrently:
getDocuments()
  .pipe(
    concatMap(response => {
      const documents = response.documents.filter(doc => doc.type === 'a');
      return forkJoin(documents.map(doc => otherRequest(doc)));
    },
  )


text:
Q: Find BPM percentage difference using math - something not adding up right? I asked this question about 2 and a half years ago on how to find the percentage difference between 2 bpms ( I apologize if this seems extremely simple... my math / algebra skills are not that good, I fell asleep in all of my algebra classes in highschool and was put in the dumb math class):
How to find percentage change between original and final BPM
At the time all my original files were 100bpm... but now I want to be able to have different source bpms... so I changed the source bpm to 120 and desired bpm to 85 and I get -.35 but when I subtract 35% from 120bpm I get 42 not 85... what am I doing wrong?
If your initial number is a and your final number is b, then the percentage change x from a to b is given by
x=b−a100
For example, if a=100 and b=134, then
x=134−100100=0.34=34%
If a=100 and b=78, then
x=78−100100=−0.22=−22%

A: You need to do $$\frac{120-85}{120}\approx0.29$$
If you want in percent, multiply the answer by $100$.
Also the number $42$ is $35\%$ of $120$, not $65\%$.


text:
Q: Does Core Motion in watchOS 2 allow access to the gyroscope? I see accelerometer mentioned but nothing of gyroscope access? can any one can help me out on this

A: According to this github project the gyroscope is not (yet?) available on watchOS 2.


text:
Q: Unable to make a Get request with Redux Query I honestly don't know what I'm doing wrong here. I am trying to use a Get request to pull API data and I am using Redux Query. Here is my code:
 export const userCartApi = api.injectEndpoints({
 endpoints: (builder)=>({
    getCart: builder.query({
        query: ()=>{
            return{
                url: "/cart",
                method: "get",

            };
        },
    }),

}),
overrideExisting: false
});

Inside the component where I used it:
 export const {useGetCartQuery } = userCartApi

import { useGetCartQuery } from "../../store/Features/CartApi/CartApi";
const [getCart, {data: cartData, isError: isCartError, isSuccess: isCartSuccess, error:
 getCartEror, isLoading: isCartLoading,}] = useGetCartQuery();

const getCart = async()=>{
    await getCart()
 }

The store
export const Store = configureStore({
reducer:{
    [userApi.reducerPath]: userApi.reducer,
    [userCartApi.reducerPath]: userCartApi.reducer,
    session: sessionSlice,
    appLoader: appLoaderSlice,
    cart: cartReducer,
    user: userSlice,
},
middleware: (getDefaultMiddleware)=> getDefaultMiddleware().concat(userApi.middleware)
});

The error that I am getting:
 Invalid attempt to destructure non-iterable instance.
 In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

If I simply change the getCart: builder.query to getCart: builder.mutation and rename the hook to useGetCartMutation instead of useGetCartQuery, it works and fetches my data. Is there where I am missing a thing or two?

A: It was all my mistake, please. I have seen how it is properly done and it is working now:
I simply needed to get the data this way:
const  {data: cartData, isError: isCartError, isSuccess: isCartSuccess,
error:
getCartEror, isLoading: isCartLoading,} = useGetCartQuery();

Instead of this way:
const [getCart, {data: cartData, isError: isCartError, isSuccess: isCartSuccess,
error:
getCartEror, isLoading: isCartLoading,}] = useGetCartQuery();


text:
Q: Best way to restrict access Java EE RESTFul APIs What is the best (and easay) way to restrict (JAX-RS Jersey) RESTFul APIs from being accessed by third party?
(I want these APIs to be used by my application only)

A: There are several. In order of simplicity they are:

*

*Block access in the firewall.

*HTTP-BASIC authentication.

*API-key (shared secret) authentication.

*CAS

*OAuth.

It kind of depends on what kind of additional requirements you have. But from your brief description, I would think a simple firewall is the best solution in your case.

A: For application level, you can try Spring Security http://www.springsource.org/spring-security and restrict at URL level, or if you want some more simple you can do it by using Servlet specification API by putting  on web.xml, remember restful web services life cycle works the same as servlets do.


text:
Q: How to populate TableView dynamically with FXML and JavaFX How do I define my table in FXML and then use my JavaFX code to populate it dynamically at runtime?

A: *

*Define the TableView in the fxml file. Few things to note:

*

*the root should have a controller class associated with it.

*the TableView and TableColumn should have fx:id attributes specified.

<BorderPane xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.MyController">
    <center>
        <ScrollPane disable="false" visible="true">
            <content>
                <TableView fx:id="myTableView" prefHeight="-1.0" prefWidth="-1.0">
                    <columns>
                        <TableColumn fx:id="idColumn" prefWidth="100.0" text="Id" />
                    </columns>
                </TableView>
            </content>
        </ScrollPane>
    </center>
</BorderPane>

*Define the controller class. Few things to note:

*

*the variables should be linked with the @FXML tag and a new object of
TableView/TableColumn should not be created.

*the variables should be named the same as the corresponding attribute value of fx:id as
mentioned in the fxml.

*the controller class should implement javafx.fxml.Initializable and hence should define the method public void initialize(URL location, ResourceBundle resources)

*a class Data Model class MyDataModel is used to populate the data.
public class MyController implements Initializable {
@FXML
private TableView<MyDataModel> myTableView;

@FXML
private TableColumn<MyDataModel, String> idColumn;

@Override
public void initialize(URL location, ResourceBundle resources) {
idColumn.setCellValueFactory(new PropertyValueFactory<MyDataModel, String>"idColumn"));

myTableView.getItems().setAll(getItemsToAdd());
}

private List<MyDataModel> getItemsToAdd(){
// this method would fetch the necessary items from database.
}

}

*Define the Data Model class. Few things to note:

*

*the variable should be named as idColumnProperty as the string passed for PropertyValueFactory is "idColumn".

*the variable must be private final SimpleStringProperty as the type mentioned in controller class is String for the column.

*the model class must have the methods getIdColumn() and setIdColumn(String id)
public class MyDataModel {
private final SimpleStringProperty idColumnProperty = new SimpleStringProperty("");

public MyDataModel(){
this("");
}

public MyDataModel(String id){
setIdColumn(id);
}

public String getIdColumn(){
idColumnProperty.get();
}

public void setIdColumn(String id){
idColumnProperty.set(id);
}

}


text:
Q: Epsilon numbers Let $\alpha$ be an ordinal number and define $f_\alpha$ as:

*

*$f_\alpha(0) = \alpha + 1$

*$f_\alpha(n+1) = \omega^{f_a(n)}$

Let $S(\alpha) = \sup\{f_a(n)\ |\ n \in \omega\}$
Then $S(\alpha)$ is an epsilon number and is the least epsilon number greater than $\alpha$.
Since none of natural numbers are epsilon number, I think $S(n)=S(m)$ for every natural numbers $n,m$. I know that I'm wrong but I don't know why. Please, help.
And I have problem with showing that $m<n\implies S(m)<S(n)$

A: Since the question was answered in comments and we don't like leaving questions unanswered, I'm adding azarel's comment as a CW answer:
Actually, $S(n)=S(m)$ for all natural numbers $n,m$. Since $\epsilon_0$ is the minimal epsilon number above of them.


text:
Q: How to preserve "this" within Typescript Mocha test hooks In the below example, token.test.ts loads a test fixture into this.token within a beforeEach, to be reused within the hooks in token.behavior.ts.
// token.test.ts
import { shouldBehaveLikeToken } from './token.behavior';

describe("TokenTest", function () {
  beforeEach('reload token fixture', async function () {
    ({ token: this.token }) = await loadFixture();
  });

  shouldBehaveLikeToken();
  // More behavioral test suites
});

// token.behavior.ts
export function shouldBehaveLikeToken(): void {
  describe('balanceOf', function () {
    it('returns the correct balance', async function() {
      expect(await this.token.balanceOf(ADDRESS).to.equal(2)); // WORKS!
    });

  });

  function balanceOf() {
    return this.token.balanceOf(ADDRESS); // DOES NOT COMPILE WITH THIS FUNCTION!
  }

}

Regardless of how deeply nested assertions on this.token are, I am able to access this.token within Mocha hooks (describe() / it()) just fine.
However, if I create a helper function that uses this.token for making tests more composable within the test suite, I get the errors that 'this' implicitly has type 'any' because it does not have a type annotation and An outer value of 'this' is shadowed by this container. This happens regardless of whether it is an arrow function or not, and regardless of where the function is defined.
Can someone explain what's going on? How can I make a helper function that uses the preserved this from the beforeEach block?

A: It looks like your external function balanceOf is requiring the this context to be that of Mocha.Context which is only available inside of a Mocha test. You must specify the this type of your balanceOf function, then bind the function to the Mocha.Context context explicitly like so:
export function shouldBehaveLikeToken(): void {
  describe('balanceOf', function () {
    it('returns the correct balance', async function() {
      // It is only within this callback that your `this` context is `Mocha.Context`.
      // The context will not carry over outside of the callback.

      expect(await balanceOf.bind(this)().to.equal(2)); // Bind the function here.
    });
  });

  function balanceOf(this: Mocha.Context) { // explicit `this` type here.
    return this.token.balanceOf(ADDRESS);
  }
}

The reason why your first balanceOf function cannot correctly type this is because all function declarations (functions created with the function keyword) will bind either window or global by default, or to undefined if you're in strict mode. You can read more about how functions bind their this context here.


text:
Q: How to handle message chaining in this situation I'm currently trying to figure out what would be the best approach to solving the following issue.
We are using a microservice architecture and in order for some product features to be enabled they require previous services to have finished their job.
In the example below Service4 requires that Service1 and Service2 finish their tasks.
I was considering using an orchestration service which knew which service depended
on which and released the service messages in the correct order.
But I was wondering if there is a way to avoid this orchestration service and do it entirely using a choreographed saga?
              ┌────────┐
     ┌───────►│Service1├───────┐
     │        └────────┘       ▼
┌────┴────┐                ┌────────┐
│  Start  │                │Service4│
└────┬────┘                └───▲────┘
     │        ┌────────┐       │
     └───────►│Service2├───────┘
              └────────┘

My main concerns here are that Service4 will have to keep record of every message it has received in a database and keep track whether all required messages for the task have been received and that the same logic will have to be reimplemented on every service which has multiple dependencies.

A: To expand on the correct comment above by Maxim that some service has to own partial-state responsibility, I submit the following:
If Service 1 and Service 2 completing for some aggregated task is ONLY relevant to Service 4 - i.e. it doesn't represent an actual functional process completing - then Service-4 should be responsible for tracking the partial state.
If the fact those two services have completed has some standalone relevance - even if Service 4 didn't exist - then it makes sense to have an Orchestration service of some sort to aggregate, implement rules, and generate new events.
If nobody except Service-4 understands the rules in the above-mentioned Orchestration service, that's a good sign they should exist within Service-4.
EDIT: Since you've indicated Service-4 is NOT the only service that cares about the fact that the other two services have completed, it absolutely makes sense to add what's (probably) more properly called a Choreography Service.
There are a number of options, but in general I'd expect it to monitor for Service-1 and Service-2 to complete and generate a new event that Service-4 will consume.


text:
Q: List Rarible Lazy Minted Tokens on OpenSea How can I list Rarible Lazy Minted off-chain tokens on OpenSea?
I am Lazy Minting tokens on Rarible that go to a custom smart contract during the sale. Before the sale, the tokens are stored off-chain but still listed on Rarible. How do I get these off-chain tokens to also be listed on OpenSea?
In other words, I need to list off-chain lazy minted tokens on Rarible and OpenSea that mint to a custom smart contract at sale.


text:
Q: How to execute other Plug-in in my own Eclipse Plug-in? I often do some sequential eclipse plugin-in operation for code quality,such as:pmd,checkstyle,findbug...
so,I would like to do following:
Create a own Eclipse Plug-in, that (for example) can integrate/execute these installed code quality plugin-in one by one.
is there a plug-in to do it?
or how to do implement the plug-in?

A: You can do this, but there are no need for it :-)
You can add most of these systems as builders to your projects or your headless build - ant, PDEBuild or Tycho.


text:
Q: How to change cursor on iFrame "Select File" I am using an iFrame to simulate an <input type="file">. Here is what it does:
1 - A link shows that says "Choose your file".
2 - A user clicks the link, browses a file on their local computer.
3 - When a user selects the file, it starts uploading automatically.
This is working great. However,I am unable to control the type of cursor. How would I force the cursor to be a pointer?
http://jsfiddle.net/4paY6/ is an example of the below code.

    <form method="post" action="." enctype="multipart/form-data" style="position: inline">

           Attach File
            <input type="file" name="attachment" />

    </form>

What do I need to add or change for the above to simulate a cursor in Firefox when hovering over the iFrame?

A: The CSS
input[type="file"]:hover {
        cursor: default;
    }

is overriding the other style definitions.  Remove it, and you get the pointer cursor.

A: If you put the opacity back to 1 you can see what the problem is - the input takes up the whole page. If you change the height to 0px it seems to work as expected. Note that your span tag is not closed properly (you have  instead of )


text:
Q: CTRL keyCode (17) not working in JavaScript? I have the following code which adds an eventListener to a HTML textarea. It's supposed to console log the keycode which was pressed, and, if the keyCode is == to 17 (CTRL), console log "You pressed CTRL.". For some reason, when I press CTRL in the textarea, it's not console logging the keyCode which was pressed, nor "You pressed CTRL." If I press "A" for example, console log return "97" which is correct. It also works with all other letters.
Here's the code:
document.getElementById("msgBox").addEventListener("keypress",function(e){
    console.log(e.keyCode);
    if(e.keyCode == 17){
        console.log("You pressed CTRL.");
    }
});

What am I doing wrong?
UPDATE : It's also not working with other special keys like "shift, Fx, alt, home etc.
HTML for the textarea :
<textarea id="msgBox" placeholder="Enter your message" autofocus></textarea>

A: For some reason, special keys do not work with the keypress event, but they do with the keydown event.

A: Try this instead: (e.which == 17)

A: Check for e.ctrlKey.
See the MDN documentation at https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey
If you want an easy way to manage keypress you could use a dedicated library like https://dmauro.github.io/Keypress/


text:
Q: Flatlist reference is undefined react native My Flatlist reference continues to be undefined. When I scroll vertically I want the horizontal scroll to move to the beginning

    _renderRow(type, data, index) {
        switch (type) {
            default:
                return (
                    <View style={styles.container}>
                        <FlatList
                            data={data}
                            ref={(ref) => { this.scroll = ref; }}
                            showsHorizontalScrollIndicator={false}
                            horizontal={true}
                            renderAheadOffset={2}
                            pagingEnabled={true}
                            keyExtractor={(item, index2) => index2.toString()}
                            renderItem={({item, index2}) => (
                                <View
                                    onLayout={() => console.log('index2 ', item)}
                                    style={[
                                        styles.centerContent, {
                                        height: fullHeight,
                                        width: fullWidth,
                                        backgroundColor: (index % 2 == 0) ? 'red':'blue',
                                    }]}
                                >
                                    <Text
                                        style={{
                                            fontSize: 40
                                        }}
                                    >
                                        {item[0]} {item[1]}
                                    </Text>
                                </View>
                            )}
                        />
                    </View>
                )
            }
    }

  scrollFront = () => {

        console.log(this.scroll)
        if(typeof(this.scroll) !== 'undefined') {
            this.scroll.scrollToIndex(0)
        }
    }

    render() {
        return (
            <View style={[styles.container, {backgroundColor: 'black'}]}>
                {this.state.loaded && (
                    <RecyclerListView
                        style={{height: fullHeight, width: fullWidth}}
                        extendedState={this.state}
                        rowRenderer={this._renderRow}
                        dataProvider={this.state.dataProvider}
                        layoutProvider={this._layoutProvider}
                        showsVerticalScrollIndicator={false}
                        pagingEnabled={true}
                        renderAheadOffset={1}
                        onMomentumScrollBegin={() => {
                            this.scrollFront()
                        }}

                        //onMomentumScroll={() => this.scrollFront()}
                            //this.scroll.scrollToOffset({ animated: false, offset: 0 })

                            //: null
                    />
                )}

I think that recyclerListView only keeps one or two views in memory and perhaps that is why I cannot reference the scrollview. Or it could have something to do with renderRow being a function. I am not sure how to fix it either way


text:
Q: Is there a built-in create an absolute (fully qualified) url from a relative path such as "~/page.aspx" given the current URL? Scenario is I have a application relative url like "~/path/to/page.aspx?query=string".  I need to programatically create a web request to that page and currently using WebRequest.Create.  The problem is WebRequest.Create requires a fully qualified url including the protocol/domain/port etc.
I have access to the current Request.Url object but there doesn't seem to be an easy way to get just the base url keeping the protocol (HTTP vs HTTPS) as well as any port numbers as well as the path to the application.
I mean all the info there, so if need be I could just take all the parts and combine them but it seems like it might be error prone and it would be great to have something built-in that's well tested to do the job.  Page.ResolveUrl gets me almost there, but it's missing the protocol and the domain/port.

A: Try System.Web.VirtualPathUtility.ToAbsolute().  I've used that (albeit in VB.NET, but I'm sure there's a C# equivalent) with a great deal of success.  It can even translate just a base virtual path (i.e. System.Web.VirtualPathUtility.ToAbsolute("~") will turn into the base url of your app).
EDIT
How about Request.Url.GetLeftPart(UriPartial.Authority)?  That should get the Scheme and Authority parts of the Url (which I believe are the protocol and domain you refer to).  Here's the MSDN doc: http://msdn.microsoft.com/en-us/library/system.uri.getleftpart.aspx


text:
Q: How to use apostrophe (') in xpath while finding element using webdriver? I need to use apostrophe (') in my xpath expression which i need to use in finding elements using webdriver
i need to use below Xpath expression
//input[@text="WE'd like to hear from you"]

while using the above expression in find elements function i am replacing double quotes with single quotes
driver.findelements(By.xpath("//input[@text='WE'd like to hear from you']"))

A: You have to use double-quotes as your XPath string literal delimiter, since XPath 1.0 doesn't provide a way of escaping quotes. In addition to that, you can escape the double-quotes in Java, to avoid it from conflicting with your Java string delimiter, which also use double-quotes :
driver.findelements(By.xpath("//input[@text=\"WE'd like to hear from you\"]"))

A: The Escape character usage does not serve the purpose. I tried the concatenation function and it worked like a charm. Please see the below xpath.

tag: li Manager of Workflow Initiator's Manager /li

Concatenate function and split the string as –
concat('Manager of Workflow Initiator',"'",'s Manager')

Single quote is kept in double quote while other characters are kept in single quotes..
So XPath looks as –
//li[.=concat('Manager of Workflow Initiator',"'",'s Manager')]

A: Use the xpath as shown below:
driver.findElements(By.xpath("//input[contains(@text,\"WE'd\")]"));

Hope this helps.

A: if the above solution doesn't work then use the below solution using escape sequence.
xpath: //li[.=\"Manager of Workflow Initiator's Manager\"]

Here we are treating the whole text as a string using the escape character

A: I Encountered a similar situation where I need to write an xpath for an element shown below:
Element:
<img src="webwb/pzspacer.gif!!.gif" class="inactvIcon" data-ctl="["DatePicker"]" style="cursor:pointer;">

I was able to grep the element using below Xpath, where I used the backslash to escape the characters [ and  ".
Xpath : //img[@data-ctl='\[\"DatePicker\"\]']
Hope this helps.

A: None of the above approaches cover a situation where both Quote and Apostrophe cos exist. I've created a function for that,
driver.findElements(By.xpath(String.format("//input[contains(@text,%s))]"),escapeQuotes(textVal));

Implemenatation of the escape Quote.
private String escapeQuotes(String text) {

    // If we don't have any Quote then enquote string in Quote
    if (!text.contains("\"")) {
        return String.format("\"%s\"", text);
    }

    // If we have some Quote but no Apostrophe then enquote in Apostrophe
    if (!text.contains("'")) {
        return String.format("'%s'", text);
    }

    // If input is like Administr"ati'on then we have both " and ' in the string so must use Concat
    // we will be building the xPath like below and let the browser xPath evaluation to handle the concatenation
    // output : concat('Administr\"',\"ati'on\")
    StringBuilder sb = new StringBuilder("concat(");

    // Looking for " as they are LESS likely than '
    int lastPos = 0;
    int nextPos = text.indexOf("\"");
    while (nextPos != -1) {
        // If this is not the first time through the loop then seperate arguments with ,
        if (lastPos != 0) {
            sb.append(",");
        }

        sb.append(String.format("\"%s\",'\"'", text.substring(lastPos, nextPos - lastPos)));
        lastPos = ++nextPos;

        // Find next occurrence
        nextPos = text.indexOf("\"", lastPos);
    }

    sb.append(String.format(",\"%s\")", text.substring(lastPos)));
    return sb.toString();
}


text:
Q: What is the the role of using OneVsRestClassifier wrapper around XGBClassifier? I have a multiclass classficiation problem with 3 classes.

*

*0 - on a given day (24h) my laptop battery did not die

*1 - on a given day my laptop battery died before 12AM

*2 - on a given day my laptop battery died at or after 12AM

(Note that these categories are mutually exclusive. The battery is not recharged once it died)
I am interested to know the predicted probability for each 3 classes. More specifically, I intend to derive 2 types of warning:

*

*If the prediction for class 1 is higher then a threshold x: 'Your battery is at risk of dying in the morning.'

*If the prediction for class 2 is higher then a threshold y: 'Your battery is at risk of dying in the afternoon.'

I can generate the the probabilities by using xgboost.XGBClassifier with the appropriate parameters for a multiclass problem.
import numpy as np
from sklearn.multiclass import OneVsRestClassifier, OneVsOneClassifier
from xgboost import XGBClassifier

X = np.array([
[10, 10],
[8, 10],
[-5, 5.5],
[-5.4, 5.5],
[-20, -20],
[-15, -20]
])
y = np.array([0, 1, 1, 1, 2, 2])

clf1 = XGBClassifier(objective = 'multi:softprob', num_class = 3, seed = 42)
clf1.fit(X, y)
clf1.predict_proba([[-19, -20]])

Results:
array([[0.15134096, 0.3304505 , 0.51820856]], dtype=float32)

But I can also wrap this with sklearn.multiclass.OneVsRestClassifier. Which then produces slightly different results:
clf2 = OneVsRestClassifier(XGBClassifier(objective = 'multi:softprob', num_class = 3, seed = 42))
clf2.fit(X, y)
clf2.predict_proba([[-19, -20]])

Results:
array([[0.10356173, 0.34510303, 0.5513352 ]], dtype=float32)

I was expecting the two approaches to produce the same results. My understanding was that XGBClassifier is also based on a one-vs-rest approach in a multiclass case, since there are 3 probabilities in the output and they sum up to 1.
Can you tell me where the difference comes from, and how the respective results should be interpreted? And most important, which is approach is better suited to solve my problem.


text:
Q: Copy specific files from directory and subdirectories into new directory Python I am a beginner on Python. I would like to copy specific files (using pattern matching and shutil.copy) from  directory and sub directories (using os.walk) into a new directory.
The code works only for one file from one sub directory but not with multiple sub directories.
One specific file in only one sub directory can be copied into a new directory by using pattern matching and shutil.copy.
When I want to match specific files from different sub directories it's not possible to copy into the new directory.
Here the code for the file in one sub directory :
import os
import shutil
import shutil
from fnmatch import fnmatch

root = r'C:\Users\Fabien.Seychelles\Documents\Projects\Python_weather\Weather_Files'
dest =r'C:\Users\Fabien.Seychelles\Documents\Projects\Python_weather\CSV_converted'

pattern2 = '*TMY*.epw'

for path, subdirs, files in os.walk(root):
    for filename in files:
        if fnmatch(filename, pattern2):
            shutil.copy(root + '\\'+ filename, dest)

I was thinking about using a recursive copy, or shutil.copytree but I am not really sure.
Thank you

A: I'm guessing you're on windows?
You could call the "dir" command programmatically using subprocess or os.system and consume the output. The flags you could use are
dir /s /b

/s for sub-directories and /b for bare output


text:
Q: Not able to test Sagepay Repeat Payment I am using test environment and I am able to do simple payment but when I trying to test repeat payment then I am not able to understand 4 mandatory fields
which are
1.RelatedVPSTxId
2.RelatedVendorTxCode
3.RelatedSecurityKey
4.RelatedTxAuthNo
Pls someone explain that what I need to put in these fields and also I already read this tutorial
https://www.sagepay.co.uk/file/21071/download-document/SHARED_Protocol_Guidelines_010814.pdf?token=D4jfiGwtOMRN8Hu7oASnlhGCGV98PojRSXSfxSY77G4

A: Those 4 fields all relate to an original transaction that you would like to repeat i.e. you are using the details of a successful payment already made (e.g. through the checkout page of your online store) to perform the repeat transaction against (although obviously it can be for a completely different monetary value).
If you want to perform repeat transactions then you'll need to store these values from the initial transaction in a database so you can retrieve them as required to process the repeat:

*

*VPSTxId (posted back to you from SagePay when the original transaction was made)

*VendorTxCode (created by you to make the original payment)

*SecurityKey (posted back to you from SagePay when the original transaction was made)

*TxAuthNo (posted back to you from SagePay when the original transaction was made)


text:
Q: Ruby directly from command line I know that I can run ruby code directly from the command line, like so:
ruby file.rb

But is there any way to run ruby code directly from the command line so that I don't have to save the file in the first place?

A: ruby -e 'puts("foobar :)"); puts(2 + 2)'
should print foobar :) and 4

A: The quick help invoked using ruby -h says:
$ ruby --help
Usage: ruby [switches] [--] [programfile] [arguments]
  ...
  -e 'command'    one line of script. Several -e's allowed. Omit [programfile]
  ...

@djaszczurowski's answer provides you an example.
Another, better, option is to use irb (the interactive Ruby interpreter). It displays a prompt and waits for you to enter Ruby code. Multiple lines of code can be entered; it is executed when the block is closed.
@ho-man's answer shows you how to use it.

A: If you have more code that you'll like to run you can use irb instead.
$ irb
2.4.1 :001 > puts (2+2)
4
 => nil


text:
Q: how to select variable in sqlit3 table I tried to get some variable from my SQLite table for some reasons  I get an error that the column "user1" is no in the table
what I try to do is go to my table users from there get the user_id value-form where username in the same table equal to the value user1
sql.cur.execute("SELECT user_id FROM users WHERE username = {}".format('user1'))

A: Since you're using normal Python string formatting, your query is this.
SELECT user_id FROM users WHERE username = user1

Note the lack of quotes. where username = user1 is where the column username equals the column user1.
You need to quote your values.
SELECT user_id FROM users WHERE username = 'user1'

But do not treat SQL like strings. From the Python sqlite3 docs...

Usually your SQL operations will need to use values from Python variables. You shouldn't assemble your query using Python's string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see https://xkcd.com/327/ for humorous example of what can go wrong).

Instead, use bind parameters. They treat the query more like passing parameters to a function.
sql.cur.execute("SELECT user_id FROM users WHERE username = ?", 'user1')


text:
Q: How to use magnific popup with ajax post and url? Hi all is there a way to use magnific popup with ajax, I will be using it to insert data once magnific popup triggered.
here's my code:
$(function () {

    $('.popup-modal').magnificPopup({

    $.ajax({
    type: "POST",
    url: "insertVote.php",
    data: dataString,
    cache: false,

    success: function(html) {
    parent.html(html);
     }
});

    });
return false;

A: you need to use callback function:
$('.popup-modal').magnificPopup({

  callbacks : {

    open : function(){
       $.ajax({
          type: "POST",
          url: "insertVote.php",
          data: dataString,
          cache: false,
          success: function(html) {
             parent.html(html);
          }
       });
    }
  }
});


text:
Q: Wronski-Test for linear ODE To test solutions of linear ODEs for lineary independence you can determine the wronski determinant. The theorem says if you have a solution to the linear ODE in the form:
$$
\dot{\vec{x}}(t) = A \cdot \vec{x}(t)
$$
you can test for linear independence by showing
$$\exists t_0 \in I\colon\;
\operatorname{det}(W(t_0)) \neq 0
$$
with $W(x)$ being the Wronski-Matrix:
$$
W(t) = \begin{pmatrix}
\vec{x_1}(t)& \cdots & \vec{x_n}(t)
\end{pmatrix}
$$ where $x_i$ is the i-th vector of the solution.
If you find just one $t_0$ it follows that:
$$\forall t \in I\colon\;\operatorname{det}(W(t)) \not\equiv 0$$
(With $\not\equiv 0$ i mean constant not zero).
I don't understand why this implication holds true.
Why can I conclude from the fact that the Wronski determinant is at one point equal zero that it must be everywhere? $ det (W (t)) $ is not constant and it depends on $t$.
I'm happy about any answers!
Many Greetings,
Sebi2020

A: This matter may be resolved via Liouville's formula, which affirms that if $X(t)$ an $n \times n$ matrix solution of the differential equation
$\dot X(t) = A(t)X(t) \tag 1$
the determinant of $\det(X(t))$ of $X(t)$ is given by
$\det(X(t)) = \det(X(t_0)) \exp \left ( \displaystyle \int_{t_0}^t \text{trace}(A(s)) \; ds \right ); \tag 2$
since
$\exp \left ( \displaystyle \int_{t_0}^t \text{trace}(A(s)) \; ds \right ) \ne 0, \; \forall t_0, t \in I, \tag 3$
we see that
$\det(X(t)) \ne 0 \Longleftrightarrow \det(X(t_0)) \ne 0. \tag 4$
Now we may conclude with the simple observation that we may take
$W(t) = \det(X(t)) = \det(\vec x_1(t), \vec x_2(t), \ldots, \vec x_n(t)). \tag 5$


text:
Q: Is the command in Tkinter button stored in the button? I am making a simple calculator application using tkinter in python.
but firstly i want that what button i press should be printed in the entry.
import tkinter as tk
base = tk.Tk()
base.title("First Calculator")
lst,lst2 = [0,1,2,"+",3,4,5,"-",6,7,8,"*",9,".","=","/"],[]
val = 0
base.configure(bg = "grey")
text_box = tk.Entry(width = 43)

frame = tk.Frame()
text_box.grid(row = 0,column = 0)
for j in range(4):
   for i in range(4):
        a =  lst[val]
        b = tk.Button(master = frame,text = a,height = 3, width = 8, bg =
   "white",command = lambda: text_box.insert(0,a))
        b.grid(row = j, column = i)
        val += 1
frame.grid()

base.mainloop()

but whatever button i press i gives "/".
please help.


text:
Q: Passing objects as parameters, no viable overloaded '=' We are starting to cover objects and classes. I have three files: bigNumberTest.cpp, bigNumber.cpp, and bigNumber.h.
I'm having an error that say's "No viable overloaded '=' " in my main with:
bigNumberTest.cpp(provided by instructor)

int main(){
    //code
    sum = num1.addBig(num2);
    //code
}

I get a second error when I define the function in my bigNumber.cpp file with:
num[i] = num[i] + num2[i];

error here is: "Type 'bigNumber' does not provide a subscript operator."
bigNumber.cpp

void bigNumber::addBig(bigNumber num2){

    //sums the two arrays
    for (int i = 0; i < MAX_DIGITS; i++){
    num[i] = num[i] + num2[i];
    }
}

The overall code is not completely finished, but I would like to address these issues. I provided what I believed to be just the necessary code, but let me know if you need more info. I'm not fully understanding objects and classes just yet.
bigNumber.h file:

class bigNumber{

private:

    const int MAX_DIGITS = 100;
    int num[100];

public:

    void readBig();
    void addBig(bigNumber);
    void printBig();
};

A: In main program, the operands are of type bigNumber. Compiler doesn't know how to perform an '=' operation on them. You'll have to write it yourself. Overload the '=' symbol that supports your datatype.
It should be something like this:
void bigNumber::operator=(bigNumber rhs)
{
    for(int i=0 ; i<MAX_DIGITS ; i++)
    {
        this->num[i] = rhs.num[i];
    }
}

And for the second error, num2 is just a variable. num2 object has a variable num in it.
So, the actual code has to be:
bigNumber.cpp

void bigNumber::addBig(bigNumber num2){

    //sums the two arrays
    for (int i = 0; i < MAX_DIGITS; i++){
        this->num[i] = this->num[i] + num2.num[i];
    }
}

Try learning more about this operator.


text:
Q: C++ Concepts: How to use 'concept' to check the property of a templated struct? I'm currently experimenting with the new c++2a 'concepts' feature. The goal of my code below is to check some property of a templated struct. As the first template argument is 'reserved' for the type to be checked, I have difficulties using the concept without a requires expression or specifying template arguments manually. This is not a big deal, but I like the concept notation for its clarity. Is there a way to work around this?
Compiler
gcc-g++-10.0 (GCC) 10.0.1 20200119 (experimental)
Copyright (C) 2020 Free Software Foundation, Inc.

Compile command
g++-10.0 -std=c++2a file.cc

Code

#include <concepts>

/// Struct has template arguments and a property that can be checked in a concept.
template <bool a> struct A {
  constexpr static bool property() noexcept { return a; }
};

template <typename T, bool a> concept hasProp = std::is_same_v<T, A<a>> && A<a>::property();

template <bool a> requires hasProp<A<a>, a> void works(A<a> c) {}
template <bool a, hasProp<a> c> void deductionError(c d) {};

// This is a sketch of what I'd like to do:
// template <A<a, b> Class, bool a, bool b> concept hasProp = Class::property;

int main() {
  A<true> a;
  A<false> b;

  works(a);
  //works(b); //doesn't compile as the constraint is not fulfilled, which is desired.

  //deductionError(a); // I get why this deduction error occurs, but is it possible to do this
                      // in a clean way using concepts without having so specify template arguments?
}

A: Partial class template specializations to the rescue:
template<class T>
struct HasProp : std::false_type{};

template<bool a>
struct HasProp<A<a>> : std::integral_constant<bool, A<a>::property()>
{};

template <class T>
concept hasProp = HasProp<T>::value;

template <bool a>
requires hasProp<A<a>>
void works(A<a>) {}

template<hasProp C>
void deductionError(C){} // no longer a deductionError

Demo

This does (perhaps needlessly) tie your concept to A directly.
You could instead do this (Like @Barry answered):
template <class T>
concept hasProp = T::property();

Demo2

A: Do you really need the tie-in to A?
template <typename T> concept hasProp = T::property();

template <bool a> requires hasProp<A<a>> void works(A<a>); // ok
template <hasProp C> void deductionError(C);               // also ok

If you do need the tie-in, you can add that entirely local to hasProp:
// unfortunately this is hard to generalize due to the non-type template parameter
template <typename T> struct is_A : std::false_type { };
template <bool b> struct is_A<A<b>> : std::true_type { };

template <typename T> concept hasProp = is_A<T>::value && T::property();

// ... and the rest works as before
template <bool a> requires hasProp<A<a>> void works(A<a>); // ok
template <hasProp C> void deductionError(C);               // also ok

Either way, hasProp should just take a type.


text:
Q: How to make a logo image in the centre of QRcode in Vue? I'm working on a Vue project, and I want to add a logo image to the centre of a QRcode component. My code structure is similar as below shows:

  <QRcode :text="url />

I'm currently just add position: absolute; property to the , and calculate the position manually and make it looks like that the logo is in the centre of the QRcode component.
So, I'm looking forward to a better solution for this.

A: You can put any image on your Qrcode as long as your scanner detects them because they basically cover the center part of the Qrcode!
<template>

    <vue-qrcode
      value="https://github.com/fengyuanchen"
      tag="svg"
      :options="{
        errorCorrectionLevel: 'Q',
        width: 200,
      }"
    ></vue-qrcode>

</template>

image on Qrcode: source


text:
Q: Get elapsed time to swap img src using JavaScript I'd like to get the elapsed time to change the src of an img using JavaScript.  Something like the following:
var startTime = new Date().getTime();
document.getElementById('img1').src = someNewUrl;
var elapsedTime = (new Date().getTime()) - startTime;

This code apparently is measuring only the time it takes the browser to set the src attribute of the img.
What I'd like instead is code that will actually measure the time elapsed until the image is actually loaded.
Is there a way I can accomplish that?  A solution using jQuery would be delightful.
Thanks.

A: You need to use onload method to accomplish this. For example
var startTime = new Date().getTime();
document.getElementById('img1').onload = function(){
  var elapsedTime = (new Date().getTime()) - startTime;
}
document.getElementById('img1').src = someNewUrl;

With jQuery
var startTime = new Date().getTime();
$('#img1').load(function(){
  var elapsedTime = (new Date().getTime()) - startTime
).attr({src: someNewUrl});

A: To elaborate on @Marc's answer (using jQuery and Date.now() for conciseness):
var start = Date.now();

$('#img1').one('load', function()
{
    console.log('Image load took', Date.now() - start, 'ms');
}).attr('src', someNewUrl);

Without jQuery and whatnot:
var img = document.getElementById('img1'),
    start;

img.onload = function ()
{
    var duration = new Date().getTime() - start;
    console.log('Image load took ' + duration + ' ms');
    img.onload = null;
};

start = new Date().getTime();
img.src = someNewUrl;

A: $('#img1').load(function() {
   ... image has been loaded ...
}

You'd have to have the load handler call another function (or do it itself) to do the elapsed time calculation/display.


text:
Q: Pick and flatten a type signature in TypeScript I was looking over some of the cooler type functions that are included in the standard library and I got around to playing. Is something like this actually possible in TypeScript?
interface OriginalType {
    A: { a : string }
    B: { b1 : string, b2: number }
    C: {}
    D: {c: string}
}

const r : {a: string, b1: string, b2: string} = pickAndFlatten<OriginalType>(['A', 'B'])

A: We can so this by creating an intersection of the picked property types.
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type PickAndFlatten<T, K extends keyof T> = UnionToIntersection<T[K]>;

UnionToIntersection was provided by @jcalz here and you should see the explanation there (don't forget to thank him with an upvote :) ). T[K] will give us the type of the key K. If K is a union of keys, T[K] will be a union of all property types in the union.
To use this in a function we will need two type parameters, one representing the type we are picking from an one to represent the keys we are picking.
interface OriginalType {
  A: { a: string };
  B: { b1: string, b2: number };
  C: {};
  D: { c: string };
}

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type PickAndFlatten<T, K extends keyof T> = UnionToIntersection<T[K]>;

function pickAndFlatten<T, K extends keyof T>(o: T, keys: K[]): PickAndFlatten<T, K> {
  // Untested implementation
  const entries = Object.entries(o)
      .filter(([k, v]) => keys.includes(k as K))
      .map(([k, v]) => v);

  return Object.assign({}, entries) as any;
}

let o: OriginalType;
const r = pickAndFlatten(o, ['A', 'B']); // { a: string; } & { b1: string; b2: number; }


text:
Q: Why is Cases[] so slow here? Are there any tricks to speed it up? While trying to paste images, I noticed that Cases[] is very slow.
To reproduce, first copy a large image to the clipboard (just press Print Screen), then evaluate the following:
In[33]:= SetSystemOptions["PackedArrayOptions" -> "UnpackMessage" -> True];

In[34]:= AbsoluteTiming[nb = NotebookGet@ClipboardNotebook[];]
Out[34]= {0.4687500, Null}

In[35]:= AbsoluteTiming[d1 = nb[[1, 1, 1, 1, 1, 1, 1]];]
Out[35]= {0., Null}

In[36]:= AbsoluteTiming[d2 = First@Cases[nb, r_RasterBox :> First[r], Infinity, 1];]

During evaluation of In[36]:= Developer`FromPackedArray::unpack: Unpacking array in call to Notebook. >>

Out[36]= {0.9375000, Null}

(I did this on Windows, not sure if the paste code is the same on other systems.)
Note that extracting the data using Cases is extremely slow compared to using Part directly, even though I explicitly tell Cases that I need only one match.
I did find out (as shown above) that Cases triggers unpacking for some reason, even though the search should stop before it reaches the packed array inside.  Using a shallower level specification than Infinity might avoid unpacking.
Question:  Using Cases here is both easier and more reliable than Part (what if the subexpression can appear in different positions?)  Is there a way to make Cases fast here, perhaps by using a different pattern or different options?

Possibly related question: Mathematica's pattern matching poorly optimized?
(This is why I changed the Cases rule from RasterBox[data_, ___] -> data to r_RasterBox :> First[r].)

A: I don't have access to Mathematica right now, so what follows is untested. My guess is that Cases unpacks here because it searches depth-first, and so sees the packed array first. If this is correct, then you could use rules instead (ReplaceAll, not Replace), and throw an exception upon first match:
Module[{tag},
   Catch[
     nb /. r_RasterBox :> Block[{}, Throw[First[r], tag] /; True];
     $Failed,
     tag]
]

As I said, this is just an untested guess.
Edit 2: an approach based on shielding parts of expression from the pattern-matcher
Preamble
In the first edit (below) a rather heavy approach is presented. In many cases, one can take an alternative route. In this particular problem (and many others like it), the main problem is to somehow shield certain sub-expressions from the pattern-matcher. This can be achieved also by using rules, to temporarily replace the parts of interest by some dummy symbols.
Code
Here is a modification of Cases which does just that:
Clear[casesShielded];
casesShielded[expr_,pt_,shieldPattern_,levspec_,n_,opts:OptionsPattern[]]:=
   Module[{dummy,inverseShieldingRules, shielded, i=0},
      inverseShieldingRules =
        If[#==={},#,Dispatch@First@#]&@
           Reap[shielded= expr/.(p:shieldPattern):>
             With[{eval = With[{ind = ++i},Sow[dummy[ind]:>p];dummy[ind]]},
                eval/;True];
           ][[2]];
      Cases[shielded,pt,levspec,n,opts]/.inverseShieldingRules];

This version of Cases has one additional parameter shieldPattern (third one), which indicates which sub-expressions must be shielded from the pattern-matcher.
Advantages and applicability
The code above is pretty light-weight (compared to the suggestion of edit1 below), and it allows one to fully reuse and leverage the existing Cases functionality. This will work for cases when the main pattern (or rule) is insensitive to shielding of the relevant parts, which is a rather common situation (and in particular, covers patterns of the type _h, including the case at hand). This may also be faster than the application of myCases (described below).
The case at hand
Here, we need this call:
In[55]:=
(d4=First@casesShielded[nb,x_RasterBox:>First@x,
    p_List/;Developer`PackedArrayQ[p],Infinity,1]);//Timing

Out[55]= {0.,Null}

and the result is of course the same as before:
In[61]:= d2===d4
Out[61]= True

Edit: an alternative Cases-like function
Motivation and code
It took me a while to produce this function, and I am not 100 percent sure it always works correctly, but here is a version of Cases which, while still working depth-first, analyzes expression as a whole before sub-expressions:
ClearAll[myCases];
myCases[expr_, lhs_ :> rhs_, upToLevel_: 1, max : (_Integer | All) : All,
    opts : OptionsPattern[]] :=
 Module[{tag, result, f, found = 0, aux},
   With[{
    mopts = FilterRules[{opts}, {Heads -> False}],
    frule =
       Apply[
         RuleDelayed,
         Hold[lhs, With[{eval =  aux}, Null /; True]] /.
            {aux :> Sow[rhs, tag] /; max === All,
             aux :> (found++; Sow[rhs, tag])}
       ]
    },
    SetAttributes[f, HoldAllComplete];
    If[max =!= All,
       _f /; found >= max := Throw[Null, tag]
    ];
    f[x_, n_] /; n > upToLevel := Null;
    f[x_, n_] :=
      Replace[
       HoldComplete[x],
       {
          frule,
          ex : _[___] :>
            With[{ev =
              Replace[
                HoldComplete[ex],
                y_ :> With[{eval = f[y, n + 1]}, Null /; True],
                {2},
                Sequence @@ mopts
              ]},
              Null /; True
            ]
       },
       {1}
      ]
   ]; (* external With *)
   result =
     If[# === {}, #, First@#] &@
        Reap[Catch[f[expr, 0], tag], tag, #2 &][[2]];
   (* For proper garbage-collection of f *)
   ClearAll[f];
   result
 ]

How it works
This is not the most trivial piece of code, so here are some remarks. This version of Cases is based on the same idea I suggested first - namely, use rule-substitution semantics to first attempt the pattern-match on an entire expression and only if that fails, go to sub-expressions. I stress that this is still the depth-first traversal, but different from the standard one (which is used in most expression-traversing functions like Map, Scan, Cases, etc). I use Reap and Sow to collect the intermediate results (matches). The trickiest part here is to prevent sub-expressions from evaluation, and I had to wrap sub-expressions into HoldComplete. Consequently, I had to use (a nested  version of the) Trott-Strzebonski technique (perhaps, there are simpler ways, but I wasn't able to see them), to enable evauation of rules' r.h.sides inside held (sub)expressions, and used Replace with proper level spec, accounting for extra added HoldComplete wrappers. I return Null in rules, since the main action is to Sow the parts, so it does not matter what is injected into the original expression at the end. Some extra complexity was added by the code to support the level specification (I only support the single integer level indicating the maximal level up to which to search, not the full range of possible lev.specs), the maximal number of found results, and the Heads option. The code for frule serves to not introduce the overhead of counting found elements in cases when we want to find all of them. I am using the same Module-generated tag both as a tag for Sow, and as a tag for exceptions (which I use to stop the process when enough matches have been found, just like in my original suggestion).
Tests and benchmarks
To have a non-trivial test of this functionality, we can for example find all symbols in the DownValues of myCases, and compare to Cases:
In[185]:=
And@@Flatten[
    Outer[
       myCases[DownValues[myCases],s_Symbol:>Hold[s],#1,Heads->#2]  ===
       Cases[DownValues[myCases],s_Symbol:>Hold[s],#1,Heads->#2]&,
       Range[0,20],
       {True,False}
    ]]

Out[185]= True

The myCases function is about 20-30 times slower than Cases though:
In[186]:=
Do[myCases[DownValues[myCases],s_Symbol:>Hold[s],20,Heads->True],{500}];//Timing
Out[186]= {3.188,Null}

In[187]:= Do[Cases[DownValues[myCases],s_Symbol:>Hold[s],20,Heads->True],{500}];//Timing
Out[187]= {0.125,Null}

The case at hand
It is easy to check that myCases solves the original problem of unpacking:
In[188]:= AbsoluteTiming[d3=First@myCases[nb,r_RasterBox:>First[r],Infinity,1];]
Out[188]= {0.0009766,Null}

In[189]:= d3===d2
Out[189]= True

It is hoped that myCases can be generally useful for situations like this, although the performance penalty of using it in place of Cases is substantial and has to be taken into account.


text:
Q: Unknown provider I have come across a quite peculiar error on my AngularJS code of a web application.
I have an application which has a form for inserting new data in the database, but before that it's going to look for any coincidences.
Now, the object that we insert in database has a series of collections and if it already exists the application will show the whole content on the UI, where the user will be able to add new items to the collections
The collections are made of entities which each have their own view and independent access to them from the navbar menu, so when I call the add new item method in the form it's actually recycled from the previous one, and here is the funny part
I have done three of them in the form and they all work fine, same view shows, same functionality, but when I try with the fourth one, this error comes up:
angular.js:13294 Error: [$injector:unpr] Unknown provider: pagingParamsProvider <- pagingParams <- TreatmentController2
http://errors.angularjs.org/1.5.2/$injector/unpr?p0=pagingParamsProvider%20%3C-%20pagingParams%20%3C-%20TreatmentController

Now, the even funnier thing is that I am using the same code for the controller and for the view as what is used on the separate entity view access, yet when I do it from the form it won't work.
If I remove the paging params injection, it loads the view, but of course, it loses all functionality.
Here's the code:
Controller:
  (function() {
    'use strict';

    angular
        .module('vivaxDataManagerApp')
        .controller('TreatmentController', TreatmentController);

    TreatmentController.$inject = ['$scope', '$state', 'Treatment', 'TreatmentSearch', 'ParseLinks', 'AlertService', 'pagingParams', 'paginationConstants'];

    function TreatmentController ($scope, $state, Treatment, TreatmentSearch, ParseLinks, AlertService, pagingParams, paginationConstants) {
        var vm = this;
        vm.loadAll = loadAll;
        vm.loadPage = loadPage;
        vm.predicate = pagingParams.predicate;
        vm.reverse = pagingParams.ascending;
        vm.transition = transition;
        vm.clear = clear;
        vm.search = search;
        vm.searchQuery = pagingParams.search;
        vm.currentSearch = pagingParams.search;
        vm.loadAll();

         function loadAll () {
                if (pagingParams.search) {
                    TreatmentSearch.query({
                        query: pagingParams.search,
                        page: pagingParams.page - 1,
                        size: paginationConstants.itemsPerPage,
                        sort: sort()
                    }, onSuccess, onError);
                } else {
                    Treatment.query({
                        page: pagingParams.page - 1,
                        size: paginationConstants.itemsPerPage,
                        sort: sort()
                    }, onSuccess, onError);
                }
                function sort() {
                    var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')];
                    if (vm.predicate !== 'id') {
                        result.push('id');
                    }
                    return result;
                }
                function onSuccess(data, headers) {
                    vm.links = ParseLinks.parse(headers('link'));
                    vm.totalItems = headers('X-Total-Count');
                    vm.queryCount = vm.totalItems;
                    vm.treatments = data;
                    vm.page = pagingParams.page;
                }
                function onError(error) {
                    AlertService.error(error.data.message);
                }
            }

            function loadPage (page) {
                vm.page = page;
                vm.transition();
            }

            function transition () {
                $state.transitionTo($state.$current, {
                    page: vm.page,
                    sort: vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc'),
                    search: vm.currentSearch
                });
            }

            function search (searchQuery) {
                if (!searchQuery){
                    return vm.clear();
                }
                vm.links = null;
                vm.page = 1;
                vm.predicate = '_score';
                vm.reverse = false;
                vm.currentSearch = searchQuery;
                vm.transition();
            }

            function clear () {
                vm.links = null;
                vm.page = 1;
                vm.predicate = 'id';
                vm.reverse = true;
                vm.currentSearch = null;
                vm.transition();
            }

        }
    })();

The call from the HTML code:

            Insert new Treatment:

The function in the form controller:
 $scope.newTreatment = function () {
                $scope.myHidingValue=true;
                $uibModal.open({
                    templateUrl: 'app/entities/treatment/treatment-dialog.html',
                    controller: 'TreatmentController',
                    size: 'lg',
                    controllerAs: 'vm',
                    backdrop: 'static',
                    resolve: {
                        entity: function () {
                            return {};
                        }
                    }
                }).result.then(function (result) {
                    $scope.publi = result;
                }, function () {
                })
            };

I'm only posting what I think is the most relevant code, as I have thousands of lines in this project, but if necessary, I don't mind posting more code
Thank you all in advance
Steven

A: Mistery solved, the problem was that I wasn't using the right controller, where I should of had TreatmentDialogController, I had TreatmentController, shame on me, I know.
Thank you to The Head Rush for leading me in the right direction!


text:
Q: when changing video source, downloading starts automatically before streaming I have a bootstrap modal contains a video that appears when click on play button
-code:

        <video class="show-video" controls crossorigin="" autoplay="" id="player" [src]="source" __idm_id__="3612673">
          <source [src]="source" type="video/mp4">
        </video>

this play button when clicked it calls back a function sending the streaming link as a parameter
-button code:
<button (click)="playIframe(show.stream)" class="btn btn-success play" type="submit" *ngIf="show.stream != ''"
          data-bs-toggle="modal" data-bs-target="#showModal">
          Watch Now</button>

-playIframe code:
 playIframe(_source: string) {
    this.source = _source;
  }

and when closing the modal I call back another function that change the variable "source" to empty string so I can stop the video.
-Problem: what happens is everything is going ok but when I click the play button a downloading -of the video- starts automatically before streaming starts
I want to stop downloading, only streaming.
Thanks.


text:
Q: AWS Cognito UserMigration_ForgotPassword not trigger on forgot_password flow I am doing an authentication project with Cognito and I am trying to migrate my user to cognito pool with UserMigration in custom trigger flow using forgot password flow (following documentation, there are 2 ways to trigger this are sign-in and forgot-password [1]) on sign-in the trigger works properly but the problem occurs on forgot password, the trigger is not working, not any trigger in cloudwatch-log!
I have been trying and searching many where but, still not working. Here is my lambda code with python boto3. that used on forgot-password:
def forgot_password(username):
    try:
        response = cognito_client.forgot_password(
            ClientId=MY_APP_CLIENT_ID,
            SecretHash=MY_SECRET_HASH,
            Username=username,
            ClientMetadata={"key":"value"}
        )
        return response
    except Exception as e:
        logging.error(e)

my expectation is the User Migration trigger should work and wake in forgot-password flow simply.
Thank you in advance for helping or answering this issue
Thanks a lot :)
Note: I also add ClientMetadata like in this question[2] but, the trigger is still not working as expected.
[1] https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html#aws-lambda-triggers-user-migration-example-1
[2] AWS Lambda UserMigration_ForgotPassword Trigger | Not Migrating Users

A: Not confident with python boto3, but I would suggest also to double check you're using USER_PASSWORD_AUTH flow → reference


text:
Q: How do I split up a year range into individual years in a given field? I was working in Access to make a query of a few tables, and realized that a column of a table does not meet a specific requirement.
I have a field that consists of thousands of records, and it contains "years" in the following format (an example) : 1915-1918.
What I want to accomplish is to make that value individual in the records. So
the end result would be : 1915,1916,1917,1918.
Basically, I want to convert 1915-1918 to 1915,1916,1917,1918.
I thought a simple concatenation would suffice, but could not wrap my head around how to make it so that it can do it for all thousands of records. I did some research and reached the conclusion that a user defined function might be the way to go. How would I go about this?

A: You can use the Split function to return an array from the "years" field that contains the upper and lower year.  Then loop from the lower year to the upper year and build the concatenated string.  For example:
Public Function SplitYears(Years As String) As String
    Dim v As Variant
    Dim i As Long
    Dim s As String

    v = Split(Years, "-", 2)
    If UBound(v) = 1 Then
        For i = v(0) To v(1)
            s = s & "," & CStr(i)
        Next i
        s = Right(s, Len(s) - 1)
    Else
        s = v(0)
    End If
    SplitYears = s

End Function

A: When your field value consists of 4 digits followed by a dash followed by 4 more digits, this function returns a comma-separated list of years.
In any other cases (Null, a single year such as "1915" instead of a year range, or anything else), the function returns the starting value.
Public Function YearList(ByVal pInput As Variant) As Variant
    Dim astrPieces() As String
    Dim i As Long
    Dim lngFirst As Long
    Dim lngLast As Long
    Dim varReturn As Variant

    If pInput Like "####-####" Then
        astrPieces = Split(pInput, "-")
        lngFirst = CLng(astrPieces(0))
        lngLast = CLng(astrPieces(1))
        For i = lngFirst To lngLast
            varReturn = varReturn & "," & CStr(i)
        Next
        If Len(varReturn) > 0 Then
            varReturn = Mid(varReturn, 2)
        End If
    Else
        varReturn = pInput
    End If
    YearList = varReturn
End Function

However, this approach assumes the start year in each range will be less than the end year.  In other words, you would need to invest more effort to make YearList("1915-1912") return a list of years instead of an empty string.
If that function returns what you want, you could use it in a SELECT query.
SELECT years_field, YearList(years_field)
FROM YourTable;

Or if you want to replace the stored values in your years field, you can use the function in an UPDATE query.
UPDATE YourTable
SET years_field = YearList(years_field);

A: In Excel, make a sequential reference table of Years, for the range of years that you expect to encounter.
Next, use left and right functions to get the start and end of the range.
Create an update query and update the target field with a concatenation of target field to itself and then also the reference year values between that also fit between the start and end of the range.
Or I guess you could make a user function.

A: Add the code below to a module in Visual Basic
Public Function CommaDates(Start_End) As String
    Dim strt As String
    Dim endd As String
    Dim x As Long

    strt = Left(Start_End, 4)
    endd = Right(Start_End, 4)
    CommaDates = strt

    For x = strt + 1 To endd
        CommaDates = CommaDates & "," & x
    Next x
End Function

Call this in a query like NEW_DATE: CommaDates([OLD_DATE_FIELD_NAME])