text:
Q: Ranking results from a SUMMARIZECOLUMNS operation I created the following DAX code in DAX Studio which works correctly:
EVALUATE
    SUMMARIZECOLUMNS(
        'Florida Sightings'[Locality Id],
        Hotspot[Subnational 1 Code],
        Hotspot[Name],
        'Calendar'[Month],

        FILTER(Hotspot, Hotspot[Subnational 1 Code] = "US-FL"),

        "Species Count", COUNTROWS(VALUES('Florida Sightings'[Common Name]))
        )

The output looks like this, sorted by month and species count:

I would like to take the results of the SUMMARIZECOLUMNS and add a rank column based on species count for each locality Id and month. So, for the first locality Id (L127258) and Month (1), the rank would be 1. And, for the second locality Id (L123565) and month (1), the rank would be 2 etc.
The months run from 1 through 12 for each locality.

A: Without sample data to work with, I'm shooting in the dark a bit but try something along these lines:
ADDCOLUMNS (
    SummaryTable,
    "Rank", RANKX (
        FILTER (
            SummaryTable,
            [Locality Id] = EARLIER ( 'Florida Sightings'[Locality Id] )
               && [Month] = EARLIER ( 'Calendar'[Month] )
        ),
        [Species Count]
    )
)


text:
Q: How to choose GPU when running phoronix-test-suite benchmark? I am new to Phoronix Test Suite and ran my first test with phoronix-test-suite benchmark testname. This ran the test for one of my GPUs but not the other. How can I choose which GPU to use for the benchmark?
I've searched Google and skimmed the documentation for an answer but found nothing.
EDIT
The test I am trying to run is here, using
phoronix-test-suite benchmark 2102179-HA-NVIDIAGEF76

I've also tried using the method described here but to no avail.
I am using Phoronix Test Suite v10.2.2 (Harstad) on Ubuntu 20.04.2 LTS.
UPDATE
According to this issue, phoronix-test-suite always chooses the default GPU on a given system.

PTS currently sticks to using the default GPU configured by your system whether it be configured via PRIME handling or other multi-GPU setup configurations. Basically, it doesn't override your default GPU choice(s) or interfere beyond simply reporting the enumerated GPUs.

So the official way to change the GPU utilized by a phoronix benchmark is to change the 'default GPU' on the broader system. I don't understand what determines which GPU is the default or how to change the default. The above quote indicates that the default GPU might be changed using PRIME.
When running nvidia-settings the following message is printed.

** (nvidia-settings:9809): WARNING **: 15:46:41.950: PRIME: Failed to execute child process "/usr/bin/prime-supported" (No such file or directory)
** Message: 15:46:41.950: PRIME: is it supported? no

So it seems that whatever PRIME is, it's not part of my system.

A: As you were looking to configure an Nvidia GPU, the logic is slightly different:
looking at the source, PTS seems to always use the first GPU it can find on nvidia-settings --query PCIID output.
This theory has been further confirmed by PTS lead developer on github. So unfortunately there's no switch in PTS that would help achieve that.

A: This can be done if you are using a Nividea GPU you can go to the Nividea control panel:

*

*Go to Manage 3D settings

*Go to "Program Settings"

*Select your app (i.e in this case Phoronix-test-suite benchmark) and select the high-performance Nividea GPU.

Now run the benchmark test. <---- For Windows
for more help visit: https://www.phoronix-test-suite.com/documentation/phoronix-test-suite.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: unable to figure jboss error can someone figure out whats the error in jboss. when i enter localhost:8080 in url it says INVALID REQUEST. PLEASE CHECK URL.
I am using jboss 5.0.1
JBOSS_HOME: D:\Jboss\jboss-5.0.1.GA
JAVA: C:\Program Files\Java\jdk1.6.0_13\bin\java
JAVA_OPTS: -Dfile.encoding=UTF-8 -Dprogram.name=run.bat -server -Xms512m -Xmx1024m -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000
CLASSPATH: D:\Jboss\jboss-5.0.1.GA\bin\run.jar
===============================================================================

20:46:16,640 INFO  [ServerImpl] Starting JBoss (Microcontainer)...
20:46:16,640 INFO  [ServerImpl] Release ID: JBoss [Morpheus] 5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)
20:46:16,640 INFO  [ServerImpl] Bootstrap URL: null
20:46:16,656 INFO  [ServerImpl] Home Dir: D:\Jboss\jboss-5.0.1.GA
20:46:16,656 INFO  [ServerImpl] Home URL: file:/D:/Jboss/jboss-5.0.1.GA/
20:46:16,656 INFO  [ServerImpl] Library URL: file:/D:/Jboss/jboss-5.0.1.GA/lib/
20:46:16,656 INFO  [ServerImpl] Patch URL: null
20:46:16,656 INFO  [ServerImpl] Common Base URL: file:/D:/Jboss/jboss-5.0.1.GA/common/
20:46:16,656 INFO  [ServerImpl] Common Library URL: file:/D:/Jboss/jboss-5.0.1.GA/common/lib/
20:46:16,656 INFO  [ServerImpl] Server Name: default
20:46:16,656 INFO  [ServerImpl] Server Base Dir: D:\Jboss\jboss-5.0.1.GA\server
20:46:16,671 INFO  [ServerImpl] Server Base URL: file:/D:/Jboss/jboss-5.0.1.GA/server/
20:46:16,671 INFO  [ServerImpl] Server Config URL: file:/D:/Jboss/jboss-5.0.1.GA/server/default/conf/
20:46:16,671 INFO  [ServerImpl] Server Home Dir: D:\Jboss\jboss-5.0.1.GA\server\default
20:46:16,671 INFO  [ServerImpl] Server Home URL: file:/D:/Jboss/jboss-5.0.1.GA/server/default/
20:46:16,671 INFO  [ServerImpl] Server Data Dir: D:\Jboss\jboss-5.0.1.GA\server\default\data
20:46:16,671 INFO  [ServerImpl] Server Library URL: file:/D:/Jboss/jboss-5.0.1.GA/server/default/lib/
20:46:16,671 INFO  [ServerImpl] Server Log Dir: D:\Jboss\jboss-5.0.1.GA\server\default\log
20:46:16,671 INFO  [ServerImpl] Server Native Dir: D:\Jboss\jboss-5.0.1.GA\server\default\tmp\native
20:46:16,687 INFO  [ServerImpl] Server Temp Dir: D:\Jboss\jboss-5.0.1.GA\server\default\tmp
20:46:16,687 INFO  [ServerImpl] Server Temp Deploy Dir: D:\Jboss\jboss-5.0.1.GA\server\default\tmp\deploy
20:46:17,296 INFO  [ServerImpl] Starting Microcontainer, bootstrapURL=file:/D:/Jboss/jboss-5.0.1.GA/server/default/conf/bootstrap.xml
20:46:17,859 INFO  [VFSCacheFactory] Initializing VFSCache [org.jboss.virtual.plugins.cache.CombinedVFSCache]
20:46:17,859 INFO  [VFSCacheFactory] Using VFSCache [CombinedVFSCache[real-cache: null]]
20:46:18,140 INFO  [CopyMechanism] VFS temp dir: D:\Jboss\jboss-5.0.1.GA\server\default\tmp
20:46:18,156 INFO  [ZipEntryContext] VFS force nested jars copy-mode is enabled.
20:46:20,218 INFO  [ServerInfo] Java version: 1.6.0_13,Sun Microsystems Inc.
20:46:20,234 INFO  [ServerInfo] Java Runtime: Java(TM) SE Runtime Environment (build 1.6.0_13-b03)
20:46:20,234 INFO  [ServerInfo] Java VM: Java HotSpot(TM) Server VM 11.3-b02,Sun Microsystems Inc.
20:46:20,234 INFO  [ServerInfo] OS-System: Windows XP 5.1,x86
20:46:20,265 INFO  [JMXKernel] Legacy JMX core initialized
20:46:22,593 INFO  [ProfileServiceImpl] Loading profile: default from: org.jboss.system.server.profileservice.repository.SerializableDeploymentRepository@126c5a5(root=D:\Jboss\jboss-5.0.1.GA\server, key=org.jboss.profileservice.spi.Pro
fileKey@143b82c3[domain=default,server=default,name=default])
20:46:22,593 INFO  [ProfileImpl] Using repository:org.jboss.system.server.profileservice.repository.SerializableDeploymentRepository@126c5a5(root=D:\Jboss\jboss-5.0.1.GA\server, key=org.jboss.profileservice.spi.ProfileKey@143b82c3[doma
in=default,server=default,name=default])
20:46:22,593 INFO  [ProfileServiceImpl] Loaded profile: ProfileImpl@1e779a7{key=org.jboss.profileservice.spi.ProfileKey@143b82c3[domain=default,server=default,name=default]}
20:46:24,421 INFO  [WebService] Using RMI server codebase: http://127.0.0.1:9283/
20:46:30,656 INFO  [NativeServerConfig] JBoss Web Services - Stack Native Core
20:46:30,671 INFO  [NativeServerConfig] 3.0.5.GA
20:46:42,218 INFO  [JMXConnectorServerService] JMX Connector server: service:jmx:rmi://127.0.0.1/jndi/rmi://127.0.0.1:2290/jmxconnector
20:46:42,375 INFO  [MailService] Mail Service bound to java:/Mail
20:46:44,015 WARN  [JBossASSecurityMetadataStore] WARNING! POTENTIAL SECURITY RISK. It has been detected that the MessageSucker component which sucks messages from one node to another has not had its password changed from the installat
ion default. Please see the JBoss Messaging user guide for instructions on how to do this.
20:46:44,031 WARN  [AnnotationCreator] No ClassLoader provided, using TCCL: org.jboss.managed.api.annotation.ManagementComponent
20:46:44,203 INFO  [TransactionManagerService] JBossTS Transaction Service (JTA version) - JBoss Inc.
20:46:44,203 INFO  [TransactionManagerService] Setting up property manager MBean and JMX layer
20:46:44,656 INFO  [TransactionManagerService] Initializing recovery manager
20:46:44,843 INFO  [TransactionManagerService] Recovery manager configured
20:46:44,843 INFO  [TransactionManagerService] Binding TransactionManager JNDI Reference
20:46:44,875 INFO  [TransactionManagerService] Starting transaction recovery manager
20:46:45,453 INFO  [Http11Protocol] Initializing Coyote HTTP/1.1 on http-127.0.0.1-8080
20:46:45,453 INFO  [AjpProtocol] Initializing Coyote AJP/1.3 on ajp-127.0.0.1-8218
20:46:45,453 INFO  [StandardService] Starting service jboss.web
20:46:45,453 INFO  [StandardEngine] Starting Servlet Engine: JBoss Web/2.1.2.GA
20:46:45,531 INFO  [Catalina] Server startup in 146 ms
20:46:45,562 INFO  [TomcatDeployment] deploy, ctxPath=/invoker
20:46:46,156 INFO  [TomcatDeployment] deploy, ctxPath=/jbossws
20:46:46,203 INFO  [TomcatDeployment] deploy, ctxPath=/web-console
20:46:46,265 INFO  [[/web-console]] SystemFolder: Failed to init plugin, Resource not found: SystemFolder.bsh
20:46:46,296 INFO  [[/web-console]] J2EEFolder: Failed to init plugin, Resource not found: J2EEFolder.bsh
20:46:46,421 INFO  [RARDeployment] Required license terms exist, view vfszip:/D:/Jboss/jboss-5.0.1.GA/server/default/deploy/jboss-local-jdbc.rar/META-INF/ra.xml
20:46:46,531 INFO  [RARDeployment] Required license terms exist, view vfszip:/D:/Jboss/jboss-5.0.1.GA/server/default/deploy/jboss-xa-jdbc.rar/META-INF/ra.xml
20:46:46,578 INFO  [RARDeployment] Required license terms exist, view vfszip:/D:/Jboss/jboss-5.0.1.GA/server/default/deploy/jms-ra.rar/META-INF/ra.xml
20:46:46,609 INFO  [RARDeployment] Required license terms exist, view vfszip:/D:/Jboss/jboss-5.0.1.GA/server/default/deploy/mail-ra.rar/META-INF/ra.xml
20:46:46,640 INFO  [RARDeployment] Required license terms exist, view vfszip:/D:/Jboss/jboss-5.0.1.GA/server/default/deploy/quartz-ra.rar/META-INF/ra.xml
20:46:46,796 INFO  [SimpleThreadPool] Job execution threads will use class loader of thread: main
20:46:46,843 INFO  [QuartzScheduler] Quartz Scheduler v.1.5.2 created.
20:46:46,843 INFO  [RAMJobStore] RAMJobStore initialized.
20:46:46,843 INFO  [StdSchedulerFactory] Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
20:46:46,843 INFO  [StdSchedulerFactory] Quartz scheduler version: 1.5.2
20:46:46,843 INFO  [QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
20:46:47,531 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=DefaultDS' to JNDI name 'java:DefaultDS'
20:46:48,062 INFO  [ServerPeer] JBoss Messaging 1.4.1.GA server [0] started
20:46:48,296 INFO  [ConnectionFactory] Connector bisocket://127.0.0.1:4657 has leasing enabled, lease period 10000 milliseconds
20:46:48,296 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@3dc250 started
20:46:48,359 INFO  [ConnectionFactory] Connector bisocket://127.0.0.1:4657 has leasing enabled, lease period 10000 milliseconds
20:46:48,359 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@188ef97 started
20:46:48,406 INFO  [QueueService] Queue[/queue/A] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,406 INFO  [QueueService] Queue[/queue/ex] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,406 INFO  [QueueService] Queue[/queue/ExpiryQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,406 INFO  [QueueService] Queue[/queue/B] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,406 INFO  [QueueService] Queue[/queue/C] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,421 WARN  [ConnectionFactoryJNDIMapper] supportsFailover attribute is true on connection factory: jboss.messaging.connectionfactory:service=ClusteredConnectionFactory but post office is non clustered. So connection factory wil
l *not* support failover
20:46:48,421 WARN  [ConnectionFactoryJNDIMapper] supportsLoadBalancing attribute is true on connection factory: jboss.messaging.connectionfactory:service=ClusteredConnectionFactory but post office is non clustered. So connection factor
y will *not* support load balancing
20:46:48,421 INFO  [ConnectionFactory] Connector bisocket://127.0.0.1:4657 has leasing enabled, lease period 10000 milliseconds
20:46:48,421 INFO  [ConnectionFactory] org.jboss.jms.server.connectionfactory.ConnectionFactory@2de670 started
20:46:48,421 INFO  [QueueService] Queue[/queue/D] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,421 INFO  [QueueService] Queue[/queue/MailQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,421 INFO  [TopicService] Topic[/topic/testDurableTopic] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,421 INFO  [QueueService] Queue[/queue/DLQ] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,437 INFO  [TopicService] Topic[/topic/securedTopic] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,437 INFO  [QueueService] Queue[/queue/testQueue] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,437 INFO  [TopicService] Topic[/topic/testTopic] started, fullSize=200000, pageSize=2000, downCacheSize=2000
20:46:48,640 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=JmsXA' to JNDI name 'java:JmsXA'
20:46:48,703 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=PostgresDSDYPK' to JNDI name 'java:PostgresDSDYPK'
20:46:48,734 INFO  [TomcatDeployment] deploy, ctxPath=/
20:46:50,312 INFO  [TomcatDeployment] deploy, ctxPath=/ap
20:46:50,406 WARN  [JAXWSDeployerHookPreJSE] Cannot load servlet class: org.jboss.jmx.adaptor.html.HtmlAdaptorServlet
20:46:50,406 WARN  [JAXWSDeployerHookPreJSE] Cannot load servlet class: org.jboss.jmx.adaptor.html.ClusteredConsoleServlet
20:46:50,421 INFO  [TomcatDeployment] deploy, ctxPath=/jmx-conso1e
20:46:50,500 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-8080
20:46:50,531 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8218
20:46:50,546 INFO  [ServerImpl] JBoss (Microcontainer) [5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)] Started in 33s:859ms

A: You will also have to specify the binding address for the jboss server. For jboss5.x, the command will be like
Jboss\jboss-5.0.1.GA\bin\run.jar -b0.0.0.0

A: Check your port number under /deploy/jbossweb.sar/server.xml, I think the problem is right there.
It should be like this ==>
<!-- A HTTP/1.1 Connector on port 8080 -->
   <Connector protocol="HTTP/1.1" port="8080" address="${jboss.bind.address}"
    maxThreads="250" strategy="ms" maxHttpHeaderSize="8192"
    emptySessionPath="true"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    connectionTimeout="20000" disableUploadTimeout="true"/>

Check the port number!


text:
Q: How to backfill currency data using calendar table and currency data updated monthly I have an SQL problem that I can't figure out or seem to find any solutions that help out. I am using an SQL serverless pool on Azure Synapse.
My problem is that I can't figure out how to backfill rates for each date until there is an update. For example CNY to USD updated on the 1st and 30th of the month. I need to fill in the same exchange rate as the 1st for every day up until the 30th when the rate changes and so on...
My tables:
1 - Exchange Rate

FromCurrencyCode
ToCurrencyCode
Exchange Rate
ExchangeDate

CHF
USD
0.98068059233108
2019-04-30 22:30:01.0

CHF
USD
0.98068059233108
2019-04-30 22:30:02.0

2 - Calendar Table

Calendar_Date
Calendar_Day
Calendar_Month
Calendar_Year

2019-01-03
3
January
2019

2019-01-04
4
January
2019

This is a problem because I am joining a list of IDs with foreign currencies to the Exchange Rate table based on the creation date. So I can create a project on the 15th of the month, in between the 2 updates and use the latest updated rate for it (ie. the 1sts rate).
I have tried using left joins as a starting point like below:
SELECT distinct t1.[FromCurrencyCode],
t1.[ToCurrencyCode],
t1.[ExchangeRate],
t2.[Calendar_Date]
FROM [dbo].[ExchangeRate] t1 join [dbo].[Calendar] t2 on convert(date,t1.ExchangeDate) =
t2.Calendar_Date
order by t1.FromCurrencyCode, t2.Calendar_Date

Which results in:
[1]: https://i.stack.imgur.com/cNSqz.png
I have looked at a lot of older solutions involving recursive common table expressions (CTEs) but none have seemed to work for me so far. The currencies are not the same across the examples as it is sample data in the tables so you can understand the layout!
Any help would be much appreciated!

A: If i understand your question, you want to have for every date between two ExchangeDate the same ExchangeRate every day, to do so, you can use this query:
SELECT DISTINCT t1.[FromCurrencyCode]
   ,t1.[ToCurrencyCode]
   ,t1.[ExchangeRate]
   ,t2.[Calendar_Date]
FROM (
    SELECT DISTINCT [FromCurrencyCode]
        ,[ToCurrencyCode]
        ,[ExchangeRate]
        ,ExchangeDate StartExchangeDate
        ,LEAD(ExchangeDate) OVER (
            PARTITION BY [FromCurrencyCode]
            ,[ToCurrencyCode] ORDER BY ExchangeDate
        ) EndExchangeDate
    FROM [dbo].[ExchangeRate]
) t1
JOIN [dbo].[Calendar] t2 ON t2.Calendar_Date >=  t1.StartExchangeDate AND
    t2.Calendar_Date < t1.EndExchangeDate
ORDER BY t1.FromCurrencyCode
    ,t2.Calendar_Date


text:
Q: is there a good way to save and show web document edits So I'm building a website in php codeigniter, and I have user submitted articles... and I want to have an editing system, kind of like SVN where you can see the changes that have been made, and you can revert to older changes if necessary.. so my question is how do you do that? is there a library that helps with that.. or are there any articles that you guys can recommend on the subject. I was thinking of just making a db table where it has an edit id and a date, and the changes made, then compare it to the original doc.. but I don't think that is a very officiant method. so any suggestions would be greatly appreciated.

A: You actually already have an answer to this: use git or svn.  If you trust your users to make edits and such, you simply have to script something that will submit their changes to the repository.  You can then use diff to compare two versions. This can also be nice if you want your users to be able to rollback changes and do other things version control libraries do.
If showing the diff syntax is insufficient, you can try to parse it into something prettier or use another method.  I'm sure they exist.


text:
Q: MCMC sampler for multiple measures distribution I currently have a custom probability distribution defined on multiple measures, i.e. I am measuring choice $c \in \{0,1\}$, reaction times $rt \in \mathbb{R}_+$, and confidence $conf \in [-1,+1]$ (see e.g. here) for each trial. Now from my computational model I can derive $p(c, rt, conf | \theta)$ for each parameter set $\theta$ and therefore also the multiple-measure likelihood $L(\theta)=p(c, rt, conf | \theta)$.
Now I would like to sample from the resulting posterior (given some priors over $\theta$), but I cannot find any MCMC sampler, which would allow me to do this. Looking for example at the distributions defined for pymc3, they are either univariate or taking a vector of similar types of values (e.g. multivariate Gaussian). However, for my data, the three measurements are quite dissimilar being defined over different sets. Is there any MCMC implementation, which would allow me to implement the complete model (needs to be Turing complete and allow for stochastic parts) and to implement a distribution on this kind of data? If possible, I would prefer to do this in pymc3, but I cannot really see how to do it.
I know a common approach would be to split the distribution into dependent distributions, e.g. $p(c|\theta)$, $p(conf | c,\theta)$ and $p(rt|conf, c, \theta)$, which would allow me to write
$p(c,rt,conf|\theta)=p(c|\theta) \cdot p(conf | c,\theta) \cdot p(rt|conf, c, \theta)$
and then use the measurements as parameters within some of the distributions. However, I cannot derive the dependent probabilities as such, the best I could do would be marginalized distributions of $p(conf | c,\theta)$ and $p(rt | c,\theta)$.


text:
Q: jsonp string to number returning wrong number For an app that requires data about poi's I retreive jsonp dat from a server. That data is in the following form:
{
"id":"31775",
"x1":"5.141329",
"y1":"51.593395",
"x2":"5.141974",
"y2":"51.593472",
"p1":"0",
"p2":"0"
}

Because the server runs php 5.2.17 I cannot use JSON_NUMERIC_CHECK.
So when I have received the files I try to convert them to numbers. The chrome console and the converted numbers are however wrong as can be seen below.
Object {id: "31775", x1: "5.141329", y1: "51.593395", x2: "5.141974", y2: "51.593472"…}
id: "31775"
p1: "0"
p2: "0"
x1: 5.261592156887178
x2: 5.261092156887178
y1: 8736.838921620045
y2: 8736.836754225322
__proto__: Object

Any ideas as to how I can fix this? In the mean time I have asked my hoster to upgrade the php version so we can use the numeric check.
Thanks in advance!

A: From my Chrome console:
var o = {
  "id":31775,
  "x1":5.141329,
  "y1":51.593395,
  "x2":5.141974,
  "y2":51.593472,
  "p1":0,
  "p2":0
};

JSON.stringify(o, null, 2)
"{
  "id": 31775,
  "x1": 5.141329,
  "y1": 51.593395,
  "x2": 5.141974,
  "y2": 51.593472,
  "p1": 0,
  "p2": 0
}"
If you are getting wildly different numbers, your convert from string to number is broken.
If you are getting slightly different numbers, then welcome to [http://floating-point-gui.de/](welcome to floating point).


text:
Q: CSS3 border-radius on toggle input not working in IE11 For some reason my toggle button styles are not working in IE11. The input button should be a green circle but it's showing as a square box with a quite background and black border in IE11:

Here is how it is intended to look:

My code:

.toggle-field {
  position: relative;
  padding-top: 0.35rem;
}

.toggle-field .Toggle {
  padding-left: 75px;
}

.toggle-field .toggle-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 68px;
  height: 34px;
  border-radius: 18px;
  border: 2px solid #ccc;
}

.toggle-field input {
  appearance: none;
  display: block;
  position: absolute;
  left: 4px;
  top: 4px;
  width: 26px;
  height: 26px;
  background: #ccc;
  border-radius: 15px;
  transition: left 117ms ease;
  border: none;
}

.toggle-field input:focus + .toggle-element {
  border-color: #aaa;
}

.toggle-field b {
  position: absolute;
  font-weight: normal;
  line-height: 34px;
  top: 1px;
  left: 40px;
  font-size: 0.65rem;
}

.toggle-field .Toggle.On input {
  left: 38px;
  background: #2ea664;
}

.toggle-field .Toggle.On b {
  left: 12px;
}

    <input type="checkbox" id="button1" name="button1" value="on">

    YES Question goes here

Most of what I have read says that I need to have a certain compatibility tag included, which I have:
<meta http-equiv="X-UA-Compatible" content="IE=edge">

Not sure what else to do. Has anyone else had this issue before?

A: I found a different way of doing this that works in IE11.
.toggle-field {
  position: relative;
  padding-top: 0.35rem;
}

.toggle-field .Toggle {
  padding-left: 80px;
}

.toggle-field input {
  appearance: none;
  display: block;
  position: absolute;
  left: 6px;
  top: 4px;
  width: 26px;
  height: 26px;
  background: #ccc;
  border-radius: 15px;
  transition: left 117ms ease;
  border: none;
}

.toggle-field .toggle-element {
  background-color: #fff;
  border: 2px solid #ccc;
  bottom: 0;
  cursor: pointer;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: .4s;
  width: 68px;
  height: 32px;
}

.toggle-element:before {
  background-color: #ccc;
  bottom: 3px;
  content: "";
  height: 26px;
  left: 4px;
  position: absolute;
  transition: .4s;
  width: 26px;
}

input:checked + .toggle-element {
  background-color: #fff;
}

input:checked + .toggle-element:before {
  transform: translateX(34px);
  background-color: #2ea664;
}

.toggle-element {
  border-radius: 34px;
}

.toggle-element:before {
  border-radius: 50%;
}

    <input type="checkbox" id="checkbox" />


text:
Q: How to start new intent from PostExecute in Android? Here is the code I'm working on.  When I'm running my app with this code, it's getting stopped, with no errors.
I have changed manifest.xml, but it's not working.
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ok=(Button)findViewById(R.id.Button01);
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                new jsdetails().execute();

                }

        });
    }
    public class jsdetails extends AsyncTask<String,String,String> {

        Boolean validUser = false;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Verifying.. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected String doInBackground(String... args) {

            //int valoreOnPostExecute = 0;
            error=(TextView)findViewById(R.id.TextView01);
            un=(EditText)findViewById(R.id.EditText01);
            pw=(EditText)findViewById(R.id.EditText02);

            params.add(new BasicNameValuePair("JS_Email",un.getText().toString()));
            params.add(new BasicNameValuePair("JS_Password",pw.getText().toString()));

            JSONObject json = jParser.makeHttpRequest(url,"POST",params);
            Log.d("All Products: ", json.toString());
                try {
             int success = json.getInt(TAG_SUCCESS);
                                 if (success == 1)
                 {
                     validUser = true;

                 }
                                } catch (JSONException e) {
                e.printStackTrace();
            }
                 return null;
        }
        protected void onPostExecute(String file_url) {

            pDialog.dismiss();
            if(validUser)
            {
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);
                finish();
            }

             params.clear();
                }
            }

}

A: You must make view action on UIThread. Async doInBackground method on background thread. You don't get editText' s text in background thread.

A: Try this.. Remove the finish();
if(validUser)
{
      Intent i = new Intent(MainActivity.this, UserManage.class);
      startActivity(i);
}

A: You are returning null in doinbackground() method instead return valid user and in onPostExecute
protected void onPostExecute(String validUser) {

        pDialog.dismiss();
        if(validUser)
        {
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);
            finish();
        }

         params.clear();
            }
        }

A: Do it like this
 public class jsdetails extends AsyncTask<String,String,Boolean> {

        Boolean validUser = false;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Verifying.. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected Boolean doInBackground(String... args) {

            //int valoreOnPostExecute = 0;
            error=(TextView)findViewById(R.id.TextView01);
            un=(EditText)findViewById(R.id.EditText01);
            pw=(EditText)findViewById(R.id.EditText02);

            params.add(new BasicNameValuePair("JS_Email",un.getText().toString()));
            params.add(new BasicNameValuePair("JS_Password",pw.getText().toString()));

            JSONObject json = jParser.makeHttpRequest(url,"POST",params);
            Log.d("All Products: ", json.toString());
                try {
             int success = json.getInt(TAG_SUCCESS);
                                 if (success == 1)
                 {
                     validUser = true;

                 }
                                } catch (JSONException e) {
                e.printStackTrace();
            }
                 return validUser;
        }
        protected void onPostExecute(Boolean validUser) {

            pDialog.dismiss();
            if(validUser)
            {
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);
                finish();
            }

             params.clear();
                }
            }

}***

A: I made a few changes and suggestions. Refer following code.
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
            error=(TextView)findViewById(R.id.TextView01);
            un=(EditText)findViewById(R.id.EditText01);      // Note
            pw=(EditText)findViewById(R.id.EditText02);
        ok=(Button)findViewById(R.id.Button01);
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                new jsdetails(MainActivity.this).execute(un.getText().toString(),pw.getText().toString());
// Note

                }

        });
    }
    public class jsdetails extends AsyncTask<String,Integer,Boolean > {    // Note
        Context context;    // Note
        Boolean validUser = false;
        jsdetails(Context context){    // Note
           this.context=context;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Verifying.. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected Boolean doInBackground(String... args) {    // Note

            //int valoreOnPostExecute = 0;

            params.add(new BasicNameValuePair("JS_Email",args[0]));      // Note
            params.add(new BasicNameValuePair("JS_Password",args[1]));

            JSONObject json = jParser.makeHttpRequest(url,"POST",params);
            Log.d("All Products: ", json.toString());
                try {
             int success = json.getInt(TAG_SUCCESS);
                                 if (success == 1)
                 {
                     validUser = true;

                 }
                                } catch (JSONException e) {
                e.printStackTrace();
            }
                 return validUser ;
        }
        protected void onPostExecute(String result) {

            pDialog.dismiss();
            if(result)    // Note
            {
                Intent i = new Intent(context, UserManage.class);    // Note
                startActivity(i);
                finish();
            }

             params.clear();
                }
            }

}


text:
Q: What do job colors mean? When taking a job, the jobs are sometimes presented in different colors. Most jobs are white, but I've discovered that green jobs mean you're awarded Bux instead of coins for completion. Now I've discovered blue jobs, but I can't tell their significance. What are all the possible job colors and what do they mean?

A: Blue jobs are cargo and/or passengers for the current global event. Delivering them to the city of the event count towards completing it. Green jobs are indeed rewarded with bux, and white are regular jobs. There are also rare mystery parts, which are gold/orange, like the one in the image:


text:
Q: Passing javascript variable into jinja array I have a simple but frustrating problem.
On the backend, I have a 2d list being passed from python over to the frontend with jinja. I then want to iterate over this array using a for loop, but I can't pass the variable from that for loop into the jinja array because it won't recognize it.
For example (this is taken from a larger function):
for (let i = 0; i < {{rows}}; i++) {
 clone.getElementById("name").innerHTML = "{{data[i+1][0]}}";
}

Jinja has no idea what "i" is. Is there a way to pass that variable into jinja?

A: As previous speakers have explained, there is a difference in execution time between a jinja template and the JavaScript code.
However, you can pass data to JavaScript inside jinja. The solution is the tojson filter, which allows you to serialize a python variable to json and then assign it to a variable in JavaScript. It is then possible, for example, to iterate over a resulting array, as in the following example.
from flask import (
    Flask,
    render_template
)

app = Flask(__name__)

@app.route('/')
def index():
    data = [
        ['one', 'more', 'thing'],
        ['some', 'thing', 'else']
    ]
    return render_template('index.html', **locals())

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <script type="text/javascript">
      (function(data) {
        data.forEach(row => {
          console.log(row[0]);
        });
      })({{data|tojson}});
    </script>

  </body>
</html>

If you want to send data from JavaScript to the server for processing in python, send an AJAX request.
from flask import (
    Flask,
    jsonify,
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', **locals())

@app.post('/recieve')
def recieve():
    data = request.json
    print(data)
    return jsonify(success=True)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <script type="text/javascript">
        (function(url) {
          const data = [
            ['one', 'more', 'thing'],
            ['some', 'thing', 'else']
          ];
          fetch(url, {
            method: 'post',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
          }).then(resp => resp.json())
            .then(data => console.log(data));
        })({{url_for('recieve')|tojson}})
    </script>

  </body>
</html>


text:
Q: Is there a way to insert a formatted character while typing in a cell? I need to be able to insert a colored symbol while entering text in a cell.  I can do it in Word with a macro but in Excel I can only replace the entire cell.
Alternatively is there a way to apply a font style to selected characters (not the whole cell) using vba?

A: From a simple use of the macro recorder, you should be able to use .characters().font to add font/color/etc. to a portion of a string:
ActiveCell.FormulaR1C1 = "Text here"
Range("A1").Select
With ActiveCell.Characters(Start:=9, Length:=1).Font
    .Name = "Verdana"
    .FontStyle = "Regular"
    .Size = 9
    .Strikethrough = False
    .Superscript = False
    .Subscript = False
    .OutlineFont = False
    .Shadow = False
    .Underline = xlUnderlineStyleNone
    .ThemeColor = xlThemeColorLight1
    .TintAndShade = 0
    .ThemeFont = xlThemeFontNone
End With


text:
Q: Angular 2: How to use JavaScript Date Object with NgModel two way binding I'm working with Angular 2 and I have this code:
JS, this code initiates the employee-variable for the template:
handleEmployee(employee : Employee){
        this.employee = employee;
        this.employee.startDate = new Date('2005/01/01');
        console.log(this.employee);
    }

Template:
...

    Start date:
    <input [(ngModel)]="employee.startDate" type="date" name="startDate"/>

...

Other data like firstname is displayed correctly. But for the date I just get:
mm/dd/yyyy

In the input element, which should be a date.
How can I do this?

A: FormControls (both template-driven and reactive) subscribe for values and write values via Directives that implement ControlValueAccessor. Take a look at the relevant method selectValueAccessor, which is used in all necessary directives. Normal input controls (e.g. <input type="text">) or textareas are handled by the DefaultValueAccessor. Another example is the CheckboxValueAccessor which is applied to checkbox input controls.
The job isn't complicated at all. We just need to implement a new value accessor for date input controls.
DateValueAccessor is a nice name:
// date-value-accessor.ts

import { Directive, ElementRef, HostListener, Renderer, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

export const DATE_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DateValueAccessor),
  multi: true
};

/**
 * The accessor for writing a value and listening to changes on a date input element
 *
 *  ### Example
 *  `<input type="date" name="myBirthday" ngModel useValueAsDate>`
 */
@Directive({
  selector: '[useValueAsDate]',
  providers: [DATE_VALUE_ACCESSOR]
})
export class DateValueAccessor implements ControlValueAccessor {

  @HostListener('input', ['$event.target.valueAsDate']) onChange = (_: any) => { };
  @HostListener('blur', []) onTouched = () => { };

  constructor(private _renderer: Renderer, private _elementRef: ElementRef) { }

  writeValue(value: Date): void {
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'valueAsDate', value);
  }

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
  registerOnTouched(fn: () => void): void { this.onTouched = fn; }

  setDisabledState(isDisabled: boolean): void {
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
  }
}

We attach the DateValueAccessor to the multi-provider DATE_VALUE_ACCESSOR, so that selectValueAccessor can find it.
The only question is, which selector should be used. I decided for an opt-in solution.
Here the DateValueAccessor selects on the attribute "useValueAsDate".
<input type="date" name="myBirthday" ngModel useValueAsDate>

OR

<input type="date" name="myBirthday" [(ngModel)]="myBirthday" useValueAsDate>

OR

<input type="date" formControlName="myBirthday" useValueAsDate>

It is also possible to fix the default implementation.
The following selector would activate the feature magically.
// this selector changes the previous behavior silently and might break existing code
selector: 'input[type=date][formControlName],input[type=date][formControl],input[type=date][ngModel]'

But please be aware, that this might break existing implementations that rely of the old behaviour. So I would go for the opt-in version!
It's all on NPM and Github
For your convenience, I created the project angular-data-value-accessor on Github.
There is also a NPM package available:
npm install --save angular-date-value-accessor

Then just import the module via NgModule:
// app.module.ts

import { DateValueAccessorModule } from 'angular-date-value-accessor';

@NgModule({
  imports: [
    DateValueAccessorModule
  ]
})
export class AppModule { }

Now you can apply the "useValueAsDate" to your date input controls.
Demo
Of course, there is a demo at:
http://johanneshoppe.github.io/angular-date-value-accessor/

A: I began trying to implement Ankit Singh's solution and ran in to a few problems with validation and timezone stuff. (Even after trying the suggestions in the comment section of that answer)
Instead I chose to utilize moment.js to handle the transforming between string and date using ISO8601 format date strings. I've had great results in the past using moment.js so this was not a difficult decision. Seems to be working well for me, hopefully someone else finds this useful.
For my Angular 2 app I ran npm install --save moment and then turned Ankit's solution into a wrapper around a js Date object:
import * as moment from 'moment';

export class NgDate {

    date: any;

    constructor() {
        this.date = new Date();
    }

    set dateInput(e) {
        if (e != "") {
            var momentDate = moment(e, moment.ISO_8601).toDate();
            this.date = momentDate;
        }
        else {
            this.date = null;
        }
    }

    get dateInput() {
        if(this.date == null)
        {
            return "";
        }

        var stringToReturn = moment(this.date).format().substring(0, 10);
        return stringToReturn;
    }
}

Then for the HTML:
<input type="date" name="someDate" [(ngModel)]="ngDateModel.dateInput"/>

A: I think the accepted answer lacks a function call to transform input date string to Date object. So this:
(ngModelChange)="startDate = $event"

Should be something like:
(ngModelChange)="startDate = toDate($event)"

I'm using Moment.js, which makes things MUCH easier:
my.component.ts

...
import * as moment from 'moment';
...
@Component ({
  ...
})
export class MyComponent implements OnInit {

  public fromDate: moment.Moment;
  public toDate: moment.Moment;

  ngOnInit() {
    this.toDate = moment();
    this.fromDate = moment().subtract(1, 'week');
  }

  dateStringToMoment(dateString: string): moment.Moment {
    return moment(dateString);
  }

my-component.html

...
<input type="date" min="{{ fromDate | date:'yyyy-MM-dd' }}" name="toDate" [ngModel]="toDate | date:'yyyy-MM-dd'" (ngModelChange)="toDate = dateStringToMoment($event)">
<input type="date" max="{{ toDate | date:'yyyy-MM-dd' }}" name="fromDate" [ngModel]="fromDate | date:'yyyy-MM-dd'" (ngModelChange)="fromDate = dateStringToMoment($event)">
...

A: Read pipes and ngModel
and my deсision:
<input type="date" class="form-control" id="myDate" [ngModel]="myDate | date:'y-MM-dd'" (ngModelChange)="myDate = $event" name="birthday">

A: Fixed it with this code:
handleEmployee(employee : Employee){
        this.employee = employee;

        let dateString : string = employee.startDate.toString();
        let days : number = parseInt(dateString.substring(8, 10));
        let months : number = parseInt(dateString.substring(5, 7));
        let years : number = parseInt(dateString.substring(0, 5));
        let goodDate : Date = new Date(years + "/" + months + "/" + days);
        goodDate.setDate(goodDate.getDate() + 2);
        this.date = goodDate.toISOString().substring(0, 10);
    }

Html:

    Start date:
    <input [(ngModel)]="date" type="date" name="startDate"/>

A: UPDATE:
StackBlitz
when I wrote this answer DatePipe did not exist, now you can just do this
<input [ngModel]="startDate | date:'yyyy-MM-dd'" (ngModelChange)="startDate = $event" type="date" name="startDate"/>

`

Old Answer:
PLUNKER
You need to convert date object in the input type="date" format which is yyyy-mm-dd, this is how it will work
Template:
<input [(ngModel)]="humanDate" type="date" name="startDate"/>

Component (TS):
export class App {
  startDate: any;

  constructor() {
    this.startDate = new Date(2005, 1, 4);
  }

  set humanDate(e){
    e = e.split('-');
    let d = new Date(Date.UTC(e[0], e[1]-1, e[2]));
    this.startDate.setFullYear(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
  }

  get humanDate(){
    return this.startDate.toISOString().substring(0, 10);
  }
}

A: Created a local string variable
dateField: string;

And I'm binding that to my form
Date input
<input type="text" class="form-control" required [(ngModel)]="dateField" />

Later just assign that back to the Date property just before making any API call
insert() {
    this.myObjet.date = new Date(this.dateField);
    ... call api

update() {
    this.myObjet.date = new Date(this.dateField);
    ... call api


text:
Q: Remove margin while switching text using textswitcher I'm using a TextSwitcher to animate the text changes. I'm using a slide up animation when the text is changed. However the text is not sliding up to the container. Have a look at the video posted below. The text is neither  sliding in from the red border nor sliding out to the red order. How should i go about to achieve a behavior where the text slides in from the red border and slides out to the red border?

The layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top">

    <androidx.cardview.widget.CardView
        android:id="@+id/iv_background"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="0dp"
        app:cardPreventCornerOverlap="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.imageview.ShapeableImageView
            android:id="@+id/iv_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            app:shapeAppearance="@style/ContainerShape" />

        <View
            android:id="@+id/border"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/border" />

    </androidx.cardview.widget.CardView>

    <TextSwitcher
        android:id="@+id/tv_textswitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:inAnimation="@anim/slide_up_from_bottom"
        android:outAnimation="@anim/slide_up_to_top"
        android:visibility="visible"
        app:layout_constrainedWidth="true"
        app:layout_constraintBottom_toBottomOf="@+id/iv_background"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/iv_background"
        app:layout_constraintTop_toTopOf="@+id/iv_background"
        app:layout_constraintVertical_bias="1.0">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/text_background"
            android:ellipsize="end"
            android:lineHeight="20dp"
            android:text="Text 1"
            android:paddingStart="12dp"
            android:paddingTop="8dp"
            android:paddingEnd="12dp"
            android:paddingBottom="8dp"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/text_background"
            android:ellipsize="end"
            android:lineHeight="20dp"
            android:paddingStart="12dp"
            android:paddingTop="8dp"
            android:paddingEnd="12dp"
            android:paddingBottom="8dp"
            android:textSize="14sp" />

    </TextSwitcher>

</androidx.constraintlayout.widget.ConstraintLayout>

Animation files:
slide_up_from_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="1000"
        android:fromYDelta="100%"
        android:toYDelta="0" />
</set>

slide_up_to_top.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="1000"
        android:fromYDelta="0"
        android:toYDelta="-100%" />
</set>

text_background.xml
<shape android:shape="rectangle">
            <corners android:radius="18dp" />
            <solid android:color="#e8e8e8" />
        </shape>

A: There are actually multiple issues which need to be fixed here.

*

*Remove the margin from TextSwitcher and set it to TextViews. As mentioned by @D.McDermott.

<TextSwitcher
        android:id="@+id/tv_textswitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:inAnimation="@anim/slide_up_from_bottom"
        android:outAnimation="@anim/slide_up_to_top"
        android:visibility="visible"
        app:layout_constrainedWidth="true"
        app:layout_constraintBottom_toBottomOf="@+id/iv_background"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/iv_background"
        app:layout_constraintTop_toTopOf="@+id/iv_background"
        app:layout_constraintVertical_bias="1.0">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:background="@drawable/text_background"
            android:ellipsize="end"
            android:lineHeight="20dp"
            android:paddingStart="12dp"
            android:paddingTop="8dp"
            android:paddingEnd="12dp"
            android:paddingBottom="8dp"
            android:text="Text 1"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:background="@drawable/text_background"
            android:ellipsize="end"
            android:lineHeight="20dp"
            android:paddingStart="12dp"
            android:paddingTop="8dp"
            android:paddingEnd="12dp"
            android:paddingBottom="8dp"
            android:textSize="14sp" />

    </TextSwitcher>

*The yDelta in animation should be with respect to the parent and not with respect to the view. So, we need to use 100%p instead of 100%.

slide_up_from_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="1000"
        android:fromYDelta="100%p"
        android:toYDelta="0" />
</set>

slide_up_to_top.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="1000"
        android:fromYDelta="0"
        android:toYDelta="-100%p" />
</set>

*Put the red border above the textview in the layout hierarchy. This is very important as this will ensure that the textview disappears into the red border and doesn't go beyond it.
So, i moved the border view to the bottom of the layout. Ideally, you can just give the border to your parent and not worry about putting this view at all. But i had some other usecase, so i had to do that.

<View
        android:id="@+id/border"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/border"
        app:layout_constraintBottom_toBottomOf="@+id/iv_background"
        app:layout_constraintEnd_toEndOf="@+id/iv_background"
        app:layout_constraintStart_toStartOf="@+id/iv_background"
        app:layout_constraintTop_toTopOf="@+id/iv_background" />

The complete layout looks like this now:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top">

    <androidx.cardview.widget.CardView
        android:id="@+id/iv_background"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="0dp"
        app:cardPreventCornerOverlap="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.imageview.ShapeableImageView
            android:id="@+id/iv_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            app:shapeAppearance="@style/ContainerShape" />

    </androidx.cardview.widget.CardView>

    <TextSwitcher
        android:id="@+id/tv_textswitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:inAnimation="@anim/slide_up_from_bottom"
        android:outAnimation="@anim/slide_up_to_top"
        android:visibility="visible"
        app:layout_constrainedWidth="true"
        app:layout_constraintBottom_toBottomOf="@+id/iv_background"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/iv_background"
        app:layout_constraintTop_toTopOf="@+id/iv_background"
        app:layout_constraintVertical_bias="1.0">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:background="@drawable/text_background"
            android:ellipsize="end"
            android:lineHeight="20dp"
            android:paddingStart="12dp"
            android:paddingTop="8dp"
            android:paddingEnd="12dp"
            android:paddingBottom="8dp"
            android:text="Text 1"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:background="@drawable/text_background"
            android:ellipsize="end"
            android:lineHeight="20dp"
            android:paddingStart="12dp"
            android:paddingTop="8dp"
            android:paddingEnd="12dp"
            android:paddingBottom="8dp"
            android:textSize="14sp" />

    </TextSwitcher>

    <View
        android:id="@+id/border"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/border"
        app:layout_constraintBottom_toBottomOf="@+id/iv_background"
        app:layout_constraintEnd_toEndOf="@+id/iv_background"
        app:layout_constraintStart_toStartOf="@+id/iv_background"
        app:layout_constraintTop_toTopOf="@+id/iv_background" />

</androidx.constraintlayout.widget.ConstraintLayout>

And here's a GIF for the resulting animation:

A: Although the CardView and the TextSwitcher are constrained to the exact same positions, they aren't the same size. The text switchers height (and width) is smaller due to the margin you set to it.
The solution would be to remove the margin from the TextSwitcher and set it to the TextViews instead. If this covers the red border you should set the background of the TextSwitcher to something transparent.


text:
Q: compare an object to null! I am trying to verify whether an object is null or not and i am using this syntax:
void renderSearch(Customer c){
         System.out.println("search customer rendering>...");
         try {
             if(!c.equals(null)){
                 System.out.println("search customer  found...");
             }else{
                 System.out.println("search customer not found...");
             }
         } catch (Exception e) {
             System.err.println ("search customer rendering error: "
                                     + e.getMessage()+"-"+e.getClass());
         }
     }

I get the following exception :

search customer rendering error: null
  class java.lang.NullPointerException

I thought that I was considering this possibility with my if and else loop.  Any help would be appreciated.

A: Use c==null
The equals method (usually) expects an argument of type customer, and may be calling some methods on the object. If that object is null you will get the NullPointerException.
Also c might be null and c.equals call could be throwing the exception regardless of the object passed

A: Most likely Object c is null in this case.
You might want to override the default implementation of equals for Customer in case you need to behave it differently.
Also make sure passed object is not null before invoking the functions on it.

A: Try c != null in your if statement. You're not comparing the objects themselves, you're comparing their references.

A: !c.equals(null)

That line is calling the equals method on c, and if c is null then you'll get that error because you can't call any methods on null.
Instead you should be using
c != null

A: Use c == null, since you're comparing references, not objects.

A: if C object having null value then following statement used to compare null value:
if (c.toString() == null) {

    System.out.println("hello execute statement");

}

A: The reality is that when c is null, you are trying to do null.equals so this generates an exception. The correct way to do that comparison is "null".equals(c).


text:
Q: How to fetch API and store some value and then fetch again with that stored value in React Currently I am fetching some data and I save the response via useState. The response is saved but the problem is the second fetch takes place before the state was saved making that value undefined.
I tried to do like this:
  useEffect(() => {
    fetchTrackingData().finally(() => {
      console.log("Destination", destination.coordinates);
      fetchDriverLocation().finally(() => {
        setLoading(false);
      });
    });
  }, []);

Basically fetchTrackingData function has destination coordinates which I save with:
const [destination, setDestination] = useState('');
In the fetchTrackingData function I am setting the state after receiving the response. After fetchTrackingData is done fetching and it has saved state of destination I then use finally() method and then call the second fetch which is fetchDriverLocation but it has destination undefined and even I logged to see if the value gets saved after finally() but it is undefined in log as well.
How can I store the value from one API in that API call and then use that value in another API call?

A: What you're experiencing is a race condition.
When you call fetchTrackingData, it makes the HTTP request to your API, gets a response and then the last thing it does is saves destination to the state. But when you call setDestination, this is another asynchronous task that is kicked off, then you move directly to trying to access it from the state (which it may or may not be there, depending on how long it takes to set the state).
My recommendation would be to either not rely on state for this process (perhaps a variable will do? or even just passing along the result of your http request) or to lean more heavily on chaining these Promises and have the setting of the state be included in the Promise chain. However, I would favour the former suggestion
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
and: Chain React setState callbacks

A: As another answer has stated, you are experiencing a race condition because setState in react is often asynchronous.
My suggestion would be to use two useEffects to accomplish this:
useEffect(() => {
  fetchTrackingData();
}, []);

useEffect(() => {
  console.log("Destination", destination.coordinates);
  fetchDriverLocation().finally(() => {
    setLoading(false);
  });
}, [destination]);

The above will wait until destination changes before moving on with fetching the driver location

A: You can try with the async await methods and call the other APIs after the first one is done.
Example :
function App() {
  const [data, setData] = useState();
  const [data2, setData2] = useState();

  useEffect(() => {
    (async () => {
      const response = await fetch("someURL");
      const json = await response.json();
      setData(json);
      const responseList = await fetch("someURL" + json.data);
      const jsonData = await responseList.json();
      setData2(jsonData)
    })();
  }, []);

  return (
    <div>
        Hello
    </div>
  );
}

export default App;

A: by using useEffect fetching data from firstURI and sending to secondURI
  const [firstDate, setFirstData] = useState();
  const [secondDate, setSecondData] = useState();

  useEffect(() => {
    (async () => {
      const firstResponse = await fetch("firstURI");
      const firstResponseData = await firstResponse.json();
      setFirstData(firstResponseData);

      const secondResponse = await fetch("secondURI" + firstResponseData.data);
      const secondResponseData = await secondResponse.json();
      setSecondData(secondResponseData)
    })();
  }, []);


text:
Q: How to modify price and currency in order receipt email with woocommerce? i'm doing a woocommerce plugin in order to allow payments with paypal using foreign currency. It work but the problem is that the order email is still containing default prices and default currency.
What I have tried to do is to change them using this action hook:
do_action ('woocommerce_email_before_order_table', $order, $sent_to_admin, $plain_text, $email);

… inside email template file email-order-details.php, but I don't now how I should modify an order object to change the prices of each item, I didn't see a method like set_price or set_total inside the woocommerce doc for order class.
How this could be done? Any advice please?


text:
Q: Difference Triangles In a difference triangle, a row of $n$ integers is given, then their differences are written underneath, and then another row of difference is added, until there is a triangle of $n (n+1)/2$ integers. For example:

The above triangle also has the property that it has 15 distinct values with no values from 1 to 15 either missing or repeated.  According to this query, this is the last difference triangle with nothing missing and nothing repeated.
That's similar to the last perfect ruler, with marks ${0,1,3,6}$. These marks measure all differences 1 to 6 with no lengths missing or repeated.  For longer rulers, there are two options.

*

*No repeats allowed. The smallest ruler with $n$ marks is called a Golomb ruler.

*No missing values. The longest ruler with $n$ marks is an optimal sparse ruler.

We can look at difference triangles with these same conditions.
Order 6.  $T_6 = 21$.
The smallest difference triangle with no repeats has large value 22 ($T_6  +1$) and misses 15.
The largest difference triangle with no misses has large value 20 ($T_6  -1$) and repeats 4.

Order 7.  $T_7=28$.
The smallest known difference triangle with no repeats has large value 33 ($T_7  +5$) and misses ${16, 20, 22, 29, 30}$.
The largest known difference triangle with no misses has large value 24 ($T_7  -4$) and repeats 1 and 3.

What happens with orders 8 and beyond?  With $T_8=36$, how close can we get to $36$ with either no repeats or no misses?

A: I wrote a hill-climbing algorithm that finds solutions. Here are my best results, but I don't know if any of them are optimal.
For order 7 no misses, I found 3 other solutions. Here is one:
10 24 21 22 3 23 8
14 3 1 19 20 15
11 2 18 1 5
9 16 17 4
7 1 13
6 12
6
For order 8 no repeats, I found one with largest value 44. It misses: 12, 20, 21, 25, 27, 31, 32, 35.
29 6 43 44 3 42 33 7
23 37 1 41 39 9 26
14 36 40 2 30 17
22 4 38 28 13
18 34 10 15
16 24 5
8 19
11
For order 8 no misses, I found a solution with largest value 30:
16 30 28 1 5 3 29 20
14 2 27 4 2 26 9
12 25 23 2 24 17
13 2 21 22 7
11 19 1 15
8 18 14
10 4
6
For order 9 no repeats, I found one with largest value 59. It misses: 15, 22, 27, 29, 31, 33, 34, 35, 38, 41, 44, 51, 52, 56.
43 53 13 59 55 1 58 49 17
10 40 46 4 54 57 9 32
30 6 42 50 3 48 23
24 36 8 47 45 25
12 28 39 2 20
16 11 37 18
5 26 19
21 7
14
For order 9 no misses, I found one with largest value 36:
36 5 34 33 27 32 2 35 14
31 29 1 6 5 30 33 21
2 28 5 1 25 3 12
26 23 4 24 22 9
3 19 20 2 13
16 1 18 11
15 17 7
2 10
8
For order 10 no misses, I found one with largest value 41:
22 38 2 41 37 3 36 40 5 19
16 36 39 4 34 33 4 35 14
20 3 35 30 1 29 31 21
17 32 5 29 28 2 10
15 27 24 1 26 8
12 3 23 25 18
9 20 2 7
11 18 5
7 13
6
For order 11 no misses, I found one with largest value 47:
38 26 1 43 44 7 45 40 1 47 29
12 25 42 1 37 38 5 39 46 18
13 17 41 36 1 33 34 7 28
4 24 5 35 32 1 27 21
20 19 30 3 31 26 6
1 11 27 28 5 20
10 16 1 23 15
6 15 22 8
9 7 14
2 7
5

A: (Not an answer. Simply short algorithm description and some of results)
If denote upper row of the triangle as
$$
(t_1, t_2, \ldots, t_{n-1}, t_n), \tag{1}
$$
then (w.l.o.g.) we'll consider only rows with $t_1 \le t_n$ (if $t_1=t_n$, then $t_2 \le t_{n-1}$ and so on).

To find largest difference triangle with no misses for relatively small $n$ $(n \le 9)$, one can apply exhaustive search for upper row (I'm unable to find smarter deterministic algorithm).

Rough estimation:

$n=7$:

up to $28^7 \approx 13.5 \times 10^9$ tests to check the value $28$ for optimality;

up to $27^7 \approx 10.5 \times 10^9$ tests to check the value $27$ for optimality;

...
$n=8$:

up to $36^8 \approx 2.8 \times 10^{12}$ tests to check the value $36$ for optimality;

up to $35^8 \approx 2.3 \times 10^{12}$ tests to check the value $35$ for optimality;

...
This way,

"$8$-no-misses" problem has three $30$-solutions (only upper rows are listed here):
(9, 28, 30, 5, 27, 24, 3, 29)

(16, 30, 28, 1, 5, 3, 29, 20)

(18, 4, 28, 26, 1, 30, 21, 27)

and there are no $k$-solutions for $k\ge 31$.
"$9$-no-misses" problem has at least one $38$-solution
(19, 35, 34, 3, 36, 38, 11, 37, 32)

(I didn't check it completely for this time).

To find smallest difference triangle with no repeats for relatively small $n$ $(n\le 10)$, I used recursive triangle construction.
Let $(n,k)$-no-repeats triangle is triangle with upper row $(1)$, where
$$t_j \le k, \; j=1,2,\ldots,n.$$
Then if $n$-triangle is $(n,k)$-no-repeats triangle, then its left $(n-1)$-triangle (with upper row $(t_1,t_2,\ldots,t_{n-1})$) has the same property:
 it is $(n-1,k)$-no-repeats triangle.
Which admits to apply recursion.
This way,

"$8$-no-repeats" problem has only one $44$-solution:
 (7, 33, 42, 3, 44, 43, 6, 29)

and no $k$-solutions for $k\le 43$.
"$9$-no-repeats" problem has only one $59$-solution:
 (17, 49, 58, 1, 55, 59, 13, 53, 43)

and no $k$-solutions for $k\le 58$.
"$10$-no-repeats" problem has only one $76$-solution:
 (45, 69, 12, 76, 73, 15, 75, 66, 16, 52)

and no $k$-solutions for $k\le 75$.
"$11$-no-repeats" problem has at least one $102$-solution:
 (12, 77, 98, 19, 100, 95, 8, 102, 99, 16, 70)

and no $k$-solutions for $k\le 78$ (currently checking cases $k\in[79 .. 102]$).

For larger $n$ heuristic or randomized algorithms can probably give (almost) optimal solutions.
Actually algorithm developed by Dmitry Kamenetsky works pretty nice and fast:
when I've seen his $(8,44)$ and $(9,59)$ (optimal!) results  for smallest difference triangle with no repeats, my "records" were $(8, 45)$ and $(9, 66)$ at that time.

A: I don't have a nontrivial solution yet,
but we can easily see that the "minimal default"
$$
  m(N) :=  T_N - \max_{S\in {\rm NoMiss}(N)} S,
$$
where $T_N = N(N+1)/2$ and NoMiss($N$) is the set of all no-miss solutions of order $N$, satisfies the relation
$$m(N+1) \le m(N)+ N-1.$$
Indeed, we can simply "grow" an order $N$ solution $S$ to $S'\in{\rm NoMiss}(N+1)$ by adjoining $\max(S)+1$ to the left or right of the first row of $S$.
So we do know that $m(8) \le 11$, by adding a column starting with 25 to the left of the triangle $S_{20,21,3,22,9,24,23}$ you gave for $N=7$, with $m = 4 \ge m(7)$.


text:
Q: InfoPath Repeating Table-Add Filtered Data from Secondary List I have the following scenario that I am trying to get find a solution for.
I have two lists within my SharePoint site called Supplier and Factory. The relationship between the supplier and factory list is one to many, that is for each unique supplier there can be multiple factories that are related to it.
So in the factory list there is a lookup column to the supplier list, a parent-child type relationship between them.
Within InfoPath I am trying to create a form for the Supplier list that will show all of the "child" factories related to that supplier in a repeating table. I have managed to get the repeating table into the supplier form, however the problem I have is that at the moment it includes all of the factories in the list, not just those related to the specific supplier I am looking at.
Is there a way to auto-filter the repeating table so that when the supplier form is opened up, it only displays those factories that have identified themselves as factories of that specific supplier?
I am using SharePoint 365 and InfoPath 2013.
Thanks
Edit
I have added an image below to help better illustrate my scenario.
The image is the view of an item in the supplier list, specifically supplier S2 with ID 2. The table in latter half of the image is the repeating table which is pulling in from the factory list. As you can see it is pulling in everything that exists in that list at the moment, I want it to only pull in those factories which have a matching Supplier ID of the supplier item that is open. So in this case it would be the bottom two factories F5 and F6 (they are the only factories with a matching supplier ID of 2).

A: It sounds like you're looking to do cascading drop downs? If so, here's a link to a video that seems very helpful.


text:
Q: On-screen typing in Pygame For a programming project in school I have to create a spelling game using pygame. However, as I am fairly new to this whole thing, I can't manage to work out how to allow the user to input letters and make them appear on the game display. This is my code so far (along with my failing attempt at solving this problem):
import pygame
import random

pygame.init()

display_width = 800
display_height = 600

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Spelling Game")
myfont = pygame.font.SysFont("Arial", 50)
clock = pygame.time.Clock()
mouse = pygame.mouse.get_pos()

city = pygame.image.load("city.png")

charac_str = ""  #new string to store written character
# font object to render str to surface
font_renderer = pygame.font.SysFont("Arial",30)

def background(x,y):
    gameDisplay.blit(city,(-200,-100))

with open("words.txt") as f:
    WORDS = f.read().split()

def random_word():
    return random.choice(WORDS)

gameExit = False
word = random_word()

while not gameExit:
    #event-handling loop based on user input
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    gameDisplay.fill(white)

    background(0,0)
    textsurface = myfont.render(word, True, red)
    gameDisplay.blit(textsurface, (340, 400))     #the random word

    rendered_charac = font_renderer.render(charac_str, True, red)
    gameDisplay.blit(rendered_charac, (100,100))

    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if pygame.K_0 < event.key < pygame.K_9: #checks key pressed
                character = chr(event.key) #conv num to char
                charac_str += str(character) # add num to end of string
                gameDisplay.blit(charac_str) # display the input?doesn't work

A: pygame.KEYDOWN events have a unicode attribute which you can simply add to a string, e.g. text += event.unicode. Then the text is rendered and displayed in the main loop.
import pygame as pg

def main():
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 32)
    clock = pg.time.Clock()
    color = pg.Color('dodgerblue2')
    text = ''

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_RETURN:
                    print(text)
                    text = ''
                elif event.key == pg.K_BACKSPACE:
                    text = text[:-1]
                else:
                    text += event.unicode

        screen.fill((30, 30, 30))
        txt_surface = font.render(text, True, color)
        screen.blit(txt_surface, (50, 100))

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

A: This is how you 're going to solve your little problem:
 def name():

        pygame.init()
        screen = pygame.display.set_mode((480, 360))
        name = ""
        font = pygame.font.Font(None, 50)

        while True:
            for evt in pygame.event.get():
                if evt.type == KEYDOWN:
                    if evt.unicode.isalpha():
                        name += evt.unicode
                    elif evt.key == K_BACKSPACE:
                        name = name[:-1]
                    elif evt.key == K_RETURN:
                        name = ""
                elif evt.type == QUIT:
                    return

        screen.fill ((0, 0, 0))
        block = font.render(name, True, (255, 255, 255))

        rect = block.get_rect()
        rect.center = screen.get_rect().center
        screen.blit(block, rect)
        pygame.display.flip()


text:
Q: Regex replace pattern - PHP I need some help, I have a replacement pattern:
/(?<!\S)(\b|\(|\[)(?:\d+\s*x\s*)?\d+(?:\.\d+)?\s*litres($|\s|\.|;|,|\)|\])/is

with function:
preg_replace('/(?<!\S)(\b|\(|\[)(?:\d+\s*x\s*)?\d+(?:\.\d+)?\s*litres($|\s|\.|;|,|\)|\])/is', '', $string);

which replace to '' - empty string and in 99% cases works great, however there is some which are not working as exprected.
So i.e.
Bottle (blue, 10 Litres) - will be replaced to Bottle (blue, instead of Bottle (blue,).
it looks like the right boundry {in example above ) sign} is being treated as a part of the string to replace. Any ideas?
cheers

A: Seems that backreference works: ${2}
so i.e.
preg_replace('/(?<!\S)(\b|\(|\[)(?:\d+\s*x\s*)?\d+(?:\.\d+)?\s*litres($|\s|\.|;|,|\)|\])/is', '${2}', $string);

should do the trick.
What you reckon?


text:
Q: how to use MonkeyDevice.broadcastintent() and MonkeyDevice.instrumentate() How does one use MonkeyDevice.broadcastintent() and MonkeyDevice.instrumentate()?

A: Did you mean MonkeyDevice.instrument()? If yes then the question here might be of use.
For MonkeyDevice.bordcastintent() I would take a look at the android documentation here. Personally I've found that using the shell works much better than bordcastintent. For example if I wanted to use the shell to bordcast an intent to add a contact I would use device.shell("am start -a android.intent.action.INSERT -t vnd.android.cursor.dir/contact -e name 'Donald Duck' -e phone 555-1234").


text:
Q: Emulating Qualcomm Snapdragon I am trying to boot an Android image that was designed for Qualcomm Snapdragon 210 (MSM8909 SoC) on my computer.
I have all the necessery files (initrd, zImage, system.img, boot.img).
What is the best way to do so? qemu did not work for me.

A: There is a lot more to modelling a full SoC like a Snapdragon than just having an ARM emulation. You would need to model the peripheral devices as well as a board that incorporates the chip with additional devices. As far as I'm aware the only Android images that work under emulation specifically target emulation targets (goldfish, ranchu and now cuttlefish). I'm not aware of any work to model the Snapdragon or any of the boards that use it in QEMU.


text:
Q: JS webView Xamarinforms I have been trying to call action from JS code in Xamarin forms on iOS. once I click on the code js is not called. this is an example I have been testing. Once I click the text gets highlighted but the function is not triggered, I don't want to display the action after clicking the button but I after I click the text. Please can you tell me what am I doing wrong.
 <StackLayout x:Name="slHybridView" >
                </StackLayout>

    public MainPage()
    {
        InitializeComponent();
        BindingContext = new LearningPageViewModel();

        ((LearningPageViewModel)BindingContext).TextChanged += TextChanged;
        hybridWebView = new HybridWebView()
        {
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.FillAndExpand,
            Content = ((LearningPageViewModel)BindingContext).ArticleHtmlFormat,
        };
        hybridWebView.RegisterAction(data => DisplayAlert("Alert", "Hello " + data, "OK"));
        slHybridView.Children.Clear();
        slHybridView.Children.Add(hybridWebView);

    }

        public class HybridWebViewRenderer : WkWebViewRenderer, IWKScriptMessageHandler
        {
            const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
            WKUserContentController userController;

            public HybridWebViewRenderer()
            {
            }

            public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
            {
                userController = config.UserContentController;
                var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
                userController.AddUserScript(script);
                userController.AddScriptMessageHandler(this, "invokeAction");
            }

            protected override void OnElementChanged(VisualElementChangedEventArgs e)
            {
                base.OnElementChanged(e);

                if (e.OldElement != null)
                {
                    userController.RemoveAllUserScripts();
                    userController.RemoveScriptMessageHandler("invokeAction");
                    HybridWebView hybridWebView = e.OldElement as HybridWebView;
                    hybridWebView.Cleanup();
                }

                if (e.NewElement != null)
                {
                    var html = string.Empty;
                    var iOSHtmlWithScaling = html.Insert(0, "<meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1' />");
                    var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
                    Configuration.UserContentController.AddUserScript(script);
                    Configuration.UserContentController.AddScriptMessageHandler(this, JavaScriptFunction);
                    LoadData(((HybridWebView)Element).Content, iOSHtmlWithScaling, "utf-8", new NSUrl(""));
                }
            }

            public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
            {
                ((HybridWebView)Element).InvokeAction(message.Body.ToString());
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    ((HybridWebView)Element).Cleanup();
                }
                base.Dispose(disposing);
            }

        }

      public LearningPageViewModel()
            {
                articleHtmlFormat = ArticleHtml();
            }

            public string ArticleHtml()
            {
               var articleHtml = @"<html>
    <head>
      <meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1' />
    </head>
    <body class='avat'>
        <style>

    .avat {
        font-family: sans-serif;
        font-size: 15px;
        text-align: justify;
    }

    .title {
        font-size: 16px;
    }

    .red {
      color: red;
    }

    .word {
      font-weight: bold;
    }
    .phrase {
      text-decoration: underline;
    }
        </style>
        <script type='text/javascript'>
                   function invokeCSCode(data) {

               var els = document.getElementsByClassName('red');
                 while (els[0]) {
                    els[0].classList.remove('red');
                  }

                invokeCSharpAction(data);
                var my_element = document.querySelector('[sentenceId=' + data + ']');
                 my_element.scrollIntoView({
                                behavior: 'smooth',
                    block: 'center',
                    inline: 'nearest'
                              });

                var sentenceName = my_element.getAttribute('sentenceName');

                if (data[0] === 's')
                {
                    var x = document.querySelectorAll('[sentenceName=' + sentenceName + ']');
                    var i;
                    for (i = 0; i < x.length; i++)
                    {
                        x[i].classList.add('red');
                    }
                }
                else
                {
                    my_element.classList.add('red');
                }

            }

    function scrollToPosition(data) {

                var els = document.getElementsByClassName('red');
                 while (els[0]) {
                    els[0].classList.remove('red');
                  }

                var my_element = document.querySelector('[sentenceId=' + data + ']');
                 my_element.scrollIntoView({
                                behavior: 'smooth',
                    block: 'center',
                    inline: 'nearest'
                              });

                var sentenceName = my_element.getAttribute('sentenceName');

                if (data[0] === 's')
                {
                    var x = document.querySelectorAll('[sentenceName=' + sentenceName + ']');
                    var i;
                    for (i = 0; i < x.length; i++)
                    {
                        x[i].classList.add('red');
                    }
                }
                else
                {
                    my_element.classList.add('red');
                }

            }
        </script>
     ";

                 var spans = FindAllClickableSpans(Article()).ToArray();

                 for (int i = 0; i < spans.Length; i++)
                 {
                     articleHtml += "<span ";
                     articleHtml += " sentenceId='" + i + "' onclick='javascript: invokeCSCode(\"" + i + "\");' sentenceName='" + i + "'>" + spans[i] + "</span>";
                 }

                articleHtmlFormat = articleHtml;

                 return articleHtmlFormat;
            }

            public string Article()
            {
               return @"Excuse me," said a girl, "you look lost. Can I help you?"\"Yes, please. Thank you.";
            }

            private IEnumerable<string> FindAllClickableSpans(string article)
            {
                article = article.ToLower();

                return article.Split('.');

            }


text:
Q: Validate Multiple email address columns and concate both columns value into 1 column value delimited by pipe using pyspark dataframe I have two email address in pyspark dataframe and need to validate both the email address columns value and then merge into 1 column value using pipe as delimiter.
Primary_Email_Address       Alternate_Email_Address      Output(email_address)
navg@gmail.com                nvgng@gm@.com              navg@gmail.com
ggg@gmail.com                 nnnn@gmail.com             ggg@gmail.com|nnnn@gmail.com
nave@gmail.com|gg@gmail.com   ndg@gmail.com          nave@gmail.com|gg@gmail.com|ndg@gmail.com

I need to pass columns dynamically  from spark dataframe csv file and handle it.
I have written below code but need some modification.
from pyspark.sql.session import SparkSession
from pyspark.sql.functions import concat, lit, col, trim, when
from pyspark.sql import functions as F

spark = SparkSession.builder.getOrCreate()
regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'

df = spark.read.option("header",True).csv("file_name.csv")

# select specific columns

df1 = df.select("primary_email_addr","alt_email_addr")

# concat the columns

df_email = df1.withColumn('email_addr',concat(df1['primary_email_addr'],lit("|"),df1['alt_email_addr'])))

df_email_1 = df_email.drop("primary_email_addr","alt_email_addr")

df_email_2 = df_email_1.withColumn("email_addr_status",when(F.col("email_addr").rlike("^(([a-zA-Z0-9_.+-]+)+@.+\\.[A-Za-z]+)(| ([a-zA-Z0-9_.+-]+)+@.+\\.[A-Za-z]+)*$"),"Valid").otherwise("Invalid"))

df_email_2.show(truncate=False)

A: Here another approach using regexp_extract_all and array_join with Spark >= 3.1.0:
from pyspark.sql.functions import expr

cols = ['Primary_Email_Address', 'Alternate_Email_Address']
data = [("navg@gmail.com", "nvgng@gm@.com"),
        ("ggg@gmail.com", "nnnn@gmail.com")]

df = spark.createDataFrame(data, cols)

concat_expr = expr("concat_ws(',', Primary_Email_Address, Alternate_Email_Address)")
extract_expr = expr("regexp_extract_all(concat, '(\\\w+([\\\.-]?\\\w+)*@\\\w+([\\\.-]?\\\w+)*(\\\.\\\w{2,3})+)', 0)")
join_expr = expr("array_join(extract, '|')")

df.withColumn("concat", concat_expr) \
  .withColumn("extract", extract_expr) \
  .withColumn("output", join_expr) \
  .select("Primary_Email_Address", "Alternate_Email_Address", "output")

# +---------------------+-----------------------+----------------------------+
# |Primary_Email_Address|Alternate_Email_Address|output                      |
# +---------------------+-----------------------+----------------------------+
# |navg@gmail.com       |nvgng@gm@.com          |navg@gmail.com              |
# |ggg@gmail.com        |nnnn@gmail.com         |ggg@gmail.com|nnnn@gmail.com|
# +---------------------+-----------------------+----------------------------+

Logic:

*

*Use concat_ws to concatanate emails.

*Call regexp_extract_all to extract the array of valid emails.

*Call array_join to produce s string from the previous array with items seperated by |.

A: I am not sure if you looking for below solution or not -

*

*compare both the column

*If there is a mismatch - identify it

*Based on the identification, merge again

Modified my answer - Used from validate_email import validate_email module to validate the email
DF
    from validate_email import validate_email

df = spark.createDataFrame([("navg@gmail.com","nvgng@gm@.com "),("ggg@gmail.com","nnnn@gmail.com")],["Primary_Email_Address","Alternate_Email_Address"])

valid_email_udf = udf(lambda e: validate_email(e), T.BooleanType())
df = df.withColumn('is_valid_primary', valid_email_udf('Primary_Email_Address'))
df = df.withColumn('is_valid_alternate', valid_email_udf('Alternate_Email_Address'))
df.show()

Condition and final output
df = df.withColumn("cond_col", F.when(F.col("is_valid_primary") == F.col("is_valid_alternate"), True).otherwise(False))
df = df.withColumn("merged_email", F.when(F.col("cond_col") == True, F.concat_ws("|","Primary_Email_Address", "Alternate_Email_Address" )).otherwise(None))
df.show(truncate=False)

+---------------------+-----------------------+----------------+------------------+--------+----------------------------+
|Primary_Email_Address|Alternate_Email_Address|is_valid_primary|is_valid_alternate|cond_col|merged_email                |
+---------------------+-----------------------+----------------+------------------+--------+----------------------------+
|navg@gmail.com       |nvgng@gm@.com          |true            |false             |false   |null                        |
|ggg@gmail.com        |nnnn@gmail.com         |true            |true              |true    |ggg@gmail.com|nnnn@gmail.com|
+---------------------+-----------------------+----------------+------------------+--------+----------------------------+


text:
Q: A weakening of the Littlewood conjecture For real numbers $x$, let $\|x\|$ denote the distance from $x$ to the nearest integer. Define a function $\ell:\mathbb{R}^2\rightarrow\mathbb{R}$ by
$$\ell(\alpha,\beta)=\liminf_{n\rightarrow\infty}n\|n\alpha\|\|n\beta\|.$$
The Littlewood conjecture asserts that, for all $(\alpha,\beta)\in\mathbb{R}^2$, we have $\ell (\alpha,\beta)=0$.
Can anyone see how to prove the (seemingly much weaker) statement that, for all $(\alpha,\beta)\in\mathbb{R}$,
$$\inf_{A\in\mathrm{SL}_2(\mathbb{Z})}\ell\left(A\left(
\begin{array}{c}
\alpha\\
\beta\\
\end{array}
\right)\right)=0\quad ?$$
I wouldn't be surprised if this problem has an easy solution, but I haven't yet been able to find one. For the purposes of orientation note that, in the definition of $\ell$ if we replace $\liminf$ by $\inf$, then the problem becomes close to trivial.

A: I believe so.  Let $K$ be a large positive integer, and $N$ an integer parameter going to infinity. By Dirichlet approximation we can find $n \in [N,2N]$ such that $\|n\alpha\|, \|n\beta\| = O(N^{-1/2})$; we can in fact assume that $\|n\alpha\|, \|n \beta\| \asymp N^{-1/2}$ since otherwise we are done.  For sake of notation let's suppose that the signed fractional parts $\{n\alpha\}, \{n\beta\} \in (-1/2,1/2]$ are positive (and thus comparable to $N^{-1/2}$).  Let $p_j/q_j$ be the last continued fraction approximant to $\{n\alpha\}/\{n\beta\}$ (a quantity comparable to 1) with $q_j \leq K$.  (Note we may assume this ratio is irrational, since Littlewood's conjecture is easy in the commensurate case.) Standard continued fraction theory tells us that
$$ p_{j-1} q_j - p_j q_{j-1} = \pm 1$$
and
$$ p_j - q_j \{n\alpha\}/\{n\beta\} = O(1/q_{j+1})$$
$$ p_{j-1} - q_{j-1} \{n\alpha\}/\{n\beta\} = O(1/q_{j})$$
and so $\| n (p_j \beta - q_j \alpha) \| = O( N^{-1/2}/q_{j+1} ) = O( N^{-1/2}/K)$ and $\| n (p_{j-1} \beta - q_{j-1} \alpha) \| = O( N^{-1/2}/q_j ) = O(N^{-1/2})$.  After pigeonholing we can find (for fixed $K$) an infinite sequence of $N$ such that the $p_j,q_j,p_{j-1},q_{j-1}$ are constant, and thus $\ell( p_j \beta - q_j \alpha, p_{j-1} \beta - q_{j-1} \alpha ) = O(1/K)$.  Letting $K$ to infinity we obtain the claim.


text:
Q: better way to modify sudoers file We used to run our application as a special user (say "suser") instead of root user. So we will give some permissions to this suser for running some commands without needing a password by adding this in the /etc/sudoers file.
I believe changing this file will require a reboot or log off. Correct me if I am wrong.
Which one is better changing directly /etc/sudoers file or adding a separate sudoers file in /etc/sudoers.d directory ? Is there any reason to avoid modifying /etc/sudoers file directly ?
During uninstall of my application, is removing the user (suser) alone enough?

A: Changing /etc/sudoers file does not require a reboot or log off changes are reflected immediately once the file is saved.using the visudo command is the recommended way to update sudoers content, since it protects against many failure modes.
keeping changes in /etc/sudoers.d directory is a convenient way to add and remove permissions(application specific) instead of modifying the /etc/sudors file.


text:
Q: How to call MoveDataTableCursor in a web test plugin to go through a limited set of rows in a table? I have some difficulties understanding how the access method "Do not move cursor automatically" works for a web test data source. And the documentation out there seems to be far from exhaustive.
First of all, let's assume there is a simple web test with only one request. It uses a data source called DS with a table called StepList, that contains 5 rows.
The Access Method for the table is set to "Do not move cursor automatically" and the current test settings have "One run per data source row" enabled in the web test properties. The web test is not part of a load test.
In these conditions, the test is run 5 times, for each row, so it basically moves the cursor automatically. Is this intended?
Now, on to the practical question, which is the subject of this post.
My StepList table above has, among others, an identity column and a StepId column. The web test in question is actually called from another web test, and it's supposed to run only for the table rows that have a StepId set in the test context.
Id  StepId
1   1
2   1
3   2
4   2
5   2

In order to achieve this, I followed the guidelines from here and wrote a web test plugin with the PreWebTest method looking like this:
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
    string stepId = string.Empty;

    if (e.WebTest.Context.ContainsKey(ContextParameterName))
    {
        stepId = e.WebTest.Context[ContextParameterName].ToString();
    }

    while (e.WebTest.Context["DS.StepList.StepId"].ToString() != stepId)
    {
        e.WebTest.MoveDataTableCursor("DS", "StepList");
    }
}

The code above seems to work properly on the example table only if the stepId has the value "2". If it's "1", then MoveDataTableCursor throws WebTestEndOfDataException exception: "No more rows of data in a data source table with AccessMethod Unique".
I tried catching the exception and stopping the web test, but this doesn't work, as the test seems to never end.

A: To answer your first question: the setting "Do not move cursor automatically" applies to runs within a load test only, which is why the cursor still moves automatically during a web test where you are using the setting "One run per data source row".   Of course, the latter setting applies to web test runs only.
The reason you are getting the WebTestEndOfDataException is:

*

*The way "One run per data source row" is implemented by the Visual Studio test engine includes the fact that there is only one data cursor for all five tests; i.e. the state of the cursor is remembered between all 5 tests.

*Each test iteration automatically increments the data cursor by itself.

*Your plugin advances the data cursor within this set of 5 tests, necessarily exhausting the available rows before the 5 tests have completed.

The simplest way to make your test work is to manually set the number of iterations instead of using "One run per data source row".  For example, there are only two valid rows in your data, so set the iterations to 2.  However, this is also a bad solution because you would have to manually count rows and change the value.
The next best way is to change your WebTestPlugin such that all it does is check the value of DS.StepList.StepId and do WebTest.Stop() if it doesn't match the desired value.  This way, the unwanted iterations will terminate immediately.  However, they will still waste time and add visual clutter.
If the parent test should always run, and it is only the called test that should be skipped, then wrap the "Call to WebTest" in a "String Comparison" Conditional Rule that checks the value of DS.StepList.StepId against the stepId context parameter, thus only calling the child test when the StepId is correct.


text:
Q: Autoplay for slides in fullpage.js I have this code.
$('#fullpage').fullpage({
    anchors: ['home', 'about', 'contact'],
    afterRender: function () {
        setInterval(function () {
            $.fn.fullpage.moveSlideRight();
        }, 2000);
    }
});

By default slides move from left to right. My problem: when we come to last slide - animate of slides is happening from right to left, through other slides. How can i implement animate slides from last slide to first by default animate (from left to right)?
For vertical scrolling it have already done. If we write continuousVertical: true will get this rusult.

A: There is an issue on the fullPage github project which I think is talking about what you're trying to do: https://github.com/alvarotrigo/fullPage.js/issues/124
The plugin author says he will not include the feature but later says you can contact him for help customising the plugin.
There is also a comment from someone with a workaround you could try:

*

*when scroll to the last slide, start a setTimeout() for the display time, then "fade out" all slides.

*when scroll to the first slide, start a setTimeout() for the "pull back" action, then "fade in" all slides.


text:
Q: MPAndroidChart:- How to reduce the distance between the x axis points in a line chart? I am plotting a real time data using MPAndroidChart. The X axis and Y axis are defined as below. Data is populating to the graph without any issues. The result is supposed to be in a wave form. Since the Y axis range is too high I am getting the values as lines. Could anyone help me on how to adjust the X axis range based on the Y axis vale, so that it can plot the values correctly.
    XAxis xl = mChart.getXAxis();
    xl.setTextColor(Color.WHITE);
    xl.setDrawGridLines(false);
    xl.setDrawLabels(false);
    xl.setAvoidFirstLastClipping(true);
    xl.setSpaceBetweenLabels(5);
    xl.setEnabled(true);

    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.setTextColor(Color.WHITE);
    leftAxis.setAxisMaxValue(4000f);
    leftAxis.setAxisMinValue(-4000f);
    leftAxis.setDrawGridLines(true);

A: Setting the chart property chart.setVisibleXRange(100,100) properly solved my issue. There was nothing to do with the X-axis value.


text:
Q: Extracting year from a date timestamp in SQL I am trying to convert a column in a database into a timestamp format, then I want to see the number of counts for each year.
I have:
SELECT
    (column_name::date), count(*)
    EXTRACT(YEAR FROM column_name)
FROM table
GROUP BY column_name;

'I get an error message that says no function matches the given name and argument types. You might need to add explicit type casts.'
Is extract the wrong function?

A: You probably want something like this if column_name is timestamp
search for EXTRACT documentation
SELECT
    EXTRACT(YEAR FROM column_name), count(*)
FROM table
GROUP BY EXTRACT(YEAR FROM column_name);

if column_name is string you need to_timestamp() function