text:
Q: What happened to the Inductosyn? From what I have read the Inductosyn has incredible accuracy (~3um) and repeatability (~600nm) yet it seems to be phased out for position sensing applications and nobody talks about it anymore. What was the drawback? Cost, speed, reliability? If anyone knows I would greatly appreciate it, I've spent days looking but it seems like it was already superseded by optical encoders before the internet.
http://www.ruhle.com/rotary%20transducers.htm
https://www.maccon.com/rotary-linear-encoders/magnetic-encoders/inductosyn.html
The link below provides a great comparison for Encoders vs Resolvers which is similar and I understand, but the Inductosyn doesn't have the accuracy drawback.
https://ormec.com/Portals/ormec/files/Services/Applications/ApplicationNotes/EncoderVsResolver.pdf
1999 website that goes over inductosyns
http://what-when-how.com/electric-motors/linear-and-rotary-inductosyns-electric-motors/

A: No sure answers but I can postulate a few possibilities:

*

*Optical encoders are in a class of technology completely different from resolvers and InductoSyn. That makes them easier to differentiate. If the low resolution of resolvers compared to optical encoders is widely known, it's going to cause more people to just pick the optical encoder rather than the InductoSyn which is more difficult to differentiate from the resolver.

*The InductoSyn disc sounds like it would be more expensive to make than a quadrature optical encoder disc since it requires two discs while the optical encoder only requires one.

*It could be the case that magnetic encoders, rather than optical encoders, supplanted Inductosyn . The description of the InductoSyn sounds a LOT like the magnetic encoders I use at work, down to the available pole counts and interpolation factors, except that instead of a hall sensor it uses induction. This is the possibility I lean towards the most since optical encoders and magnetic/inductive encoders have different advantages and disadvantages so it doesn't make too much sense for one to supplant the other. Magnetic and inductive encoders, on the other hand, seem to share most of the same advantages and disadvantages, but induction sensors are more complex (and therefore expensive) than magnetic sensors. Though I suppose they are immune to demagnetization.

A: The outsourcing of manufacturing to Asia and ease of interfacing already digital incremental sensors possibly had a significant role.
I noticed the biggest shift correlated with increased integration (74 shifting to ASICs) Early ASICs were not mixed signal like now. Also incremental systems seemed easy to copy where Inductosyn is extensively copyright, patent protected.
PS brushless resolvers from the 70, 80's are very repeatable and low noise. Modern equivalents have a hard time replacing them unless you go to extremely expensive military grade units.
The article above references the ratiometric interpolation resolver interface and its limitations. Most machinetool manfufacturers used a phase difference measurement which was easier to do digitally.
There is always lag in a digital servo system, and having a defined time window eases some aspects of programming in a real-time scenario.
Incremental systems have to avoid missing counts, absolute measures have to measure before the transition to the next cycle.
Just different engineering tradeoffs.


text:
Q: Prove that a countable completely regular space is zero dimensional Proposition A countable completely regular space is zero dimensional.
I'm going to need some help showing this is the case. First, suppose $X$ is a completely regular and countable. Then for each closed $E \subset X$ and $a \not\in E$, there is a continuous $f:X \to [0,1]$ so that $f(a) = 0$ and $f(E)=\{1\}$; also $X$ has countably many members.
I'm not sure where to go with this. Any suggestions? I have a couple of ideas.

*

*Utilize the continuity of $f$ to arrive at a conclusion about openness
using the fact that open $V$ in $[0,1]$ implies $f^{-1}(V)$ is open in $X$.

*Assume that $X$ is countable and completely regular and suppose $X$ is not zero dimensional (to arrive at a contradiction)

*Something else regarding the countability of the space

I'm having a hard time seeing how countability ties into this proof. Are any of the suggestions I've made on the right track?

A: Let $p\in U$ where $U$ is an open subset of $X.$ We show there is an open-and-closed $V$ with $p\in V\subseteq U.$
Let $f:X\to [0,1]$ be continuous with $f(p)=0$ and $f[X\setminus U]\subseteq \{1\}.$ There must exist $r\in (0,1)$ such that $f^{-1}\{r\}=\emptyset.$ Otherwise the set $B=\cup_{r\in (0,1)}f^{-1}\{r\}$ would be the union of an uncountable family of pairwise-disjoint non-empty sets, which would make $B$ an uncountable subset of $X.$
So let $r\in (0,1)$ with $f^{-1}\{r\}=\emptyset.$ Let $V=f^{-1}[0,r).$ Then $V$ is open and $p\in V\subseteq U.$ And $V$ is also closed because $X\setminus V=f^{-1}[r,1]=f^{-1}(r,1]$ is open.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disabling html button using JavaScript won't POST I have this Javascript and HTML code for my button:

function lockoutSubmit(button) {
  var oldValue = button.value;

  button.setAttribute('disabled', true);
  button.value = '...processing...';

  setTimeout(function(){
    button.value = oldValue;
    button.removeAttribute('disabled');
  }, 3000)
}
<button style="margin-right:-160px;" type="submit" name="gen" onclick="lockoutSubmit(this)" class="btn btn-danger btn-block">Generate account!</button>

The code works fine for disabling the button for 3 seconds but the button is no longer posting to "gen".

A: Change the innerHTML instead of the value and bind the parameters to the settimeout instead of relying on the context.
Also button value might not be what you think it is:
http://www.w3schools.com/tags/att_button_value.asp
<html>
    <head>
        <script>
            function _Unlock(){
                var tB = document.getElementById('gen');
                tB.removeAttribute('disabled');
                tB.innerHTML = 'Generate account!';

                localStorage.setItem('Lock', 0);
            }

            function Unlock(){
                var tS = localStorage.getItem('Lock');

                if (tS != '1') _Unlock()
                else{
                    setTimeout(function(e, v){
                        _Unlock()
                    }, 3000)
                }
            }

            function setToLock(){
                localStorage.setItem('Lock', 1);
            }
        </script>
    </head>

    <body onload = 'Unlock()'>
        <!-- Do you have a form and is it setup correctly? -->
        <form action = '' method = 'post' id = 'myForm' onsubmit = 'setToLock()'>
            <button id = 'gen' type = 'submit' name = 'gen' disabled = 'disabled'>...processing...</button>
        <form>
    </body>
</html>


text:
Q: construct binary search tree from Post-order traversal in Java I am implementing code to construct BST(binary search tree) from a given post-order traversal array following this algorithm. I do not get back the binary Search Tree back. I am getting something that makes no-sense. here is my code
public class BinaryTreemethods {
     public static void main(String[] args) {
             int[] preOrder = { 5, 3, 1, 4, 8, 6, 9 };
        int[] inOrder = { 1, 3, 4, 5, 6, 8, 9 };
        int[] postOrder = {1,4,3,8,6,9,5};

           static int postIndex=postOrder.length-1;
           Node postordertree= buildBinarytreefromPostOrder(postOrder, 0, postOrder.length-1);
           System.out.println("pre order traversal of node from postorder reconstructed tree ");
           printPreOrder(postordertree);

      }
      private static void printPreOrder(Node tree) {
        if (tree != null) {
            System.out.print(" " + tree.data);
            printPreOrder(tree.left);
            printPreOrder(tree.right);
        }

    }
      //this just reconstructs BT from post-order traversal elements
    public static Node buildBinarytreefromPostOrder(int[] post, int start, int end){
        if (postIndex<start || start > end ){
            return null;
        }

        Node root = new Node(post[postIndex]);
        postIndex--;
        if (end == start){
            //System.out.println("called");
            return root;
        }

        int i = 0;
        for (i=end;i>=start;i--){
            if (post[i]<root.data)
                break;
        }

        // Use the index of element found in postorder to divide postorder array
        // in two parts. Left subtree and right subtree
            root.right=buildBinarytreefromPostOrder(post,i+1, postIndex);
        root.left=buildBinarytreefromPostOrder(post,start,i);
             //root.left=buildBinarytreefromPostOrder(post,start,i);
        //root.right=buildBinarytreefromPostOrder(post,i+1, postIndex);

        return root;
    }
}

The output when I print in pre-order traversal is 5 9 6 8 3 4 which is not correct.
Any idea where I could be going wrong?
EDIT: After swapping the order of lines for root.right and root.left (commented out one were before),
the left tree is build correctly, but the right tree is not. The output I get is
5 3 1 4 9 6 8

A: As the root of each subtree you are taking postIndex which is global for the whole structure. You should take the last element of the subarray (end).
It should rather be like this
public static Node buildBinarytreefromPostOrder(int[] post, int start, int end)
{
    if (end < start)
        return null;

    Node root = new Node(post[end]);

    if (end == start)
        return root;

    int i;
    for (i = end; i >= start; i--)
        if (post[i] < root.data)
            break;

    root.left = buildBinarytreefromPostOrder(post, start, i);
    root.right = buildBinarytreefromPostOrder(post, i + 1, end - 1);

    return root;
}


text:
Q: How to install App to test iPad to reproduce deployment i created an "IPA" file to try my IOS App on the iPad before deploying to the apple store.
Once i export the "IPA" from Xcode and import it in iTunes , the app appears on the iPad semi-transparent and even after selecting "instal" in iTunes, it won't start.
Every time you tap on the icon , it says "installing" but it will not install it...
I tried to sync several times but without any success..
What am I doing wrong???
Thank you in advance

A: *

*go developer.apple.com

*in Certificates, Identifiers & Profiles section. Create a provisioning profile for your app.

*add your ipad's udid to that profile.

*install profile

*drag and drop that profile to itunes

and did what you wrote above. Good luck.
edit: if problem continues check ipad's profiles. (settings - general - profiles)


text:
Q: MySQL - 1075 Incorrect table definition, there can be only one auto column and it must be defined as a key I have the following code:
use Phinx\Migration\AbstractMigration;

class CreateNewTableForJobListLanguages extends AbstractMigration
{
    /**
    * Migrate up.
    */
    public function up()
    {
        $this->execute('
        CREATE TABLE `v2_joblist_languages` (
        `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
        `joblist_id` int(11) NULL,
        `language_id` int(11) NULL,
        FOREIGN KEY (`joblist_id`) REFERENCES `v2_job_alerts` (`id`),
        FOREIGN KEY (`language_id`) REFERENCES `v2_languages` (`id`))
    ');
}

When trying to migrate, I get the following error:
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key

Broke my head trying to solve it, and understand why is it happening. Grateful for any assistance, thanks in advance.

A: This is a many:many mapping table?  Is there really any need for id?  I doubt it; get rid of it.
Also provide PRIMARY KEY(joblist_id), language_id), INDEX(language_id, joblist_id)
Do you really want the two columns to be NULLable?  I doubt it.
More tips on many:many: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table


text:
Q: Aggregate info by quarters in data.table, setting a new name to column used in by I have this data.table that is a result from aggregating a bigger one:
data.table(Period = c('2018.01', '2018.02'), sales = c(8850, 7950), qty = c(650, 650))

    Period sales qty
1: 2018.01  8850 650
2: 2018.02  7950 650

What I need to achieve and can't get a way to do it, is to aggregate the info by quarters, so the result would be:
data.table(Period = c('2018.01', '2018.02', '2018Q1', '2018'), sales = c(8850, 7950, 16800, 16800), qty = c(650, 650, 1300, 1300))

   Period sales  qty
1: 2018.01  8850  650
2: 2018.02  7950  650
3:  2018Q1 16800 1300
4:    2018 16800 1300

I've tried with: dt = rbind(dt, dt[, lapply(.SD, sum), by = .(Period), .SDcols = c('sales', 'qty')])
but I get duplicated columns:
    Period  ums men
1: 2018.01 8850 650
2: 2018.02 7950 650
3: 2018.01 8850 650
4: 2018.02 7950 650

Besides, I'd need to rename the Period cell with Q1 (Q2, Q3, Q4) for the quarters and only the year for the total. How could it be done?
EDIT
Although the accepted answer is correct, I've reworked it so that I didn't need to add extra columns nor install new libraries:
DT = data.table(Period = c('2018.01', '2018.02'), sales = c(8850, 7950), qty = c(650, 650))

DT$Period = as.double(str_replace(DT$Period, "\\.", ""))
ints      = setInterval(2018)
dt        = DT[, lapply(.SD, sum), by = .(Period = cut(Period, breaks = ints$i, labels = ints$q)), .SDcols = c('sales', 'qty')]
dt        = rbind(dt, dt[Period %in% ints$q, lapply(.SD, sum), by = .(Period = '2018'), .SDcols = c('sales', 'qty')], fill = T)
DT$Period = paste(substr(DT$Period, 1, 4), ".", right(DT$Period, 2), sep = "")
DT        = rbind(DT, dt)

I needed to create this auxiliary function:
setInterval = function (year) {
   y = year * 100
   return (list(
      i = c(y, y + 3, y + 6, y + 9, y + 12),
      q = paste(year, '.', c('Q1', 'Q2', 'Q3', 'Q4'), sep = '')
   ))
}

A: dt <- data.table(Period = c('2018.01', '2018.02'), sales = c(8850, 7950), qty = c(650, 650))
library(zoo)
dt$Period_YQ <- as.character(as.yearqtr(paste(dt$Period, "01", sep="."), "%Y.%m.%d"))
dt$Period_Y <- strtrim(dt$Period, 4)

dt1 <- dt[,.SD,.SDcols=c(1:3)]
dt2 <- dt[,lapply(.SD,sum), by="Period_YQ", .SDcols = c('sales', 'qty')]
colnames(dt2) <- c('Period','sales', 'qty')
dt3 <- dt[,lapply(.SD,sum), by="Period_Y", .SDcols = c('sales', 'qty')]
colnames(dt3) <- c('Period','sales', 'qty')
rbind(dt1,dt2,dt3)

A: A similar but different approach that uses lubridate and dplyr:
Convert your Period to a DATE format. I like using lubridate::parse_date_time. Note that I also create new columns for each Year and Quarter:
library(lubridate)
df <- df %>%
      mutate(Period = parse_date_time(Period, "ym")) %>%
      mutate(Year = year(Period)) %>%
      mutate(Quarter = quarter(Period))

Then you calculate the Yearly and Quarterly sums separately:
Yearly <- df %>%
          group_by(Year) %>%
          summarise(Y.sales = sum(sales), Y.qty = sum(qty))

Quarterly <- df %>%
             group_by(Year, Quarter) %>%
             summarise(Q.sales = sum(sales), Q.qty = sum(qty))

Finally, you combine all the data using full_join:
final <- full_join(Yearly, Quarterly, by=c("Year")) %>%
         full_join(., df, by=c("Year","Quarter"))

This gives you a tidier (IMO) output organized by Year, Quarter, then Period:
   Year Y.sales Y.qty Quarter Q.sales Q.qty     Period sales   qty
  <dbl>   <dbl> <dbl>   <int>   <dbl> <dbl>     <dttm> <dbl> <dbl>
1  2018   16800  1300       1   16800  1300 2018-01-01  8850   650
2  2018   16800  1300       1   16800  1300 2018-02-01  7950   650


text:
Q: IPN - Handle empty string working with paypal´s IPN i do this:
$variable1 = "string";
$variable2 = "";
$test = array('cmd'=>'_xclick',
                        'business'=>'email@email.com',
                        'notify_url'=> 'url/to/ipn-script',
                        'item_name'=>'product',
                        'amount'=>'1.00',
                        'currency_code'=>'USD',
                        'lc'=>'US',
                        'custom'=>serialize( array( "variable1" => $variable1,"variable2" => $variable2)));

                        $url = "https://www.sandbox.paypal.com/cgi-bin/webscr?".http_build_query($test);

                        header("Location:".$url);
                        exit();

Using this code i get this error:
Failure: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'NULL,'.',NULL)'

Can i send empty strings in url and handle them in ipn-script or not?
Greetings!

A: It appears you have a MySQL error not a PayPal error?
From your script I cannot tell what queries might be executing. Try and replace 'custom' with a blank value and see if the error goes away, if you believe that is the culprit.
As a side note keep in mind the custom variable has a 200 character limit IIRC.


text:
Q: How to block access to certain pages to Users who are neither ADMIN nor STAFF in my case in PHP? I would like to know:
1 - How to create two different middlewares (for ADMIN and STAFF) from SESSION variables to use them later to prevent users who are neither ADMIN nor STAFF from accessing pages I don't want that they have access ???
Here's what I did, but I'm completely unsure and stuck:
FUNCTION PROCESSING ACCESS FOR ADMIN MEMBERS:
function checkAdmin()
{
    $_SESSION['hlbank_admin_user'] = array('name' => 'Admin');
    // if the session id is not set, redirect to login page
    if (!isset($_SESSION['hlbank_admin_user'])) {
        header('Location: ' . WEB_ROOT . 'admin/login.php');
        exit;
    }

    // the user want to logout
    if (isset($_GET['logout'])) {
        doLogout();
    }
}

FUNCTION PROCESSING ACCESS FOR STAFF MEMBERS:
function checkStaff()
{
    // if the session id is not set, redirect to login page
    if(strlen($_SESSION['staff_id'])==0) {
        $host = $_SERVER['HTTP_HOST'];
        $uri  = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
        $extra= WEB_ROOT . "admin/pages_staff_index.php";
        $_SESSION["staff_id"]="";
        header("Location: http://$host$uri/$extra");
    }

    // the user want to logout
    if (isset($_GET['logout'])) {
        doLogout();
    }
}

*

*So please help me to correct my two functions above which aim to
check via THE SESSION if the connected User is an ADMIN and a
STAFF.

*How to use both functions at the same time in a Page to check if the
User is an ADMIN or a STAFF and thus block access to users who are
neither ADMIN nor STAFF ???
Thank you please help me.

A: There are lots of ways to implement this but here's one. I'd simplify the functions so that they each return a boolean. Move all the redirect logic, logout stuff into the calling code.
I am not sure the name of the session keys you use so I just used hlbank_admin_user and staff_id. I also made the assumption that if they're set, then the user is that role.
I renamed the functions to isAdmin and isStaff.
function isAdmin(): bool
{
    return isset($_SESSION['hlbank_admin_user']);
}

function isStaff(): bool
{
    return isset($_SESSION['staff_id']);
}

Then, in your calling code, you can check for either one.
if (!isAdmin() && !isStaff()) {
    // Not authorized >> redirect
}

Taking it one step further, you can create a single function to check if they are either an admin or staff.
function isPrivileged(): bool
{
    return isAdmin() || isStaff();
}

Then, in your calling code, you can check for that.
if (!isPrivileged()) {
    // Not authorized >> redirect
}

Thank you for your reply. But I'm confused by your answer. Actually,
what I don't understand is why you didn't first declare the session
variables $_SESSION['hlbank_admin_user'] and $_SESSION['staff_id']
returned in the isAdmin() functions and isStaff() because you just
returned them with isset in each of those two functions ???
But why return them knowing that they have not yet declared???

Just to clear up any confusion, the way this normally works is during log-in, you set some session variables that you want to track in future requests. You don't need to redeclare them at all in the future. You can simply check for them, or read them.
Pseudocode for log in,
session_start()

if (username & password = true) {
    // These sessions values will persist for the entire session.
    // Just make sure to call `session_start()` on every page before trying to access them
    $_SESSION['isLoggedIn'] = true;
    $_SESSION['role'] = admin;
}

Then, when they try to access a restricted page you simply check if they are logged in and of a specific role.
Pseudocode to check access,
session_start()

$loggedIn = $_SESSION['isLoggedIn'] ?? false;
$role = $_SESSION['role'] ?? '';

if ($isLoggedIn === true && $role === 'admin') {
    // You are logged in and an admin
}

A: Thank you for your reply. But I'm confused by your answer. Actually, what I don't understand is why you didn't first declare the session variables $_SESSION['hlbank_admin_user'] and $_SESSION['staff_id'] returned in the isAdmin() functions and isStaff() because you just returned them with isset in each of those two functions ???
But why return them knowing that they have not yet declared???


text:
Q: Mongoose query returns empty array I'm using Express to do a find operation in a Mongo collection and return the result. I know that there is data in the collection, but the result array comes back empty. I suspect that it's an issue with the schema, but can't figure out what. Thoughts?
Route:
const PlotStatus = require('../models/plotStatus');
exports.plotStatuses = async (req, res) => {
    const plotStatus = await PlotStatus.find({
        company: req.user.companyCode
    }).lean();
    if (!plotStatus) {
        throw new Error('Plot Statuses not found');
    } else {
        res.send(plotStatus);
    }
};

Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const plotStatusSchema = new Schema(
    {
        recordDate: Date,
        blockName: String,
        growerName: String,
        company: String,
        variety: String,
        planted: Number,
        region: String,
        yieldInKG: Number,
        currentRipeness: String,
        nextStage: String,
        timeToNextInDays: Number,
        status: Number
    },
    { bufferCommands: false },
    { collection: 'plotStatuses' }
);

const ModelClass = mongoose.model('plotStatus', plotStatusSchema);

module.exports = ModelClass;

Sample plotStatus:
{
    "_id" : ObjectId("stringhere"),
    "recordDate" : ISODate("2018-01-02T12:50:51.236Z"),
    "blockName" : "name",
    "growerName" : "grower's name",
    "company" : "mycompany",
    "variety" : "myvariety",
    "planted" : 2010,
    "region" : "myregion",
    "yieldInKG" : 960,
    "changeInPcnt" : -1.6,
    "currentRipeness" : "ripeness",
    "nextStage" : "nextstage",
    "timeToNextInDays" : 42,
    "status" : 0
}

A: Okay, got it.
Typically, Mongoose infers the collection name from the model name, but you can pass it explicitly. Apparently, plotStatus => plotStatuses was a bridge too far. This fixed it:
const ModelClass = mongoose.model(
    'plotStatus',
    plotStatusSchema,
    'plotStatuses'
);


text:
Q: Create array of last 12 months based upon current date in jquery This is the currentdate i.e today's date
  var currentDate = new Date();

Let's say today's date is Sat Mar 21 2015 17:19:15 GMT+0530. I extracted the month from the date using the below code
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var month = monthNames[currentTime.getMonth()];

In my case month = MAR
Based upon the current month I want to create an array of last 12 months in increasing order from month-12 up to the present month that is MAR. The array must like this if current month is MAR
  date = ["APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];

How to get a dynamic array based on current date?
Thanks in advance


text:
Q: Reconstruction 3d on plane from 2d projection with camera calibration parametrs of plane Trying to reconstruct 3D-coordinates of point on plane from 2D-Pixel-Coordinates in a Camera Picture, using a extrinsic and intrinsic camera parameters from "Camera Calibration Toolbox for Matlab".
intrinsic parameters:
Focal Length:          fc = [ 1017.21523   1012.54901 ]
Principal point:       cc = [ 319.50000   239.50000 ]
extrinsic parameters:
Translation vector: Tc_ext = [ 4.409693      -74.116018      393.057934 ]
Rotation matrix:    Rc_ext = [ -0.083632     0.991715    -0.097501
                               0.832136      0.015674    -0.554350
                               -0.548230     -0.127495   -0.826553 ]
Can anybody help how to get 3d-coordinates of point on plane from 2d from camera image?

A: There are 4 cases to consider, in order of increasing complexity. The basic goal is to locate in space the plane of interest. After you have it, you can just intersect it with the ray that back-projects your pixel and thus obtain the solution.

*

*The plane of interest contains the checkerboard target AND the image is one of those you used to calibrate the camera. Then the extrinsic parameters [R | T] for that image returned by the calibration routine contain the answer, since the target is the XY plane of the returned world-to-camera coordinate transform at that image, and the world origin is one of the corners (you can see which corner it is by projecting point (0,0,0) into image coordinates. The XY plane (in camera coordinates) is the plane spanned by the first two columns of the rotation matrix R, and its origin is at point T.

*The plane of interest contains the checkerboard target, but its image is NOT one of those used to calibrate. You could just add it to the set, re-calibrate and goto 1., but a faster alternative is to (a) extract the corners as you do for calibration, (b) compute the homography H from their image positions to their "true" position on the physical target at Z=0; (c) decompose H into K * [R | T] using the known K from the calibration (you use an algorithm called "RQ decomposition" for this purpose, look it up). Then goto 1.

*The calibration target is not in the image, but you can identify in the image at least 4 points on that plane, such that no 3 of them are collinear and they are at known positions with respect to each other. For example, you see a rectangle of known sides in the image. Then, just like in point 2. you can compute the homography between those physical points and their images, and extract the [R|T] transform knowing the camera matrix. Then goto 1.

*None of the above: sorry, you are stuck.


text:
Q: Boolean Algebra with Max terms I want to simplify the following expression:
F = (A+B+C)(A+B'+C)(A'+B+C)
I have simplified it accordingly.
F = (A+B+C)(A+B'+C)(A'+B+C)
F = (A+C)(A'+B+C)
F = AA' + AB + AC + A'C + BC + C
F = AB + C(A + A' + B + 1) = AB + C
However, the correct answer is (A+C)(B+C).
Where in my "current" proof am I going wrong? I have seen the solution, but I want to know why my current approach is wrong.

A: Nothing wrong - it's just two different ways of expressing the same thing.
If the goal is minimization I would argue that your solution is "better" since it only references each term once.
Wolfram Alpha is your friend in cases like this.


text:
Q: How to fit SwiftUI content to split view layout margins? I have a sidebar in NavigationView with searchable and a grouped list that both inset properly to the largeTitle. However when I want to place additional views in the sidebar, I have trouble aligning them to match the width/insets of the searchable text field or the list sections or the largeTitle. padding(.horizontal) doesn't match.
How can I add padding or insets to match these system elements? I've tried using layoutMarginGuide and readableContentGuide and these have wider layouts that don't match the search bar or table. See the screenshot - how can I align the Picker to the largeTitle or list row inset?

And here is sample code
import SwiftUILayoutGuides

struct SidebarComprehensionTab: View {
    @SceneStorage("comprehensionItemSelection") private var comprehensionSelection: String?

    var body: some View {
        HStack(alignment: .top, spacing: 0) {
            VStack(alignment: .leading, spacing: 0) {
                Picker("", selection: $comprehensionSelection) {
                    Text("Vocabulary").tag(1)
                    Text("Kanji").tag(2)
                    Text("Lookups").tag(3)
                }
                .pickerStyle(.segmented)
//                .fitToReadableContentWidth()
                .padding(.horizontal) // Neither of these approaches work.
            }
        }
        .searchable(...)
    }
}


text:
Q: can't get database to connect during magento installation - using wizard I'm trying to install magento on my live web server , I've checked the server with magento-check.php and thats fine.
I've set up a mysql db with the user name and password the of the mysql server
I've entered this into the host* along with the username and password into the installation wizard but it will not connect. ?
Can anybody help me with this I know it seems so simple ??

A: The problem was that the server i was trying to install magento onto did not support mysql InnoDB - only MyISAM , Magento uses the InnoDB engine. I have now installed several versions of Magento on 1and1 servers.


text:
Q: OpenCV line detection and extraction using ios Hi i am using opencv for the line detection in ios. This is for my final year project. I want to  upload the image of ecg and then extract the line from this for that i have used the opencv and sucessfuly i have extracted the line but now i want to save the line and facing much problem in that can anyone help me or any tutorial ?

A: I wrote something quickly, I think it can help you:
void write_lines_to_file ( string file_name, vector<vector<Point> > lines )
{
  FileStorage fs ( file_name, FileStorage::WRITE );
  fs << "lines" << "[";
  for ( unsigned int i = 0; i < lines.size(); i++ )
    {
      // I've assumed each line is a vector< Point >, in index [0] the head and index [1] the tail.
      fs << "{:" << "x1" << lines[i].at ( 0 ).x << "y1" << lines[i].at ( 0 ).y << "x2" << lines[i].at ( 1 ).x << "y2" << lines[i].at ( 1 ).y << "}";
    }
  fs.release();
}

I didn't test it and I made my own assumptions, so please be cautious when you want to use it.


text:
Q: Cannot reuse (inherit) HMENU/TMENU and reset values like linkWrap or typolink.ATagParams
I created a language selector like that:
lib.language = HMENU
lib.language {
    special = language
    special.value = 0,1,2
    special.normalWhenNoLanguage = 0
    wrap =
    1 = TMENU
    1 {
        noBlur = 1
        NO = 1
        NO {
            linkWrap = |
            doNotLinkIt = 1
            stdWrap.override = deutsch || english || français
            stdWrap {
                typolink {
                    parameter.data = page:uid
                    additionalParams = &L=0 || &L=1 || &L=2
                    ATagParams = class="dropdown-item" hreflang="de-DE" || class="dropdown-item" hreflang="en-GB" || class="dropdown-item" hreflang="fr-FR"
                    addQueryString = 1
                    addQueryString.exclude = L,id,cHash,no_cache
                    addQueryString.method = GET
                    useCacheHash = 1
                    no_cache = 0
                    forceAbsoluteUrl = 1
                }
            }
        }

        ACT < .NO
        ACT.ATagParams = class="dropdown-item active"
    }
}

For mobile I wanted that menu to be inherited, but with a different linkWrap (and classes):
lib.languageMobile < lib.language
lib.languageMobile.1.NO {
    linkWrap =

|

    stdWrap.typolink {
        ATagParams = class="btn btn-sub" hreflang="de-DE" || class="btn btn-sub" hreflang="en-GB" || class="btn btn-sub" hreflang="fr-FR"
        ATagBeforeWrap = 1
        wrap = |
    }
}
lib.languageMobile.1.ACT.ATagParams = class="btn btn-sub active"

But all values specifically reset for lib.languageMobile are not rendered in frontend. The TypoScript Object Browser does show the values as set though.
I didn't find anything about, that resetting values for inherited HMENU/TMENU does not apply, or that there are known issues like that.

I am using latest TYPO3 8.7 LTS: 8.7.4.
Can someone point out, what I am missing or doing wrong? Thanks in advance.

A: Since @BerndWilkeπφ brought me on the right track, I wanted to share what resolved it for me.
Because I have indeed all available language set in the language selector, but not all pages are fully translated to all languages yet. So I stumbled upon the usage of USERDEF1 and USERDEF2.
When I added them to lib.language I changed lib.languageMobile to:
lib.languageMobile < lib.language
lib.languageMobile.1 {
    NO {
        linkWrap =

|

        stdWrap.typolink {
            ATagParams = class="btn btn-sub" hreflang="de-DE" || class="btn btn-sub" hreflang="en-GB" || class="btn btn-sub" hreflang="fr-FR"
            ATagBeforeWrap = 1
            wrap = |
        }
    }
    ACT < .NO
    ACT.ATagParams = class="btn btn-sub active"
    USERDEF1 < .NO
    USERDEF2 < .ACT
}

After that the mobile language selector was rendered as intended.


text:
Q: If $L$ is a normal subgroup of $G$ and if $L=HK$ (where $H$ is normal in $G$ and $K$ is any subgroup), then must $K$ also be normal? I think the answer is yes, but I just want to ask in case I'm missing something...
We know that $aKH=KHa$ for all a in G. But we also know that $aH = Ha$, so $KHa = KaH$.
So $aKH = KaH \implies aK=Ka$.
Thanks in advance

A: This is false. Take G=L=H to be nonabelian of order 6, and K of order 2.
Notice that aKH = aKG = G, and that KaH = KaG = G, so aKH = KaH only tells you G = G, nothing about K or a. You cannot generally cancel subsets.

A: So $aKH=KaH  \ then  K^{-1}a^{-1}Ka\in H$\
It seems this way cannot be Ok. you can use this way :
$K=H^{-1}L$ is normal subgroup ,because $H\  L$ are both normal .


text:
Q: Atmel Cortex-M7(ATSAME70Q21) GPIO I want to develop an industrial board with Cortex-M7 board and i selected Atmel because of Atmel Studio looks very nice for coding. I developed some projects with Arduino. My questions :

*

*ATSAME70Q21 has 114 I/O . Can i use all of these I/O as GPIO?

*If answer of first question is "yes" then all of thee GPIO will be
interrupted IO?

*I want to buy "SAM E70 Xplained Evaluation Kit" to start Atmel Studio
development case. Description of this kit says that kit includes
information about to built custom board. My biggest problem is building
custom board which i can use all power of this MCU. So i should trust to
this evaluation kit or somebody has any advice for building such board?

*I read some informations about GPIO pin speed(operating frequency).
These pins work at same operating frequency as with MCU speed at
some MCUs and slower at some other MCUs. I couldn't see any information
for Atmel cortex-M7 MCUs. Is it very important property? What about this
property at ATSAME70Q21?
Building a custom board for ATSAME70Q21 is the most difficult step for me. I don't know how should i start. So especially i wait a solution for it.
Tthanks in advance.

A: 1) Basically you can use every pin on the SAM as GPIO, except for some special pins like power pins (VCC, GND, ...), dedicated USB pins (HSDM, HSDP), oscillator pins (OSCx, ..), some JTAG pins (TCK, ..) and analog reference pins (AREF, ..). You will have to go through the table in chapter 5.2. Usually the pins labeled PAx,PBx,.. can be used as GPIOs
2) Chapter 32.2, point #4; Yet, they use a combined interrupt line. This means that you will have one interrupt for multiple pins and you need to find out in software which pins was actually triggered by reading the respective register in your interrupt handler
3) The EVK has additional hardware so you will not be able to access each pin directly. Yet, the board itself is pretty good and perfect for a start. By building: Do you mean a new board? You should take a look at the datasheet, chapter 58 - Schematic checklist.
4) Chapter 56.13.1.3 ff. - I/O characteristics


text:
Q: Structuring Session Data in MongoDB This might be a bad title, but I was having trouble thinking of a good way to phrase my problem. Basically, I have a NodeJS application that has session management. Each session interacts with a set of data independent from the other sessions. I am having trouble coming up with a way to structure this in MongoDB. Things I have thought of:
Currently I'm storing a list of JSON "pages" that each have an ID corresponding to the session using it. I am almost positive this will not scale well though, because these "pages" will be read and updated frequently, so if I'm connected to Session1000, I'm going to have to search through 1000 items looking for the correct ID every time I update something from that session. If 1000 people are doing that roughly once a second, well...
Ideally I would like to store each session in a different collection, but the sessions need to be created and referenced dynamically, and I can't find a way in MongoDB to access a collection without hard-coding the name.
Hopefully this accurately describes my problem. Does anyone have any ideas to help me structure the db so that accessing/updating will give fast performance/scalability?


text:
Q: Performing an efficient query on a many to many relationship in EF Core In Entity Framework Core one can setup a many-to-many relationship via a join table.
I don't know how to query a relationship like this in an efficient way. Given the reference relationships below, I have, a Post entity and the PostTags collection is null. I want to load all the Tags associated with the Post and the best I have so far is something that looks like this:
void GetAllTags(Post somePost)
{
    await dbContext.Entry(somePost)
        .Collection(p => p.PostTags)
        .LoadAsync();
    foreach(var postTag in somePost.PostTags)
    {
        await dbContext.Entry(postTag)
            .Reference(p => p.Tag)
            .LoadAsync();
    }
}

I really would prefer to return an ICollection<Tag> via a single query to the DB.

This is the reference implementation from Relationships - EF Core | Microsoft Docs
class MyContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PostTag>()
            .HasKey(t => new { t.PostId, t.TagId });

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Tag)
            .WithMany(t => t.PostTags)
            .HasForeignKey(pt => pt.TagId);
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}

A: If all you need is to get a list of the tags associated with a post, you can use simple projection query. Just make sure to start with a DbSet<> (i.e. EF Core IQueryable<>) rather than materialized object / collection, e.g.
ICollection<Tag> GetAllTags(Post somePost)
{
    return await dbContext.Set<PostTag>()
        .Where(pt => pt.PostId == somePost.PostId)
        .Select(pt => pt.Tag)
        .ToListAsync();
}

If you indeed want to load them into the passed Post entity instance, you can use a combination of explicit and eager loading via Query method:
void LoadAllTags(Post somePost)
{
    await dbContext.Entry(somePost)
        .Collection(p => p.PostTags)
        .Query()
        .Include(pt => pt.Tag)
        .LoadAsync();
}


text:
Q: Round to nearest 5 with numpy df
        A
0  503.36
1  509.80
2  612.31
3  614.29

I want to round to nearest 5 in a new B column, using numpy if possible.
Output should be:
        A        B
0  503.36   505.00
1  509.80   510.00
2  612.31   610.00
3  614.29   615.00

A: Since you mention numpy
np.around(df.A.values/5, decimals=0)*5
Out[31]: array([505., 510., 610., 615.])

A: You can use:
df['B'] = df.div(5).round(0) * 5

Or as @piRSquared states:
df['B'] = df['A'].mul(2).round(-1).div(2)

Output:
        A      B
0  503.36  505.0
1  509.80  510.0
2  612.31  610.0
3  614.29  615.0

A: df.assign(B=df.mul(2).round(-1).div(2))

        A      B
0  503.36  505.0
1  509.80  510.0
2  612.31  610.0
3  614.29  615.0


text:
Q: How to use string value as a variable name in Python? Suppose I have lists as follows:
candy = ['a','b','c']
fruit = ['d','e','f']
snack = ['g','h','i']

and a string
name = 'fruit'

I want to use string name for accessing list and it's content. In this case it should be fruit. I will use name for iterating list. As:
for x in name:
    print x

A: Use a dictionary!
my_dictionary = { #Use {} to enclose your dictionary! dictionaries are key,value pairs. so for this dict 'fruit' is a key and ['d', 'e', 'f'] are values associated with the key 'fruit'
                   'fruit' : ['d','e','f'], #indentation within a dict doesn't matter as long as each item is separated by a ,
             'candy' : ['a','b','c']           ,
                      'snack' : ['g','h','i']
    }

print my_dictionary['fruit'] # how to access a dictionary.
for key in my_dictionary:
    print key #how to iterate through a dictionary, each iteration will give you the next key
    print my_dictionary[key] #you can access the value of each key like this, it is however suggested to do the following!

for key, value in my_dictionary.iteritems():
    print key, value #where key is the key and value is the value associated with key

print my_dictionary.keys() #list of keys for a dict
print my_dictionary.values() #list of values for a dict

dictionaries by default are not ordered, and this can cause problems down the line, however there are ways around this using multidimensional arrays or orderedDicts but we will save this for a later time!
I hope this helps!

A: You can use globals() like so:
for e in globals()[name]:
    print(e)

Output:
d
e
f

And if your variables happen to be in some local scope you can use locals()
OR you can create your dictionary and access that:
d = {'candy': candy, 'fruit': fruit, 'snack': snack}
name = 'fruit'

for e in d[name]:
    print(e)

A: I don't understand what exactly you're trying to achieve by doing this but this can be done using eval. I don't recommend using eval though. It'd be better if you tell us what you're trying to achieve finally.
>>> candy = ['a','b','c']
>>> fruit = ['d','e','f']
>>> snack = ['g','h','i']
>>> name = 'fruit'
>>> eval(name)
['d', 'e', 'f']

EDIT
Look at the other answer by Sнаđошƒаӽ. It'll be better way to go. eval has security risk and I do not recommend its usage.


text:
Q: What property of the hypergeometric function is employed to relate it to Bessel functions in this limit? In this Physics paper the authors claim a relation between the hypergeometric function $_2 F_1$ and the spherical Bessel functions in one particular limit. More specifically, in equation (2.3) they define functions
$$\phi_{n\ell J}(t,\hat{x},\rho)=\dfrac{1}{N^\phi_{\Delta n \ell}}e^{iE_{n,\ell}t}Y_{\ell J}(\hat{x})\bigg[\sin^\ell \rho \cos^\Delta \rho {_2F_1}\left(-n,\Delta+\ell+n,\ell+\frac{d}{2},\sin^2\rho\right)\bigg]\tag{2.3}$$
where $E_{n,\ell}=\Delta+2n+\ell$ and $Y_{\ell J}(\hat{x})$ are the spherical harmonics in $S^{d-1}$. The $N^{\phi}_{\Delta n\ell}$ are normalization constants: $$N^\phi_{\Delta n\ell}=(-1)^n\sqrt{\dfrac{n!\Gamma^2(\ell+\frac{d}{2})\Gamma(\Delta+n-\frac{d-2}{2})}{\Gamma(n+\ell+\frac{d}{2})\Gamma(\Delta+n+\ell)}}.$$
In that case they claim that if $\rho \ll 1$ the following limit holds
$$\dfrac{1}{N^\phi_{\Delta n\ell}}\sin^\ell \rho \cos^\Delta \rho {_2F_1}\left(-n,\Delta+\ell+n,\ell+\frac{d}{2},\sin^2\rho\right)\to \dfrac{1}{\rho^{(d-2)/2}}J_{\ell+(d-2)/2}\big((E_{n,\ell}^2-\Delta^2)^{1/2}\rho\big)\tag{2.5}.$$
My question here is: where does this limit connecting the hypergeometric and the Bessel functions come from? What property of the hypergeometric function is being employed?  This seems to be non-trivial since it involves these rather complicated constants $N^\phi_{\Delta n\ell}$.


text:
Q: In an isosceles triangle with base $AB$ and $\angle CAB=80^\circ$ taken $D$ on $CA$, $E$ on $CB$ such that ... For the well-known problem

In an isosceles triangle with base $AB$ and $\angle CAB=80^\circ$ taken $D$ on the segment $CA$, $E$ on the segment $CB$ such that $\angle BAE=60^\circ$, $\angle ABD=50^\circ$, find $\angle EDB$.

The question is what is a canonical or otherwise simple without being too artificial way of solving it? Or what was the solution you heard/seen/found first?

Btw, simple angle chasing does not help. The first way I can think of is considering difference of heights $DH_d$ and $EH_e$ of triangles $ABD$ and $ABE$ respectively along with $H_dH_e$ which together give the inclination angle of $DE$ relative to $AB$ and thus the desired angle. Needed for that lengths of $AD,\,BD,\,AE,\,BE$ can be expressed in terms of $AB$ and known angles by the sine rule. Almost like putting the thing into Cartesian coordinates.
Another approach could be vectors, then taking $A$ or $B$ as the origin makes things more simple, than taking $CA,\,CB$ as basis vectors, IMHO.
By "too artificial" I mean things like this:

constructing a regular $18$-gon with side $AB$, proving lines $AE,\,BD,\,DE$ contain some diagonals and then finding the angle very easy by angle chasing.
Update:

The solutions are not as trivial as one would expect from the statement. It's called Langley's problem of adventitious angles first posed in The Mathematical Gazette in 1922.
Check out An Intriguing Geometry Problem by Tom Rike.

(from this answer).

A: The following solution can be found in Coxeter-Greitzer's book $\textit{Geometry Revisited}$ [Problem $4$ in the last set of exercises in Chapter $1$], one of my favourite books, also I will type out the solution just because it is so beautiful.

Let $EF$, parallel to $AB$, meet $AC$ at $F$. Let $BF$ meet $AE$ at $G$.

$\Delta ABG$ is equilateral $\implies AG = AB$.

$\Delta BAD$ is isosceles $\implies AD = AB$. Hence $\Delta AGD$ is isosceles,
$\angle AGD = 80^{\circ}, \ \angle FGD = 40^{\circ}$.
Since $\angle DFG = 40^{\circ}$, $\Delta FDG$ is isosceles and $FD=DG$.

Also,
$EF = EG \implies \Delta GED \stackrel{\sim}{=} \Delta FED$, $DE$ bisects $\angle FEG$, and $\angle DEA = 30^{\circ} \implies \angle EDB =80^{\circ}$.

A solution I did on my own did not require any constructions, observed a pair or two of similar triangles and used only the sine rule a couple of times along with one useful formula
$$\sin(\theta)\sin\left(\theta-\dfrac{\pi}3\right)\sin\left(\theta+\dfrac{\pi}3\right)=\dfrac{\sin{(3\theta)}}4$$

A: I think this is a very simple solution:

A:
For an arbitrary isosceles triangle with given angles $\alpha,\> \beta$ and $\gamma$ shown in the graph, the trigonometric solution for the unknown angle $x$ is
$$ \cot x = \frac{ \cos\alpha \cos(\gamma+\alpha)}
{\sin\gamma\cos(\beta+\alpha)\cos(\beta-\alpha)}-\tan(\beta-\alpha)
$$
(which is derived from the sine rule applied to three triangles.) Then, substitute $\alpha=10$, $\beta= 60$ and $\gamma=50$ into the expression to get
\begin{align}
\cot x & = \frac1{\cos 70} -\tan 50 =\frac1{\sin20}-\frac{\cos40}{\sin40}\\
&= \frac{2\cos20-\cos40 }{ \sin40}= \frac{\cos20+\cos80}{ \sin40}\\
&= \frac{2\cos30\cos50}{\sin40}=\sqrt3
\end{align}
Thus, $x=30$ and in turn $\angle EDB = 80$.


text:
Q: some issues about Angularjs Directive first I will show you my html:

my purpose of this "directive" is making pager.
 and this is the js file blew:
var paging = angular.module('paging',[]);

paging.controller('pageCtrl',function($scope,$timeout){

$scope.currentPageIndex = 0;
$scope.model = [
  { name: 'www'},
  { name: 'www'},
  { name: 'www'},
  { name: 'www'},
  { name: 'www'}
];

$scope.getPageNumber = function(){
  var len = 10,ret=[];
  for(i = 0;i < 10; i++) {
    ret.push(i);
  }
  return ret;
};

$scope.getPageData = function(index) {
  $scope.currentPageIndex = index;
  alert('trigger!');
};
});

paging.directive('pagerControl',function(){

 return {
  restict: 'A',
  replace: false,
  transclude: true,
template: '

{{$index + 1}}

',
scope: {

},

link: function(scope,elem,attr) {

}

};
});
expect to "when you click the page item,the color will change ",but nothing happends..
this is the jsbin url:
http://jsbin.com/vijax/2/edit

A: I fixed your jsbin:
http://jsbin.com/kaziqice/2/edit
There are 2 issues with your code:
1) ng-repeat creates child scopes.
You have to replace ng-click="$parent.getPageData($index)" with ng-click="$parent.$parent.getPageData($index)" to access the correct scope
2) Replace currentIndex="currentPageIndex" with current-index="currentPageIndex". This is the naming convention of angular Angular JS naming conventions ($, camelCase and PascalCase)
For the first problem, you should not bind directly to your parent scope as it will create a tight coupling in code. You should bind to your scope's own properties instead.


text:
Q: Running command in a docker I have an ELK stack docker cloned from here:
https://github.com/deviantony/docker-elk
The docker contains the following docker-compose.yml file:
elasticsearch:
  image: elasticsearch:latest
  command: elasticsearch -Des.network.host=0.0.0.0
  ports:
    - "9200:9200"
    - "9300:9300"
logstash:
  image: logstash:latest
  command: logstash -f /etc/logstash/conf.d/logstash.conf
  volumes:
    - ./logstash/config:/etc/logstash/conf.d
  ports:
    - "5000:5000"
  links:
    - elasticsearch
kibana:
  build: kibana/
  volumes:
    - ./kibana/config/:/opt/kibana/config/
  ports:
    - "5601:5601"
  links:
    - elasticsearch

Now I can start the docker daemon using docker-compose up -d command - but now I want to import something using logstash, so I need to use logstash command - how can I do this? Being in the docker location I get an error that the command cannot be found.

A: I don't know if this is still the case, but on their Dockerfile, someone posted the following - https://hub.docker.com/_/logstash/
''It looks like this is impossible to use from docker-compose? As it doesn't support passing arguments. Is there another way I can tell logstash where the config file is, perhaps an environment variable?''


text:
Q: I am stuck with some details when graphing this function
Let $f(x) = \frac{x^3 + 1}{x}. $ Plot the function using derivatives criteria.

First of all, $f$ is indeterminate at $x=0.$ So I would have to deal with 2 intervals, separately: $(- \infty, 0)$, and $(0, \infty)$.
I would also have to consider:
$\lim_{\to \infty} f(x) = \lim_{\to \infty} \frac{1}{x} + x^2 = 0 + \infty = \infty$
$\lim_{\to -\infty} f(x) = \lim_{\to -\infty} \frac{1}{x} + x^2 = 0 + (-\infty)^2 = \infty$
If $x\neq 0,   \frac{x^3 + 1}{x} = 0 \implies x^3 + 1 = 0,$ so the only root in $\mathbb{R}$ is $x=-1.$
If $x>0, \lim_{x \to 0}  \frac{x^3 + 1}{x} = ( \lim_{x \to 0} \frac{1}{x} ) ( \lim_{x \to 0} x^3 + 1) = (\infty)(1) = \infty $
And if  $x <0, \lim_{x \to 0}  \frac{x^3 + 1}{x} = ( \lim_{x \to 0} \frac{1}{x} ) ( \lim_{x \to 0} x^3 + 1) = (-\infty)(1) = -\infty $
Then $f '(x) = \frac{2x^3 -1}{x^2}$
It should happen that, at $(\infty, 0)$, $f$ is decreasing. And $x<0 \implies 2x^3 -1 < 0 \implies \frac{2x^3 -1}{x^2} < 0.$ So $f'(x) < 0 \implies f$ is decreasing at $(-\infty, 0)$
and it should also happen that, at $(0, \infty)$, the function is increasing.
But, if $x<0$, it doesn't neccessarily happen that $2x^3 -1 > 0,$ So I am stuck here. However if i could assume that $2x^3 -1 > 0, $ then $f '(x) = \frac{2x^3 -1}{x^2} > 0,$ so $f$ would be increasing.
To find critical points, $f '(x) = \frac{2x^3 -1}{x^2} = 0 \implies_{x \neq 0} x =  \frac{1}{\sqrt[3]{2}},$ or $x = -\frac{1}{\sqrt[3]{2}} ,$ and $f''(x) = \frac{2x^3+2}{x^3},$ so $f''(\frac{1}{\sqrt[3]{2}}) = 4(\frac{1}{2} + 1) = 6 >0,$ that would mean that $f$ has a local minimum. So my last question is why doesn't $x = -\frac{1}{\sqrt[3]{2}}
$, the other critical point appears in the graph?

A: A qualitative approach.
The function can be written as $x^2+\dfrac1x$, and is the sum of a parabola and an equilateral hyperbola.
The hyperbola has a vertical asymptote at $x=0$ and the horizontal asymptote $y=0$. Hence for small $|x|$ it is dominant, and for large $|x|$, it is neglectible and the function gets closer and closer to the parabola.
In the negatives, both functions are decreasing and the sum is decreasing (to $-\infty$).
In the positives we sum increasing and decreasing and we cannot conclude about the variation. The first derivative is $2x-\dfrac1{x^2}$, which has a single positive root, hence the function has a single minimum.
This is confirmed by a plot:


text:
Q: Mobile site not resizing correctly but fine on pc I'm building a site for a client http://www.patsybeautyclinic.co.nz (I'm a novice at html so go easy). It's fully responsive on pc but when loading it on android and ios it isn't as successful, it's almost as the media query isn't loading properly? (I have "meta name="viewport" content="width=device-width, initial-scale=1.0" in my head tags)
I hate how I can't provide more specifics but I'm lost and have been stuck on this for awhile. Hopefully I have missed something simple so I don't waste anyones time...thanks in advance.
Here is what my s3 sees on the home page. (sorry it's so big)


text:
Q: Adding visual force page to a custom object based on criteria There is a custom object called Competitor. For this object there is a field called "Primary Competitor (Data type:Check Box)".
Requirement:if primary competitor=checked-->then before saving it has to check if there are any primary competitors has present.If so it has to display an error message in a popup with "yes" "no" buttons on it.As shown in image

If yes then it has to add new competitor else remain same.
Workaround: for this i created a vf page and added it to pagelayout but it's not firing .
<apex:page standardController="Competitor__c">

<script type="text/javascript">
if(Competitor__c.Primary_Competitor__c=="True")

document.body.style.cursor="auto";
var box=new SimpleDialog("Test", true);
box.setTitle("Is Primary Competitor");
box.createDialog();
    box.setContentInnerHTML("<b>There is a primary Competitor existing, setting this Competitor as primary will remove the primary check on the other Competitor. Please confirm if you want to go ahead?</b><input type=\"button\" value=\"Yes\"  onclick=\"javascript:box.hide();\" /> <input type=\"button\" value=\"No\"  onclick=\"No();\" />");
box.show();
function No()
{
Competitor__c  c =new Competitor__c();
c.Primary_Competitor__c=False;
}
</script>

</apex:page>

Need help.
Thank you in advance

A: Your code will fire as soon as the page is loaded and only generate the alert if the initial value of primary competitor is true.
When you say have added it to the page layout, is that as an embedded Visualforce page in the record view?  The Visualforce will only be present for the view page, not for the edit page.
There's no supported way to achieve what you are attempting using standard pages - you either need to go completely Visualforce or use some JavaScript in a sidebar HTML component to attach your code to the save button - this is not supported by Salesforce though and could break at any time.

A: One error in your code is
"if(Competitor__c.Primary_Competitor__c=="True")"
This line should be
"if({!Primary_Competitor__c=="True"})"
I feel you need to use JavaScript to identify if checkbox is checked. It is not Visualforce but Javascript that you need to think about.


text:
Q: PrimeNg accordion giving ExpressionChangedAfterItHasBeenCheckedError Any help or hint would be greatly appreciated it!!
I am getting ExpressionChangedAfterItHasBeenCheckedErrror: Expression has changed after it was checked. Previous value: 'ui-state-active: undefined'. Current value: 'ui-state-active: true'.
I am using Angular 7.
I am using CLI 7.3.6
I am using primeng 7.1.0
I am using primeicons 1.0.0
I look online but I didn't find any solutions to my problem.

              {{sym.symptomDescription}}

              {{scores[i]}}

              Mild

              Moderate

              Severe

                    What did you do to manage?

                    <input  type="text" [(ngModel)]="actions[i]"  name="actions-{{i}}" style="width:100%"/>

    <button type="button" class="btnSecondary" (click)="onReturnCalendar()">Cancel</button>
    <button type="submit" class="btn btn-primary {{status == 'Active'? 'visible': 'invisible'}}">Submit</button>

I don't expect to get the error when using the accordion.


text:
Q: How to get a list of fields in a unique constraint I have a table with a unique constraint on one or more fields. Given the constraint name, I want to query the system views to get the list of fields that are part of this constraint.
SQL Server 2005.
Thanks.

A: Look at information_schema.constraint_column_usage
select column_name from information_schema.constraint_column_usage
where constraint_name = 'your constraint'


text:
Q: How to stop Visual Studio from formatting whitespace on 'save'? This question (How to disable all whitespace autoformatting in Visual Studio 2015?) shows different formatting options when writing in a language - for example C#. But it doesn't cover the problem of everytime I save a file all whitespace is stripped.
This is INCREDIBLY irritating since I can't go into a file an edit just a line of it and commit. I get merge conflicts everytime there is an extra space anywhere in the file.
I don't want VS 2015 to change white space when I save a file. I do want VS to format my code for me...

A: The solution is to upgrade to 2017. The default configuration does what I want. I was not able to get this to work with 2015.
Also I should mention that I was previously running Windows 10 on a mac via Bootcamp and now I'm not. It really shouldn't have mattered but who knows...


text:
Q: Pytorch : TypeError when I call my data_transformation function inside where I define my train_dataset object When I try to make an object from my get_data function :
   train = get_data(root ="My_train_path",
                     transform = data_transforms[TRAIN] )

it returns an TypeError: 'function' object is not subscriptable.

data_dir = 'my_dataset_dir'

TEST  = 'test'
TRAIN = 'train'
VAL   = 'val'
def data_transforms(phase):
    if phase == TRAIN:
        transform = A.Compose([
            A.CLAHE(clip_limit=4.0, p=0.7),
            A.CoarseDropout(max_height=8, max_width=8, max_holes=8, p=0.5),
            A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
            ToTensorV2(),

        ])

    if phase == VAL:
        transform = A.Compose([
            A.Resize(height=256,width=256),
            A.CenterCrop(height=224,width=224),
            A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
            ToTensorV2(),
        ])

    if phase == TEST:
        transform = A.Compose([
            A.Resize(height=256,width=256),
            A.CenterCrop(height=224,width=224),
            A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
            ToTensorV2(),
        ])

    return transform

def get_data(root,transform):

  image_dataset = CustomImageFolder(root=".",
                                    transform = transform,
                                                         )
  return image_dataset

def make_loader(dataset, batch_size,shuffle,num_workers):
    loader = torch.utils.data.DataLoader(dataset=dataset,
                                         batch_size=batch_size,
                                         shuffle=shuffle,
                                         pin_memory=True, num_workers=num_workers)
    return loader

A: The problem is exactly as the error message says it: data_transforms is a function you have defined, and you want to call it with the training phase as the argument. However, you are erroneously subscripting the function, with your use of square brackets ([]). To fix this, replace the square brackets with parentheses (()), as is done for a function call.
That is,
train = get_data(root ="My_train_path",
                 transform = data_transforms(TRAIN) )


text:
Q: How to recursively check each KPI in JSON I wants to put logic on each KPI value. So, where ever I found "KPI" I will put that in strKey like in below I wants to put "Directs" in first iteration and in second iteration "Process". Post that implement some logic.
{
"kpis": [
  {
     "KPI":"Directs",
     "definition":{
        "type":{
           "exec":"aggregate"
                },
        "result":{
           "columns":[
              "Month",
              "Last Touch Marketing Channel"
           ]
        }
     }
  },
  {
     "KPI":"Process",
     "definition":{
        "type":{
           "exec":"aggregate"
                },
        "result":{
           "columns":[
              "Month",
              "Last Touch Marketing Channel"
           ]
        }
     }
  }
 ]
}

javacode
JSONTokener objJSONTokener = new JSONTokener(objFileReader);
JSONObject objJSONRoot = (JSONObject) objJSONTokener.nextValue();
JSONObject objElement;
JSONObject thisDefinition;
String strKey;
java.util.Iterator<String> objDictionary = objJSONRoot.keys();
while (objDictionary.hasNext()) {
          strKey = objDictionary.next();
          //to do..
       }


text:
Q: Making a faster executing sort function I have a data set thats over 1000 items and the issue Im having is the amount of time it takes for the table to be sorted. Ive built a few tables recently and the sort function Ive been using has always been sufficient until now I am assuming its the size data thats causing it to return so slow? I dont have the option of doing this on the backend. Im not sure how to update the loading state in my function properly so the time between when the sort is clicked and the and sorted data is returned is at least showing loading.
this is my sort function and Im wondering if there is any way to optimize it:
const sortTable = (field, order) => {
    let sorted = formItems?.sort((a, b) => {
        setLoading(true)
        if (order === "asc") {
            return a[field] > b[field] ? 1 : -1;
        } else {
            return a[field] < b[field] ? 1 : -1;
        }
    })
    setLoading(false)
    setFormItems(sorted)
}

A: try this:
const sortTable = (field, order) => {
  // run just once
  setLoading(true);

  // avoid batching (react < 18)
  setTimeout(() => {
    // change value based on previous state
    setFormItems((prev) => {
      if (!prev) return prev; // avoid optional chaining (subjective)
      const formItemsCopy = [...prev]; // stay immutable

      // simplify
      const x = order === 'asc' ? 1 : -1;
      formItemsCopy.sort((a, b) => {
        return (a[field] - b[field]) * x;
      });

      return formItemsCopy;
    });

    setLoading(false);
  }, 0);
};

A: Move your condition and setLoading funtion outside of sort funtion
const sortTable = (field, order) => {
   setLoading(true)
   Var sorted = []
   if (order === "asc") {
     sorted = formItems?.sort((a, b) => a[field] > b[field] ? 1 : -1)
    } else {
      sorted = formItems?.sort((a, b) =>  a[field] < b[field] ? 1 : -1)
    }
    setLoading(false)
    setFormItems(sorted)
}


text:
Q: Can't access any Stack Exchange site For about a week now, I have been unable to access any Stack Exchange sites from my home network. Whenever I try, the browser tries to load for a while, then says it cannot connect. The only way I have been able to access the sites is via a proxy.
All packets are lost when I ping the server:
>ping stackoverflow.com

Pinging stackoverflow.com [198.252.206.16] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 198.252.206.16:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

I believe this is perhaps something to do with the recent change of the data centre. I first thought that this was a DNS issue, but it has been a week now (and I assume you have proxies in your old data centre). The only alternative I can think of is that my IP address is, for some reason, blacklisted.
Is this a known issue? Is there a solution?

A: We are contacting the virgin media NOC, hopefully we will be able to help expedite resolution of this for you guys.
As we get more info we will update this answer.


text:
Q: Python eval integer in string, and return integer instead of ascii char I'm getting some data from a file, which looks like this:
[200, "Hello", "World"]

Now, since this is a file, this array is inside a string; I turn it into an array using eval().
This works fine BUT the integer at the start is converted to an ascii char, instead of an integer as I want it to (the euro sign).
How can I fix this?

A: You could use the simplejson module. E.g.
>>> import simplejson
>>> a = simplejson.loads('[200, "Hello", "World"]')
>>> print a
[200, 'Hello', 'World']

This way "malicious" data such as os.execvp() would not be evaluated but an JSONDecodeErrorwould be thrown.

A: You can use literal_eval. Really depends on the source - is the source speaking Python or JSON - there is a lot of overlap where they have identical representations
>>> from ast import literal_eval
>>> literal_eval('[200, "Hello", "World"]')
[200, 'Hello', 'World']


text:
Q: Convert DD-MMM-YY to YYYY/MM/DD in Pandas DoB column in my dataset has date in the format below:
0       12-Jan-79
1       13-Jan-70
2       11-Mar-84
3       11-Mar-84
4       01-May-86
          ...
1080    15-Mar-81
1081    07-Jul-96
1082    11-Apr-90
1083    22-Oct-64
1084    12-Jul-95

I need to convert the same into standard date format YYYY/MM/DD.
I tried df['DateOfBirth'] = pd.to_datetime(df['DateOfBirth']). This is working fine for most of the cases.
But in some instances like 22-Oct-64, I can observe the data is converted into the future dates for example 2064-10-22.
I want to try something like DoB.str[:-2]+'19'+DoB.str[-2:] on entire column.
How to fix the problem?

A: You should specify the format:
df['DateOfBirth'] = pd.to_datetime(df['DateOfBirth'], '%d/%m/%y')

A: You can do this. Take my sample df for example:
In [922]: df
Out[922]:
         DOB
0  22/Oct/64

In [925]: df['DOB'] = pd.to_datetime(df['DOB'])

In [927]: from datetime import timedelta, date

In [928]: future = df['DOB'] > date(year=2050,month=1,day=1)
In [930]: df.loc[future, 'DOB'] -= timedelta(days=365.25*100)

In [931]: df
Out[931]:
         DOB
0 1964-10-22

This will take care of the issues with future dates also.
From the docs

Year 2000 (Y2K) issues: Python depends on the platform's C library, which generally doesn't have year 2000 issues, since all dates and times are represented internally as seconds since the epoch. Function strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.

A: The objective can be achieved by cut the two characters,add 19 and then paste the last two characters.
df['DateOfBirth']

Out[14]:
0       12-Jan-79
1       13-Jan-70
2       11-Mar-84
3       11-Mar-84
4       01-May-86
          ...
1080    15-Mar-81
1081    07-Jul-96
1082    11-Apr-90
1083    22-Oct-64
1084    12-Jul-95
Name: DateOfBirth, Length: 1085, dtype: object

Code: df['DateOfBirth'] = df['DateOfBirth'].str[:-2]+'19'+df['DateOfBirth'].str[-2:]
Output:
Out[16]:
0       12-Jan-1979
1       13-Jan-1970
2       11-Mar-1984
3       11-Mar-1984
4       01-May-1986
           ...
1080    15-Mar-1981
1081    07-Jul-1996
1082    11-Apr-1990
1083    22-Oct-1964
1084    12-Jul-1995
Name: DateOfBirth, Length: 1085, dtype: object

Simply use df['DateOfBirth'] = pd.to_datetime(df['DateOfBirth']) to convert the columnn to datetime format.


text:
Q: How to add typescript-eslint rules to eslint I'm using NX to build out Angular apps and I've configured it to use ESLint. We are able to configure built in rules like no-console but @typescript-eslint/no-inferrable-types is not accepting our overrides. We even tried moving the rule into variables entries of the overrides section, but nothing worked.
Where do we specify the typescript-eslint rules?

Our root level .eslintrc.json:
{
  "root": true,
  "ignorePatterns": ["**/*"],
  "plugins": ["@nrwl/nx"],
  "overrides": [
    {
      "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
      "rules": {
        "@nrwl/nx/enforce-module-boundaries": [
          "error",
          {
            "enforceBuildableLibDependency": true,
            "allow": [],
            "depConstraints": [
              { "sourceTag": "*", "onlyDependOnLibsWithTags": ["*"] }
            ]
          }
        ]
      }
    },
    {
      "files": ["*.ts", "*.tsx"],
      "extends": ["plugin:@nrwl/nx/typescript"],
      "parserOptions": { "project": "./tsconfig.*?.json" },
      "rules": {}
    },
    {
      "files": ["*.js", "*.jsx"],
      "extends": ["plugin:@nrwl/nx/javascript"],
      "rules": {}
    }
  ],
  "rules": {
    "no-console":"warn",
    "@typescript-eslint/no-inferrable-types": "off"
  }
}

A: Based on my understanding of how NX linting works, I think you can add the rule to the overrides section.
In the JSON below you can see the no-console is added to the "rules" of the overrides array element that has file matches for *.ts and *.tsx.
{
  "root": true,
  "ignorePatterns": ["**/*"],
  "plugins": ["@nrwl/nx"],
  "overrides": [
    {
      "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
      "rules": {
        "@nrwl/nx/enforce-module-boundaries": [
          "error",
          {
            "enforceBuildableLibDependency": true,
            "allow": [],
            "depConstraints": [
              { "sourceTag": "*", "onlyDependOnLibsWithTags": ["*"] }
            ]
          }
        ]
      }
    },
    {
      "files": ["*.ts", "*.tsx"],
      "extends": ["plugin:@nrwl/nx/typescript"],
      "parserOptions": { "project": "./tsconfig.*?.json" },
      "rules": {
        "no-console":"warn"
      }
    },
    {
      "files": ["*.js", "*.jsx"],
      "extends": ["plugin:@nrwl/nx/javascript"],
      "rules": {}
    }
  ],
  "rules": {
    "@typescript-eslint/no-inferrable-types": "off"
  }
}

It matters which overrides array element you put the rule in. I encountered a similar issue, and you can see a full explanation of different approaches I tried in the answer on https://stackoverflow.com/a/71230627/990642.
It is worth noting that it seems people have mixed luck overriding rules already specified in a plugins or extends.

A: You are missing the plugin in your plugs reference array.So only "@nrwl/nx" rules , and other rules with no namespace will apply .
Try this :
"plugins": [
"@nrwl/nx",
"@typescript-eslint"].
Oh, and you could as well add this inside the "overrides" section if you just want it to be applied only to some kind of file(e.g. .ts or .tsx files), or/and change the processing parser


text:
Q: PhoneGap FileTransfer to Java Servlet I am using PhoneGap 1.5 for an iOS app and I need to upload photos to a Java Servlet via the FileTransfer object. Has anyone done this before? The only examples I've seen utilize PHP and it's not clear to me what's going on when my servlet is invoked. Will post code shortly.

A: If the PhoneGap FileTransfer sends a HTTP multipart/form-data request conform the RFC2388 spec, then you could just use the standard request.getPart() method or, when you're still on Servlet version 2.5 or older, the Apache Commons FileUpload for this as outlined in detail in this answer: How to upload files to server using JSP/Servlet?


text:
Q: Notification couldn't disappear after click, and Notification setAutoCancel(true) doesn't work Notification couldn't disappear after click, and Notification setAutoCancel(true) doesn't work. The following is my code:
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("New Message")
                                .setDefaults(Notification.DEFAULT_ALL)
                                .setContentText("New Question")
                                .setAutoCancel(true);
                        notifyManager.notify(1, builder.build());

A: Try setContentIntent():
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(), 0);
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContentTitle("New Message")
                                    .setDefaults(Notification.DEFAULT_ALL)
                                    .setContentText("New Question")
                                    .setContentIntent(pendingIntent)
                                    .setAutoCancel(true);
                            notifyManager.notify(1, builder.build());


text:
Q: MongoDB error while hosting web app on Cyclic.sh? When I hosted my web-app on cyclic.sh "npm run start" script is returning an error in deployment logs.
App is working fine when i am running it on my localhost.
2022-12-09 23:24:41.993: MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"
    at new ConnectionString (/var/task/node_modules/mongodb-connection-string-url/lib/index.js:86:19)
    at parseOptions (/var/task/node_modules/mongodb/lib/connection_string.js:200:17)
    at new MongoClient (/var/task/node_modules/mongodb/lib/mongo_client.js:45:63)
    at /var/task/node_modules/mongoose/lib/connection.js:801:16
    at new Promise (<anonymous>)
    at Connection.openUri (/var/task/node_modules/mongoose/lib/connection.js:798:19)
    at /var/task/node_modules/mongoose/lib/index.js:412:10
    at /var/task/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/var/task/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
2022-12-09 23:24:42.011:

ERROR: Failed to run "npm run start". Start script defined in package.json:

            "scripts": {
                "start":  "node server.js"
                 ...

Exited with code: 1

Here is code:
file: db.js
const mongoose = require('mongoose');
const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI,{ useNewUrlParser: true, useUnifiedTopology: true });
    console.log(`MongoDB Connected`);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
}
module.exports= connectDB;

file: server.js
const PORT = process.env.PORT ||4000;
connectDB().then(() => {
  app.listen(PORT, () => {
      console.log("listening for requests");
  })
})

I tried including useNewUrlParser but it didn't work.

A: Did you set the environment variables in the app dashboard? If you did, be sure to remove the quotes if you have them


text:
Q: Is there a way of processing list of number integers entered via terminal without saving them into list? I am trying to write a similar code in Python, but I am new to it.
int counts[] = { 0, 0, 0, 0, 0 };
for (int i = 0; i < groups; i++) {
    int groups_size;
    scanf(" %d", &groups_size);

    counts[groups_size] += 1;
}

Please note that it does not all the save the numbers into memory.
I tried to do this in Python as:
for group in range(groups):
    num = int(input().strip())
    counts[num] += 1

This does not work. When I enter 1 2 3 4 5 into terminal, I get ValueError: invalid literal for int() with base 10: '1 2 3 4 5'.
Is there a way of doing this in Python the same as I did in C?

A: In python, it will not automatically take one number and then loop for the other. You input() command will read the whole line at once. So, what you can do is read the whole line in a string and then split it into a list as follows -
str = input()
num = list(map(int,str.split()))

Now you have all the input given by user stored in the num variable. You can just iterate over it and complete your process as follows -
counts = [0]*5       #assuming you want it to be of size 5 as in your question
for inp in num :
    counts[inp] = counts[inp] + 1

Hope this helps!


text:
Q: I cant update two window at the same time - countdown I am writing again because of a problem that I cannot solve, I have a main window which has a timer in a label, at the same time it starts a toplevel with another timer in other label, my idea is that the 2 timers start when you click the button on the main window, but I can't figure it out, it just starts the one in the main window.
    self.is_running=False

    self.tablero_principal = window
        self.tablero_principal.title('Tablero')

    #SECOND WINDOW TOPLEVEL
        self.control_wind = customtkinter.CTkToplevel()
        self.control_wind.title('Posesion')

    def countdown(self,segundos,posesion):

            if self.is_running:
                segundos_final=int(segundos)
                minutos_final=int(self.text_minutos.get())
                posesion_final=int(posesion)

                self.text_minutos.set(f"{minutos_final:02d}")
                self.text_segundos.set(f"{segundos_final:02d}")

                if segundos_final > 0:

                    self.tablero_principal.after(1000, self.countdown, segundos_final-1,posesion_final-1)

    def iniciar(self):

            if not self.is_running:
                self.countdown(self.text_segundos.get(),self.text_segundos_posesion.get())

    def parar(self):

            self.is_running = False


text:
Q: MySql returns wrong results for emoji strings My database, tables, fields all are using utf8mb4. I can store well emoji symbols into some fields. Now I try to query such as:
SELECT * FROM user WHERE name=''
Amazing, the result are records with field names different such as ''
Looks like mysql matches emoji strings by their lengths but not contents.
Any idea to fix that problem? Many thanks.

A: Just did this command to my table:

ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

that's all. the result is correct then.

A: Try this:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;

A: What is the collation order on your table? Since you are using utf8mb4 it should be utf8mb4_unicode_ci. Anything else and you are likely to get the problem you are seeing - worse you might even get multiple records coming back.
To set the collation order use:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;


text:
Q: Creating a Debian package that does not remove directories after it's purged I'm trying to create a Debian package that doesn't delete an empty directory after it's purged. Specifically, I'm creating my own package containing some CA certificates I trust.
I'm following Debian's suggested method of installing the certificates to /usr/local/share/ca-certificates. The problem I'm running in to is that the ca-certificates package creates /usr/local/share/ca-certificates when it's installed and I'd like that directory to stick around when my package is purged.
My goal is to install my trust chain into /usr/local/share/ca-certificates/mychain but when my Debian package is removed I want dpkg to not remove /usr/local/share/ca-certificates if it's empty since the ca-certificates package explicitly created that directory.
I searched around for a definitive answer but all I managed to find were long forum posts and e-mail threads.

A: Install to a different local path and write a postinst script to create the directory in /usr/local and copy the files there.
As you can imagine, this probably violates both the letter and the spirit of the Debian policy. But it's your network, your rules, your users (and their easily discoverable workarounds).
For better usability, you could mark these files as conffiles so that at least they will be removed if you purge the package, but stay if you merely uninstall it.
Bottom line, files dpkg doesn't know about, it cannot remove.

A: Add postrm script:
#!/bin/sh

set -e

case "$1" in
  purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
    # Recreate the /usr/local/share/ca-certificates directory, since we are
    # ignoring Debian Policy by intentionally installing here. Removal of
    # ca-certificates-local removes this directory if empty.
    if [ ! -e /usr/local/share/ca-certificates ]; then
        if mkdir /usr/local/share/ca-certificates 2>/dev/null; then
            chown root:staff /usr/local/share/ca-certificates
            chmod 2775 /usr/local/share/ca-certificates
        fi
    fi
;;

*)
    echo "postrm called with unknown argument \`$1'" >&2
    exit 1
;;
esac

#DEBHELPER#

exit 0

This code is from ca-certificates-local:

This is an example stub source package that includes a dummy CA
  certificate in the local/ directory. Remove the dummy certificate, copy
  your trusted local root CA (in PEM format with the filename ending in
  ".crt") to the local/ directory, edit files in the debian/ directory as
  desired, and build your custom package.

See README, Steps to build your custom local root CA package from this example
So, the quick way to create and install such packages:
git clone git://anonscm.debian.org/collab-maint/ca-certificates.git ~/ca-certificates
cd ~/ca-certificates/examples/ca-certificates-local/
rm local/Local_Root_CA.crt
cp <path-to-your-cert> local/
# edit debian/control: change package-name, description, etc
# install build dependencies: http://unix.stackexchange.com/questions/177505/how-to-install-parse-build-dependencies-from-debian-control/211319#211319
dpkg-buildpackage
dpkg -i ../<package-name-version>.deb


text:
Q: Recursive function that determines if the first n characters in two different strings are the same Here is the iterative solution:
def firstNCharsSame(string, string2, n):
    same = True
    for i in range(n):
        same &= string[i] == string2[i]
    return same

print(firstNCharsSame("apple", "appll", 5))# ->false
print(firstNCharsSame("aaaae", "appll", 5))# ->false
print(firstNCharsSame("apple", "apple", 5))# ->true

I am need to make a recursive function to do the same thing. I find recursion very confusing but here is my attempt.
def firstNCharsSame(string, string2, n):
    if n > 1:
        firstNCharsSame(string, string2, n-1)
    return string[n - 1] == string2[n - 1]

This effectively only checks if the last characters in the strings are the same. I need to & the all values returned by all the calls of this function like I have done in the iterative version but I am struggling to understand how I can access what the "inner(higher up the stack)" function returns from the "outer(lower down the stack)" function.

A: You need to combine the recursive result with testing the current index.
def firstNCharsSame(string, string2, n):
    if n == 0: # base case
        return True
    if n > len(string) or n > len(string2):
        return False
    return string[n - 1] == string2[n - 1] and firstNCharsSame(string, string2, n-1)

A: You can use the base case as 0, and implement like so:
def firstNCharsSame(string, string2, n):
    if n == 0:
        return True
    if n > min(len(string), len(string2)):
        return False
    return string[n - 1] == string2[n - 1] and firstNCharsSame(string, string2, n-1)

A: Maybe something like this:
def firstNCharsSameRec(string, string2, current, n):
    if current >= n:
        return True

    if string[current] != string2[current]:
        return False

    return firstNCharsSameRec(string, string2, current + 1, n)

And calling it like this:
print(firstNCharsSameRec("apple", "appll", 0, 5))
print(firstNCharsSameRec("apple", "appll", 0, 3))

A: You only need to use the last parameter as a decreasing counter.  Just compare the first characters and recurse for the rest:
def firstNCharsSame(a, b, n):
    return not n or a and b and a[0]==b[0] and firstNCharsSame(a[1:],b[1:],n-1)


text:
Q: How to remove character inside element tag in jQuery? I am formatting a registration form in WordPress. The last p element tag contains a |. This form cannot be edited directly. This is the current markup of the forgot password tag:

 |  Forgot password?

How can I remove the | inside the #nav so that the 'Forgot password?' link will remain?

A: If the textnode containing the | is always the first child of the p you can use childNodes[0].remove(), like this:
document.getElementById('nav').childNodes[0].remove();

Or in jQuery:
$('#nav').contents()[0].remove()

document.getElementById('nav').childNodes[0].remove();

  | Forgot password?

A: Easy solution would be to just super simple replace the pipe char with nothing. ;)
$("#nav").html($("#nav").html().replace("|", ""));

Edit:
As discused (and mentioned by A. Wolff) in another answer, it is even a good idea to do this in a function, to prevent double DOM search of the p#nav element. You can do it like this:
$("#nav").html(function(i, html){
    return html.replace("|", "");
});

A: You can use .html( function ) to changing html of element. In function remove target character.

$("#nav").html(function(i, html){
    return html.replace("|", "");
});

 |  Forgot password?


text:
Q: How to programmatically detect a system hotkey? I'm looking for a way to programmatically detect hotkeys in the system. My app supports configurable hotkeys to do different things, and I'd like to be able to tell if another app has snagged one already or it's a built-in Windows hotkey (like Win-L to lock the workstation).
And if it is another app that owns the hotkey, I'd like to be able to show that to the user. At least the name of the exe.
I'm aware of three ways to do hotkeys:

*

*System hook using standard API's

*Using the hotkey feature in the properties dialog for a shortcut

*Polling async key state and responding

I doubt I can detect the third type, but what about the other two? And are there any other situations I need to know about?

A: I can think of three ways to do it with Standard API:

*

*RegisterHotkey

*SetWindowsHookEx(WH_KEYBOARD)

*SetWindowsHookEx(WH_LL_KEYBOARD)
With the first approach, you will get in the return value whether another application already registered the very same hotkey (or whether a shortcut uses this hotkey, or Explorer.exe registered the hotkey because it is Win+E or win+R). You don't get the application name this way, though.
Using Windows Hooks or async key states for "hotkeys": I don't think it is possible to detect hotkeys there, since you might use hotkeys in a context (like replace "t" by "irst" if the last four keystrokes were "Fris") that way. You could inject the hotkey using keybd_event (with your window focused) and test if the event "gets through"; on the other hands, some cases of "hotkeys" that are implemented via hooks do not consume the keystroke so it will still get through.
The approach I would use: First make sure that for entering a shortcut, you have to type that exact shortcut into your shortcut box (if that fails, the user will see which application uses it). Then use RegisterHotkey, so you will notice (in future sessions) if another "well-behaving" application tried to steal this shortcut from you.


text:
Q: In Powershell Script, how to convert '%5c' delimted CSV file to '/' delimited CSV file? I wrote a powershell script to retrive NAME & PATH of VM's(virtula machine) and save them in CSV file, But when ever there is '/' it displays as '%5c' i have no idea why its showing like that and I dont know how to change it.
Here is my powershell CODE:
function Get-Path{
        param($Object)

        $path = $object.Name
        $parent = Get-View $Object.ExtensionData.ResourcePool
        while($parent){
        $path = $parent.Name + "/" + $path

            if($parent.Parent){
                $parent = Get-View $parent.Parent
            }
            else{$parent = $null}
        }
        $path
    }

    Get-VM `
| Select Name, @{N="Path";E={(Get-Path -Object $_) -replace "^.*?Resources"}} `
| ConvertTo-Csv -NoTypeInformation `
| Select-Object -Skip 1 `
| Set-Content -Path C:\izaz\test.csv


text:
Q: How to solve allocate memory problem while working with huge datasets in python? I'm programming a BOW code for a dataset of 30000 rows.
I have X_train which is (21000, 2). Those 2 rows are: title and description.
SO, I have the following code:
def text_to_bow(text: str) -> np.array:
    text = text.split()
    res = np.zeros(len(bow_vocabulary)) #bow_vocabulary includes 10000 most popular tokens
    for word in text:
        for i in range(len(bow_vocabulary)):
            if word == bow_vocabulary[i]:
                res[i] += 1
    return res
def items_to_bow(items: np.array) -> np.array:
    desc_index = 1
    res = np.empty((0,k), dtype='uint8')
    for i in range(len(items)):
        description = items[i][desc_index]
        temp = text_to_bow(description)
        res = np.append(res, [temp], axis=0)
    return np.array(res)

My code seems to work right as there are several asserts in my task.
So, when I run:
X_train_bow = items_to_bow(X_train)

I get the error:
MemoryError: Unable to allocate 12.1 MiB for an array with shape (158,
10000) and data type float64

I've already set overcommit_memory to 1 in Ubuntu, but it hasn't helped. I dont/t want to use 64bit python as well because there may be problems with modules.
I've also tried another function (with regular arrays):
def items_to_bow(items: np.array) -> np.array:
    desc_index = 1
    res = []
    for i in range(len(items)):
        description = items[i][desc_index]
        temp = text_to_bow(description)
        res.append(temp)
        if len(res)//1000 > 0:
            print(len(res))
    return np.array(res)

But it seems to be working for an hour or so, which is not convenient.
Are there any ways to solve the problem? Would be grateful for any possible help.

A: Do chunking. In pandas, you use the chunksize param for this. Read a data chunk. Process the data. Append your output to a file. Make sure the chunk is deleted. Repeat.


text:
Q: How to give a child div width/height 100% if the parent's div is also 100% width/height I want two divs having the width and height 100%. I know that the child div won't work because the parents div has not a specific height but is there a way to fix this?
HTML:

CSS:
body
{
      width: 100%;
      height: 100;
}

.container
{
      position: relative;
      min-width: 100%;
      min-height: 100%;
      background-image: url('http://www.earthbusinessdirectory.com/web/images/london.jpg');
}

.child-container
{
      position: relative;
      min-width: 100%;
      min-height: 100%;
      background-image: url('/images/black.png');
}

A: You use viewport relative values and give the element a min-height of 100vh. (example)
(This obviously assumes you are wanting the element to be 100% of the viewport and not the parent element)
.child-container {
    position: relative;
    min-width: 100%;
    min-height: 100vh;
    background-image: url('/images/black.png');
}

5.1.2. Viewport-percentage lengths: the 'vw', 'vh', 'vmin', 'vmax' units
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

Alternatively, you could set the height of the html element to 100% and change the .container element's  min-height to a height. (example)
html, body {
    height: 100%;
}
.container {
    position: relative;
    min-width: 100%;
    /* min-height: 100%; */
    height: 100%;
}


text:
Q: Why is Python3's cmd.Cmd autocomplete not working on Mac OS? After testing a while with the Cmd.cmd framework in python 3.6 on Mac OS, I noticed a problem I don't know what to do about. Autocomplete doesn't seem to work. I tested with a simple code found on a forum :
import cmd

addresses = [
    'here@blubb.com',
    'foo@bar.com',
    'whatever@wherever.org',
]

class MyCmd(cmd.Cmd):
    def do_send(self, line):
        pass

    def complete_send(self, text, line, start_index, end_index):
        if text:
            return [
                address for address in addresses
                if address.startswith(text)
            ]
        else:
            return addresses

if __name__ == '__main__':
    my_cmd = MyCmd()
    my_cmd.cmdloop()

It doesn't seem to work, it just adds a blank space (normal tab). Any workaroud ?

A: please see the following examples >>> https://pymotw.com/2/cmd/ for python autocompletion.
Below is your modified code:
import cmd

class MyCmd(cmd.Cmd):

addresses = [
'here@blubb.com',
'foo@bar.com',
'whatever@wherever.org']

def do_send(self, line):
    "Greet the person"
    if line and line in self.addresses:
        sending_to = 'Sending to, %s!' % line
    elif line:
        sending_to = "Send to, " + line + " ?"
    else:
        sending_to = 'noreply@example.com'
    print (sending_to)

def complete_send(self, text, line, begidx, endidx):
    if text:
        completions = [
            address for address in self.addresses
            if address.startswith(text)
        ]
    else:
        completions = self.addresses[:]

    return completions

def do_EOF(self, line):
    return True

if __name__ == '__main__':
    MyCmd().cmdloop()

Test and see that it works. Good luck


text:
Q: Concatenar text en tabla datatable con AJAX Como concateno texto extra dentro de una tabla que se enlista por AJAX ejemplo tengo el siguiente código que en la columna 7 muestra un valor int que es el monto de pago, pero lo muestra en el front como por ejemplo 1500, necesito que aparezca como "$1500 MXN" ¿Cómo hago eso?
Pense que solo tenía que colocar como:
{"data":"montoPago" + "MXN"}, //Por ejemplo

"columns":[
      {"data":"idPago"},
      {"data":"nombreCliente"},
      {"data":"numeroSubcredito"},
      {"data":"campanaProducto"},
      {"data":"tipoPago"},
      {"data":"fechaPago"},
      {"data":"montoPago"},
      {"data":"fechaRegistro"}
    ]

Y en caso de fechaPago me regresa 2021-01-01 y otra columna que es fechaRegistro me regresa en formato aaaa-mm-dd hh:mm:ss: en ambas solo quiero formato dd-mm-aaaa ¿Alguien me puede ayudar?


text:
Q: Convert C++ UTF-8 literal to vector to uint32_t array[] I must admit that my experience in coding C++ is very low, some few hundred lines.
I solved the problem but I'm sure there is a better solution. At least I write this because I found no solutions via Google or stackoverflow, and other users maybe have a similar problem.
This is the portion of code in C99 to be ported to C++11:
// src/levtest.c

char utf_str2[] = "Chſerſplzon";
uint32_t utf_len2 = strlen(utf_str2);

// convert to ucs
uint32_t b_ucs[(utf_len2+1)*4]; // plenty of space
int b_chars;
b_chars = u8_toucs(b_ucs, (utf_len2+1)*4, utf_str2, utf_len2);

int distance;

distance = dist_uni(a_ucs, a_chars, b_ucs, b_chars);
printf("[dist_uni]      distance: %u expect: 4\n", distance);

Background is that the code in src/levbv.c should work via Perl XS, C, C++ (maybe other language bindings like Python). It's highly optimised and should use C-types. vector<wchar_t> is needed, because one C++ distribution (training of Tesseract-OCR) uses vector<wchar_t> for the relevant portions.
Here is my corresponding code in C++:
// src/levbvcpp.cpp

char utf_str2[] = u8"Chſerſplzon";

uint32_t utf_len2 = strlen(utf_str2);

// convert u8 to wstring
std::wstring b_string = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(utf_str2);

// convert wstring to vector<wchar_t>
std::vector<wchar_t> b_uv(b_string.begin(), b_string.end());
int b_chars = b_uv.size();

uint32_t b_ucs[(utf_len2+1)*4];

// convert vector<wchar_t> to uint32_t array[]
unsigned int index = 0;
for (uint32_t b_char : b_uv) {
    b_ucs[index] = b_char;
    index++;
}

int distance;

distance = dist_uni(a_ucs, a_chars, b_ucs, b_chars);
printf("[dist_uni]      distance: %u expect: 4\n", distance);

The source is on https://github.com/wollmers/Text-Levenshtein-BVXS.
Questions:

*

*Is there a better way to convert?

*What datatype and encoding would L"こんにちは世界" or u"こんにちは世界" have? The reference manual is somewhat untechnical.

*Code is compiled with -std=c++11 -Wall -g -finput-charset=utf-8 -O3 and clang on MacOS. Is there something to consider on other platforms/compilers with source encoded in UTF-8? Did not find a clear answer on stackoverflow.


text:
Q: Remote control Slideshow via SOAP webservice I want to remote control my slideshow (jQuery plugin Cycle2) that displays pictures that are selected by the user and requested from a server via AJAX. The server side script returns the whole HTML output for the pictures and additionally a navigation bar for stopping/pausing the slideshow.
Now, what I want is to have these navigating functions as a small web app on a smartphone to remote control the slideshow run on the server. I thought about a SOAP based webservice for the interaction between smartphone and server. The problem is how do I write functions that execute actions on my slideshow? Is it possible to trigger a button of a PHP script from within a function of another one?
I hope the problem became clear. I'm not asking for code, I simply don't know how to proceed here.

A: Ok, it just came to my mind. I can execute AJAX calls on the slideshow from a function of the webservice. Then however, I have to deal with these problems: Ways to circumvent the same-origin policy
Would that be a good way to do this?


text:
Q: Prevent rotation of markers on google map in android I am using google map and added several custom markers.
My problem is when i rotate my map using fingers, my markers are also rotated.
Can any one give me suggestion, how can i prevent rotation for markers?
Thanks in advance.

A: I found answer my self and posting answer so it can help to others.
Just set marker's flat property to false will prevent rotation of marker.

  MY_MARKER = mMap.addMarker(new MarkerOptions()
                    .flat(false)

A: You can use public MarkerOptions rotation (float rotation)
http://developer.android.com/reference/com/google/android/gms/maps/model/MarkerOptions.html#rotation(float)
This method returns the object for which the method was called, with the new rotation set.
So when you rotate, you can keep calling this function to rotate the marker back