text:
Q: UIView anchorPoint->drag->rotate transform causes flickering Goal
I am trying to replicate the UI Dynamics pull animation/behaviour. I have setup a UIPanGestureRecognizer on my UIView for dragging it around. When drag occurs, I set the touch point as UIView.layer.anchorPoint to allow rotation around the touch point. During the drag, I check the touch velocity direction and apply CGAffineTransformRotate either clockwise or anticlockwise. Here's what I am talking about.

Issue
The animation does not happen smoothly, the UIView flickers(multiple traces of view appear in short instances) when dragging and applying the rotation. The video recording is 30fps hence, flickering is not visible clearly. I hope my explanation is making it clear.
Source code in my view controller is as below. I am trying this on iOS5.0+
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIView *animationView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
    animationView.layer.backgroundColor = [UIColor redColor].CGColor;
    animationView.layer.shouldRasterize = YES; // Does not help :(
    animationView.autoresizingMask = UIViewAutoresizingNone; // Does not help :(

    [self.view addSubview:animationView];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [animationView addGestureRecognizer:pan];
    [animationView release];
    [pan release];
}

- (void) pan:(UIPanGestureRecognizer*) gesture {

    if(gesture.state==UIGestureRecognizerStateBegan) {
        CGPoint anchor = [gesture locationInView:gesture.view];

        gesture.view.layer.anchorPoint = CGPointMake(anchor.x/gesture.view.bounds.size.width,
                                                     anchor.y/gesture.view.bounds.size.height);

        gesture.view.center = CGPointMake(anchor.x/gesture.view.bounds.size.width,
                                          anchor.y/gesture.view.bounds.size.height);
    }
    else if(gesture.state==UIGestureRecognizerStateChanged) {
        CGPoint point1 = [gesture locationInView:self.view];
        gesture.view.center=point1;

        CGPoint velocity = [gesture velocityInView:gesture.view];
        if(velocity.x > 0)
        {
            // Dragged right
            if(velocity.y > 0) {
                // Dragged down
                // counter clock
                CGFloat angle = -0.2;
                gesture.view.transform = CGAffineTransformRotate(gesture.view.transform, angle);
            }
            else {
                // Dragged up
                // clock
                CGFloat angle = 0.2;
                gesture.view.transform = CGAffineTransformRotate(gesture.view.transform, angle);
            }
        }
        else
        {
            // Dragged left
            if(velocity.y > 0) {
                // Dragged down
                // clock
                CGFloat angle = 0.2;
                gesture.view.transform = CGAffineTransformRotate(gesture.view.transform, angle);
            }
            else {
                // Dragged up
                // counter clock
                CGFloat angle = -0.2;
                gesture.view.transform = CGAffineTransformRotate(gesture.view.transform, angle);
            }
        }
    }
}

I have tried applying CATransform3DMakeRotation (angle, 0.0f, 0.0f, 1.0f) to layer instead of view CGAffineTransformRotate. But the flickering still happens. Any ideas why this issue? I welcome advice on any other approach to achieve the same result.

A: After some serious thought in solving this issue, I realised that it was a trivial mistake. The flicker was caused because I am making the rotation for even slightest change in drag direction. To solve this, I assumed an arbitrary margin of pixel-change before I make rotation.
The modified code that solved the issue is as below
- (void) pan:(UIPanGestureRecognizer*) gesture {

    if(gesture.state==UIGestureRecognizerStateBegan) {
        CGPoint anchor = [gesture locationInView:gesture.view];
        gesture.view.layer.anchorPoint = CGPointMake(anchor.x/gesture.view.bounds.size.width,
                                                     anchor.y/gesture.view.bounds.size.height);
    }
    else if(gesture.state==UIGestureRecognizerStateChanged) {
        CGPoint point1 = [gesture locationInView:self.view];
        gesture.view.layer.position=point1;

        CGPoint velocity = [gesture velocityInView:gesture.view];
        CGFloat angle = 0.0;
        if(velocity.x > self.view.bounds.size.width*0.15)
        {
            // Dragged right
            if(velocity.y > self.view.bounds.size.height*0.02) {
                // Dragged down
                // counter clock
                angle = -0.05;
            }
            else if (velocity.y < -self.view.bounds.size.height*0.02) {
                // Dragged up
                // clock
                angle = 0.05;
            }
        }
        else if (velocity.x < -self.view.bounds.size.width*0.15)
        {
            // Dragged left
            if(velocity.y > self.view.bounds.size.height*0.02) {
                // Dragged down
                // clock
                angle = 0.05;
            }
            else if (velocity.y < -self.view.bounds.size.height*0.02) {
                // Dragged up
                // counter clock
                angle = -0.05;
            }
        }
        [self applyRotationToView:gesture.view byAngle:angle];
    }
}

- (void) applyRotationToView:(UIView*)rotationView byAngle:(CGFloat)angle {
    rotationView.transform = CGAffineTransformRotate(rotationView.transform, angle);
}

Animations are still not as smooth as one would expect, however I have managed to reduce the annoying flicker.


text:
Q: QGIS Essen 2.14.0 OpenLayers plugins running Windows 7 64 bit I cannot make any OpenLayers plugin visible for the part of the world for which I plot vector points. I set CRS to WGS 84 / Pseudo Mercator. After adding a layer of points it should be trivial to click on one of the opened layers and have a map, but the map does not show.

A: The problem is solved: I figured out that it is a matter of CRS. I must not take pseudo mercator (as advertised by some), but mercator then I can display an open map along with my points.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Random rows in neighbourhood I have this table (PERSONS) with 25M rows:
ID int(10) PK
points int(6) INDEX
some other columns

I want to show the user 4 random rows which are somewhat close to each other in points. I found this query after some searching and tuning to generate random rows which is impressive fast:
SELECT person_id, points
FROM persons AS r1 JOIN
       (SELECT (RAND() *
                     (SELECT MAX(person_id)
                        FROM persons)) AS id)
        AS r2
 WHERE r1.person_id>= r2.id and points > 0
 ORDER BY r1.person_id ASC
 LIMIT 4

So I query this in the PHP. Which gives me great and fast results (below 0.05 seconds when warmed up). But these rows are really just random (with at least 1 point since the points > 0). I would like to show some rows which are a little bit close, doesn't have to be every time, but let's say I do this query with limit 50 and than select a random row in PHP and the 3 closest rows (based on points) next to it. I would think you would need to sort the result, pick a random row and show the rows after/before it. But i have no idea how I can make this, since I am quite new to PHP.
Anyone suggestions, all feedback is welcome :)

A: Build an index on your points column (if it does not already exist), then perform your randomisation logic on that:
ALTER TABLE persons ADD INDEX (points);

SELECT   person_id, points
FROM     persons JOIN (
           SELECT RAND() * MAX(points) AS pivot
           FROM   persons
           WHERE  points > 0
         ) t ON t.pivot <= points
ORDER BY points
LIMIT    4

Note that this approach will select the pivot using a uniform probability distribution over the range of points values; if points are very non-uniform, you can end up pivoting on some values a lot more often than others (thereby resulting in seemingly "non-random" outcomes).
To resolve that, you can select a random record by a more uniformly distributed column (maybe person_id?) and then use the points value of that random record as the pivot; that is, substitute the following for the subquery in the above statement:
           SELECT   points AS pivot
           FROM     persons JOIN (

                      SELECT FLOOR(
                               MIN(person_id)
                             + RAND() * (MAX(person_id)-MIN(person_id))
                             ) AS random
                      FROM   persons
                      WHERE  points > 0

                    ) r ON r.random <= person_id
           WHERE    points > 0
           ORDER BY person_id
           LIMIT    1

A: Removing a subquery from it will drasticly improve the performance and caching so you could for example get list your IDs, put it in a file and then random from it (for example by reading random lines from file). This will improve it by a whole lot, as you can see if you will run EXPLAIN on this query and compare it by changing the query to load just data for the 4 (still random) ids.

A: I would suggest doing two separate sql queries in PHP and not join/subquery them. In many cases the optimizer can not simplify your query and has to perform each one separatly. So, in your case. if you have 1000 persons the optimizer will do the following wueries at worst case:

*

*Get 1000 persons rows

*Do Sub Select for each person which get's 1000 persons rows

*Join 1000 persons with joined rows resulting in 1.000.000 rows

*Filter all of them

In short:
1001 queries with 1.000.000 rows
My advice?
Perform two queries and NO joins or sub-selects as both (especially in combination have dramatic performance drops in most cases)
SELECT person_id, points
FROM persons
ORDER BY RAND() LIMIT 1

Now use the found points for your second query
SELECT person_id, points, ABS(points - <POINTS FROM ABOVE>) AS distance
FROM persons
ORDER BY distance ASC LIMIT 4


text:
Q: Artillery not launching scenarios I'm running my node server on http://localhost:5000 and wanted to do a performance test using artillery.
Here is my yaml file:
config:
  target: http://localhost:5000
phases:
- duration: 20
  arrivalRate: 3
  name: Warm up
scenarios:
- name: Test1
  flow:
  - post:
      url: /give
      json:
        item:
          'name': 'book'
          'price': '4.99'
        total:
          'cost': '7.56'

But I'm getting this result (seems like test didn't run at all)
Elapsed time: 0 seconds
  Scenarios launched:  0
  Scenarios completed: 0
  Requests completed:  0
  Mean response/sec: NaN
  Response time (msec):
    min: NaN
    max: NaN
    median: NaN
    p95: NaN
    p99: NaN

All virtual users finished
Summary report @ 15:48:49(+0530) 2021-07-07
  Scenarios launched:  0
  Scenarios completed: 0
  Requests completed:  0
  Mean response/sec: NaN
  Response time (msec):
    min: NaN
    max: NaN
    median: NaN
    p95: NaN
    p99: NaN
  Scenario counts:

Any idea what I'm doing wrong?

A: I made mistake in writing yaml file, phases should be inside config
config:
  target: http://localhost:5000
  phases:
  - duration: 20
    arrivalRate: 3
    name: Warm up
scenarios:
- name: Test1
  flow:
  - post:
      url: /give
      json:
        item:
          'name': 'book'
          'price': '4.99'
        total:
          'cost': '7.56'


text:
Q: Erro - HTTP Status 404 Estou com problema para no tomcat o meu site de teste. Quando eu entro ele dá um erro:

HTTP Status 404 - /liferay/
type Status report
message /liferay/
description The requested resource is not available.
Apache Tomcat/7.0.57

Aqui são a parte da msg console, que parece ser um problema:
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Server version:        Apache Tomcat/7.0.57
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Server built:          Nov 3 2014 08:39:16 UTC
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Server number:         7.0.57.0
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: OS Name:               Windows 8
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: OS Version:            6.2
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Architecture:          x86
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: JAVA_HOME:             C:\Program Files (x86)\Java\jdk1.8.0\jre
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: JVM Version:           1.8.0-b132
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: JVM Vendor:            Oracle Corporation
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: CATALINA_BASE:         C:\Tomcat\apache-tomcat-7.0.57
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: CATALINA_HOME:         C:\Tomcat\apache-tomcat-7.0.57
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Command line argument: -Djava.util.logging.config.file=C:\Tomcat\apache-tomcat-7.0.57\conf\logging.properties
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Command line argument: -Djava.endorsed.dirs=C:\Tomcat\apache-tomcat-7.0.57\endorsed
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Command line argument: -Dcatalina.base=C:\Tomcat\apache-tomcat-7.0.57
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Command line argument: -Dcatalina.home=C:\Tomcat\apache-tomcat-7.0.57
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFORMAÇÕES: Command line argument: -Djava.io.tmpdir=C:\Tomcat\apache-tomcat-7.0.57\temp
dez 08, 2014 11:52:37 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFORMAÇÕES: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jdk1.8.0\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Java\jre8\bin;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x64;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Java\jdk1.8.0\bin;C:\cygwin64\bin;;.
dez 08, 2014 11:52:37 AM org.apache.coyote.AbstractProtocol init
INFORMAÇÕES: Initializing ProtocolHandler ["http-bio-8080"]
dez 08, 2014 11:52:37 AM org.apache.coyote.AbstractProtocol init
INFORMAÇÕES: Initializing ProtocolHandler ["ajp-bio-8009"]
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.Catalina load
INFORMAÇÕES: Initialization processed in 600 ms
dez 08, 2014 11:52:37 AM org.apache.catalina.core.StandardService startInternal
INFORMAÇÕES: Starting service Catalina
dez 08, 2014 11:52:37 AM org.apache.catalina.core.StandardEngine startInternal
INFORMAÇÕES: Starting Servlet Engine: Apache Tomcat/7.0.57
dez 08, 2014 11:52:37 AM org.apache.catalina.startup.HostConfig deployDescriptor
INFORMAÇÕES: Deploying configuration descriptor C:\Tomcat\apache-tomcat-7.0.57\conf\Catalina\localhost\ROOT.xml
dez 08, 2014 11:52:38 AM org.apache.catalina.startup.HostConfig deployDescriptor
INFORMAÇÕES: Deployment of configuration descriptor C:\Tomcat\apache-tomcat-7.0.57\conf\Catalina\localhost\ROOT.xml has finished in 437 ms
dez 08, 2014 11:52:38 AM org.apache.catalina.startup.HostConfig deployWAR
INFORMAÇÕES: Deploying web application archive C:\Tomcat\apache-tomcat-7.0.57\webapps\liferay.war
dez 08, 2014 11:52:38 AM org.apache.catalina.startup.HostConfig deployWAR
INFORMAÇÕES: Deployment of web application archive C:\Tomcat\apache-tomcat-7.0.57\webapps\liferay.war has finished in 156 ms
dez 08, 2014 11:52:38 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deploying web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\docs
dez 08, 2014 11:52:38 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deployment of web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\docs has finished in 94 ms
dez 08, 2014 11:52:38 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deploying web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\examples
dez 08, 2014 11:52:39 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deployment of web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\examples has finished in 344 ms
dez 08, 2014 11:52:39 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deploying web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\host-manager
dez 08, 2014 11:52:39 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deployment of web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\host-manager has finished in 109 ms
dez 08, 2014 11:52:39 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deploying web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\manager
dez 08, 2014 11:52:39 AM org.apache.catalina.startup.HostConfig deployDirectory
INFORMAÇÕES: Deployment of web application directory C:\Tomcat\apache-tomcat-7.0.57\webapps\manager has finished in 94 ms
dez 08, 2014 11:52:39 AM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["http-bio-8080"]
dez 08, 2014 11:52:39 AM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["ajp-bio-8009"]
dez 08, 2014 11:52:39 AM org.apache.catalina.startup.Catalina start
INFORMAÇÕES: Server startup in 1298 ms

A: Você está tentando acessar a raiz da aplicação lifeway. Pelo log, o liferay.war for carregada com sucesso.
Porém, parece haver algo de errado com esse WAR, pois o tempo de inicialização de 156 milissegundos é muito pequeno, menor que dos exemplos.
O mais provável é que o WAR esteja vazio ou que a aplicação não tenha um mapeamento para a URL em questão.
Este é um WAR do conhecido gerenciador de portais Liferay ou é algum projeto seu? Se for do portal, verifique se o WAR não está corrompido ou se baixou a versão correta.
Verifique também se há outros logs específicos, eles podem mostrar erros internos da aplicação.

A: Erro 404 significa que você está tentando acessar um arquivo/resource no servidor, do qual não existe, por isso, o servidor te retorna um status 404 que seria este tal "Erro 404" para que você saiba que o servidor não conseguiu encontra-lo, verifique qual arquivo estás tentando acessar e corrija o caminho e o nome do arquivo, pois se o arquivo existir, este erro 404 não irá acontecer.


text:
Q: how to make desktop file ask for sudo password through gui I want to run an app that needs sudo to run.
I do not want to run it through terminal but through its desktop file or by clicking on a file associated with the program.
is there anyway to have it ask for sudo through gui like some system utilities do? I know muon package manager does when you want to upgrade in it.
additionally I need the sudo timeout to be kept like it is in terminal or for the password to timeout immediately so not to pose a security risk.


text:
Q: Removing Elements using DOM I am attempting to create an appear and disappear effect with an input. When the radio button is "no", the item should appear. When the radio button is "yes", the item should disappear. I have got the item to appear so far, but cannot get it to be removed through DOM. I have included my example on how I can remove my email which i commented out, but can't seem to remove the innerHTML or the input.
<!DOCTYPE html>

<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">

Shipping costs are free:

  <input type="radio" name="tip3" value="3" onclick="myFunction2()" />Yes
  <input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No

Email of seller:

  <input class="averageTextBox" type="email" id="emailAddress" value="" required>

  <button>Submit</button>

</form>

A: It's not working, because the lines anchor = document.getElementById("label"); and anchor2 = document.getElementById("INPUT"); are looking for elements with the id label and input, but can't find them. Those are actually tag names.
You need to add an id to the elements you create in the first function:
label.setAttribute("id", "idForLabel");
x.setAttribute("id", "idForInput");

and then change the lines in the second function to:
anchor = document.getElementById("idForLabel");
anchor2 = document.getElementById("idForInput");


text:
Q: Is there a planar network whose path give a TNN matrix whose entries are Eulerian numbers? It is well-known that for each planar graph, the number of paths from each source to each sink will give rise to a totally non-negative matrix.
However, did anyone ever come up with a planar network whose paths give a matrix whose entries are Eulerian numbers?

A: There is a Bratelli diagram which satisfies this. Consider $\mathbb N^2$ as a graph where the edges are given by k parallel directed edges from $(n,k)$ to $(n+1,k)$, and $n-k+1$ parallel directed edges from $(n,k)$ to $(n+1,k+1)$. Here the number of paths from $(1,1)$ (the unique source) to any vertex $(n,k)$ is the Eulerian number $A(n,k)$, the number of permutations in $S_n$ with exactly $k$ ascents. For a picture see fig.1 in "Random permutations and unique fully supported ergodicity for the Euler adic transformation" by Frick and Petersen. This can be proven quickly using the recurrence $$A(n, k) = (k+1)  A(n-1, k) + (n-k+1)  A(n-1, k-1).$$
Somewhat similarly one can give a directed graph where the number of paths from the source to any vertex in the graph is equal to an Euler number $E(n,k)$, which counts the number of alternating permutations of $S_n$ which start with $k$. For a picture of how this looks like look at fig.5 in "Generating alternating permutations lexicographically" by Bauslaugh and Ruskey.


text:
Q: MATLAB filtering having little effect I'm hoping someone will be able to tell me why no filtering is helping in my application.
I have a MEMS microphone monitoring the pressure of a small chamber, which has a membrane stretched over the far end. This device is placed on a human muscle and when I flex said muscle the membrane is disturbed, producing a pressure difference in the chamber, which the microphone picks up. Therefore, by flexing a muscle I can see nice spikes of activity. However, this method is very susceptible to noise, both motion artefacts and other undesirable artefacts.
The muscle activity I'm interested in is above 10Hz and below 100Hz, so I'm trying to bandpass (or at the very least, highpass) the noise. If I tap the device, or if I have the device on my upper forearm and tap my wrist, I'm to understand that this is a very low frequency noise, somewhere in the region of 1Hz/2Hz, but I can't get rid of this noise!
I'm using MATLAB to process. Generally I sample this microphone at 1KHz, but I currently have it hooked up to a DAQ at 5KHz sampling rate. I desperately want to get rid of this low frequency noise but nothing I try seems to make any difference, it's very hard to see what the filter is doing at all. It's definitely attenuating the signal, but not getting rid of the noise I want. I don't expect perfect results, but certainly better than what I'm seeing.
I've used lots of methods to create filters in MATLAB (manually and fdatool), along with different types of filters (Butterworth, Chebyshev, Elliptic) all not helping. I'm worried that my desired frequency of 10Hz is perhaps too close to the noise I'm trying to filter out, and it's not able to attenuate the noise enough.
Any ideas, code samples, or recommendations would be very helpful.

A: Tapping or percussive sounds are broad spectrum, producing frequency content well above the repeat rate of 1 Hz or so.  So any linear band pass or high pass filter will not be able to completely remove this broad spectrum noise.


text:
Q: Zotac NVida GT640 2GB Video Card Mini HDMI output I cannot get my 42" Samsung TV to show my computer on the HDMI cable which has a mini HDMI cable hooked to the computer.
It works fine if I use the DVI connections from the tv to the computer but I would like to hook it up to HDMI mini to HDMI and can't figure out why it won't work. I have set the settings on the computer to High Definition 1920 x 1080.
I have an updated video driver. Television setting is ok just no transfer, saying no signal found.

A: To connect the display using an HDMI connection (and HDMI cable):

*

*Shut down the computer.

*Turn off the monitor or TV.

*Connect an HDMI cable to the computer and to the display.

*Turn on the display, and select the HDMI input as the input source
to view.

*Turn on the computer.


text:
Q: Compact Set for Dummies Can any one tell me in simple words what is a compact set?
I read the definition of Compact set, but do not get it.
BTW, I do not know topology.
In particular, is the probability simplex,  $W\ge0, W1=1$, a compact set?

A: One useful characterization, especially as regards optimization: a set $S$ (in a metric space) is compact if and only if every continuous function on $S$ has a maximum.


text:
Q: Dropdown list for reporting hierarchy data I have two tables reporting,employee_details
reporting contains suprvisor_id,subordinate_id fields which are emp_id in employee_details table .And reporting table contains three levels (supervisors->subordinates->subordinates->employees) and i want to show this data as dropdown by fetching name from employee_details table, as hierarchy .so please help me is there any way to do it?

A: You defititly need to get the hole tree in an array if you want to display it. And this is a little bit tricky.
I think you arent't really shure how many levels you have in tree.
So the simplest way is the following but in big trees it have a bad performance. When the tree grows really big you need to check other technics.
The following is fast written, not tested an could have some bugs. But I post it to show you a possible solution:
<?php

class tree {

    private $level = 0;

    public function getChildsRecoursive($parentid=0,$recoursive=false) {
        // you would have your own db object... please replace this...
        $db->select("select * from reporting r JOIN employee_details d ON(r.subordinate_id=d.emp_id) where supervisor_id='$parentid' ORDER BY d.name");
        $r = array();
        while($data = $db->fetchArray()) {
            $sid = $data['supervisor_id'];
            $cid = $data['subordinate_id'];
            if($recoursive) {
                $this->level++;
                $data['level'] = $this->level;
                $data['childs'] = $this->getChildsRecoursive($cid, true);
                $this->level--;
            }
            $r[] = $data;
        }
        return $r;
    }

    public function getDropdown() {
            // I suspect the top Level have a supervisor_id = 0
        $data = $this->getChildsRecoursive(0,true);
            // you can do a print_r($data) here to see if the results are correct

        $r = "<select>";
        foreach($data as $d) {
            $r .= $this->getOptionsRecoursive($d);
        }
        $r .= "</select>";
            return $r;
    }

    public function getOptionsRecoursive($data) {
          $r = "<option>";
          for($i=0;$i<$data['level'];$i++) {
            $r .= " ";
          }
          $r .= $data['name'];
          $r .= "</option>\n";

          if(isset($data['childs'])) {
            foreach($data['childs'] as $c) {
                $r .= $this->getOptionsRecoursive($c);
            }
          }
          return $r;
    }

}
    ?>

Hope it helps to understand. (Please recognize that this will cause many queries depending on how big your tree is).
To Start you need to do
$tree = new tree();
echo $tree->getDropdown();


text:
Q: Dropdown Menu Problem in CSS. Whenever I hover off the element that is being hovered and trying to hover the
* items the menu closes Description:
There are two examples for a dropdown menu. When the dropdown menu
 is the child of the element being hovered it works fine, but when the element is a sibling it simple refuses to work the same way. I don't understand why is this the case, in theory it should work regardless or am I missing something?
Reason:
The reason I'm trying to have it that way as I want the "buggy" nav menu .hidden-menu--2 to occupy the whole width of the Parent.
Things I have tried:
I've tried to play with the selectors without any luck and tried to move around the
 itself in the HTML which solves the hover issue, but I wouldn't have the width I want. I want the width of the whole right block for the .hidden-menu--2.
I have seen similar questions, but none of them really explains what the real issue is.
Url:
https://codepen.io/Kristof1992/pen/PoBRamr
HTML

A

B

C

James

A

B

C

CSS
/* BASE */

* {
  margin: 0;
  padding: 0;
}

*,
::before,
::after {
  box-sizing: inherit;
}

html {
  box-sizing: border-box;
  font-size: 62.5%;
}

/* ********* */

.container {
  width: 80%;
  margin: 0 auto;
  background-color: brown;
}

.navigation {
  display: flex;
  justify-content: space-between;
}

.child-one img {
  width: 2.5rem;
  height: 2.5rem;
  background-color: aqua;
}

.child-two img {
  width: 2.5rem;
  height: 2.5rem;
  background-color: black;
}

/* LAST BLOCK */
.child-three {
  display: flex;
  position: relative;
  gap: 1rem;
  border: 1px solid aqua;
}

.imgs {
  width: 2.5rem;
  height: 2.5rem;
  background-color: yellow;
}

.specific {
  width: 2.5rem;
  height: 2.5rem;
  background-color: blue;
  position: relative;
}

/* INSIDE OF LAST BLOCK */

.profile {
  display: flex;
  position: relative;
  background-color: orangered;
  gap: 1rem;
}

.profile-img {
  width: 2.5rem;
  height: 2.5rem;
  background-color: black;
}

.profile-name {
  font-size: 2rem;
}

.hidden-menu {
  position: absolute;
  list-style:none;
  background-color: blue;
  top: 100%;
  left: 0;
  width: 100%;
  transform: scale(0);
}

.hidden-menu--2 {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  list-style: none;
  background-color: pink;
  transform: scale(0);
  z-index: 999;
}

.hidden-menu {
  position: absolute;
  transform: scaleY(0);
  z-index: 99;
  background-color: blue;
  top: 100%;
  width: 100%;
  left: 0;
  list-style: none;
  transform-origin: top;
  transition:  all .25s ease;
}

.profile:hover .hidden-menu {
  transform: scale(1);
}

.specific:hover ~ .hidden-menu--2 {
  transform: scale(1);
}

/* .hidden-menu--2 li:hover .hidden-menu--2 {
  transform: scale(1);
} */


text:
Q: MethodError: no method matching Weights(::Array{Any,1}, ::Float64) I'm trying to do a sample of a string array, incorporating weights for each of the elements of the array. Specifically,
new_name_event = sample(events,Weights(dict_betas_choices[string(new_player)][new_zone][string(new_time)][string(new_loc)][string(new_res)]))

>ERROR:
MethodError: no method matching Weights(::Array{Any,1}, ::Float64)
Closest candidates are:
  Weights(!Matched::var"#18#V", ::var"#16#S") where {var"#16#S"<:Real, var"#17#T"<:Real, var"#18#V"<:AbstractArray{var"#17#T",1}} at C:\Users\semed\.julia\packages\StatsBase\ZxhK8\src\weights.jl:13
  Weights(::Any) at C:\Users\semed\.julia\packages\StatsBase\ZxhK8\src\weights.jl:16

Stacktrace:
 [1] Weights(::Array{Any,1}) at C:\Users\semed\.julia\packages\StatsBase\ZxhK8\src\weights.jl:16
 [2] top-level scope at .\In[22]:62
 [3] include_string(::Function, ::Module, ::String, ::String) at .\loading.jl:1091

Where,
println(events, typeof(events))
>["Shot", "Duel", "Pass"]Array{String,1}

pesos = dict_betas_choices[string(new_player)][new_zone][string(new_time)][string(new_loc)][string(new_res)]
println(pesos, typeof(pesos), typeof(pesos[1]))
>Any[0.00114591, 0.69774462, 0.30110947] Array{Any,1} Float64

A: This should fix it in your case:
Float64.(dict_betas_choices[string(new_player)][new_zone][string(new_time)][string(new_loc)][string(new_res)])

If it errors it would mean that your data are not consisting of only numbers.
In general you should fix the data in the source to have eltype not Any but some real number type, e.g. Float64 as suggested above (this should be fixed at data structure creation time).


text:
Q: How to send emails with smtpjs in reacts without typescript I tried creating a contact form with SMTP js in react but it did not work tried checking stack over flow but no good answer for using only react not typescript
I was expecting the stmp is to be installed like normal swiper
Because I'm still a junior frontend dev

A: You can also find more information and documentation on using smtp.js in React app on the following resources:
Official smtp.js documentation: https://github.com/kimmobrunfeldt/smtp.js
SMTP in Node.js: https://nodemailer.com/smtp/
this also explains better:
https://victorbruce82.medium.com/how-to-send-emails-using-react-through-emailjs-no-server-code-needed-8e1453ef8796
Yes, you can install smtp.js in a similar way to installing other packages in your React app. You can use npm or yarn to install it:
CODE :
npm install smtpjs
or
yarn add smtpjs
After installation, you can import and use smtp.js in your React component.


text:
Q: How to import 3dmax model in cocos3d Example iphone I am working with cocos3d Game development I have to import 3dmax model in my application can anyone suggest how to work with cocos3d??

A: According to the documentation, cocos3d ships with a loader framework which adds a category on the class CC3World with a method for loading PowerVR POD-files called
addContentFromPODResourceFile:

Further, the vendor of PowerVR makes available a plugin for 3dsmax enabling POD-file exporting of 3ds scenes.
I have not tried it myself, so YMMV.


text:
Q: grpc-gateway runtime version conflict from last few days the protoc generator is generating code with v2 version of github.com/grpc-ecosystem/grpc-gateway. I want to keep using github.com/grpc-ecosystem/grpc-gateway v1.16.0. I am unable to remove the v2 version which is causing conflict. I tried removing from go.mod, clearing from $GOPATH. I suppose my protoc generator is not able to use v1 version. Kindly guide me as how shall I sync the grpc-gateway runtime package.
Using below commands to generate the messages and service
protoc -I . --go-grpc_out=. api/protobuf-spec/catalog_fetch/*.proto
protoc -I . --grpc-gateway_out=logtostderr=true:. api/protobuf-spec/catalog_fetch/*.proto

Note: It is generating both grpc.pb.go file and pb.go file, which is further causing issue.
cannot use mux (type *"github.com/grpc-ecosystem/grpc-gateway/runtime".ServeMux) as type *"github.com/grpc-ecosystem/grpc-gateway/v2/runtime".ServeMux ```

A: I have spent 3 hours debugging the exact same problem.
You have to remove the binary from your GOPATH and GOROOT.
For simplicity, just use which protoc-gen-grpc-gateway.
This should point you to the binary protoc is using under the hood. Remove it and rerun go get -u  github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v1.16.0.

A: I think you have installed the v2 version of the generator. Unfortunately, you cannot use v1.16.0 with newer versions of the go protobuf generators. If you want to keep using v1.16.0, you can download the generator from the releases page https://github.com/grpc-ecosystem/grpc-gateway/releases/tag/v1.16.0.


text:
Q: Derivative ParametricNDSolveValue i'm work with heat conduction in cylindrical coordinates, my problem is how to calculate a derivative for a parameter using ParametricNDSolveSolution.
L = 0.04;(*comprimento do phantom*)
b = 0.0375;(*raio do cilindro*)
kp = 0.150;(*condutividade do phantom*)
Ro = 1046.83;(*massa específica do phantom*)
Alfap = 8.05*10^-8;(*difusividade do phantom*)
Ta = 24.484;(*temperatura do meio ambiente*)
(*Betad=0.9;(*atenuação do phantom*)*)
I0 = 10000;(*intensidade do transdutor*)
Eal = 0.0048;(*espessura do alumínio*)
kal = 204;(*condutividade do alumínio*)
h1 = 5;(*coeficiente de convecção do ar para Biot 1*)
h2 = 5;(*coeficiente de convecção do ar para Biot 2*)
t5 = 300;(*tempo de duração do ultrassom*)
Tg = 24.5;(*temperatura do gel*)
\[Epsilon]1 = N[10^-5];

hef = 1/(1/h1 + Eal/kal);(*coeficiente de convecção efetivo*)
Betas = Betad*L;(*atenuação do phantom*)
Bi1 = (hef*b)/kp;(*número de Biot 1*)
Bi2 = (h2*L)/kp;(*número de Biot 2*)
Gama = L/b;(*razão de aspecto*)
I0s = (2*Betad*I0*b^2)/(kp*Ta);(*intensidade*)
Tau5 = (Alfap*t5)/b^2;(*tempo adimensional de duração ultrassom*)
Tetag = (Tg - Ta)/Ta;(*temperatura do gel adimensional*)

G[Z_, \[Tau]_] = I0s*Exp[-Betas*Z]*UnitStep[Tau5 - \[Tau]]
edp1 = D[\[Theta][R, Z, \[Tau]], \[Tau]] ==
   D[\[Theta][R, Z, \[Tau]], R, R] +
    1/R*D[\[Theta][R, Z, \[Tau]], R] +
    1/Gama^2*D[\[Theta][R, Z, \[Tau]], Z, Z] + G[Z, \[Tau]];

CI = (\[Theta][R, Z, \[Tau]] /. \[Tau] -> 0) == 0;
CC2 = (\[Theta][R, Z, \[Tau]] /. R -> \[Epsilon]1) == 0;
CC3 = (D[\[Theta][R, Z, \[Tau]], R] + Bi1* \[Theta][R, Z, \[Tau]]) ==
    0 /. R -> 1;
CC4 = (\[Theta][R, Z, \[Tau]] /. Z -> 0) == Tetag;
CC5 = (D[\[Theta][R, Z, \[Tau]], Z] + Bi2*\[Theta][R, Z, \[Tau]]) ==
    0 /. Z -> 1;

eqns = Flatten[{edp1, CI, CC2, CC3, CC4, CC5}]

sol = ParametricNDSolveValue[
  eqns, \[Theta], {R, \[Epsilon]1, 1}, {Z, 0, 1}, {\[Tau], 0,
   0.35}, {Betad}, PrecisionGoal -> 2]

Evaluate[D[sol[Betad], Betad]] /. Betad -> 0.9 This is my problem !
Any suggestions, Thanks.

A: You might take a central difference numerical derivative:
d0[b_, del_] :=
 d0[b, del] = (sol[b + del][x, y, z] - sol[b - del][x, y, z])/del/2
d[b_, del_][x0_, y0_, z0_] := d0[b, del] /. {x -> x0, y -> y0, z -> z0}

This does not seem to converge however as you reduce del:
d[.9, 0.001][.1, .1, .1]
d[.9, 0.0001][.1, .1, .1]
d[.9, 0.00001][.1, .1, .1]
d[.9, 0.000001][.1, .1, .1]

-0.0914891
-1.41497
-1.15597
2.30509

That might be what is causing your expression to take a long time.
FWIW I first evaluated the general approaches with a 1-d function,
pfun = ParametricNDSolveValue[{y'[t] == a y[t], y[0] == 1},
  y, {t, 0, 10}, {a}]
dp = D[pfun[a], a] /. a -> .1
del = .1;
Plot[{(pfun[.1 + del]@x - pfun[.1 - del]@x)/del/2  , dp[x]} , {x, 0,
  10} ]

this does quickly converge if you reduce del


text:
Q: unable to submit form having multi select in spring mvc application Using spring mvc, I am working on a page which allows users to select multiple skills (using multi-select). I am able to display skills.But when I select skills and click on submit, I am seeing below error.
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'candidate' on field 'skills': rejected value [1,3,4]; codes [typeMismatch.candidate.skills,typeMismatch.skills,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [candidate.skills,skills]; arguments []; default message [skills]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.List' for property 'skills'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.cts.form.SkillForm] for property 'skills[0]': no matching editors or conversion strategy found]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:113)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)

Below is my code :
public class CandidateForm {

private String name;
..........
private List<SkillForm> skills;
.. setters ad getters

}
public class SkillForm {
    private Integer id;
    private String name;
    private String description;
    private String isSelected;
  ......... setters and getters
}

--- jsp
 <div class="form-group col-md-6 col-sm-6">
                            <form:label for="skills" path="skills">Candidate Primary Skills *</form:label>
                            <form:select multiple="true" path="skills" class="form-control input-sm" id="skills" >
                                <c:forEach var="item" items="${candidate.skills}">
                                    <form:option selected="${item.isSelected}" value="${item.id}" >${item.name}</form:option>
                                </c:forEach>
                            </form:select>
                        </div>

formatter
@Component
public class SkillFormatter implements Formatter<SkillForm>{

    public SkillFormatter() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public String print(SkillForm object, Locale locale) {
        // TODO Auto-generated method stub
        return object.getId().toString();
    }

    @Override
    public SkillForm parse(String text, Locale locale) throws ParseException {
        // TODO Auto-generated method stub
        SkillForm form = new SkillForm();
        form.setId(Integer.parseInt(text));
        return form;
    }

bean configuration
<context:component-scan base-package="com.cts.formatter" />
    <beans:bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <beans:property name="formatters">
            <beans:set>
                <beans:ref bean="skillFormatter" />
            </beans:set>
        </beans:property>
    </beans:bean>

    <annotation-driven conversion-service="conversionService" />

controller
 @RequestMapping(value = "/candidate/submit", method = RequestMethod.POST)
        public String submitNewCandidate(@ModelAttribute("candidate") CandidateForm form, ModelMap model,BindingResult bindingResult) {
            if(logger.isDebugEnabled()){
                logger.debug("createCandidate is executed!");
            }
            -----------------------
            return "newCandidate";
        }

I have this page as reference . CAn you anybody give some inputs as to why, even though I have configured formatter, it is not invoked ? Should I do anything in the controller method ?.. Is there any better implementation ?

A: I copy your code to my springmvc project ,but it's successful.I paste my code following.
<bean id="skillFormatter" class="org.spring.test.test.SkillFormatter"></bean>

<mvc:annotation-driven conversion-service="conversionService"/>

are you sure that your formatter is registered correctly and the spring version is appropriate?


text:
Q: SQL Syntax error when I execute query I have in this query an syntax error:
$sql = "CREATE TABLE cb (
id INT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
p VARCHAR(255) NOT NULL,
t1 VARCHAR(255) NOT NULL,
t2 VARCHAR(255) NOT NULL,
type ENUM,
title VARCHAR(255) NOT NULL
)

Anyone can help me to resolve this error?
EDIT: The error is

Error creating table:
  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 ' title VARCHAR(255) NOT NULL )' at line 6

A: ENUM needs enumeration values to be supplied as string literals something as
CREATE TABLE cb (
id INT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
p VARCHAR(255) NOT NULL,
t1 VARCHAR(255) NOT NULL,
t2 VARCHAR(255) NOT NULL,
type ENUM('1','2'),
title VARCHAR(255) NOT NULL
)

https://dev.mysql.com/doc/refman/5.0/en/enum.html


text:
Q: Unable to merge untracked working tree I am working on a Project and wanted to merge changes from a git repository.
The remote repo is not ignoring some build files, but i have added those build files to my gitignore (because with different build systems the built files would obviously differ).
So when i try to merge with:
git merge -X ours ns3-mmwave-ext/master

I get an error saying that those build files would be overwritten with merge.
I do not want them to be overwritten, so i followed this answer
https://stackoverflow.com/a/26639255/4126652
and tried to do:
git add -f * // Without -f git is complaining because those build files are in my gitignore
git stash
git merge -X ours ns3-mmwave-ext/master

But that still shows the same error that the same untracked working tree files would be overwritten by merge.
Note that ns3-mmwave-ext is a remote and has already been fetched.
Edit:
I can obbiously clean the build files, but the build process is very long and i don't want to rebuild the whole thing for just a few minor changes.
Edit 2:
I am not a contributor to the remote repo so i can't just remove the build files in remote.

A: My suggession would be commit your build folders in other local tmp branch. Then reset your local/master with ns3-mmwave-ext/master, then pull.
# First remove 'builds' folder from .gitignore

$ git checkout tmp
$ git commit -am 'builds folder commmit'

$ git checkout master
$ git fetch
$ git reset --hard ns3-mmwave-ext/master
$ git pull origin ns3-mmwave-ext/master

$ git checkout tmp
$ git rebase master                  # now your 'builds folder commit' will be kept in top here


text:
Q: No module named 'oauthlib' Python 3.4 I can't import requests_oauthlib, I've tried looking for a fix, but have had no luck.  When I try to import it I get the following error
Traceback (most recent call last):

  File "/home/steven/PycharmProjects/howareyou/questions.py", line 4, in <module>

    import requests_oauthlib

  File "/usr/local/lib/python3.4/dist-packages/requests_oauthlib/__init__.py", line 1, in <module>

    from .oauth1_auth import OAuth1

  File "/usr/local/lib/python3.4/dist-packages/requests_oauthlib/oauth1_auth.py", line 6, in <module>

    from oauthlib.common import extract_params

ImportError: No module named 'oauthlib'

import sys; print (sys.path) gives me:
['/home/steven/PycharmProjects/howareyou',
 '/usr/lib/python3/dist-packages',
 '/home/steven/PycharmProjects/howareyou',
 '/usr/lib/python3.4',
 '/usr/lib/python3.4/plat-x86_64-linux-gnu',
 '/usr/lib/python3.4/lib-dynload',
 '/home/steven/howareyouve/lib/python3.4/site-packages',
 '/usr/local/lib/python3.4/dist-packages']

The actual package is located in /usr/local/lib/python3.4/dist-packages as are all of my packages, and I can import everything else, it's just seems to be oauthlib. I've tried uninstalling it and reinstalling as well.

A: Alright, I think I figured it out finally.  It looks like there were two copies of oauthlib installed.  I installed oauthlib using pip to /usr/local/lib/python3.4/dist-packages, and at sometime or another oauthlib was also installed to the /usr/lib/python3/dist-packages
I was able to simply use:
apt-get remove python3-oauthlib

and everything seems to work again


text:
Q: Loading a document in XSLT using BASIC authentication in ASP.net For development purposes we have a site setup with BASIC authentication in IIS7. One aspect of the site is that it does a lot transformations using XSLT. However this is causing authentication problems when loading documents in XSLT like this:
<xsl:with-param
     name="value"
     select="document('/mod_cms/xml/fixed/phaedrus_object_menu_display.xml')
                /menuDisplay/option[value=$pagingValue]/name"/>

I get the error:

The remote server returned an error:
  (401) Unauthorized.

Looking on the web for solutions, I have come across suggestions to use Credentials, eg:
Dim sw As New StringWriter()
Dim xslArg As New XsltArgumentList()
Dim xslt As New XslCompiledTransform()
Dim settings As New XsltSettings
settings.EnableDocumentFunction = True
Dim resolver As New XmlUrlResolver
Dim xml As New XmlDocument
xml.LoadXml(sXml)

Dim myCache As New System.Net.CredentialCache()
myCache.Add(New Uri("http://URL.net/"), "Basic", New System.Net.NetworkCredential("???", "???"))
myCache.Add(New Uri("http://URL.net/mod_cms/xml/fixed/"), "Basic", New System.Net.NetworkCredential("???", "???"))
resolver.Credentials = myCache '

xslt.Load(sXsl, settings, resolver)
xslt.Transform(xml, xslArg, sw)

But this doesn't seem to work.
Has someone else had this problem.
Thanks in advance for any help.

A: Try using an XmlUrlResolver object.


text:
Q: Find a newly created record in a controller test using RSpec 3 and Rails 4 I'm doing a controller spec in Rails 4, and I'm wanting to test the attributes of a record created by a controller action. How do I find the newly created record?
For example, what could I do instead of
it 'Marks a new user as pending' do
  post :create, params
  # I don't want to use the following line
  user = User.last
  expect(user).to be_pending
end

The Rails guides only briefly talks about controller tests, where it mentions testing that Article.count changes by 1, but not how to get a new ActiveRecord model.
The question Find the newest record in Rails 3 is about Rails 3.
I'm reluctant to use User.last, because the default sorting may be by something other than creation date.

A: It is not a good idea to compare records or objects in controller tests. In a controller create test, you should test the correct redirection and the changing of the record.
You can easily compare your objects in a model test, because you can easily track your record.
Still, you can access the created record from a test if your action has a variable that holds the record like
In controller
 def create
   @user = #assign user
 end

In Test
assigns(:user).name.should eq "Name" # If it has a name attribute
assigns(:user).pending.should be_true # I don't know how you implemented pending

You can take a look at this article

A: If a controller has an instance variable named @user, then we can access it in RSpec by assigns(:user).


text:
Q: Classic Azure Mobile services scheduler in new Azure Portal I am using classic Azure portal and it does have Mobile services.I was able to create mobile service and run javascript(Node backend) backend code for sending push notifications connecting notification hubs.But in the new portal I am trying to do the same that is creating a new mobile service and run Javascript code (Node backend) for push notifications.As expected I am unable to find mobile services as old mobile service is now Mobile App.I am exploring Mobile App under App services but unable to find a option to create new scheduler that runs a Node script.I am only able to create a web job.Is it not possible to create a scheduler that runs Node script in new Azure?

A: Generally speaking, you can build up your own Node.js application with several functionalities you need, and expose them as HTTP REST APIs. Then you can use new Scheduler jobs on new Azure protal (https://ms.portal.azure.com) to call your own APIs in a schedule.
Please refer to https://azure.microsoft.com/en-us/documentation/articles/scheduler-intro/ for more info.


text:
Q: user login redirect using PHP not working I want it to redirect the user based on the if statements, but it doesn't seem to work. Any ideas?
<?php
$username = $_POST['username'];
$password = $_POST['password'];

if ($username == 'co323'){
if($password == 'marking'){
    $link = "menu.php";
 }
else{
    echo "Wrong Username/Password";
    $link = "loginform.html";
 }
}
else{
echo "Wrong Username/Password";
$link = "loginform.html";
}
header($link);

?>

A: To redirect, you need a Location header, so the proper line would be:
header("Location: $link");

Note that you must not echo any output before the redirect header, so remove all your echos to make this work.


text:
Q: Why do I have to constantly trigger a GET request in this chat application? I am new to AJAX and PHP, and I don't quite understand this code:
https://github.com/Artifx/PHP-and-MySQL-Web-Development-5th-Edition/blob/master/Chapter23/client.js

var pollServer = function() {
    $.get('chat.php', function(result) {

        if(!result.success) {
            console.log("Error polling server for new messages!");
            return;
        }

        $.each(result.messages, function(idx) {

            var chatBubble;

            if(this.sent_by == 'self') {
                chatBubble = $('
' +
                               this.message +
                               '

');
            } else {
                chatBubble = $('
' +
                               this.message +
                               '

');
            }

            $('#chatPanel').append(chatBubble);
        });

        setTimeout(pollServer, 5000);
    });
}

$(document).on('ready', function() {
    pollServer();

    $('button').click(function() {
        $(this).toggleClass('active');
    });
});

$('#sendMessageBtn').on('click', function(event) {
    event.preventDefault();

    var message = $('#chatMessage').val();

    $.post('chat.php', {
        'message' : message
    }, function(result) {

        $('#sendMessageBtn').toggleClass('active');

        if(!result.success) {
            alert("There was an error sending your message");
        } else {
            console.log("Message sent!");
            $('#chatMessage').val('');
        }
    });

});

Is it not possible to trigger a GET request only after a POST request has been made? What is wrong with this logic, that makes it necessary to run the pollServer function every 5 seconds?


text:
Q: Show that the function $u(x)=1 \in W^{m,\ 2}(\Omega)$, but not in $W_0^{m,\ 2}(\Omega)$ I have a problem:

For $\Omega$ be a domain in $\Bbb R^n$. Show that the function $u(x)=1 \in W^{m,\ 2}(\Omega)$, but not in $W_0^{m,\ 2}(\Omega)$, for all $m \ge 1$.

=============================
Any help will be appreciated! Thanks!

A: First I would like to answer the first comment : It is only if you take the whole $\mathbb{R}^n$ that this two spaces coincide not at all for bounded domain.
For the problem : I will do it on $\mathbb{R}$ and $m=1$ and $\Omega=(0,1)$ (easy to adapt). To show that $u$ belongs to $W^{m,2}(\Omega)$ you only need to show that the integration by parts formula (against function in $\mathcal{C}^\infty_c(\Omega)$) holds. Or just notice that $u\in \mathcal{C}^{\infty}(\Omega)$ theferore the classic (then the weak) derivatives exist and are $0$.
Now $W^{m,2}_0(\Omega)$ is by definition the closure of $\mathcal{C}^\infty_c(\Omega)$ with respect to the norm of $W^{m,2}(\Omega)$ :
$$\|\phi\|_{W^{1,2}(\Omega)}=\int|\phi|^2+\int|\phi^{\prime}|^2.$$
Now assume that $u$ belongs to $W^{m,2}_0(\Omega)$ then there exists a sequence $\phi_n$ in $\mathcal{C}^\infty_c(\Omega)$ such that. $\|\phi_n-u\|_{W^{2,1}(\Omega)}\rightarrow 0$ which by definition imply the followings
$$\int|\phi_n-1|^2\rightarrow 0\\ \int|\phi_n^{\prime}|^2\rightarrow 0\\
\phi_n(0)=\phi_n(1)=0$$ and   integration by
parts of the quantity $\int(\phi_n-1)$ leads easily to a contradiction. Generally the only constant function which belongs to this space is $0$.
Roughly speaking $W^{m,2}_0(\Omega)$ are functions (with appropriate weak derivatives)  which vanishes in some sense at the boundary (rigorously the trace sense) and this is not the case for $u=1$.
Note : if you are already familiar with the boundary trace of function in sobolev spaces it is obvious : $W^{m,p}_0(\Omega)$ are the function of $W^{m,p}(\Omega)$ for which the trace at the boundary is 0. But since $u$ is continuous the trace of $u$ on $\partial\Omega$ is only $u_{|_{\partial\Omega}}=1\neq 0$
and it is over.

A: HINT: any smooth function $u_n$ with compact support approximating $1$ well will be close to $1$ on most of $\Omega$ and close to $0$ elsewhere. This implies that there will always be a region where the approximating function has a big gradient. Try to derive a contradiction by showing that the norm of $1 - u_n$ stays bounded away frow $0$ thanks to the contribution from the gradient part of the norm.


text:
Q: Getting the 'external' IP address in Java I'm not too sure how to go about getting the external IP address of the machine as a computer outside of a network would see it.
My following IPAddress class only gets the local IP address of the machine.
public class IPAddress {

    private InetAddress thisIp;

    private String thisIpAddress;

    private void setIpAdd() {
        try {
            InetAddress thisIp = InetAddress.getLocalHost();
            thisIpAddress = thisIp.getHostAddress().toString();
        } catch (Exception e) {
        }
    }

    protected String getIpAddress() {
        setIpAdd();
        return thisIpAddress;
    }
}

A: One of the comments by @stivlo deserves to be an answer:
You can use the Amazon service http://checkip.amazonaws.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class IpChecker {

    public static String getIp() throws Exception {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(
                    whatismyip.openStream()));
            String ip = in.readLine();
            return ip;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

A: Make a HttpURLConnection to some site like www.whatismyip.com and parse that :-)

A: How about this? It's simple and worked the best for me :)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class IP {
    public static void main(String args[]) {
        new IP();
    }

    public IP() {
        URL ipAdress;

        try {
            ipAdress = new URL("http://myexternalip.com/raw");

            BufferedReader in = new BufferedReader(new InputStreamReader(ipAdress.openStream()));

            String ip = in.readLine();
            System.out.println(ip);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

A: http://jstun.javawi.de/ will do it - provided your gateway device does STUN )most do)

A: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.regex.Pattern;

public class ExternalIPUtil {

    private static final Pattern IPV4_PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

    private static final String[] IPV4_SERVICES = {
            "http://checkip.amazonaws.com/",
            "https://ipv4.icanhazip.com/",
            "http://bot.whatismyipaddress.com/"
            // and so on ...
    };

    public static String get() throws ExecutionException, InterruptedException {
        List<Callable<String>> callables = new ArrayList<>();
        for (String ipService : IPV4_SERVICES) {
            callables.add(() -> get(ipService));
        }

        ExecutorService executorService = Executors.newCachedThreadPool();
        try {
            return executorService.invokeAny(callables);
        } finally {
            executorService.shutdown();
        }
    }

    private static String get(String url) throws IOException {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
            String ip = in.readLine();
            if (IPV4_PATTERN.matcher(ip).matches()) {
                return ip;
            } else {
                throw new IOException("invalid IPv4 address: " + ip);
            }
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("IP: " + get());
    }
}

Get from multiple IP services concurrently such as:

*

*http://checkip.amazonaws.com/

*https://ipv4.icanhazip.com/

*http://bot.whatismyipaddress.com/

*and so on ...

and ExecutorService.invokeAny(tasks) return the result of the first successfully thread. Other tasks that have not completed will be cancelled.

A: The truth is: 'you can't' in the sense that you posed the question. NAT happens outside of the protocol. There is no way for your machine's kernel to know how your NAT box is mapping from external to internal IP addresses. Other answers here offer tricks involving methods of talking to outside web sites.

A: I am not sure if you can grab that IP from code that runs on the local machine.
You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:
request.getRemoteAddr()
Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.
Use a webservice like AWS and others
import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

A: All this are still up and working smoothly! (as of 10 Feb 2022)

*

*http://checkip.amazonaws.com/

*https://ipv4.icanhazip.com/

*http://myexternalip.com/raw

*http://ipecho.net/plain

*http://www.trackip.net/ip

*http://bot.whatismyipaddress.com (10 Feb 2022)

*http://curlmyip.com/ (17 Dec 2016)

Piece of advice: Do not direcly depend only on one of them; try to use one but have a contigency plan considering others! The more you use, the better!
Good luck!

A: As @Donal Fellows wrote, you have to query the network interface instead of the machine. This code from the javadocs worked for me:
The following example program lists all the network interfaces and their addresses on a machine:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
}

The following is sample output from the example program:
Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1

Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0

From docs.oracle.com

A: It's not that easy since a machine inside a LAN usually doesn't care about the external IP of its router to the internet.. it simply doesn't need it!
I would suggest you to exploit this by opening a site like http://www.whatismyip.com/ and getting the IP number by parsing the html results.. it shouldn't be that hard!

A: If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.

A: System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));

A:
An alternative solution is to execute an external command, obviously, this solution limits the portability of the application.

For example, for an application that runs on Windows, a PowerShell command can be executed through jPowershell, as shown in the following code:

public String getMyPublicIp() {
    // PowerShell command
    String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
    String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();

    // Connection failed
    if (powerShellOut.contains("InvalidOperation")) {
        powerShellOut = null;
    }
    return powerShellOut;
}


text:
Q: compiling kivy app to apk fail using python-for-android i wrote a hello world test app with python and kivy, and try to package it into apk but it has been showing me this error and i don't understand what's going on.
This is my code:
import kivy
kivy.require('1.11.1')

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    def build(self):
        return Button(text = 'Hello World')

if __name__ in ('__android__', '__main__'):
    MyApp().run()

And i try to compile to apk using this command:
p4a apk --private ./ --package=org.example.easample --name "easample" --version 0.1 --bootstrap=sdl2 --requirements=python3,kivy,pygame

It gives this error message:
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
Exception information:
Traceback (most recent call last):
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 153, in _main
    status = self.run(options, args)
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 382, in run
    resolver.resolve(requirement_set)
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/legacy_resolve.py", line 201, in resolve
    self._resolve_one(requirement_set, req)
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/legacy_resolve.py", line 365, in _resolve_one
    abstract_dist = self._get_abstract_dist_for(req_to_install)
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/legacy_resolve.py", line 313, in _get_abstract_dist_for
    req, self.session, self.finder, self.require_hashes
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/operations/prepare.py", line 224, in prepare_linked_requirement
    req, self.req_tracker, finder, self.build_isolation,
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/operations/prepare.py", line 49, in _get_prepared_distribution
    abstract_dist.prepare_distribution_metadata(finder, build_isolation)
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/distributions/source/legacy.py", line 39, in prepare_distribution_metadata
    self.req.prepare_metadata()
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/req/req_install.py", line 563, in prepare_metadata
    self.metadata_directory = metadata_generator(self)
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/operations/generate_metadata.py", line 124, in _generate_metadata_legacy
    command_desc='python setup.py egg_info',
  File "/home/ea/.local/share/python-for-android/build/venv/lib/python3.6/site-packages/pip/_internal/utils/subprocess.py", line 242, in call_subprocess
    raise InstallationError(exc_msg)
pip._internal.exceptions.InstallationError: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

  STDERR:

Pls i need help


text:
Q: Android Jetpack Compose and Navigation Let's say we have the following code:
NavHost(
        navController = navController,
        startDestination = FRAGMENT_ONE
    ) {
        composable(FRAGMENT_ONE) {
            FragmentOneScreen()
        }
        composable(FRAGMENT_TWO) {
            FragmentTwoScreen()
        }
        composable(FRAGMENT_THREE) {
            FragmentThreeScreen()
        }
    }

FragmentOneScreen, FragmentTwoScreen, and FragmentThreeScreen are methods annotated with @composable, and NavHost code is placed in MainActivity's onCreate method.
My questions are:

*

*are FragmentOneScreen, two, and three fragments?

*if the answer to the previous question is YES, is this the right way to implement navigation between fragments (no need to create three classes that extend androidx.fragment class, etc and in their onCreateView method to return ComposeView)

I need some help with this because I am having a hard time grasping these questions.

A: They are composables.
NavHost(navController = navController, startDestination = SCREEN_ONE) {
    composable(SCREEN_ONE) {
        ScreenOne()
    }
    composable(SCREENT_TWO) {
        ScreenTwo()
    }
    composable(SCREEN_THREE) {
        ScreenThree()
    }
}

Rename fragment to screen or some other terms to avoid confusion.
Navigation can be done like this,
navController.navigate("friends")

Refer Docs for more detailed explaination


text:
Q: ASP.NET MVC can't find my namespace I'm developing a simple blog system and I'm stuck on a position. I want to refer an external library Components, where I have Article class. Trying to set the type of the model in the view @model Components.Article I', receiving an error telling me that I'm missing some assembly (I've already refer it in References). Tried to use @using Components before the module - same result - CS0246: The type or namespace name 'Components' could not be found (are you missing a using directive or an assembly reference?) Any ideas how can I fix that?

A: Open the web.config file in your Views folder, and make sure it has the following:
<system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
<add namespace="Your.Namespace.Components" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>

A: When you add a folder to your solution and want to make reference to it by @using sometimes you need to Build your solution again so that this error goes away, in other words you need to refresh your solution folders.


text:
Q: Combinational loops in HDLs This is just an experiment I'm trying to wrap my brain around.
So I've got two registers r1 r2 and two wires w1 w2.  What I want is, if both r's are 1, both w's should be 1.  If one r is 1, the corresponding w should be 1 and the other should be 0.  If both r's are 0, w1 should be 1 and w2 should be 0.
11=>11
10=>10
01=>01
00=>10
The caveat is I want the assign for w1 not to include r2 directly, and vice versa.  So, I've got (in Verilog for instance--a VHDL answer would be perfectly fine too)
assign w1 = r1 | !w2;
assign w2 = r2 | !w1;

Which is necessary but not sufficient.  All the cases above are true, but 00=>01 is also true.  In fact when r1=r2=0, it just creates a cycle of wires without a driver, so I think the result is non-deterministic.
Is there any way to get the result I'm looking for without including r2 in the assignment for w1, or vice versa?  (And without introducing new variables).  Basically just to ensure that in a wire-cycle, w1 is pulled high and w2 pulled low?

A: No, I think there is no clean way to do this without extra wires/signals and without your cross dependency.
By the way, your "cyclical wires" are commonly referred to as a combinational loops and it is a good practice to avoid these.

*

*As for the simulation of a VHDL model with combinational loop, the result is deterministic provided the simulator converges to a stable point, ie no more signal value change. If signal values continuously change, then you are likely to reach your simulator's iteration limit. I don't know for Verilog but I assume it is deterministic as well.

*As for synthesis, tools with either reject this construct and raise an error, or try to handle this, with a possible very bad impact on timing.

Again, even if your simulation is ok and your synthesis tool allows this, combinational loops should be avoided.

A: What you have currently is very similar to an SR latch, and as such it has a metastable condition (also known as a race condition).
From your truth table above though, it looks like w2 should be set only to r2.
assign w2 = r2;
That change should fix your race condition; though as expressed above, be wary of the large restrictions created by combinational logic.


text:
Q: Changing Horse Attributes I have been making a plugin for a "portable horse" recently and I am very close to being done, my horses spawn in and despawn as I want them. However, the only thing that I am having a considerable amount of trouble with is changing Horse attributes like speed, color, jump height and Variant.
Here is my Code:
package io.github.bxnie.events;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Donkey;
import org.bukkit.entity.Horse;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.inventory.ItemStack;

public class HorseSpawn implements Listener {

    @SuppressWarnings({ "deprecation" })
    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent e) {
        if(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK){
            Player p = e.getPlayer();
            ItemStack item = e.getItem();

            if(item.getItemMeta().getDisplayName().equals(ChatColor.GRAY + "Donkey")) {
                Donkey donkey = (Donkey) p.getWorld().spawn(p.getLocation(), Donkey.class);
                donkey.setAdult();
                donkey.setTamed(true);
                donkey.setOwner(p);
                donkey.getInventory().setSaddle(new ItemStack(Material.SADDLE));
                donkey.setCustomName(ChatColor.GRAY + "Donkey");
                donkey.setPassenger(p);
            }

            if(item.getItemMeta().getDisplayName().equals(ChatColor.RED + "Brown Horse")) {
                Horse horsebrown = (Horse) p.getWorld().spawn(p.getLocation(), Horse.class);
                horsebrown.setAdult();
                horsebrown.setTamed(true);
                horsebrown.setOwner(p);
                horsebrown.getInventory().setSaddle(new ItemStack(Material.SADDLE));
                horsebrown.setCustomName(ChatColor.RED + "Horse");
                horsebrown.setPassenger(p);
            }

            if(item.getItemMeta().getDisplayName().equals(ChatColor.DARK_GRAY + "Black Horse")) {
                Horse horseblack = (Horse) p.getWorld().spawn(p.getLocation(), Horse.class);
                horseblack.setAdult();
                horseblack.setTamed(true);
                horseblack.setOwner(p);
                horseblack.getInventory().setSaddle(new ItemStack(Material.SADDLE));
                horseblack.setCustomName(ChatColor.DARK_GRAY + "Horse");
                horseblack.setPassenger(p);
            }

            if(item.getItemMeta().getDisplayName().equals(ChatColor.WHITE + "White Horse")) {
                Horse horsewhite = (Horse) p.getWorld().spawn(p.getLocation(), Horse.class);
                horsewhite.setAdult();
                horsewhite.setTamed(true);
                horsewhite.setOwner(p);
                horsewhite.getInventory().setSaddle(new ItemStack(Material.SADDLE));
                horsewhite.setCustomName(ChatColor.WHITE + "Horse");
                horsewhite.setPassenger(p);
            }
        }
    }
    @EventHandler
    public void onPLayerDismount(VehicleExitEvent e) {
        if(e.getExited() instanceof Player) {
            if(e.getVehicle() instanceof Donkey) {
                Donkey donkey = (Donkey) e.getVehicle();
                if(donkey.getCustomName() != null) {
                    if(donkey.getCustomName().equals(ChatColor.GRAY + "Donkey")) {
                        donkey.remove();
                    }
                }
            }
            if(e.getVehicle() instanceof Horse) {
                Horse horse = (Horse) e.getVehicle();
                if(horse.getCustomName() != null) {
                    if(horse.getCustomName().equals(ChatColor.RED + "Horse")) {
                        horse.remove();
                    }
                    if(horse.getCustomName().equals(ChatColor.DARK_GRAY + "Horse")) {
                        horse.remove();
                    }
                    if(horse.getCustomName().equals(ChatColor.WHITE + "Horse")) {
                        horse.remove();
                    }
                }
            }
        }
    }
}

I've done a ton of research but nothing really seems to help my case, is there any way that any of you know of to spawn in a horse with the custom attributes I mentioned above?

A: When you believe you've researched enough, research a little more, I searched for "bukkit change horse speed" and one of the top answers works perfectly. With that being said, let's try to solve your issue.
Everything you need is right in the horse API, more specifically #setColor(), #setStyle(), #setJumpStrength and #setVariant(). Changing variant may not work using that method due to deprecation, instead you need to create a different entity, such as a skeletonHorse
These methods are really straightforward:
Horse horseblack = (Horse) p.getWorld().spawn(p.getLocation(), Horse.class);
horseblack.setJumpStrength(2.0);
horseblack.setColor(Color.BLACK);

SkeletonHorse skeletonHorse = (SkeletonHorse) p.getWorld().spawn(p.getLocation(), SkeletonHorse.class);

Changing speed is a little different, but the method works for any mobs.
entity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED).setBaseValue(yourValue);


text:
Q: How to combine many records value into one record As you can see from the below picture I was able to combine two deals (blocked red) but the output should have one result instead of two. If anyone has any solutions on this please advise.

The red blocked component has more than one record, each record has an amount, the sum of all record amount must be shown in a single row.
record1: Amount:100
record2: Amount:200
record3: Amount:500

Merge of all records is following
record: Amount:800

Is it possible to merge many rows into a single row in integromat?

A: Based on your screenshot you aggregate an incorrect module. Source module in your aggregator has to be set to a module that generates multiple modules, in your case, it is module 10.
You aggregate module 14 that generates for every input module a single output module, there is nothing to aggregate. Module 10 returns for a single input 2 bundles.
Your case:
       /---[6]---([14]---[11 aggregator])---
---[10]                                       multiple output bundles
       \---[6]---([14]---[11 aggregator])---

Solution:
        /---[6]---[14]---\
---([10]                  [11 aggregator])--- single output bundle
        \---[6]---[14]---/

Your scenario has to look like this (Aggregator: Source module = module no.10):


text:
Q: Change a component props based on another Problem :
I  need to change two components based on an onclick event. The function displayed on the onclick event handleChange has a prop 'text' . I need to change the value of the prop 3 times whenever I run the onclick event.
1.
I have a chip component(first component) which I want to change its text and color whenever my button(second component) it's clicked; the button will change its text as well. So I did with conditional rendering and my onclick event in my button.
The thing here is that I have 3 states in which I want to change my chip and button, but only can make it with two :
-default value which I apply when creating the state const with useState:
const [change, setChange] = useState("Pending");

-the value I pass to the event in the button:
<Button variant="contained" onClick={() => handleChange("hello")}>

2.
Besides the first button I have another button which I want to hide whenever my third state of chip changes.
I have 3 states : hello,pending,cancel.
When  first button and chip change to cancel I want to hide my third button.
I tried to make a switch statement to solve the problem of the 3 states but I don't know how to use it. I don't know how to pass the 3 values(hello,pending,cancel.) inside the button either.
Here is my code example
Note: I am new in code sandbox so please tell me is you see the changes bcs I don't manage well enough the platform

A: Assuming your three states are in order
const state = ["pending", "hello", "cancel"];
const [change, setChange] = useState(0);

function handleChange() {
  setChange(prevState => prevState === 2 ? 0 : prevState + 1);
}

const style = [
  {color: 'secondary'},
  {color: 'primary'},
  {style: {backgroundColor:"#7ed6df"}}
];

return (
  <>
    <Chip label={state[change]} {...style[change]} />
    <Button variant="contained" onClick={handleChange}>
      {state[change]}
    </Button>
    {change !== 2 && <Button variant="contained">Disappear</Button>}
  </>
);


text:
Q: ¿Existe una forma posible de usar el case del switch como "case (rango de números)"? La forma en que lo digité en el título es obviamente errónea, pero es para que entiendan a lo que me refiero. Normalmente un switch case 1, el case siempre obedece a un entero, pero qué pasa si quiero un case que lea un rango de enteros posibles dentro de la variable del switch, por ejemplo
switch(edad())
     case (edad()>=1)

Aquí un ejemplo en código fácil de lo que me refiero.
switch(edadGato())
    {
    case 1:
        cout<<"Al gato le corresponde la vacuna de la Rabia";
        break;
    case 3:
        cout<<"Al gato le corresponde la vacuna de la Panleucopenia";
        break;
    default:
        cout<<"Basado en la edad, al gato no le corresponde ninguna edad";
        break;
    }

Si la edad fuese 2, no me detectaría que ya tendría una vacuna pendiente por tener más de un año (case 1), por eso, mi duda sobre si existe una forma algo como case (rango de números).
Nota: Sé que con if es más fácil, pero si en switch es posible, compártanlo conmigo. Gracias de antemano.

A: No es posible ... con un pequeño matiz: el break es opcional:
switch( edadGato( ) ) {
case 3:
  cout << "Al gato le corresponde la vacuna de la Panleucopenia.\n";

case 2:
  cout << "Al gato le falta una, que no se cual es.\n";

case 1:
  cout << "Al gato le corresponde la vacuna de la Rabia.\n";
  break;

default:
  cout << "Basado en la edad, al gato no le corresponde ninguna vacuna.\n";
  break;
}

Aunque hay otras formas, mas aptas en el caso de que sean muchos los valores ... solo hay que dejar volar la imaginación :-)
#include <vector>
#include <string>
#include <iostream>
#include <unordered_map>

const std::unordered_map< int, std::vector< std::string > > VacunasPorEdad{
  { 1, { "Rabia" } },
  { 2 , { "Desconocido" } },
  { 3, { "Panleucopenia", "Desconocido2" } }
};
constexpr int EDAD_MAXIMA = 3;

std::vector< const std::string * > generarListaVacunas( int edad ) {
  std::vector< const std::string * > result;

  for( int idx = 1; ( idx <= edad ) && ( idx <= EDAD_MAXIMA ); ++idx ) {
    const auto mapIter = VacunasPorEdad.find( idx );

    if( mapIter != VacunasPorEdad.cend( ) ) {
      for( const auto &iter : mapIter->second ) {
        result.push_back( &iter );
      }
    }
  }

  return result;
}

int main( ) {
  int edad;

  std::cout << "Edad del gato: ";
  std::cin >> edad;

  auto lista = generarListaVacunas( edad );

  std::cout << "\nLista de vacunas pendiente:\n";
  for( auto ptr : lista ) {
    std::cout << " * " << *ptr << ".\n";
  }

  return 0;
}


text:
Q: PHP - How can I replace after the 2nd occurrence of a tab I have a string like this, with several tabs in it.  I need to replace a single digit, it will always be the digit after the 2nd tab.  The numbers before that could be different lengths, so I can't simply replace after 10 digits or something like that.  It has to be after the 2nd tab.   the new string will be exactly the same except for that one digit.  example...
222[TAB]55555[TAB]9[TAB]hello[TAB]byebye[TAB]444
change to
222[TAB]55555[TAB]2[TAB]hello[TAB]byebye[TAB]444

A: $input = "222\t55555\t9\thello\tbyebye\t444";

$parts = explode("\t", $input);
$parts[2] = 2;
$output = implode("\t", $parts);

var_dump($output);

Or:
$input = "222\t55555\t9\thello\tbyebye\t444";

$parts = str_getcsv($input, "\t");
$parts[2] = 2;
$output = implode("\t", $parts);

var_dump($output);

Output:
string(28) "222 55555   2   hello   byebye  444"

str_getcsv() being more useful if your data includes encapsulated strings, line breaks, etc.

A: To replace the integer value after the second occurring tab, match the first occuring tab, then one or more non-tab characterss, then the second tab, then forget all of those matched characters with \K, then match the one or more digit number.  Replace the matched number with the new desired value.  Limit the number of replacements to one.
This is more direct than exploding or parsing the entire string just to change one value.
Code: (Demo)
$string = "222\t55555\t9\thello\tbyebye\t444";
$newInt = 2;
var_export(
    preg_replace("/\t[^\t]+\t\K\d+/", $newInt, $string, 1)
);


text:
Q: How to rearranging the components of sequence according to permutation? I have a sequence r and i need to rearanging the components of r according to the permutation k to obtain the sequence :
y = [y0 y1 y2 y3 y4 y5 y6 y7] with
abs(y0) > abs(y1) > abs(y2) > abs(y3) > abs(y4) and  abs(y5) > abs(y6) > abs(y7)
Example :
r = [-2.3 2.1 2.0 -1.4 1.2 0.5 -0.02] and k = [1 2 3 5 4 6 7]
So
y = [-2.3 2.1 2.0 1.2 -1.4 0.5 -0.02]

I used this command but I can not find the sequence searched :
[~,k] = sort(abs(r),'descend');
 y = r(k);

A: Apparently this is only valid in newer MATLAB versions, but if you have one (not sure when it was introduced, but above 2014b for sure) this will work:
y=sort(r,'direction','descend','ComparisonMethod','abs')


text:
Q: Instance method inheritance Is there a way to declare inheritance for a method of an instance.
//SOME CLASS
class SomeClass{
    someMethod{
        //SOMETHING HAPPENS
    }
}
function myComponent(){
    this.subcomponents={
        popup:function(){
            //SOMETHING HAPPENS
        }
    }
    this.init=()=>{
        //NEW INSTANCE OF SUBCOMPONENT POPUP
        var popup = new this.subcomponents.popup();
        //DESIRED RESULT WOULD BE ABLE TO CALL
        popup.someMethod();
    }
}
//myComponent inherits someMethod()
myComponent.prototype = new SomeClass();
//IS THERE ANYWAY TO ASSIGN INHERITANCE TO SUBMETHODS OF AN INSTANCE
myComponent.subcomponents.popup.prototype = new SomeClass();

Desired output would be to have the new instance of the method popup with inheritance of SomeClass so I would be able to call popup.someMethod().
Question: How can I assign popup method, inheritance of SomeClass so I could call popup.someMethod()?

A: If i understand correctly, you want to somehow use the someMethod function in SomeClass and apply that to popup. In order to do that you don't need to mess with prototype chains and inheritance.
Ie
SomeClass.prototype.someMethod.call(popup, arguments)

This will take someMethod, and change the value of 'this' to popup and execute it with whatever arguments you provide


text:
Q: Configuring iptables rule I have private cloud with eucalyptus and xen. Generally while creating an instance, eucalyptus tries to contact meta data service at 169.254.169.254. But here in my setup, the service is running at 192.168.1.10. Now I want to forward all request to this ip.
I want to create pre routing rule to forward all packets from 169.254.169.254/32 (port 80) to 192.168.1.10:8773.

A: iptables -t nat -A PREROUTING -p tcp -d 169.254.169.254/32 --dport 80 -j DNAT --to-destination 192.168.1.10:8773

This is the rule you have to place in Iptables.
hope that helps.


text:
Q: Function won't work when using a list created from a file I am trying to create a list of words from a file is being read as then delete all words that contain duplicate letters. I was able to do it successfully with a list of words that I entered however when I try to use the function on the list created from a file the function still includes words with duplicates.
This works:
words = ['word','worrd','worrrrd','wordd']
alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
x = 0
while x in range(0, len(alpha)):
    i = 0
    while i in range(0, len(words)):
        if words[i].count(alpha[x]) > 1:
            del(words[i])
            i = i - 1
        else:
            i = i + 1
    x = x + 1
print(words)

This is how I'm trying to do it when reading the file:
words = []
length = 5
file = open('dictionary.txt')
for word in file:
    if len(word) == length+1:
        words.append(word.splitlines())

alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
x = 0
while x in range(0, len(alpha)):
    i = 0
    while i in range(0, len(words)):
        if words[i].count(alpha[x]) > 1:
            del(words[i])
            i = i - 1
        else:
            i = i + 1
    x = x + 1
print(words)

A: Try something like this. First, the string module is not quite deprecated, but it's unpopular. Lucky for you, it defines some useful constants to save you a bunch of typing. So you don't have to type all those quotes and commas.
Next, use the with open('filespec') as ... context for reading files: it's what it was put there for!
Finally, be aware of how iteration works for text files: for line in file: reads lines, including any trailing newlines. Strip those off. If you don't have one-word-per-line, you'll have to split the lines after you read them.
# Read words (possibly >1 per line) from dictionary.txt into lexicon[].
# Convert the words to lower case.

import string

Lexicon = []

with open('dictionary.txt') as file:
    for line in file:
        words = line.strip().lower().split()
        Lexicon.extend(words)

for ch in string.ascii_lowercase:
    for i in range(len(Lexicon)):
        word = Lexicon[i]

        if word.count(ch) > 1:
            del Lexicon[i]
            i -= 1

print('\n'.join(Lexicon))

A: How about this:
#This more comprehensive sample allows me to reproduce the file-reading
#  problem in the script itself (before I changed the code "tee" would
#  print,  for instance)
words = ['green','word','glass','worrd','door','tee','wordd']
outlist = []

for word in words:
    chars = [c for c in word]
    # a `set` only contains unique characters, so if it is shorter than the
    #  `word` itself, we found a word with duplicate characters, so we keep
    #  looping
    if len(set(chars)) < len(chars):
        continue
    else:
        outlist.append(word)
print(outlist)

Result:
['word']

A: import string

words = ['word','worrd','worrrrd','wordd','5word']

new_words = [x for x in words if len(x) == len(set(x)) if all(i in string.ascii_letters for i in x)]

print(new_words)


text:
Q: how to show iframe with JQUERY I make a simple project where I would like show iframe with method .show() of jQuery, I show on main site of jQuery and I try to do this:

$(function() {
  // run the currently selected effect
  function runEffect() {
    // get effect type from
    var selectedEffect = $( "#effectTypes" ).val();

    // most effect types need no options passed by default
    var options = {};
    // some effects have required parameters
    if ( selectedEffect === "scale" ) {
      options = { percent: 100 };
    } else if ( selectedEffect === "size" ) {
      options = { to: { width: 280, height: 185 } };
    }

    // run the effect
    $( "#effect" ).show( "blind", options, 500, callback );
  };

  //callback function to bring a hidden box back
  function callback() {
    setTimeout(function() {
      $( "#effect:visible" ).removeAttr( "style" ).fadeOut();
    }, 1000 );
  };

  // set effect from select menu value
  $( "#button" ).click(function() {
    runEffect();
  });
});
<link rel="stylesheet" href="css/style.css"/>

Sorveglianza RaspiCam

<button id="button" class="ui-state-default ui-corner-all">Run Effect</button>

But the button don't work and iframe is ever visible, where I wrong?
thanks,
Daniel.

A: 1- Style sheet link was incorrect.
2- The $(function() dose not closed.
the below code should work:

    <title>RaspiCam</title>
      <link rel="stylesheet" type="text/css" href="css/style.css">

Sorveglianza RaspiCam

        <button id="button" class="ui-state-default ui-corner-all">Run Effect</button>


text:
Q: Xamarin Studio - How to change startup code? Is there a way to change the startup code in Xamarin Studio?
It's starting to bother me the startup code, I don't need most of the code
Xamarin Studio 6.0.2
Change from this:
namespace App2
{
    [Activity(MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        int count = 1;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.myButton);

            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
        }
    }
}

to this:
namespace App1
{
    [Activity(MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);
        }
    }
}

I checked the Code Templates inside Options, but those are snippets
If so, how?

A: After some digging in my Xamarin Studio install folder I found what I was looking for...
If someone is interested, here are the startup code templates route
MainActivity.cs
Main.axml

C:\Program Files (x86)\Xamarin
  Studio\AddIns\MonoDevelop.MonoDroid\templates\Project\AndroidApp

Just don't forget to make a copy of the original files

A: You should try following url, as per your question you are reloading the state when application come from the background, so in this case you have to override methods and have to write the code. For this please follow following link.
https://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/


text:
Q: An example of how to implement firebase-auth in Polymer 1.0? I'm a bit lost on how to implement the firebase-auth element. Any examples would be appreciated, I haven't managed to find any yet.
Thanks

A: I ended up getting auth to work by adapting this example element by HackITtoday for my firebase urls. It's as simple as adding the element like:
<hi9-login></hi9-login>

A: On this question, Glenn Vandeuren posts the following:

Element
<!--
@license
Copyright (c) 2015 Glenn Vandeuren. All rights reserved.
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../paper-button/paper-button.html">

<dom-module id="login-button">

  <style>
    :host {
      display: block;
      box-sizing: border-box;
    }
  </style>

  <template>
    <paper-button raised>Login using <span>[[service]]</span></paper-button>
  </template>

</dom-module>

<script>

  Polymer({

    is: 'login-button',

    properties: {
      service: String
    },

    listeners: {
      'tap': '_handleTap'
    },

    _handleTap: function () {
      this.fire('login', this.service);
    }

  });

</script>

Index
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
    <title>login-button Demo</title>
    <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="../login-button.html">
  </head>
  <body>

    <login-button service="google"></login-button>
    <login-button service="twitter"></login-button>

    <script>
      document.addEventListener('login', function(service) {
        // handleLogin();
        alert(service.detail);
      });
    </script>

  </body>
</html>