title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Using JavaScript with Angular Component: Cannot read property 'id' of null
|
<p>I have successfully managed to connect my external <code>JavaScript</code> file to my <code>angular</code> component, however it doesn't work in some instances.</p>
<p>I connected my <code>src/custom.js</code> file to my <code>app.component.html</code> through <code>angular.json</code>, as illustrated below: </p>
<pre class="lang-js prettyprint-override"><code>"styles": [
"node_modules/bootstrap/dist/css/bootstrap.css",
"src/styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/bootstrap/dist/js/bootstrap.js",
"src/custom.js"
]
</code></pre>
<p><em>Context:</em><br/>
The demo script is a simple alert saying hello that pops every time I connect to my localhost. <br/>As far as I'm aware there's no issue with the external <code>js</code> file being referenced.</p>
<p>My issue seems to come from more complex functions.<br/>
<a href="https://www.w3schools.com/howto/howto_js_draggable.asp" rel="nofollow noreferrer">Here's the example that am trying to implement</a> from w3schools.</p>
<p>And it's set up as follows:</p>
<pre class="lang-html prettyprint-override"><code><!-- app.component.html -->
<div id="mydiv">
<div id="mydivheader">Click here to move</div>
<p>Move</p>
<p>this</p>
<p>DIV</p>
</div>
</code></pre>
<pre class="lang-js prettyprint-override"><code>// custom.js
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.clientX; pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
</code></pre>
<blockquote>
<p><strong>Error: Cannot read property 'id' of null at dragElement (custom.js:13) at custom.js:6</strong></p>
</blockquote>
<p>I have come across a similar error before.<br/>My suspicion is that it has something to do with loading the <code>DOM</code> vs running the <code>js</code>? </p>
<p>Unfortunately I'm very new to <code>Angular</code>, with no experience in setting up basic web pages.</p>
<p><strong>Does anybody have any insight?</strong></p>
| 3 | 1,091 |
Spring MVC not loading resources
|
<p>This is really frustrating I would appreciate some help with this as I have a deployment on coming weekend and suddenly the application has stopped working.
I have a Spring 4.3.3 application hosted on Apache Tomcat 7 with JDK 1.7. The application was running fine when it suddenly stopped loading all the JS, CSS and image files with an HTTP Status code of 405 (Get Method not allowed). The only noticeable change that I did was update the Java installed on my laptop. I have even uninstalled that version of java but no benefit.</p>
<p>The network tab of chrome shows the following result.</p>
<p><a href="https://i.stack.imgur.com/O1vnh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O1vnh.png" alt="enter image description here"></a></p>
<p>The error shown in Chrome browser is given below:</p>
<pre><code>General:
Request URL:http://localhost:8080/TractivityPhase3/resources/ui/jquery-ui.css
Request Method:GET
Status Code:405 Method Not Allowed
Remote Address:[::1]:8080
Referrer Policy:no-referrer-when-downgrade
Response Headers:
view source
Allow:POST
Content-Length:96
Content-Type:text/html;charset=ISO-8859-1
Date:Mon, 10 Jul 2017 12:12:49 GMT
Server:Apache-Coyote/1.1
Request Headers:
view source
Accept:text/css,*/*;q=0.1
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:JSESSIONID=8F5257A38E3AC1FBBD4BCF0A869A5A05
Host:localhost:8080
Referer:http://localhost:8080/TractivityPhase3/login
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
</code></pre>
<p>My web.xml code is given below:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>Spring MVC Application</display-name>
<welcome-file-list>
<welcome-file>createIdeaPublic</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<display-name>Tractivity</display-name>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
<servlet>
<servlet-name>Tractivity</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Tractivity</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.soft.utils.SessionListener</listener-class>
</listener>
<error-page>
<location>/jsp/components/jspError.jsp</location>
</error-page>
</web-app>
</code></pre>
<p>The dispatcher-Servlet configuration is given below.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<context:component-scan base-package="com.soft.controllers, com.soft.ajax,com.soft.services, com.soft.daos" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/templates/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/ui/**" location="/resources/ui/jquery-ui-1.12.1.custom/" />
<!-- <mvc:resources mapping="/resources/ui/**" location="/resources/ui/jquery-ui-1.12.1.custom/" /> -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven/>
<!--
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean> -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="dataSource" class="com.soft.utils.SecureDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<context:property-placeholder location="jdbc.properties, security.properties"/>
<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
setting maximum upload size
<property name="maxUploadSize" value="100000" />
</bean> -->
<bean id="emailer" class="com.soft.utils.Emailer">
<property name="host" value="localhost"/>
<property name="from" value="CIActivityTracker@abc.com"/>
<property name="username" value="368649312300d9094a62" />
<property name="password" value="cbe8181247b9785036ee" />
</bean>
<bean id="ldapContextSource" class="com.soft.utils.LdapContextSource">
<property name="url" value="${ldap.url}"/>
<property name="base" value="${ldap.base}"/>
<property name="userDn" value="${ldap.userDn}"/>
<property name="pass" value="${ldap.password}"/>
<property name="referral" value="follow"/>
<property name="ldapAuthentication" value="${ldap.authentication}"/>
</bean>
<!-- Aspect -->
<bean id="logAspect" class="com.soft.aspect.LoggingAspect" />
<bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="quartzExample" />
<property name="targetMethod" value="printMessage" />
</bean>
<bean id="quartzExample" class="com.soft.quartz.QuartzExample">
<property name="dbcViewName" value="${dbc.view}"/>
</bean>
<bean id="dailyTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="cronExpression" value="0 0/2 * * * ? *" />
</bean>
<bean id="weeklyTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="cronExpression" value="0/6 * * ? * L *" />
</bean>
<bean id="monthlyTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="cronExpression" value="0/6 * * L * ? *" />
</bean>
<bean id="quarterlyTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="cronExpression" value="0/1 * * L MAR,JUN,SEP,DEC ? *" />
</bean>
<bean id="annualTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="cronExpression" value="0/1 * * 31 12 ? *" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<!-- <ref bean="dailyTrigger" /> -->
<ref bean="dailyTrigger" />
</list>
</property>
</bean>
</beans>
</code></pre>
<p><strong>EDIT:</strong>
I have temporarliy fixed the issue by adding the following to web.xml. However, I would like a clean way of handling it through the Dispatcher Servlet's tag.</p>
<pre><code><servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.PNG</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ico</url-pattern>
</servlet-mapping>
</code></pre>
| 3 | 4,644 |
Jenkins run up an Amazon EC2 Linux Ubuntu instance failing
|
<p>I have configured and tried to run Jenkins System Configuration from AWS windows system: </p>
<p>It is failed and thrown the fallowing error.</p>
<p>I insalled manually Java 1.7</p>
<hr>
<pre><code>Jun 29, 2018 6:22:29 PM null
FINEST: Node RocketChat-Server (i-034fb93609641e1b1)(i-034fb93609641e1b1) is still pending/launching, waiting 5s
Jun 29, 2018 6:22:35 PM null
FINEST: Node RocketChat-Server (i-034fb93609641e1b1)(i-034fb93609641e1b1) is still pending/launching, waiting 5s
Jun 29, 2018 6:22:40 PM null
FINEST: Node RocketChat-Server (i-034fb93609641e1b1)(i-034fb93609641e1b1) is still pending/launching, waiting 5s
Jun 29, 2018 6:22:45 PM null
FINEST: Node RocketChat-Server (i-034fb93609641e1b1)(i-034fb93609641e1b1) is still pending/launching, waiting 5s
Jun 29, 2018 6:22:50 PM null
FINER: Node RocketChat-Server (i-034fb93609641e1b1)(i-034fb93609641e1b1) is ready
Jun 29, 2018 6:22:50 PM null
INFO: Launching instance: i-034fb93609641e1b1
Jun 29, 2018 6:22:50 PM null
INFO: bootstrap()
Jun 29, 2018 6:22:50 PM null
INFO: Getting keypair...
Jun 29, 2018 6:22:50 PM null
INFO: Using key: FirstKeyPair
e8:59:89:73:4b:c5:55:1a:f9:18:85:95:a7:53:4c:a4:27:a1:a2:26
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAlZa6EHKfbQ2Fro4pEVhb/rPwlDRpZoUYZTVzzFbLTSajMTYj3PaiZzTBcLlY
lmiJfb7wtIJJ/xo9/SxdUXZHK6b3JBrfHUH7TVGW060ugeeJmfb
Jun 29, 2018 6:22:50 PM null
INFO: Authenticating as ubuntu
Jun 29, 2018 6:22:50 PM null
INFO: Connecting to ec2-35-178-118-236.eu-west-2.compute.amazonaws.com on port 22, with timeout 10000.
Jun 29, 2018 6:22:59 PM null
INFO: Failed to connect via ssh: There was a problem while connecting to ec2-35-178-118-236.eu-west-2.compute.amazonaws.com:22
Jun 29, 2018 6:22:59 PM null
INFO: Waiting for SSH to come up. Sleeping 5.
Jun 29, 2018 6:23:04 PM null
INFO: Connecting to ec2-35-178-118-236.eu-west-2.compute.amazonaws.com on port 22, with timeout 10000.
Jun 29, 2018 6:23:04 PM null
INFO: Connected via SSH.
Jun 29, 2018 6:23:04 PM null
INFO: connect fresh as root
Jun 29, 2018 6:23:04 PM null
INFO: Connecting to ec2-35-178-118-236.eu-west-2.compute.amazonaws.com on port 22, with timeout 10000.
Jun 29, 2018 6:23:05 PM null
INFO: Connected via SSH.
Jun 29, 2018 6:23:05 PM null
INFO: Creating tmp directory (/tmp) if it does not exist
Jun 29, 2018 6:23:06 PM null
INFO: Verifying: java -fullversion
bash: java: command not found
Jun 29, 2018 6:23:06 PM null
INFO: Installing: sudo yum install -y java-1.8.0-openjdk.x86_64
sudo: yum: command not found
Jun 29, 2018 6:23:06 PM null
WARNING: Failed to install: sudo yum install -y java-1.8.0-openjdk.x86_64
Jun 29, 2018 6:23:06 PM null
INFO: Verifying: which scp
/usr/bin/scp
Jun 29, 2018 6:23:06 PM null
INFO: Copying slave.jar to: /tmp
Jun 29, 2018 6:23:06 PM null
INFO: Launching slave agent (via Trilead SSH2 Connection): java -jar /tmp/slave.jar
ERROR: SSH channel is closed
</code></pre>
<blockquote>
<p>java.io.IOException: SSH channel is closed
at >com.trilead.ssh2.channel.ChannelManager.ioException(ChannelManager.java:1543)
at >com.trilead.ssh2.channel.ChannelManager.sendData(ChannelManager.java:373)
at >com.trilead.ssh2.channel.ChannelOutputStream.write(ChannelOutputStream.java:63)
at hudson.remoting.BinarySafeStream$2._write(BinarySafeStream.java:272)
at hudson.remoting.BinarySafeStream$2.write(BinarySafeStream.java:255)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
at >java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)
at java.io.ObjectOutputStream.writeNonProxyDesc(Unknown Source)
at java.io.ObjectOutputStream.writeClassDesc(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeFatalException(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at hudson.remoting.Capability.writePreamble(Capability.java:142)
at hudson.remoting.ChannelBuilder.negotiate(ChannelBuilder.java:388)
at hudson.remoting.ChannelBuilder.build(ChannelBuilder.java:354)
at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:415)
at >hudson.plugins.ec2.ssh.EC2UnixLauncher.launch(EC2UnixLauncher.java:217)
at >hudson.plugins.ec2.EC2ComputerLauncher.launch(EC2ComputerLauncher.java:122)
at hudson.slaves.SlaveComputer$1.call(SlaveComputer.java:288)
at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
at jenkins.security.ImpersonatingExecutorService$2.call(ImpersonatingExecutorService.java:71)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Suppressed: java.io.IOException: SSH channel is closed
at com.trilead.ssh2.channel.ChannelManager.ioException(ChannelManager.java:1543)
at com.trilead.ssh2.channel.ChannelManager.sendData(ChannelManager.java:373)
at com.trilead.ssh2.channel.ChannelOutputStream.write(ChannelOutputStream.java:63)
at hudson.remoting.BinarySafeStream$2._write(BinarySafeStream.java:272)
at hudson.remoting.BinarySafeStream$2.write(BinarySafeStream.java:255)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.flush(Unknown Source)
at java.io.ObjectOutputStream.flush(Unknown Source)
at hudson.remoting.Capability$1.close(Capability.java:132)
at hudson.remoting.Capability.writePreamble(Capability.java:144)
... 12 more
Caused by: java.io.IOException: Close requested by remote
at com.trilead.ssh2.channel.Channel.setReasonClosed(Channel.java:331)
at com.trilead.ssh2.channel.ChannelManager.msgChannelClose(ChannelManager.java:1254)
at com.trilead.ssh2.channel.ChannelManager.handleMessage(ChannelManager.java:1475)
at com.trilead.ssh2.transport.TransportManager.receiveLoop(TransportManager.java:809)
at >com.trilead.ssh2.transport.TransportManager$1.run(TransportManager.java:502)
... 1 more
[CIRCULAR REFERENCE:java.io.IOException: Close requested by remote]</p>
</blockquote>
<hr>
| 3 | 2,693 |
Processing exception while streaming http response object using Data Buffer
|
<p>Getting error "Unable to find a MessageBodyReader" while writing the response to a file using DataBufferUtils.</p>
<p>My code</p>
<pre><code>
public class Downloader {
public static void main(String[] args) {
Client targetClient = ClientBuilder.newClient();
WebTarget target = targetClient.target("https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-zip-file.zip");
Flux<DataBuffer> dataBufferFlux = (Flux<DataBuffer>) target
.request()
.rx(FluxRxInvoker.class).get(DataBuffer.class);
Path path = Paths.get("file.txt");
DataBufferUtils.write(dataBufferFlux, path, StandardOpenOption.CREATE).block();
}
}
</code></pre>
<p>Error stack trace</p>
<pre><code>
javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/zip and type class org.jboss.resteasy.plugins.providers.sse.SseEventInputImpl
at org.jboss.resteasy.core.interception.jaxrs.ClientReaderInterceptorContext.throwReaderNotFound(ClientReaderInterceptorContext.java:47)
at org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:133)
at org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:75)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:217)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:90)
at org.jboss.resteasy.specimpl.AbstractBuiltResponse.readEntity(AbstractBuiltResponse.java:262)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl$EventHandler.run(SseEventSourceImpl.java:338)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceScheduler$1.run(SseEventSourceScheduler.java:92)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Exception in thread "main" javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/zip and type class org.jboss.resteasy.plugins.providers.sse.SseEventInputImpl
at org.jboss.resteasy.core.interception.jaxrs.ClientReaderInterceptorContext.throwReaderNotFound(ClientReaderInterceptorContext.java:47)
at org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:133)
at org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:75)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:217)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:90)
at org.jboss.resteasy.specimpl.AbstractBuiltResponse.readEntity(AbstractBuiltResponse.java:262)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl$EventHandler.run(SseEventSourceImpl.java:338)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceScheduler$1.run(SseEventSourceScheduler.java:92)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:93)
at reactor.core.publisher.Mono.block(Mono.java:1663)
at Downloader.main(Downloader.java:32)
</code></pre>
<p>Dependencies</p>
<pre><code>
implementation("org.jboss.spec.javax.ws.rs:jboss-jaxrs-api_2.1_spec:1.0.3.Final")
implementation("org.jboss.resteasy:resteasy-reactor:4.6.0.Final")
implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.6.2.Final")
implementation("org.springframework.boot:spring-boot-starter-webflux:2.7.1")
</code></pre>
<p>Thins I have already tried :</p>
<pre><code>I have added jackson2 provider as suggested but that didn't work for me.
I also tried registering jackson provider explicitly but that too didn't work for me.
ResteasyProviderFactory instance= ResteasyProviderFactory.getInstance();
RegisterBuiltin.register(instance);
instance.registerProvider(ResteasyJackson2Provider.class);
</code></pre>
<p>I have referred <a href="https://docs.spring.io/spring-framework/docs/5.2.4.RELEASE/spring-framework-reference/web-reactive.html#webflux-codecs-streaming" rel="nofollow noreferrer">Spring Streaming doc</a> for the understanding the concept. I am very new to this.</p>
<p>Any ideas what is causing this issue of unable to find <strong>MessageBodyReader</strong> and how can we fix it?</p>
<p>Edit:</p>
<p>Used custom MessageBodyReader. But now that returns me below error. Not sure how to fix this as I am downloading a file.</p>
<pre><code>@Consumes("application/zip")
public class CustomMessageBodyReader
implements MessageBodyReader<SseEventInputImpl> {
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return type == SseEventInputImpl.class;
}
@Override
public SseEventInputImpl readFrom(Class<SseEventInputImpl> type,
Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream)
throws IOException, WebApplicationException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(SseEventInputImpl.class);
SseEventInputImpl myBean = (SseEventInputImpl) jaxbContext.createUnmarshaller()
.unmarshal(entityStream);
return myBean;
} catch (JAXBException jaxbException) {
throw new ProcessingException("Error deserializing a SseEventInputImpl.",
jaxbException);
}
}
}
</code></pre>
<p>Error with custom MessageBodyReader</p>
<pre><code>javax.ws.rs.ProcessingException: Error deserializing a SseEventInputImpl.
at CustomMessageBodyReader.readFrom(CustomMessageBodyReader.java:41)
at CustomMessageBodyReader.readFrom(CustomMessageBodyReader.java:17)
at org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext.readFrom(AbstractReaderInterceptorContext.java:101)
at org.jboss.resteasy.core.interception.jaxrs.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:80)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readFrom(ClientResponse.java:217)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:90)
at org.jboss.resteasy.specimpl.AbstractBuiltResponse.readEntity(AbstractBuiltResponse.java:262)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceImpl$EventHandler.run(SseEventSourceImpl.java:338)
at org.jboss.resteasy.plugins.providers.sse.client.SseEventSourceScheduler$1.run(SseEventSourceScheduler.java:92)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: javax.xml.bind.UnmarshalException: null
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:335)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:563)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:249)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:204)
at CustomMessageBodyReader.readFrom(CustomMessageBodyReader.java:38)
... 15 common frames omitted
Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1472)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:994)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:243)
... 19 common frames omitted
</code></pre>
<p>You can try it out using <a href="https://github.com/sunny-shaw/WebClient-API-Playground/blob/download-file/src/main/java/Downloader.java" rel="nofollow noreferrer">Project GitHub link</a> for understanding the issue better if interested.</p>
| 3 | 4,629 |
MySql calculate multiple column
|
<p>I have code below and in my query but the results it gives me is way off chart, so I thought maybe my calculation is wrong. <code>The Logic</code> is to have multiple column <code>sum</code> <code>minus</code> and <code>times</code> to eachother and the result based on my database numbers has to be <code>4.581.709.50</code> but I get something like <code>164.610.000</code></p>
<pre><code> SUM(c.gaji_pokok + c.uang_makan + c.tunjangan + c.kendaraan + c.overtime + c.komisi + c.lain_lain + c.cuti -
m.pot_absen_hari * m.pot_absen_rate - IFNULL(g.pot_absen_hari * g.pot_absen_rate, 0) - CONCAT((c.uang_makan)/0.25)*0.05 -
n.pot_komisi_dl - n.pot_komisi_p312 - n.pot_komisi_mteg - IFNULL(g.pot_komisi_kasbon, 0) - q.bpjs4 - o.pot_ppn_21pt - o.pot_pinjaman - o.pot_ppn21 - o.pot_bayar_bonus -
o.pot_bayar_thr - c.cuti) as bulan_ppn21,
</code></pre>
<h1>Query</h1>
<pre><code>SELECT
a.nip,
SUM(c.gaji_pokok + c.uang_makan + c.tunjangan + c.kendaraan + c.overtime + c.komisi + c.lain_lain + c.cuti -
m.pot_absen_hari * m.pot_absen_rate - IFNULL(g.pot_absen_hari * g.pot_absen_rate, 0) - CONCAT((c.uang_makan)/0.25)*0.05 -
n.pot_komisi_dl - n.pot_komisi_p312 - n.pot_komisi_mteg - IFNULL(g.pot_komisi_kasbon, 0) - q.bpjs4 - o.pot_ppn_21pt - o.pot_pinjaman - o.pot_ppn21 - o.pot_bayar_bonus -
o.pot_bayar_thr - c.cuti) as bulan_ppn21,
IFNULL((
CASE
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=50000000)
THEN (0.05*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)))
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=250000000)
THEN (0.15*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.15)-(q.jht*12)))
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=500000000)
THEN (0.25*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.25)-(q.jht*12))) end),0) as tahun_pph21,
IFNULL((
CASE
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=50000000)
THEN (0.05*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)))
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=250000000)
THEN (0.15*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.15)-(q.jht*12)))
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=500000000)
THEN (0.25*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.25)-(q.jht*12))) end) -(
CASE
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=50000000)
THEN (0.05*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)))
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=250000000)
THEN (0.15*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.15)-(q.jht*12)))
WHEN ((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)<=500000000)
THEN (0.25*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.25)-(q.jht*12))) end)/12,0) - (
CASE
WHEN (((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate))<=50000000)
THEN (0.05*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate)))
WHEN (((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate))<=250000000)
THEN (0.15*((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate))-5000000)
WHEN (((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate))<=500000000)
THEN (0.25*(0.03*(c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate))-55000000)*1.2
WHEN (((c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate))<=500000000)
THEN (0.25*(0.03*(c.gaji_pokok * 12)-((c.gaji_pokok * 12)*0.05)-(q.jht*12)-(r.pt_kp_rate))-55000000)*1.2 end) as tot_pph21
FROM `t_pegawai` a
LEFT JOIN t_penggajian_karyawan c ON c.nip=a.nip
LEFT JOIN t_departemen d ON d.id_departemen=a.id_departemen
LEFT JOIN t_jabatan e ON e.id_jabatan=a.id_jabatan
LEFT JOIN t_perusahaan f ON f.kode_unitbisnis = a.unit_bisnis
LEFT JOIN absensi k ON k.pin = a.pin
LEFT JOIN t_periode l ON l.nama_periode=c.bulan and YEAR(l.periode_start) = c.tahun
LEFT JOIN t_potongan_absen m ON m.nip=a.nip and m.nip=c.nip and m.bulan = l.id_periode and m.tahun = YEAR(l.periode_start)
LEFT JOIN t_potongan_gaji g ON g.nip=a.nip and g.nip=c.nip and g.bulan = l.id_periode and g.tahun = YEAR(l.periode_start)
LEFT JOIN t_potongan_komisi n ON n.nip=a.nip and n.nip=c.nip and n.bulan = l.id_periode and n.tahun = YEAR(l.periode_start)
LEFT JOIN t_potongan_ppn o ON o.nip=a.nip and o.nip=c.nip and o.bulan = l.id_periode and o.tahun = YEAR(l.periode_start)
LEFT JOIN t_jenjang_bpjs q ON q.nip=a.nip and q.tahun = YEAR(l.periode_start)
LEFT JOIN t_ptkp r ON r.pt_kp_name=a.status_ptkp
WHERE l.id_periode='8' AND f.kode_unitbisnis ='PJS-001' and k.Tanggal >= l.periode_start and k.Tanggal <= l.periode_end
GROUP BY a.pin
</code></pre>
<p><strong>Any suggestion on calculation way to make it right?</strong></p>
| 3 | 3,229 |
Optimal way of multiprocessing a rowwise matching operation between two data frames
|
<p>I'm working on an entity resolution task with large databases (<code>df1</code> ~0.5 mil. rows, <code>df2</code> up to 18 mil. rows).</p>
<p>In <code>df1</code> I have first and last names, with first names being in regex form to allow for multiple variations of the same name - I didn't bother including it in the attached example, but the string values look something like: <code>^(^robert$|^rob$|^robb$)$</code>).</p>
<p>In <code>df2</code> I have regular first and last names.</p>
<p>My approach is to go through <code>df1</code> row by row, note the last name and first name regex, then filter <code>df2</code> first for an exact last name match, then for the first name regex match.</p>
<p>This is simulated in the below code.</p>
<pre><code>library(dplyr)
library(data.table)
set.seed(1)
df1 <- data.table(id1=sprintf("A%s",1:10000),
fnreg1=stringi::stri_rand_strings(n=10000,length=2,pattern="[a-z]"),
lname1=stringi::stri_rand_strings(n=10000,length=2,pattern="[a-z]")) %>%
dplyr::mutate(fnreg1 = paste0("^(",fnreg1,")$"))
df2 <- data.table(id2=sprintf("B%s",1:100000),
fname2=stringi::stri_rand_strings(n=100000,length=2,pattern="[a-z]"),
lname2=stringi::stri_rand_strings(n=100000,length=2,pattern="[a-z]"))
process_row <- function(i){
rw <- df1[i,]
fnreg <- rw$fnreg1
ln <- rw$lname1
ln.match <- df2[lname2==ln, ]
out.match <- ln.match[grepl(fnreg, fname2), ]
return(cbind(rw,out.match))
}
## 16 seconds
tictoc::tic()
out <- lapply(1:nrow(df1), process_row) %>% do.call(rbind,.) %>% na.omit()
tictoc::toc()
</code></pre>
<p>The <code>lapply</code> format I want to keep for parallelizing. I use the following code, note I'm on Windows so I need to prepare the clusters to get it working:</p>
<pre><code>library(parallel)
prep_cluster <- function(export_vars){
cl <- makeCluster(detectCores()-1)
clusterEvalQ(cl, library(dplyr))
clusterEvalQ(cl, library(data.table))
clusterExport(cl, export_vars)
return(cl)
}
cl <- prep_cluster(list("df1","df2","process_row"))
## 2 seconds
tictoc::tic()
out.p <- parLapply(cl, 1:nrow(df1), process_row) %>% do.call(rbind,.) %>% na.omit()
tictoc::toc()
stopCluster(cl)
</code></pre>
<p>For my large datasets, my code works pretty slowly. I'm almost certain that the way I defined <code>process_row</code> is very poorly optimized. But I'm not sure how to change the function to be faster and still conform to the <code>parLapply</code> format.</p>
<p>Any tips appreciated.</p>
<p>EDIT: I'm pretty short on memory, working with only 32GB - so I need to optimize it that way too.</p>
<p>For the largest data files (18 mil rows) I am splitting them into chunks and matching each chunk separately.</p>
| 3 | 1,222 |
How to feed a list of files into a bash script
|
<p>I'm having problems feeding a large list of filenames into a command in (git for windows git, I think it's cygwin)bash shell.</p>
<p>This is the basic command that works fine with a small set of arguments: <code>git filter-branch -f --tree-filter 'rm -rf file1 directory2 file3 file4'</code> However, I have about 1500 filenames.</p>
<p>I've tried: <code>git filter-branch -f --tree-filter 'rm -rf file1 directory2... all 1500 names here'</code> but I get an error: </p>
<blockquote>
<p>/mingw64/bin/git: Argument list too long</p>
</blockquote>
<p>I've tried to use a for loop: <code>git filter-branch -f --tree-filter 'for f in $(cat files.txt) ; do rm -fr "$f" ; done'</code> and this runs through the loop with an error: </p>
<blockquote>
<p>cat: files.txt: No such file or directory</p>
</blockquote>
<p>FYI - the files.txt contents look like this:</p>
<pre><code>./file1
./directory2
./file3
./file4
</code></pre>
<p>Then I tried: <code>git filter-branch -f --tree-filter < cat files.txt</code> and <code>cat files.txt | git filter-branch -f --tree-filter</code> but I get errors about the syntax not being correct - it shows the 'help' dialogue. eg:</p>
<blockquote>
<p>usage: git filter-branch [--setup ] [--subdirectory-filter
] [--env-filter ]
[--tree-filter ] [--index-filter ]
[--parent-filter ] [--msg-filter ]
[--commit-filter ] [--tag-name-filter ]
[--original ]
[-d ] [-f | --force] [--state-branch ]
[--] [...]</p>
</blockquote>
<p>Then I thought maybe I could just add the arguments into the file like this: <code>git filter-branch -f</code></p>
<p>File: </p>
<pre><code>--tree-filter './file1 ./directory2 ./file3 ./file4'
</code></pre>
<p>But I get the 'help' dialogue again.</p>
<p>I'm sure there is a way to do this, but my unix-fu is too weak. Please help! </p>
<hr>
<p>In response to @dash-o:</p>
<p>I tried this, but am getting an error: </p>
<blockquote>
<p>C:/Program Files/Git/mingw64/libexec/git-core\git-filter-branch: eval:
line 414: unexpected EOF while looking for matching `'' C:/Program
Files/Git/mingw64/libexec/git-core\git-filter-branch: eval: line 415:
syntax error: unexpected end of file</p>
</blockquote>
<p>The files.txt lists the files one per line. However, the rm -rf requires them to be on a single line and space-delimited. </p>
<p>I tried to put the files names on a single line, but I get a different error: </p>
<blockquote>
<p>C:/Program Files/Git/mingw64/libexec/git-core\git-filter-branch: line
414: rm -rf .vs ./file1 ./directory2: command not found tree filter
failed: 'rm -rf ./file1 ./directory2'</p>
</blockquote>
<p>Maybe the single quotes are being escaped and are not wrapped around the rm command?</p>
| 3 | 1,033 |
'paypal' is not defined in PHP
|
<p>I have codes in ajax which calls php file to show the paypal sdk button in that page :</p>
<pre class="lang-js prettyprint-override"><code>function redirectPaypal() {
$('#tabs2').html('<img src="' + webroot + 'facebox/loading.gif">');
callAjax(webroot + 'TESTS.php', 'mode=paypall', function (t) {
// $.facebox(t);
$('#walletBg').removeClass('addBgColor');
$('#paypalBg').addClass('addBgColor');
$('#neverBg').removeClass('addBgColor');
$('#authBg').removeClass('addBgColor');
// $('#paymentInfo').show();
$('#tabs2').html(t);
});
}
</code></pre>
<p>As you see it calls TESTS.php file with the mode value <code>paypal</code>. The TESTS.php file is looks like below :</p>
<pre class="lang-php-template prettyprint-override"><code><?
require_once 'application-top.php';
require_once 'includes/navigation-functions.php';
require_once 'includes/site-functions-extended.php';
require_once 'includes/buy-deal-functions.php';
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
$post = getPostedData();
print_r($post);
if ($_POST['mode'] == 'paypall')
{
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Checkout Integration | Client Demo </title>
</head>
<body>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
<script>
// Render the PayPal button into #paypal-button-container
paypal_sdk.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '88.44'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
</body>
</html>
<?
}
?>
</code></pre>
<p>File is called successfully but as you see the code below I am getting the reference error when the page is called :</p>
<pre><code>VM1597:3
Uncaught ReferenceError: paypal_sdk is not defined
at eval (eval at <anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11369), <anonymous>:3:9)
at eval (<anonymous>)
at js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11369
at Function.globalEval (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11380)
at HTMLScriptElement.<anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:2538)
at Function.each (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11776)
at init.domManip (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:2441)
at init.append (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:3:32408)
at init.<anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:1283)
at Function.access (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:13266)
</code></pre>
<p>The error is related to the script which is called in TESTS.php :</p>
<pre><code> <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
</code></pre>
<p>It seems the file is not imported or there is some errors in php file which I am not able to find it out. Can anyone help me with this please as I have spent my whole day on it. Thanks.</p>
<p><strong>EDIT :</strong>
I have seperated the codes like below in order to prevent the preloading the papyal.button codes first. And now it looks like below :</p>
<pre><code><?
require_once 'application-top.php';
require_once 'includes/navigation-functions.php';
require_once 'includes/site-functions-extended.php';
require_once 'includes/buy-deal-functions.php';
?>
<script type="text/javascript" src="https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD"></script>
<?
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
$post = getPostedData();
print_r($post);
if ($_POST['mode'] == 'paypall')
{
?>
<script src="https://example.com/TESTS.js"></script>
<?
}
?>
</code></pre>
<p>Now I am getting the error like below :</p>
<pre><code>GET https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD&_=1647908135353 net::ERR_ABORTED 400
</code></pre>
<p>When I checked the error code the requested src url is looking like different as it adds the timestamp at the end of the link therefore I am getting the error :</p>
<pre><code>https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD&_=1647908731335
</code></pre>
<p><strong>EDIT 2:</strong></p>
<p>The payment page looks like below :</p>
<p><a href="https://i.stack.imgur.com/98ymR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/98ymR.png" alt="enter image description here" /></a></p>
| 3 | 4,054 |
Vscode rust-analyser plugin, on macOS; failing to load workspace due to permission denied
|
<p><strong>Goal</strong></p>
<p>I'm trying to setup Visual Studio Code(vscode) on macOS for rust development.
I had my setup working, using the official rust extension, but it wasn't always consistent.
I saw that the rust-analyzer extension could provide a better experience.</p>
<p><strong>Problem</strong></p>
<p>Now that I have installed the extension, It keep throwing the following error:</p>
<pre><code>rust-analyzer failed to load workspace: "/Users/michaelbailey/.cargo" "--version" failed: Permission denied (os error 13)
</code></pre>
<p>From my understanding, the plugin is trying to execute the .cargo folder rather than cargo itself.</p>
<p>running</p>
<pre><code>$ /Users/michaelbailey/.cargo --version
zsh: permission denied: /Users/michaelbailey/.cargo
</code></pre>
<p>instead of</p>
<pre><code>$ /Users/michaelbailey/.cargo/bin/cargo --version
cargo 1.61.0 (a028ae42f 2022-04-29)
</code></pre>
<p>This is causing rust analyser to fail loading any project.</p>
<p><strong>What i have tried</strong></p>
<ul>
<li>Reinstalling the Rust-analyzer extension.</li>
<li>Disabling other rust based plugins.</li>
<li>Switching to the pre-release version.</li>
<li>reinstalling rust from the rust website.</li>
<li>clearing all rust settings.</li>
<li>creating a new project to test if my project was misconfigured somehow.</li>
</ul>
<p><strong>what i need help with</strong></p>
<ul>
<li>finding out a way to config rust-analyzer to point to the right file.</li>
<li>another way to resolve rust-analyzer.</li>
</ul>
<p>Any help or pointers on the matter would be greatly appreciated.</p>
<p><strong>Logs</strong></p>
<p>output of rust-analyzer, in the vscode output tab.</p>
<pre><code>INFO [6/9/2022, 6:10:00 PM]: Extension version: 0.3.1083
INFO [6/9/2022, 6:10:00 PM]: Using configuration {
cargoRunner: null,
runnableEnv: null,
server: { path: null, extraEnv: null },
trace: { server: 'off', extension: false },
debug: {
engine: 'auto',
sourceFileMap: {
'/rustc/<id>': '${env:USERPROFILE}/.rustup/toolchains/<toolchain-id>/lib/rustlib/src/rust'
},
openDebugPane: false,
engineSettings: {}
},
assist: { expressionFillDefault: 'todo' },
cachePriming: { enable: true, numThreads: 0 },
cargo: {
autoreload: true,
buildScripts: { enable: true, overrideCommand: null, useRustcWrapper: true },
features: [],
noDefaultFeatures: false,
noSysroot: false,
target: null,
unsetTest: [ 'core' ]
},
checkOnSave: {
allTargets: true,
command: 'check',
enable: true,
extraArgs: [],
features: null,
noDefaultFeatures: null,
overrideCommand: null,
target: null
},
completion: {
autoimport: { enable: true },
autoself: { enable: true },
callable: { snippets: 'fill_arguments' },
postfix: { enable: true },
privateEditable: { enable: false },
snippets: {
custom: {
'Arc::new': {
postfix: 'arc',
body: 'Arc::new(${receiver})',
requires: 'std::sync::Arc',
description: 'Put the expression into an `Arc`',
scope: 'expr'
},
'Rc::new': {
postfix: 'rc',
body: 'Rc::new(${receiver})',
requires: 'std::rc::Rc',
description: 'Put the expression into an `Rc`',
scope: 'expr'
},
'Box::pin': {
postfix: 'pinbox',
body: 'Box::pin(${receiver})',
requires: 'std::boxed::Box',
description: 'Put the expression into a pinned `Box`',
scope: 'expr'
},
Ok: {
postfix: 'ok',
body: 'Ok(${receiver})',
description: 'Wrap the expression in a `Result::Ok`',
scope: 'expr'
},
Err: {
postfix: 'err',
body: 'Err(${receiver})',
description: 'Wrap the expression in a `Result::Err`',
scope: 'expr'
},
Some: {
postfix: 'some',
body: 'Some(${receiver})',
description: 'Wrap the expression in an `Option::Some`',
scope: 'expr'
}
}
}
},
diagnostics: {
disabled: [],
enable: true,
experimental: { enable: false },
remapPrefix: {},
warningsAsHint: [],
warningsAsInfo: []
},
files: { excludeDirs: [], watcher: 'client' },
highlightRelated: {
breakPoints: { enable: true },
exitPoints: { enable: true },
references: { enable: true },
yieldPoints: { enable: true }
},
hover: {
actions: {
debug: { enable: true },
enable: true,
gotoTypeDef: { enable: true },
implementations: { enable: true },
references: { enable: false },
run: { enable: true }
},
documentation: { enable: true },
links: { enable: true }
},
imports: {
granularity: { enforce: false, group: 'crate' },
group: { enable: true },
merge: { glob: true },
prefix: 'plain'
},
inlayHints: {
bindingModeHints: { enable: false },
chainingHints: { enable: true },
closingBraceHints: { enable: true, minLines: 25 },
closureReturnTypeHints: { enable: 'never' },
lifetimeElisionHints: { enable: 'never', useParameterNames: false },
maxLength: 25,
parameterHints: { enable: true },
reborrowHints: { enable: 'never' },
renderColons: true,
typeHints: {
enable: true,
hideClosureInitialization: false,
hideNamedConstructor: false
}
},
joinLines: {
joinAssignments: true,
joinElseIf: true,
removeTrailingComma: true,
unwrapTrivialBlock: true
},
lens: {
debug: { enable: true },
enable: true,
forceCustomCommands: true,
implementations: { enable: true },
references: {
adt: { enable: false },
enumVariant: { enable: false },
method: { enable: false },
trait: { enable: false }
},
run: { enable: true }
},
linkedProjects: [],
lru: { capacity: null },
notifications: { cargoTomlNotFound: true },
procMacro: {
attributes: { enable: true },
enable: true,
ignored: {},
server: null
},
runnables: { command: null, extraArgs: [] },
rustc: { source: null },
rustfmt: {
extraArgs: [],
overrideCommand: null,
rangeFormatting: { enable: false }
},
semanticHighlighting: { strings: { enable: true } },
signatureInfo: { detail: 'full', documentation: { enable: true } },
typing: { autoClosingAngleBrackets: { enable: false } },
workspace: {
symbol: { search: { kind: 'only_types', limit: 128, scope: 'workspace' } }
}
}
INFO [6/9/2022, 6:10:00 PM]: PersistentState: { serverVersion: '0.3.1083' }
INFO [6/9/2022, 6:10:00 PM]: Using server binary at /Users/michaelbailey/.vscode/extensions/rust-lang.rust-analyzer-0.3.1083-darwin-x64/server/rust-analyzer
INFO [6/9/2022, 6:10:01 PM]: Extension version: 0.3.1083
INFO [6/9/2022, 6:10:01 PM]: Using configuration {
cargoRunner: null,
runnableEnv: null,
server: { path: null, extraEnv: null },
trace: { server: 'off', extension: false },
debug: {
engine: 'auto',
sourceFileMap: {
'/rustc/<id>': '${env:USERPROFILE}/.rustup/toolchains/<toolchain-id>/lib/rustlib/src/rust'
},
openDebugPane: false,
engineSettings: {}
},
assist: { expressionFillDefault: 'todo' },
cachePriming: { enable: true, numThreads: 0 },
cargo: {
autoreload: true,
buildScripts: { enable: true, overrideCommand: null, useRustcWrapper: true },
features: [],
noDefaultFeatures: false,
noSysroot: false,
target: null,
unsetTest: [ 'core' ]
},
checkOnSave: {
allTargets: true,
command: 'check',
enable: true,
extraArgs: [],
features: null,
noDefaultFeatures: null,
overrideCommand: null,
target: null
},
completion: {
autoimport: { enable: true },
autoself: { enable: true },
callable: { snippets: 'fill_arguments' },
postfix: { enable: true },
privateEditable: { enable: false },
snippets: {
custom: {
'Arc::new': {
postfix: 'arc',
body: 'Arc::new(${receiver})',
requires: 'std::sync::Arc',
description: 'Put the expression into an `Arc`',
scope: 'expr'
},
'Rc::new': {
postfix: 'rc',
body: 'Rc::new(${receiver})',
requires: 'std::rc::Rc',
description: 'Put the expression into an `Rc`',
scope: 'expr'
},
'Box::pin': {
postfix: 'pinbox',
body: 'Box::pin(${receiver})',
requires: 'std::boxed::Box',
description: 'Put the expression into a pinned `Box`',
scope: 'expr'
},
Ok: {
postfix: 'ok',
body: 'Ok(${receiver})',
description: 'Wrap the expression in a `Result::Ok`',
scope: 'expr'
},
Err: {
postfix: 'err',
body: 'Err(${receiver})',
description: 'Wrap the expression in a `Result::Err`',
scope: 'expr'
},
Some: {
postfix: 'some',
body: 'Some(${receiver})',
description: 'Wrap the expression in an `Option::Some`',
scope: 'expr'
}
}
}
},
diagnostics: {
disabled: [],
enable: true,
experimental: { enable: false },
remapPrefix: {},
warningsAsHint: [],
warningsAsInfo: []
},
files: { excludeDirs: [], watcher: 'client' },
highlightRelated: {
breakPoints: { enable: true },
exitPoints: { enable: true },
references: { enable: true },
yieldPoints: { enable: true }
},
hover: {
actions: {
debug: { enable: true },
enable: true,
gotoTypeDef: { enable: true },
implementations: { enable: true },
references: { enable: false },
run: { enable: true }
},
documentation: { enable: true },
links: { enable: true }
},
imports: {
granularity: { enforce: false, group: 'crate' },
group: { enable: true },
merge: { glob: true },
prefix: 'plain'
},
inlayHints: {
bindingModeHints: { enable: false },
chainingHints: { enable: true },
closingBraceHints: { enable: true, minLines: 25 },
closureReturnTypeHints: { enable: 'never' },
lifetimeElisionHints: { enable: 'never', useParameterNames: false },
maxLength: 25,
parameterHints: { enable: true },
reborrowHints: { enable: 'never' },
renderColons: true,
typeHints: {
enable: true,
hideClosureInitialization: false,
hideNamedConstructor: false
}
},
joinLines: {
joinAssignments: true,
joinElseIf: true,
removeTrailingComma: true,
unwrapTrivialBlock: true
},
lens: {
debug: { enable: true },
enable: true,
forceCustomCommands: true,
implementations: { enable: true },
references: {
adt: { enable: false },
enumVariant: { enable: false },
method: { enable: false },
trait: { enable: false }
},
run: { enable: true }
},
linkedProjects: [],
lru: { capacity: null },
notifications: { cargoTomlNotFound: true },
procMacro: {
attributes: { enable: true },
enable: true,
ignored: {},
server: null
},
runnables: { command: null, extraArgs: [] },
rustc: { source: null },
rustfmt: {
extraArgs: [],
overrideCommand: null,
rangeFormatting: { enable: false }
},
semanticHighlighting: { strings: { enable: true } },
signatureInfo: { detail: 'full', documentation: { enable: true } },
typing: { autoClosingAngleBrackets: { enable: false } },
workspace: {
symbol: { search: { kind: 'only_types', limit: 128, scope: 'workspace' } }
}
}
</code></pre>
| 3 | 4,847 |
Reading XML nodes in a C# program without the use of int.TryParse(node.InnerText)
|
<p>The following is a snippet of a much larger C# code. For the sake of convenience, I'm only providing the relevant information.</p>
<p>I'm trying to do a program that reads XML variables and puts them in a list. You then choose a name from the list based off of the names listed in the XML, and the values for that specific name are then shown in a series of text boxes in a Form. DValue is special, because it is a value that doesn't have to exist, so because of this, several elements in the XML form have empty nodes for DValue. An empty node should not affect the DValue previously presented.</p>
<p>For example If I chose "Additional 1" the values would be listed as 123, 4, 5, 6, but if we were to change it to "Pt 3" the values would be 123, 7, 8, 9. The DValue cannot change for empty nodes.</p>
<p>So this is where the problem comes in.</p>
<p>I was using int.TryParse(node.InnerText) to read my XML values, convert them into integers and display them in the form's boxes, but I recently found out that int.TryParse(node.InnerText) reads every node with said name, which makes things very messy. <strong>Basically, all of my empty nodes are being turned into 0 due to int.TryParse having 0 as a default value when it fails, and because of that, the program will not recognize when there's an empty node</strong>. As a result, every time I reference something with an empty node, <strong>it treats the DValue as 0 instead of doing nothing</strong>. I tried making a portion of code to read each individual DValue, and then perform the following if statement:</p>
<pre><code>if (element.IsEmpty)
{
DFound = false;
}
else
{
DFound = true;
int.TryParse(element.InnerText, out tempTRES.DVal);
}
</code></pre>
<p>But it still treats the empty variables as 0, and as a result every value is treated as "true" for the variable DFound. I've been working through a bunch of different potential solutions, but none of them seem to have worked because the empty variables would either be turned to zero, or the entire series of nodes just wouldn't load at all, but I'll leave that aside since this is already a pretty long question, and honestly, I'd have a tough time explaining some of the things I had done, but here are a few notable statements at least:</p>
<ul>
<li>string DValueText = Convert.ToString(element): I tried to convert a string value of each node into an integer so I'd never have to use InnerText, but trying to read nodes just breaks the code for reason's I'm not completely aware of yet.</li>
<li>element.InnerXml does nothing, and element.Value fails.</li>
<li>I tried setting the InnerText to something else, that way I could at least turn the empty variable into something that I could single out in an if statement, but the method I tried element.InnerText = "-100", didn't actually do anything.</li>
</ul>
<p>In summation. <strong>How can I make a clear distinction for when an XML node is "0", versus it being empty?</strong> Also, I'm sorry if this seems like a very simple problem. I've looked into this, but solutions for adding node values seem to always revolve around the assumption that one would be using int.TryParse(node.InnerText). Lastly, if something about this doesn't make sense, please let me know. As said, this is just a part of a much larger code, so it's very possible that some contextual information is missing.
The code and the XML can be found below:</p>
<hr />
<pre><code>int.TryParse(TRES.SelectSingleNode("AValue").InnerText, out tempTRES.AVal);
int.TryParse(TRES.SelectSingleNode("BValue").InnerText, out tempTRES.BVal);
int.TryParse(TRES.SelectSingleNode("CValue").InnerText, out tempTRES.CVal);
//Note: Every TRES needs an DValue node, even if empty.
if (TRES.SelectSingleNode("DOS/TRES/DValue") == null)
{
XmlElement element = TRES.SelectSingleNode("DValue") as XmlElement;
if (element.IsEmpty)
{
DFound = false;
}
else
{
DFound = true;
int.TryParse(element.InnerText, out tempTRES.DVal);
}
}
viewTRES_.Add(tempTRES);
viewTRES_.Add(tempTRES);
cbDVizViewTRES.Items.Add(tempTRES.name);
}
</code></pre>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<UNO>
<DOS>
<TRES Name="Pt 1">
<DValue></DValue>
<AValue>1</AValue>
<BValue>2</BValue>
<CValue>3</CValue>
</TRES>
<TRES Name="Pt 2">
<DValue></DValue>
<AValue>4</AValue>
<BValue>5</BValue>
<CValue>6</CValue>
</TRES>
<TRES Name="Pt 3">
<DValue></DValue>
<AValue>7</AValue>
<BValue>8</BValue>
<CValue>9</CValue>
</TRES>
<TRES Name="Additional 1">
<DValue>123</DValue>
<AValue>4</AValue>
<BValue>5</BValue>
<CValue>6</CValue>
</TRES>
<TRES Name="Additional 2">
<DValue>654</DValue>
<AValue>3</AValue>
<BValue>2</BValue>
<CValue>1</CValue>
</TRES>
<TRES Name="Additional 3">
<!--If you can really tell the difference between 0 and an empty variable, this shouldn't be a problem-->
<DValue>0</DValue>
<AValue>0</AValue>
<BValue>0</BValue>
<CValue>0</CValue>
</TRES>
</DOS>
</UNO>
</code></pre>
| 3 | 1,987 |
Why PMP (poor man's profiler) don't work on nginx?
|
<p>There is one very useful gdb "script" called <a href="http://poormansprofiler.org/" rel="nofollow">poor man's profiler</a>. It calls this command:</p>
<pre><code>gdb -ex "set pagination 0" -ex "thread apply all bt" --batch -p $pid
</code></pre>
<p>It works well for most linux processes, but don't work for <a href="http://nginx.org/" rel="nofollow">nginx</a> web server.</p>
<p>Normal output:</p>
<pre><code># gdb -ex "set pagination 0" -ex "thread apply all bt" -batch -p 5286
Using host libthread_db library "/lib/libthread_db.so.1".
[Thread debugging using libthread_db enabled]
[New Thread 0xb7d996c0 (LWP 5286)]
[New Thread 0xb588ab90 (LWP 5292)]
[New Thread 0xb608bb90 (LWP 5291)]
[New Thread 0xb688cb90 (LWP 5290)]
[New Thread 0xb708db90 (LWP 5289)]
[New Thread 0xb788eb90 (LWP 5288)]
0xffffe410 in __kernel_vsyscall ()
Thread 6 (Thread 0xb788eb90 (LWP 5288)):
#0 0xffffe410 in __kernel_vsyscall ()
#1 0xb7e5d7a6 in epoll_wait () from /lib/libc.so.6
#2 0xb7ef4f3b in epoll_dispatch () from /usr/lib/libevent-1.3b.so.1
#3 0xb7ee963a in event_base_loop () from /usr/lib/libevent-1.3b.so.1
#4 0x08055537 in worker_libevent (arg=0x805f3a0) at thread.c:245
#5 0xb7ed2192 in start_thread () from /lib/libpthread.so.0
#6 0xb7e5d02e in clone () from /lib/libc.so.6
[cut]
Thread 1 (Thread 0xb7d996c0 (LWP 5286)):
#0 0xffffe410 in __kernel_vsyscall ()
#1 0xb7e5d7a6 in epoll_wait () from /lib/libc.so.6
#2 0xb7ef4f3b in epoll_dispatch () from /usr/lib/libevent-1.3b.so.1
#3 0xb7ee963a in event_base_loop () from /usr/lib/libevent-1.3b.so.1
#4 0x0804f439 in main (argc=1, argv=0xbfbaff14) at memcached.c:4681
#0 0xffffe410 in __kernel_vsyscall ()
</code></pre>
<p>Nginx output:</p>
<pre><code># gdb -ex "set pagination 0" -ex "thread apply all bt" -batch -p 6120
Using host libthread_db library "/lib/libthread_db.so.1".
0xffffe410 in __kernel_vsyscall ()
</code></pre>
<p>But it works well if "bt" instead of "thread apply all bt" is used:</p>
<pre><code># gdb -ex "set pagination 0" -ex "bt" -batch -p 6120
Using host libthread_db library "/lib/libthread_db.so.1".
0xffffe410 in __kernel_vsyscall ()
#0 0xffffe410 in __kernel_vsyscall ()
#1 0xb7c83778 in epoll_wait () from /lib/libc.so.6
#2 0x080664c0 in ngx_epoll_process_events (cycle=0x80d14b8, timer=500, flags=1) at src/event/modules/ngx_epoll_module.c:530
#3 0x0805f73b in ngx_process_events_and_timers (cycle=0x80d14b8) at src/event/ngx_event.c:245
#4 0x080652b3 in ngx_worker_process_cycle (cycle=0x80d14b8, data=0x0) at src/os/unix/ngx_process_cycle.c:795
#5 0x08063ba1 in ngx_spawn_process (cycle=0x80d14b8, proc=0x80651fb <ngx_worker_process_cycle>, data=0x0, name=0x80a881d "worker process", respawn=-3) at src/os/unix/ngx_process.c:196
#6 0x080648d2 in ngx_start_worker_processes (cycle=0x80d14b8, n=8, type=-3) at src/os/unix/ngx_process_cycle.c:355
#7 0x0806581f in ngx_master_process_cycle (cycle=0xfffffffc) at src/os/unix/ngx_process_cycle.c:136
#8 0x0804d076 in main (argc=1, argv=0xbfd86544) at src/core/nginx.c:396
</code></pre>
<p>Why is that? As far as I know "thread apply all bt" must work even if there is only one execution thread in process.</p>
<p><strong>Update:</strong></p>
<p>Manual gdb connection and issuing "info threads" command.</p>
<pre><code># gdb -p 17461
GNU gdb 6.4
Copyright 2005 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i586-suse-linux".
Attaching to process 17461
Reading symbols from /export/depo/apache/linux/nginx-0.8.34/sbin/nginx...done.
Using host libthread_db library "/lib/libthread_db.so.1".
Reading symbols from /lib/libcrypt.so.1...done.
Loaded symbols for /lib/libcrypt.so.1
Reading symbols from /export/depo/mysql/linux/mysql-proxy-0.7.2/lib/libpcre.so.0...done.
Loaded symbols for /opt/gnu/mysql-proxy/lib/libpcre.so.0
Reading symbols from /usr/lib/libssl.so.0.9.8...done.
Loaded symbols for /usr/lib/libssl.so.0.9.8
Reading symbols from /usr/lib/libcrypto.so.0.9.8...done.
Loaded symbols for /usr/lib/libcrypto.so.0.9.8
Reading symbols from /lib/libdl.so.2...done.
Loaded symbols for /lib/libdl.so.2
Reading symbols from /lib/libz.so.1...done.
Loaded symbols for /lib/libz.so.1
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
0xffffe410 in __kernel_vsyscall ()
(gdb) info threads
(gdb) thread 0
Thread ID 0 not known.
(gdb) bt
#0 0xffffe410 in __kernel_vsyscall ()
#1 0xb7d0dd98 in __epoll_wait_nocancel () from /lib/libc.so.6
#2 0x08066e7d in ngx_epoll_process_events (cycle=0x816b708, timer=500, flags=1) at src/event/modules/ngx_epoll_module.c:530
#3 0x0805f4a2 in ngx_process_events_and_timers (cycle=0x816b708) at src/event/ngx_event.c:245
#4 0x08064d83 in ngx_worker_process_cycle (cycle=0x816b708, data=0x0) at src/os/unix/ngx_process_cycle.c:795
#5 0x08063661 in ngx_spawn_process (cycle=0x816b708, proc=0x8064ccb <ngx_worker_process_cycle>, data=0x0, name=0x80a42ed "worker process", respawn=-4) at src/os/unix/ngx_process.c:196
#6 0x080643a1 in ngx_start_worker_processes (cycle=0x816b708, n=8, type=-4) at src/os/unix/ngx_process_cycle.c:355
#7 0x0806595c in ngx_master_process_cycle (cycle=0x816b708) at src/os/unix/ngx_process_cycle.c:249
#8 0x0804cf7f in main (argc=1, argv=0xbfdb1874) at src/core/nginx.c:396
</code></pre>
| 3 | 2,394 |
I am trying to store the Authorization Token fetched from the Rest API and then use it in the headers of other API calls in Flutter
|
<p>As the title of the problem explains most of it but will still elaborate more.
So I am calling an API using the POST method and registering a user which gives me response data containing only the Authorization token which needs to be used while calling other APIs.</p>
<p>Now I want to store the token and use it in the headers while making other API calls.
I am herewith attaching a few code snippets that might demonstrate what I have done actually and what needs to be done in order to get the particular outcome.
I am getting the API response for fetching the key but I am unable to understand why it is not getting stored and why cannot I use it in the headers.</p>
<p><strong>API call that returns just the token in the response</strong></p>
<pre><code> final storage = SecureStorage();
Future<UserRegistration> registration(dynamic param) async {
var client = http.Client();
try {
var response = await client
.post(Uri.https("baseURL", "endpoint"),
body: param)
.timeout(Duration(seconds: TIME_CONST))
.catchError(handleError);
if (response.statusCode == 201) {
print('Response Body: ${response.body}');
final data = jsonDecode(response.body);
///////Using the flutter secure storage here to save the token
var token = storage.writeSecureToken('key', data['key']);
print("Token Here $token");
return UserRegistration(
key: data['key'],
status: true,
);
} else {
print("Something went wrong");
return param;
}
} on SocketException {
throw FetchDataException('message', 'url');
} on TimeoutException {
throw ApiNotRespondingException("message", "url");
}
}
</code></pre>
<p><strong>API response that I am getting</strong></p>
<pre><code>Response Body: {"key":"8fb303212871a80899f0b883f3554b189fddf24b"}
</code></pre>
<p><strong>API call that I am making which requires the Authorization Header as the key received in the previous response.</strong></p>
<pre><code>Future<PhoneOTPValidate> phoneOTPvalidate(dynamic param) async {
var client = http.Client();
var token = storage.readSecureToken('key');
try {
var response = await client
.post(
Uri.https("baseURL", "endpoint"),
headers: <String, String>{
'Authorization': 'Token $token',
},
body: param)
.timeout(Duration(seconds: TIME_CONST))
.catchError(handleError);
if (response.statusCode == 200) {
print('Response Body: ${response.body}');
final data = jsonDecode(response.body);
return PhoneOTPValidate(
status: data['success'],
validate: true,
);
} else {
print("The OTP is not valid");
return param;
}
} on SocketException {
throw FetchDataException('message', 'url');
} on TimeoutException {
throw ApiNotRespondingException("message", "url");
}
}
</code></pre>
<p><strong>My Classes for the above API calls are here:</strong></p>
<pre><code>class PhoneOTPValidate {
PhoneOTPValidate({this.status, this.validate});
final String? status;
final bool? validate;
}
class UserRegistration {
UserRegistration({this.key, this.status});
final String? key;
final bool? status;
}
</code></pre>
<p><strong>Flutter Secure Storage Class</strong></p>
<pre><code>class SecureStorage {
final storage = FlutterSecureStorage();
Future writeSecureToken(String key, String value) async {
var writeData = await storage.write(key: key, value: value);
print('Token Here');
return writeData;
}
Future readSecureToken(String key) async {
var readData = await storage.read(key: key);
return readData;
}
Future deleteSecureToken(String key) async {
var deleteData = await storage.delete(key: key);
return deleteData;
}
}
</code></pre>
<p><strong>Here's the output for what I have written:</strong></p>
<pre><code>Response Body: {"key":"de18d1239ed0b6be13f4c9a9d96eebeb1c401922"}
I/flutter (23010): Token Here Instance of 'Future<dynamic>'
I/flutter (23010): Token Here
</code></pre>
<p>How do I solve this problem of saving the key and using it in the headers of the other API calls?
Have almost tried all the solutions from StackOverflow but nothing gave a solid answer to how it is being done.
Am stuck at this problem for quite a few days
Would appreciate it if anyone can solve my problem considering my code.</p>
| 3 | 1,734 |
Debugging foreach in R using dorng
|
<p>I am parallelizing a task in R using <code>foreach</code> loop with reproducible results using the <code>dorng</code> operator. It is a complex code, and I have an error that I have not been able to identify even though I have run the same code with a regular <code>for</code> loop.</p>
<p>My fundamental question is: how do I debug a function within of a <code>foreach</code> loop assuming that I have reproducible results? Below is my current tentative.</p>
<p>In the <a href="https://cran.r-project.org/web/packages/doRNG/vignettes/doRNG.pdf" rel="nofollow noreferrer">vignette</a> of the doRNG package, it says that a sequence of random seeds will be generated and set at the beginning of each iteration using the R number generator "L’Ecuyer-CMRG". The sequence of random seeds can be defined using <code>set.seed</code> before the <code>foreach</code> loop:</p>
<pre><code>library(doRNG)
library(doParallel)
library(foreach)
registerDoParallel(2)
set.seed(1234)
f01 <- foreach(i = 1:100, .combine = 'c') %dorng% {
out <- 1 + i
}
r01 <- attr(f01, "rng")
set.seed(1234)
f02 <- foreach(i = 1:100, .combine = 'c') %dorng% {
out <- 1 + i
}
r02 <- attr(f02, "rng")
</code></pre>
<p>The objects <code>r01</code> and <code>r02</code> contain the sequence of seeds used in <code>f01</code> and <code>f02</code>,</p>
<pre><code>identical(f01, f02)
identical(r01, r02)
</code></pre>
<p>such that the results from the <code>foreach</code> loop and their seeds are identical as expected!</p>
<p>Then, let's consider the case when the <code>foreach</code> loop will give me a random error:</p>
<pre><code>set.seed(1234)
f03 <- foreach(i = 1:100, .combine = 'c') %dorng% {
u <- floor(runif(1, 1, 101))
if (i == as.integer(u)){
out <- "a" + "b"
} else {
out <- 1 + i
}
}
Error in { : task 67 failed - "non-numeric argument to binary operator"
</code></pre>
<p>The error occurs at iteration 67 and it is very easy to understand the error. Unfortunately, it is not the same in my case.</p>
<p>I would like to be able to use <code>debug</code> and walk through my function to understand the error. From the best of my knowlegde, I cannot use <code>debug</code> inside a <code>foreach</code> loop in R.</p>
<p>Then, I thought about capturing the error in a regular <code>for</code> loop, but running my code is very slow and, apparently, I cannot observe the error with a low number of iterations. I need to understand the error using <code>foreach</code>.</p>
<p>Although I can't recover the sequence of seeds from <code>f03</code>, I know that they will be identical to <code>r01</code> or <code>r02</code>. For iteration 67, I have</p>
<pre><code>r01[[67]]
[1] 10407 1484283582 -741709185 513087691 132931819
[6] 1318506528 -1383054295
</code></pre>
<p>Therefore, I guess that fixing my seed at <code>r01[[67]]</code> should give me the same error:</p>
<pre><code>i <- 67
set.seed(r01[[67]], kind = "L'Ecuyer-CMRG")
u <- floor(runif(1, 1, 101))
if (i == as.integer(u)){
out <- "a" + "b"
} else {
out <- 1 + i
}
u
[1] 74
</code></pre>
<p>which is not true.</p>
<p>In the doRNG <a href="https://cran.r-project.org/web/packages/doRNG/vignettes/doRNG.pdf" rel="nofollow noreferrer">vignette</a>, page 6, they have an example of using a seed in a loop from a previous loop:</p>
<pre><code>set.seed(1234)
ex01 <- foreach(i=1:5) %dorng% { runif(3) }
ex02 <- foreach(i=1:5, .options.RNG=attr(ex01, 'rng')[[2]]) %dorng% { runif(3) }
identical(ex02[1:4], ex01[2:5])
</code></pre>
<p>What am I missing?</p>
| 3 | 1,423 |
Optimizing MySQL CREATE TABLE Query
|
<p>I have two tables I am trying to join in a third query and it seems to be taking far too long.</p>
<p>Here is the syntax I am using</p>
<pre><code>CREATE TABLE active_users
(PRIMARY KEY ix_all (platform_id, login_year, login_month, person_id))
SELECT platform_id
, YEAR(my_timestamp) AS login_year
, MONTH(my_timestamp) AS login_month
, person_id
, COUNT(*) AS logins
FROM
my_login_table
GROUP BY 1,2,3,4;
CREATE TABLE active_alerts
(PRIMARY KEY ix_all (platform_id, alert_year, alert_month, person_id))
SELECT platform_id
, YEAR(alert_datetime) AS alert_year
, MONTH(alert_datetime) AS alert_month
, person_id
, COUNT(*) AS alerts
FROM
my_alert_table
GROUP BY 1,2,3,4;
CREATE TABLE all_data
(PRIMARY KEY ix_all (platform_id, theYear, theMonth, person_id))
SELECT a.platform_id
, a.login_year AS theyear
, a.login_month AS themonth
, a.person_id
, IFNULL(a.logins,0) AS logins
, IFNULL(b.alerts,0) AS job_alerts
FROM
active_users a
LEFT OUTER JOIN
active_alerts b
ON a.platform_id = b.platform_id
AND a.login_year = b.alert_year
AND a.login_month = b.alert_month
AND a.person_id = b.person_id;
</code></pre>
<p>The first table (logins) returns about half a million rows and takes less than 1 minute, the second table (alerts) returns about 200k rows and takes less than 1 minute. </p>
<p>If I run just the SELECT part of the third statement it runs in a few seconds, however as soon as I run it with the CREATE TABLE syntax it takes more than 30 minutes.</p>
<p>I have tried different types of indexes than a primary key, such as UNIQUE or INDEX as well as no key at all, but that doesn't seem to make much difference.</p>
<p>Is there something I can do to speed up the creation / insertion of this table?</p>
<p>EDIT:
Here is the output of the show create table statements</p>
<pre><code>CREATE TABLE `active_users` (
`platform_id` int(11) NOT NULL,
`login_year` int(4) DEFAULT NULL,
`login_month` int(2) DEFAULT NULL,
`person_id` varchar(40) NOT NULL,
`logins` bigint(21) NOT NULL DEFAULT '0',
KEY `ix_all` (`platform_id`,`login_year`,`login_month`,`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE `alerts` (
`platform_id` int(11) NOT NULL,
`alert_year` int(4) DEFAULT NULL,
`alert_month` int(2) DEFAULT NULL,
`person_id` char(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`alerts` bigint(21) NOT NULL DEFAULT '0',
KEY `ix_all` (`platform_id`,`alert_year`,`alert_month`,`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
</code></pre>
<p>and the output of the EXPLAIN</p>
<pre><code>id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE a (null) ALL (null) (null) (null) (null) 503504 100 (null)
1 SIMPLE b (null) ALL ix_all (null) (null) (null) 220187 100 Using where; Using join buffer (Block Nested Loop)
</code></pre>
| 3 | 1,180 |
How to create a generic function to load a view controller?
|
<p><strong>I have been trying to write a function that works with 3 parameters in order to load a view controller but I haven't been able to make it work.</strong> </p>
<p><em>I'm new into coding</em> and I am reading a tutorial that uses 2 view controllers (login & chat). In order to go from one to the other, the guide tells me to use this whether I want to log in or log out: </p>
<pre><code>@IBAction func loginDidTapped(_ sender: Any) {
// A
let storyboard = UIStoryboard (name: "Main", bundle: nil)
// B
let logVC = storyboard.instantiateViewController(withIdentifier: "LoginVC") as! LoginViewController
// C
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// D
appDelegate.window?.rootViewController = logVC
}
</code></pre>
<p>If I want to log in or log out I have to change 3 things: </p>
<ol>
<li><strong>logVC</strong> , <em>which I'd call <strong>var1</em></strong>, used in // B , // D</li>
<li><strong>"LoginVC"</strong> , <em>which I'd call <strong>var2</em></strong>, used in // B</li>
<li><strong>LoginViewController</strong> , <em>which I'd call <strong>var3</em></strong>, used in // B</li>
</ol>
<p>In my newb mind, I imagined that I could create a function that contained the <strong>"A, B, C, D"</strong> lines and let me call it anywhere later just by changing <strong>"var1, var2, var3"</strong> parameters</p>
<hr>
<p>This is what I first created using just <strong>var1</strong> and <strong>var2</strong>: </p>
<pre><code>import Foundation
import UIKit
import FirebaseAuth
class Helper {
static let helper = Helper()
func loadView (var1 : String , var2 : String) {
let storyboard = UIStoryboard (name: "Main", bundle: nil)
let var1 = storyboard.instantiateViewController(withIdentifier: var2) as! LoginViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = var1
}
}
</code></pre>
<p>I called it this way and it worked:</p>
<pre><code>Helper.helper.loadView(var1: "logVC" , var2: "LoginVC")
</code></pre>
<hr>
<p>Now, when I tried to use <strong>var3</strong> in line //B, inside the same function, Xcode underlines var3 and displays this error:</p>
<p><strong>Use of undeclared type 'var3'</strong></p>
<p>This is how it looked after adding a the <strong>var3</strong> parameter:</p>
<pre><code> func loadView (var1 : String , var2 : String , var3 : String) {
let storyboard = UIStoryboard (name: "Main", bundle: nil)
let var1 = storyboard.instantiateViewController(withIdentifier: var2) as! var3
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = var1
}
</code></pre>
<p>This is how I would have called it if it had worked:</p>
<pre><code>Helper.helper.loadView(var1: "logVC" , var2: "LoginVC" , var3: "LoginViewController")
</code></pre>
<hr>
<p>I'd like to know if is it possible to do what I am imaging since I see functions as equations in which I can replace variables with the information I need.</p>
<p>Thank you all in advance.</p>
| 3 | 1,201 |
Icons are scoped in a veird way (CSS scoping Vue.js 3)
|
<p>I am not 100% sure it is the scoping issue here, but here is the thing.</p>
<p>HTML:</p>
<pre><code><div class="search__sort">
<div class="search__bar">
<unicon class="search__icon" name="search" fill="#7f7d7d"/>
<input class="search" v-model="search" placeholder="Search for a house">
<unicon class="clear__icon" name="times" fill="#7f7d7d" @click="resetInput()" v-if="search != '' "/>
</div>
<button :class="[sortBy === 'price' ? sortDirection : '']" @click="sort('price')">Price</button>
<button :class="[sortBy === 'size' ? sortDirection : '']" @click="sort('size')">Size</button>
</div>
</code></pre>
<p>CSS:</p>
<pre><code><style lang="scss" scoped>
.search__sort {
margin-left: 290px;
.search__bar{
position: relative;
display: flex;
min-width: 100px;
.search__icon{
position: absolute;
top: 6px;
left: 8px;
width: 14px;
}
.clear__icon{
position: absolute;
top: 8px;
right: 8px;
width: 10px;
cursor: pointer;
}
.search {
border: none;
border-radius: 5px;
height: 20px;
width: 20%;
padding: 2px 23px 2px 30px;
outline: 0;
background-color: #ded9d9;
}
.search:hover, .search:focus {
border: 1.5px solid #009688;
background-color: white;
}
}
}
</style>
</code></pre>
<p>In the inspector the position of both icons (unicons) are static. Is there a way to fix that? In CSS I tried to make it a bit different, but it seems like those icons are not responding to any CSS entry in this case. I am using the Unicons <a href="https://github.com/antonreshetov/vue-unicons" rel="nofollow noreferrer">https://github.com/antonreshetov/vue-unicons</a></p>
<p><a href="https://i.stack.imgur.com/THYCa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/THYCa.png" alt="" /></a></p>
| 3 | 1,199 |
Mapbox : Add data layer for POIs - transportation, school and retail / grocery stores
|
<p>I am rendering a map using mapbox API and would like to enrich the map by displaying additional location / POI data.</p>
<p>Here's a similar example: <a href="https://github.com/patelnisarg61/Toronto-Fatal-Collisions-Analysis/blob/master/collision.py" rel="nofollow noreferrer">https://github.com/patelnisarg61/Toronto-Fatal-Collisions-Analysis/blob/master/collision.py</a></p>
<p>mock code below:</p>
<pre><code> MAPBOX_KEY = "xxxxx"
data = []
data.append({
"type": "scattermapbox",
"lat": df["Lat"],
"lon": df["Long"],
"name": "Location",
"hovertext": name,
"showlegend": False,
"hoverinfo": "text",
"mode": "markers",
"clickmode": "event+select",
"marker": {
"symbol": "circle",
"size": 12,
"opacity": 0.7,
"color": "black"
}
}
)
layout = {
"autosize": True,
"hovermode": "closest",
"mapbox": {
"accesstoken": MAPBOX_KEY,
"bearing": 0,
"center": {
"lat": layout_lat,
"lon": layout_lon
},
"pitch": 0,
"zoom": zoom,
"style": "outdoors",
},
"margin": {
"r": 0,
"t": 0,
"l": 0,
"b": 0,
"pad": 0
}
}
</code></pre>
<p>How do I add additional POI data such as transit, hospitals, schools and grocery stores using either native mapbox API endpoints or data from other providers such as OSM / Google Maps?</p>
<p>For reference, this data is available via the OSM Feed: <a href="https://docs.mapbox.com/vector-tiles/reference/mapbox-streets-v8/" rel="nofollow noreferrer">https://docs.mapbox.com/vector-tiles/reference/mapbox-streets-v8/</a></p>
<p>Plotly scattermapbox docs: <a href="https://plotly.com/python/reference/#scattermapbox-customdata" rel="nofollow noreferrer">https://plotly.com/python/reference/#scattermapbox-customdata</a></p>
| 3 | 1,705 |
Flutter: *** 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]
|
<p>I am pretty new to coding, but working on a flutter app and trying to integrate the ability to share images to Instagram Stories using the <a href="https://pub.dev/packages/social_share" rel="nofollow noreferrer">Social Share</a> package. Everything works fine to generate the photo and the dynamic link (can test by commenting out the SocialShare part), but when the app tried to open Instagram on iOS I am getting the following error</p>
<pre><code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
</code></pre>
<p>Image is generated using</p>
<pre><code>final newImage = await _socialShareService.sharedImage();
//then image is saved to Firebase and dynamic link generated
final postsUpdateData = createPostsRecordData(
sharedImage: newImage);
await containerPostsRecord.reference.update(
postsUpdateData);
var uri = await _dynamicLinkService
.createDynamicLink()
print(uri.toString());
//this is where the error is occurring
await SocialShare.shareInstagramStory(newImage,
backgroundBottomColor: "#000000",
backgroundTopColor: "#ffffff",
attributionURL: uri.toString());
</code></pre>
<p>I am having trouble understanding the error to figure out what is being called on nil. Full error message is below</p>
<pre><code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:
(0x180e350fc 0x199685d64 0x180f3e564 0x180f496e0 0x180df2514 0x180e10ebc 0x101d6c0a4 0x10507a75c 0x104bb3cf8 0x104f41bb4 0x104e691c0 0x104e6cf24 0x180e4a318 0x180dcecf0 0x180dc94ec 0x180da7d08 0x180dbb468 0x19c95f38c 0x18375e5d0 0x1834dcf74 0x100a1fb68 0x101589aa4)
libc++abi: terminating with uncaught exception of type NSException
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
frame #0: 0x00000001b84f7964 libsystem_kernel.dylib`__pthread_kill + 8
libsystem_kernel.dylib`__pthread_kill:
-> 0x1b84f7964 <+8>: b.lo 0x1b84f7984 ; <+40>
0x1b84f7968 <+12>: pacibsp
0x1b84f796c <+16>: stp x29, x30, [sp, #-0x10]!
0x1b84f7970 <+20>: mov x29, sp
Target 0: (Runner) stopped.
</code></pre>
<p>I know the error is coming from the AppDelegate.swift function, but I am not sure exactly how to solve this. Any insight is greatly appreciated!</p>
<p>UPDATED: Info.plist does include facebook and instagram.</p>
<pre><code><key>FacebookAppID</key>
<string>xxxxxxxxxxxxx</string>
<key>FacebookDisplayName</key>
<string>name</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fbauth</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
<string>instagram-stories</string>
<string>facebook-stories</string>
<string>facebook</string>
<string>instagram</string>
<string>twitter</string>
<string>whatsapp</string>
</array>
</code></pre>
<p><a href="https://i.stack.imgur.com/XuaWw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XuaWw.png" alt="enter image description here" /></a></p>
| 3 | 1,470 |
Run git post-receive hook as user1, and checkout as user2
|
<p>I'm setting up a deploy-on-git-push process on a remote Debian server. It is basically the common approach of having a bare repository with a post-receive hook which does a checkout to the web server's docroot, more or less.</p>
<p>I've used slightly simpler variations of this set up successfully for years, but this time around I'm complicating it by trying to separate ownership of the git repo and the site files between 2 different users. I don't want the user who can SSH in (the git push happens over SSH) to have write perms to the site, and vice-versa (the site user shouldn't have write perms to the git repository).</p>
<ul>
<li><p>I have 1 user, let's call her <code>git-user</code>, who owns a bare git repository at <code>/var/gitrepos/my_site.git</code>, and this user is the only user allowed to connect over SSH;</p>
</li>
<li><p>I have a 2nd user, say <code>site-user</code>, who should own the checked-out files at <code>/var/www/site</code>;</p>
</li>
</ul>
<p>I push over SSH to the repo, and this means any post-receive hook runs as the user I SSH in as - <code>git-user</code> in this case. So the post-receive hook can't do the checkout itself, as the site files would end up being owned by <code>git-user</code>, not <code>site-user</code>.</p>
<p>So my post-receive simply touches a trigger file, <code>/var/run/deploy</code>. A separate script is run from <code>site-user</code>'s cron frequently, eg every minute, looking for that file. If it sees it, it does a checkout to <code>/var/www/site</code>. The relevant part of that script looks something like:</p>
<pre><code># Running as site-user
mkdir $NEW \
&& cd $NEW \
&& git --work-tree=. --git-dir=/var/gitrepos/my_site.git checkout -f www
</code></pre>
<p>However this fails with:</p>
<blockquote>
<p>fatal: Unable to create '/var/gitrepos/my_site.git/index.lock': Permission denied</p>
</blockquote>
<p>This is true, <code>site-user</code> - intentionally - does not have write permission to <code>/var/gitrepos/my_site.git</code>. I am not sure why doing a checkout to a different directory <em>needs</em> to create a lockfile in the repo, but apparently it does, and I guess I shouldn't fight that.</p>
<p>So what are the options?</p>
<ul>
<li><p><code>git clone</code> doesn't need write perms to the repo, so this works, but it means I get the whole <code>.git/</code> directory. I have to remove that, or configure the web server to disallow access, both extra steps I'd rather avoid. Not a big deal obviously but this still feels wrong;</p>
</li>
<li><p>I could add both users to a group and set up <code>g+w</code> etc, but this voids the whole point of this approach (to deny each user write perms to the other's files);</p>
</li>
<li><p>I guess I could mess with <code>sudoers</code>, and allow one user to run a command as the other user, but again this feels like I am just chipping away at the separation I'm trying to enforce?</p>
</li>
<li><p>I can do a <code>git clone</code> to <code>$TMP_DIR</code>, followed by a <code>git checkout --git-dir=$TMP_DIR/.git/</code>, but this seems super clunky, as well as taking 2x as long;</p>
</li>
</ul>
<p>Any other neat options I am missing?</p>
<h3>UPDATE</h3>
<p>As suggested by @Matt below I tried setting <code>GIT_INDEX_FILE</code> to a writeable (by <code>site-user</code>) file outside the repository. This does seem to get past the first problem, but still fails with:</p>
<blockquote>
<p>error: Unable to create '/var/gitrepos/my_site.git/HEAD.lock': Permission denied</p>
</blockquote>
<p>I don't understand why a checkout to a new location needs to modify anything in the repository?</p>
| 3 | 1,164 |
how to count lines in a csv file in java where the file doesn't have ".csv" extension?
|
<p>I want to get file lines count where file is similar to "csv" but it doesn't have ".csv" file extension. I have only filename.</p>
<p>The code i have mentioned here is the function that count file lines of only those files which have name as abc.txt or abc.csv,, but it will not read the file if the extension doesn't have .txt or .csv. That is the code won't the file if file name is only "abc" instead of "abc.csv"</p>
<p>Here's the complete program:
There are three class</p>
<pre><code>package file_count_checker;
import java.util.Scanner;
public class File_Count_Checker {
public static void main(String[] args) {
//String s = "C:\\Users\\Nitish.kumar\\Desktop\\Automation\\Input";
String path;
System.out.println("Enter the folder Path : ");
Scanner in1 = new Scanner(System.in);
path = in1.nextLine();
FileTester ftMain = new FileTester();
ftMain.printFileList(path);
}
}
//------------
//Class2:
package file_count_checker;
import java.io.File;
import java.util.*;
public class FileTester {
// FileTester ft = new FileTester();
Map<String, List<String>> map = new HashMap();
FileLineCounter flc = new FileLineCounter();
boolean isFound; boolean isFoundTxt;
public void fileChecker(String folderPath) {
File f = new File(folderPath);
File[] listOfFiles = f.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
String path = file.getParent();
if (map.get(path) == null) {
List<String> fileList = new ArrayList<>();
map.put(path, fileList);
}
List<String> fileList = map.get(path);
fileList.add(file.getName());
} else if (file.isDirectory()) {
String s2 = file.getPath();
fileChecker(s2);
}
}
}
public void printFileList(String path){
fileChecker(path);
for(Map.Entry<String, List<String>> entry : map.entrySet()){
System.out.println("");
System.out.println("Folder Name : "+entry.getKey());
for(String file : entry.getValue()){
//Below code to check whether file is CSV, TXT or with other extension
isFound = file.contains(".csv");
isFoundTxt = file.contains(".txt");
System.out.println(" File Name : "+file);
if(isFound != true){
if(file.contains(".txt") !=true){
System.out.println(" Invalid file: unable to read " );}
}
else {
flc.startCount(entry.getKey()+"\\"+file); }
if(isFoundTxt != true ) { }
else {
flc.startCount(entry.getKey()+"\\"+file);
}
}
}
}
}
//Class 3--------------
package file_count_checker;
import java.io.File;
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;
public class FileLineCounter {
int totalLines = 0;
public void startCount(String filePath){
try {
File file =new File(filePath);
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null){
linenumber++;
}
System.out.println(" Total number of lines : " + linenumber);
System.out.println(" Size: "+getFileSizeKiloBytes(file));
lnr.close();
} //close of try block
//Below function to check file size
//File file = new File();
catch (IOException e){
System.out.println("Issues with the file at location:"+ filePath);
}
}
private static String getFileSizeKiloBytes(File file) {
return (double) file.length() / 1024 + " kb";
}
//close of main methods
}
</code></pre>
| 3 | 2,044 |
Error: Unhandled Rejection (TypeError): Cannot read property 'livres' of undefined, ReactJS, Search
|
<p><a href="https://i.stack.imgur.com/pyFda.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pyFda.png" alt="console result"></a>I am creating a search bar. The user write his request, and when he press the filter button corresponding, it's stocked in <code>search</code>, sent via Axios, and return the result at the end.However, I have the good results in my console (the code in the back is ok) but I didn't manage to display the data in my page only when I try with the edition filter (with the title filter it's ok). I have this error : Unhandled Rejection (TypeError): Cannot read property 'livres' of undefined. What can I ad/change in my code please?</p>
<pre><code>import React, {Component} from 'react';
import {
MDBContainer,MDBCol, MDBBtn,
} from 'mdbreact';
import "./accueil.css";
import axios from 'axios';
import { MDBDropdown,
MDBDropdownToggle, MDBDropdownMenu, MDBDropdownItem, } from "mdbreact";
class HomePage extends Component{
constructor(props){
super(props);
this.state = {
search:'',//va contenir la valeur entrée dans la barre de recherche
filter: [],//va contenir les resultats de la recherche
error:'',//va contenir l'erreur en cas d'erreur
}
this.searchTitle = this.searchTitle.bind(this);
this.searchEdition = this.searchEdition.bind(this);
}
change = e => {
this.setState({
[e.target.id]: e.target.value,
});
}
//search with the title filter
searchTitle = (search) => e => {
console.log(search);
let formData = new FormData();
formData.append("title",search);
const url = "http://localhost:8888/API/Accueil/recherche_titre.php"
axios.post(url, formData)
.then(response => response.data)
.then((data) => {
this.setState({filter: data.results.livres});
console.log(this.state.filter)
})
setTimeout(() => {
this.setState({
error: '',
});
}, 2000);
e.preventDefault();
}
//search with the edition filter
searchEdition = (search) => e => {
console.log(search);
let formData = new FormData();
formData.append("edition",search);
const url = "http://localhost:8888/API/Accueil/recherche_edition.php"
axios.post(url, formData)
.then((data) => {
this.setState({filter: data.results.livres});
console.log(this.state.filter)
})
setTimeout(() => {
this.setState({
error: '',
});
}, 2000);
e.preventDefault();
}
render() {
return(
<div>
<div className="searchPosition">
<MDBCol>
<div className="active-pink-3 active-pink-4 mb-4">
<input className="form-control" type="text" placeholder="Search..." aria-label="Search" />
</div>
</MDBCol>
</div>
<br></br>
<div >
<ul className="ulFilter">
<li className="liFilter">Choose a filter </li>
<li className="liFilter">
<MDBBtn onClick={this.searchTitle(this.state.search)} color="dark" size="lg">Titre</MDBBtn>
</li>
<li className="liFilter">
<MDBBtn onClick={this.searchEdition(this.state.search)} color="dark" size="lg">Edition</MDBBtn>
</li>
</ul>
<ul className="resultsSearch">
{ this.state.filter ? this.state.filter.map(book => (
<li className=".liResults" key={book.id}>{book.title},{book.edition}</li>
)) : <em>Loading</em>}
</ul>
</div>
</div>
);
}
}
export default HomePage;
</code></pre>
| 3 | 1,844 |
Android development in IntelliJ IDEA -v Eclipse (Starting an Activity)
|
<p>I am just beginning with developing Android projects and I've run into a road bump. I am starting with the developer site (http://developer.android.com/training/basics/firstapp/index.html) and my problem begins with starting a new Activity (http://developer.android.com/training/basics/firstapp/starting-activity.html)</p>
<p>The site expects Eclipse, and I suspect that I am missing something that happens behind the scenes with Eclipse, but I am using IntelliJ IDEA.</p>
<p>In DisplayMessageAcitivity.java I am getting the following Error:</p>
<pre><code>cannot find symbol variable activity_display_message.
</code></pre>
<p>In the Eclipse example, this is a Layout Name.</p>
<p>I am including my code as it was when I first encountered the issue rather than with my attempts at fixes.</p>
<p>DisplayMessageActivity:</p>
<pre><code>public class DisplayMessageActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
}
}
</code></pre>
<p>AndroidManifest:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="13"/>
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="MyActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".DisplayMessageActivity"
android:label="My Message">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.MainActivity"/>
</activity>
</application>
</manifest>
</code></pre>
<p>R.java:</p>
<pre><code>package com.example;
public final class R {
public static final class attr {
}
public static final class color {
public static final int testing_string_color=0x7f040000;
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int edit_message=0x7f060000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f050000;
public static final int button_send=0x7f050002;
public static final int edit_message=0x7f050001;
public static final int menu_settings=0x7f050003;
public static final int title_activity_main=0x7f050004;
}
}
</code></pre>
<p>main.xml:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<EditText android:id="@+id/edit_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/edit_message"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"/>
</LinearLayout>
</code></pre>
| 3 | 1,578 |
Something in this function is crashing my program!
|
<p>Howdy, When my program begins executing the code in case N of the switch statement it crashes. I am not sure why. Anyone care to take a gander?</p>
<p><strong>Code:</strong> (I suspect the problem is occurring somewhere in case N of the switch statement)</p>
<pre><code>#include "header.h"
void findSeats(int& FC_Row, int& FC_Col, int& EconRow, int& EconCol, int& ticketNum, int& rowNum, char& ticketType, char& seatType, int airplane[][6])
{
int aisle, col;
char letterCol;
if (ticketType = 'F')
{
switch (seatType)
{
case 'W':
if (airplane[rowNum - 1][0] == 0)
{
airplane[rowNum - 1][0] = 1;
cout << "Your seat is " << (rowNum) << "A" << endl;
}
else if (airplane[rowNum-1][FC_Col - 1] == 0)
{
airplane[rowNum - 1][FC_Col] = 1;
cout << "Your seat is " << (rowNum) << "D" << endl;
}
else
{
cout << "There are no window seats in that row. Please choose a different row." << '\n' << "(use the seating chart to determin where open seats are.)" << '\n' << "Row Number:" << endl;
cin >> rowNum;
while (rowNum > (FC_Row))
{
cout << "That row is not located in our first class section. choose a row numbered 1-" << (FC_Row) << endl;
cin >> rowNum;
}
findSeats(FC_Row, FC_Col, EconRow, EconCol, ticketNum, rowNum, ticketType, seatType, airplane);
}
break;
case 'A':
aisle = (FC_Col / 2);
if (airplane[rowNum - 1][aisle - 1] == 0)
{
airplane[rowNum - 1][aisle - 1] = 1;
cout << "Your seat is " << (rowNum) << "B" << endl;
}
else if (airplane[rowNum-1][aisle] == 0)
{
airplane[rowNum - 1][aisle] = 1;
cout << "Your seat is " << (rowNum) << "C" << endl;
}
else
{
cout << "There are no aisle seats in that row. Please choose a different row." << '\n' << "(use the seating chart to determin where open seats are.)" << '\n' << "Row Number:" << endl;
cin >> rowNum;
while (rowNum > (FC_Row))
{
cout << "That row is not located in our first class section. choose a row numbered 1-" << (FC_Row) << endl;
cin >> rowNum;
}
findSeats(FC_Row, FC_Col, EconRow, EconCol, ticketNum, rowNum, ticketType, seatType, airplane);
}
break;
case 'N':
col = 0;
while (airplane[rowNum - 1][col] == 1)
{
for (col; airplane[rowNum - 1][col]; col++)
{
if (col > 3)
{
cout << "There are no available seats in that row. Please choose a different row." << '\n' << "(use the seating chart to determin where open seats are.)" << '\n' << "Row Number:" << endl;
cin >> rowNum;
}
while (rowNum > (FC_Row))
{
cout << "That row is not located in our first class section. choose a row numbered 1-" << (FC_Row) << endl;
cin >> rowNum;
}
ticketType, seatType, airplane);
}
}
airplane[rowNum - 1][col] = 1;
switch (col)
{
case 0:
letterCol = 'A';
break;
case 1:
letterCol = 'B';
break;
case 2:
letterCol = 'C';
break;
case 3:
letterCol = 'D';
break;
}
cout << "Your seat is " << (rowNum) << "letterCol" << endl;
}
}
}
</code></pre>
<p>removing the function call to itself solved the issue.</p>
| 3 | 3,114 |
Issue setting up spring cloud gateway
|
<p>I'm trying to set up spring cloud gateway for a test project but it keeps failing when i use the "lb://" url.</p>
<p>This is my pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
</code></pre>
<p>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.4.1
com.blar
test
0.0.1-SNAPSHOT
test
Demo project for Spring Boot</p>
<pre><code><properties>
<java.version>11</java.version>
<kotlin.version>1.4.21</kotlin.version>
<spring-cloud.version>2020.0.0-M6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</code></pre>
<p>This is my routing function</p>
<pre><code> @Bean
fun customRouteLocator(builder: RouteLocatorBuilder): RouteLocator? {
return builder.routes()
.route("nitro-service") { r: PredicateSpec ->
r.path("/nitro")
.uri("lb://nitro-service")
}
.build()
}
</code></pre>
<p>And this is the error i get</p>
<pre><code>java.net.UnknownHostException: failed to resolve 'DESKTOP' after 10 queries
at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013) ~[netty-resolver-dns-4.1.55.Final.jar:4.1.55.Final]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
</code></pre>
<p>It works fine if i specify the actual url but throws this error when i try to combine it with eureka. It's a pretty basic project so there's no code in the gateway outside of the routing function.</p>
| 3 | 2,420 |
unable to show two observable array by one ngFor : showing same values
|
<p>I have two Observable array. They have the same number of rows and columns every time. Now I want to show them by a single ngFor for loop.</p>
<pre><code>scoreCardViewProfile$: Observable<ScoreCardView[]>;
scoreCardViewBuffer$: Observable<ScoreCardView[]>;
</code></pre>
<p>These two array will be filled by http response.</p>
<pre><code> <div *ngFor="let viewProfile of scoreCardViewProfile$ | async; let viewBuffer of scoreCardViewBuffer$ | async; let i = index">
<div class="row">
<p class="pl-5 font-weight-boldest font-size-lg">
{{viewProfile.scoreCardCategoryName}}</p>
<div class="col-12">
<mat-divider></mat-divider>
<div class="row">
<div *ngFor=" let detailsProfile of viewProfile.listOfQuestionDto; let detailsBuffer of viewBuffer.listOfQuestionDto; let j=index "
class="col-6">
<div class="row pt-5 pb-5">
<div class="col-12 text-muted font-weight-bolder">
<p align="left">{{detailsProfile.question}}</p>
</div>
<div class="row pl-4">
<div class="col-12 font-weight-bolder">
<p>profile:{{detailsProfile.configItemName}}</p>
<p>buffer: {{detailsBuffer.configItemName}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row pl-4" *ngIf="i === viewProfile.length -1">
<div class="col-12 pl-0 text-muted font-weight-bolder border-bottom">
<p>Status</p>
</div>
<div class="col-12 pl-0 font-weight-bolder">
<p class="pt-4">{{viewProfile.status}}</p>
</div>
</div>
</div>
</code></pre>
<p>As per my understanding the below two line should show different values but they are showing same values.</p>
<pre><code><p>profile : {{detailsProfile.configItemName}}</p>
<p>profile : {{detailsBuffer.configItemName}}</p>
</code></pre>
<p><a href="https://stackblitz.com/edit/ngfor-in-two-arrays" rel="nofollow noreferrer">I am following this example</a></p>
| 3 | 1,799 |
Js animate a ball wrong, slow then faster everytime
|
<p>When I run this code first time the animation speed is slow, then every time faster.The code moves a ball, and after you touch the screen, the ball goes to where you touched. </p>
<p>But the first time, it is very slow, then every time it goes faster. Why?</p>
<p>I was expecting a similar speed, not perfectly constant, but not like that.
Also on the tenth attempt the ball goes too fast.</p>
<p>I try on my smartphone, I don't know if it will work on a computer.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<style type="text/css">
.point{
width:10px; height:10px;
background-color:green;
position:absolute;
}
#ball{
width:10px; height:10px;
background-color:red;
position:absolute;
top:1px; left:50px;
}
</style>
</head>
<body>
<div class="point"></div>
<div id="ball"></div>
<script type="text/javascript">
window.addEventListener("touchstart", function(e){
var cx = e.touches[0].clientX;
var cy = e.touches[0].clientY;
});
window.addEventListener("touchmove", function(e){
var cx = e.touches[0].clientX;
var cy = e.touches[0].clientY;
endB = [cx, cy];
});
window.addEventListener("touchend", function(e){
decl();
});
function decl(){
isBmove = true;
mstep = 2;
requestAnimationFrame(step);
}
function step(ts){
if (isBmove){
var dfrein = 25;
var gb = b.getBoundingClientRect();
var ang = Math.atan2(endB[1]-gb.top, endB[0]-gb.left);
var addX = Math.cos(ang)*mstep;
var addY = Math.sin(ang)*mstep;
var difX = endB[0]-gb.left;
var difY = endB[1]-gb.top;
var dist = Math.sqrt(Math.pow(difX,2),Math.pow(difY,2));
if(dist < dfrein){
mstep *= 0.98;
l("m= "+mstep);
}
if (mstep < 1){
isBmove = false;
l("add :"+addX+","+addY);
}
b.style.top = gb.top+addY+"px";
b.style.left = gb.left+addX+"px";
}
requestAnimationFrame(step);
}
window.requestAnimationFrame =
window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame;
var isBmove = false;
var endB = [0,0];
var mstep = 2;
var b = document.getElementById("ball");
function l(p){
console.log(p);
}
</script>
</body>
</html>
</code></pre>
<p>Thanks</p>
| 3 | 1,250 |
Django markers using geoposition
|
<p>I use django-geoposition to manage my geodata.
in my home.html:</p>
<pre><code><!-- Add Google Maps -->
<script>
function myMap() {
{% for posts in post_list %}
myCenter=new google.maps.LatLng(34.8402781,135.592376);
var myLocation=new google.maps.LatLng({{posts.position.latitude}},{{posts.position.longitude}});
var mapOptions= {
center:myCenter,
zoom:7, scrollwheel: true, draggable: true,
mapTypeId:google.maps.MapTypeId.HYBRID
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapOptions);
var marker = new google.maps.Marker({
position: myLocation,
title:'{{ posts.title }}',
draggable: false,
});
marker.setMap(map);
{%endfor%}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCB1CA2DoITfJoFY4HWTLTxH4Avx7QWWqA&callback=myMap"></script>
</code></pre>
<p>But it just shows the fist post's maker on the map. I guess the for loop doesn't work. I don't know what to do. I would appreciate any help!</p>
<p>models.py</p>
<pre><code>from django.db import models
from geoposition.fields import GeopositionField
class Post(models.Model):
title = models.CharField(max_length=100)
introduction = models.TextField(blank=True)
reason = models.TextField(blank=True)
transportation = models.TextField(blank=True)
basic_info = models.TextField(blank=True)
photo = models.URLField(blank=True)
location = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
position = GeopositionField(blank=True)
website = models.URLField(blank=True)
useful_link = models.URLField(blank=True)
def __str__(self):
return self.title
</code></pre>
<p>views.py:</p>
<pre><code>from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Post
def home(request):
posts = Post.objects.all()
paginator = Paginator(posts, 6) #每页显示十个
page = request.GET.get('page')
try :
post_list = paginator.page(page)
except PageNotAnInteger :
post_list = paginator.page(1)
except EmptyPage :
post_list = paginator.paginator(paginator.num_pages)
return render(request, 'attractions/home.html', {'post_list': post_list,})
def post_detail(request, pk):
post = Post.objects.get(pk=pk)
return render(request, 'attractions/post.html', {
'post': post,
})
</code></pre>
<p>attractions\urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
app_name = 'attractions'
urlpatterns = [
url(r'^$',views.home, name = 'home'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail')
]
</code></pre>
<p>urls.py:</p>
<pre><code>from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('attractions.urls')),
url(r'^markdown/', include( 'django_markdown.urls')),
]
</code></pre>
<p>admin.py:</p>
<pre><code>from django.contrib import admin
from .models import Post
from django_markdown.admin import MarkdownModelAdmin
from django_markdown.widgets import AdminMarkdownWidget
from django.db.models import TextField
class PostAdmin(MarkdownModelAdmin):
list_display = ('title','position',) #顯示欄
search_fields = ('title',) #搜索欄
ordering = ('created_at',) #減號表示降序
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}
admin.site.register(Post,PostAdmin)
</code></pre>
| 3 | 1,399 |
Generating XML from SQL existing XSD file (complex)
|
<p>I have an XSD file. I get data from SQL and fill data to dataset.
note: I get 1000 records from SQL. </p>
<p>I want to make this; generate XML file exisiting xsd format. </p>
<p>Here is my XSD.:</p>
<pre><code> <xs:element name = 'automation'>
<xs:complexType>
<xs:sequence>
<xs:element name = 'auto' type = 'AutoType' minOccurs = '1' maxOccurs = 'unbounded' />
</xs:sequence>
</xs:complexType>
</code></pre>
<p></p>
<pre><code><xs:complexType name = "AutoType">
<xs:sequence>
<xs:element name = "autoKodu" type = "xs:string" minOccurs = '1' maxOccurs = '1' /> <!-- v -->
<xs:element name = "autoAdres" type = "xs:string" minOccurs = '1' maxOccurs = '1' /> <!-- v -->
<xs:element name = 'bill' type = 'BillType' minOccurs = '1' maxOccurs = 'unbounded' />
</xs:sequence>
</code></pre>
<p></p>
<pre><code> <xs:complexType name = "BillType">
<xs:sequence>
<xs:element name = "dateOne" type = "xs:date" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "dateTwo" type = "xs:time" minOccurs = '1' maxOccurs = '1' />
<xs:element name = 'point' type = 'PointType' minOccurs = '1' maxOccurs = 'unbounded' />
</xs:sequence>
</code></pre>
<p> </p>
<pre><code><xs:complexType name = "PointType">
<xs:sequence>
<xs:element name = "plate" minOccurs = '1' maxOccurs = '1' > <!-- v -->
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="([a-zA-Z0-9])*"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name = "aa" type = "xs:string" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "bb" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "cc" type = "xs:string" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "dd" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "ee" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "ff" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "gg" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
<xs:element name = "hh" type = "xs:decimal" minOccurs = '1' maxOccurs = '1' />
</xs:sequence>
</code></pre>
<p> </p>
<p>I have created xsd class using xsd.exe
I added it to solution.</p>
<pre><code>var data = new myClassOrSmthng? { ??? I do not know how to get datas from dataset here. }
XmlSerializer serializer = new XmlSerializer(typeof(myClassOrSmthng));
using (var stream = new StreamWriter(myPath)) serializer.Serialize(stream, data);
</code></pre>
| 3 | 1,318 |
Deploying Angular2 on Heroku yields 'Uncaught SyntaxError: Unexpected Token <' on all external references
|
<p>I'm trying to deploy an angular4 app on Heroku. But I get errors on all my <code>.js</code> references linked from my <code>.html</code>.</p>
<p>The errors are as such </p>
<pre><code>16:29:54.613 myapp.herokuapp.com/:1 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://myapp.herokuapp.com/assets/style/bootstrap.css".
16:29:54.646 jquery-1.10.2.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.647 myapp.herokuapp.com/:1 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://myapp.herokuapp.com/styles.d41d8cd98f00b204e980.bundle.css".
16:29:54.685 bootstrap.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.743 jquery.bxslider.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.744 jquery.centralized.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.776 jquery.fixedonlater.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.865 jquery.hashloader.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.867 jquery.mixitup.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.868 jquery.nav.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.869 jquery.parallax-1.1.3.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.946 jquery.responsivevideos.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.947 jquery.scrollTo.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.948 jquery.tweet.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:54.999 jquery.tweetCarousel.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:55.001 holder.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:55.003 application.min.js:1 Uncaught SyntaxError: Unexpected token <
16:29:55.005 inline.230e19a62ca0cc6cf333.bundle.js:1 Uncaught SyntaxError: Unexpected token <
16:29:55.007 polyfills.2a6cee40ee8af30fbaec.bundle.js:1 Uncaught SyntaxError: Unexpected token <
16:29:55.018 vendor.20becde8ac8acd1f3058.bundle.js:1 Uncaught SyntaxError: Unexpected token <
16:29:55.019 main.f037d06044d7934ea073.bundle.js:1 Uncaught SyntaxError: Unexpected token <
</code></pre>
<p>All these files exist in my <code>src/client/assets/js/</code> directory.</p>
<p>My <code>server.js</code> is as such</p>
<pre><code>const express = require('express');
const path = require('path');
const root = './dist/public';
const pub = process.env.PUBLIC || `${root}`;
const app = express();
app.use(express.static(path.join(__dirname, 'dist/public/assets')));
app.use(express.static(path.join(__dirname, 'dist/public')));
app.get('/*', (req, res) => {
res.sendFile(`index.html`, { root: pub });
});
const port = process.env.PORT || 3000;
app.set('port', port);
app.listen(port, () => console.log(`API running on localhost:${port}`));
</code></pre>
<p>Am I missing something? The app works just fine locally.</p>
| 3 | 1,132 |
Difference in .htaccess behaviour
|
<p>I have finished developing a micro app with Phalcon and tried to move it to production server, but have encountered some problems with <code>.htaccess</code> rules.</p>
<p>Directory layout on the serwer is like this : </p>
<pre><code>/var/www
|- .htaccess
|- redmine/
|- wordpress/
|- (other dirs)
|- MyApp/
|- .htaccess
|- public/
|- .htaccess
|- api.php
</code></pre>
<p>/var/www/.htaccess : </p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} !(redmine|MyApp) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>/var/www/MyApp/.htaccess :</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !(\.gif|\.jpg|\.png|\.mp3|\.ods|\.csv|\.xls)$ [NC]
RewriteRule ^$ public/ [L]
RewriteCond %{REQUEST_URI} !(\.gif|\.jpg|\.png|\.mp3|\.ods|\.csv|\.xls)$ [NC]
RewriteRule (.*) public/$1 [L]
</IfModule>
</code></pre>
<p>/var/www/MyApp/public/.htaccess :</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ api.php?_url=/$1 [QSA,L]
</IfModule>
</code></pre>
<p>I'm really new to all this. The top-most <code>.htaccess</code> was not setup by me, and frankly I don't know what is going on in there. The others are based on Phalcon tutorials.</p>
<p>Everything worked on my local machine, but stopped when I uploaded it. I turned on logging in both places.</p>
<p>Local log :</p>
<pre><code>[perdir /Users/Losiowaty/MyApp/] add path info postfix: /Users/Losiowaty/MyApp/api -> /Users/Losiowaty/MyApp/api/poeci
[perdir /Users/Losiowaty/MyApp/] strip per-dir prefix: /Users/Losiowaty/MyApp/api/poeci -> api/poeci
[perdir /Users/Losiowaty/MyApp/] applying pattern '^$' to uri 'api/poeci'
[perdir /Users/Losiowaty/MyApp/] add path info postfix: /Users/Losiowaty/MyApp/api -> /Users/Losiowaty/MyApp/api/poeci
[perdir /Users/Losiowaty/MyApp/] strip per-dir prefix: /Users/Losiowaty/MyApp/api/poeci -> api/poeci
[perdir /Users/Losiowaty/MyApp/] applying pattern '(.*)' to uri 'api/poeci'
[perdir /Users/Losiowaty/MyApp/] RewriteCond: input='/MyApp/api/poeci' pattern='!(\\.gif|\\.jpg|\\.png|\\.mp3|\\.ods|\\.csv|\\.xls)$' [NC] => matched
[perdir /Users/Losiowaty/MyApp/] rewrite 'api/poeci' -> 'public/api/poeci'
[perdir /Users/Losiowaty/MyApp/] add per-dir prefix: public/api/poeci -> /Users/Losiowaty/MyApp/public/api/poeci
[perdir /Users/Losiowaty/MyApp/] strip document_root prefix: /Users/Losiowaty/MyApp/public/api/poeci -> /MyApp/public/api/poeci
[perdir /Users/Losiowaty/MyApp/] internal redirect with /MyApp/public/api/poeci [INTERNAL REDIRECT]
[perdir /Users/Losiowaty/MyApp/public/] add path info postfix: /Users/Losiowaty/MyApp/public/api -> /Users/Losiowaty/MyApp/public/api/poeci
[perdir /Users/Losiowaty/MyApp/public/] strip per-dir prefix: /Users/Losiowaty/MyApp/public/api/poeci -> api/poeci
[perdir /Users/Losiowaty/MyApp/public/] applying pattern '^(.*)$' to uri 'api/poeci'
[perdir /Users/Losiowaty/MyApp/public/] RewriteCond: input='/Users/Losiowaty/MyApp/public/api' pattern='!-d' => matched
[perdir /Users/Losiowaty/MyApp/public/] RewriteCond: input='/Users/Losiowaty/MyApp/public/api' pattern='!-f' => matched
[perdir /Users/Losiowaty/MyApp/public/] rewrite 'api/poeci' -> 'api.php?_url=/api/poeci'
split uri=api.php?_url=/api/poeci -> uri=api.php, args=_url=/api/poeci
[perdir /Users/Losiowaty/MyApp/public/] add per-dir prefix: api.php -> /Users/Losiowaty/MyApp/public/api.php
[perdir /Users/Losiowaty/MyApp/public/] strip document_root prefix: /Users/Losiowaty/MyApp/public/api.php -> /MyApp/public/api.php
[perdir /Users/Losiowaty/MyApp/public/] internal redirect with /MyApp/public/api.php [INTERNAL REDIRECT]
[perdir /Users/Losiowaty/MyApp/public/] strip per-dir prefix: /Users/Losiowaty/MyApp/public/api.php -> api.php
[perdir /Users/Losiowaty/MyApp/public/] applying pattern '^(.*)$' to uri 'api.php'
[perdir /Users/Losiowaty/MyApp/public/] RewriteCond: input='/Users/Losiowaty/MyApp/public/api.php' pattern='!-d' => matched
[perdir /Users/Losiowaty/MyApp/public/] RewriteCond: input='/Users/Losiowaty/MyApp/public/api.php' pattern='!-f' => not-matched
[perdir /Users/Losiowaty/MyApp/public/] pass through /Users/Losiowaty/MyApp/public/api.php
</code></pre>
<p>Remote log :</p>
<pre><code>[perdir /var/www/MyApp/] add path info postfix: /var/www/MyApp/api -> /var/www/MyApp/api/poeci
[perdir /var/www/MyApp/] strip per-dir prefix: /var/www/MyApp/api/poeci -> api/poeci
[perdir /var/www/MyApp/] applying pattern '^$' to uri 'api/poeci'
[perdir /var/www/MyApp/] add path info postfix: /var/www/MyApp/api -> /var/www/MyApp/api/poeci
[perdir /var/www/MyApp/] strip per-dir prefix: /var/www/MyApp/api/poeci -> api/poeci
[perdir /var/www/MyApp/] applying pattern '(.*)' to uri 'api/poeci'
[perdir /var/www/MyApp/] RewriteCond: input='/MyApp/api/poeci' pattern='!(\\.gif|\\.jpg|\\.png|\\.mp3|\\.ods|\\.csv|\\.xls)$' [NC] => matched
[perdir /var/www/MyApp/] rewrite 'api/poeci' -> 'public/api/poeci'
[perdir /var/www/MyApp/] add per-dir prefix: public/api/poeci -> /var/www/MyApp/public/api/poeci
[perdir /var/www/MyApp/] strip document_root prefix: /var/www/MyApp/public/api/poeci -> /MyApp/public/api/poeci
[perdir /var/www/MyApp/] internal redirect with /MyApp/public/api/poeci [INTERNAL REDIRECT]
[perdir /var/www/MyApp/public/] add path info postfix: /var/www/MyApp/public/api.php -> /var/www/MyApp/public/api.php/poeci
[perdir /var/www/MyApp/public/] strip per-dir prefix: /var/www/MyApp/public/api.php/poeci -> api.php/poeci
[perdir /var/www/MyApp/public/] applying pattern '^(.*)$' to uri 'api.php/poeci'
[perdir /var/www/MyApp/public/] RewriteCond: input='/var/www/MyApp/public/api.php' pattern='!-d' => matched
[perdir /var/www/MyApp/public/] RewriteCond: input='/var/www/MyApp/public/api.php' pattern='!-f' => not-matched
[perdir /var/www/MyApp/public/] pass through /var/www/MyApp/public/api.php
[perdir /var/www/MyApp/public/] add path info postfix: /var/www/MyApp/public/api.php -> /var/www/MyApp/public/api.php/poeci
[perdir /var/www/MyApp/public/] strip per-dir prefix: /var/www/MyApp/public/api.php/poeci -> api.php/poeci
[perdir /var/www/MyApp/public/] applying pattern '^(.*)$' to uri 'api.php/poeci'
[perdir /var/www/MyApp/public/] RewriteCond: input='/var/www/MyApp/public/api.php' pattern='!-d' => matched
[perdir /var/www/MyApp/public/] RewriteCond: input='/var/www/MyApp/public/api.php' pattern='!-f' => not-matched
[perdir /var/www/MyApp/public/] pass through /var/www/MyApp/public/api.php
[perdir /var/www/] strip per-dir prefix: /var/www/poeci -> poeci
[perdir /var/www/] applying pattern '^index\\.php$' to uri 'poeci'
[perdir /var/www/] strip per-dir prefix: /var/www/poeci -> poeci
[perdir /var/www/] applying pattern '.' to uri 'poeci'
[perdir /var/www/] RewriteCond: input='/poeci' pattern='!(redmine|MyApp)' [NC] => matched
[perdir /var/www/] RewriteCond: input='/var/www/poeci' pattern='!-f' => matched
[perdir /var/www/] RewriteCond: input='/var/www/poeci' pattern='!-d' => matched
[perdir /var/www/] rewrite 'poeci' -> '/index.php'
[perdir /var/www/] trying to replace prefix /var/www/ with /
[perdir /var/www/] internal redirect with /index.php [INTERNAL REDIRECT]
</code></pre>
<p>The differences begin with the first line with <code>[perdir (...)]</code> ending with <code>/public/</code>. I don't understand why it adds <code>.php</code> and why the <code>!-f</code> rule doesn't match on the remote server.</p>
<p>Local server :<br>
OSX 10.9.3, MAMP 3.0.4, Apache 2.2.26</p>
<p>Remote server :<br>
Debian GNU/Linux 6.0.9, Apache 2.2.16</p>
<p>I wonder whether this is caused by the additional <code>.htaccess</code> file on the remote, or by the difference in Apache version.</p>
<p>I'd appreciate some explanation as to what's going on and any directions on where to look for answers.</p>
<p>Cheers!</p>
| 3 | 3,528 |
generating POJOs from JSON Schema for non-object types
|
<p>I am trying to generate POJOs from the JSON Schema of XMBC.
I do this with <a href="http://www.jsonschema2pojo.org/" rel="nofollow">jsonschema2pojo</a>.
However, nothing gets generated. It doesn't even bring me an error.</p>
<p>This is a reduced sample json schema I am trying to generate from:</p>
<pre><code>{
"description": "JSON-RPC API of XBMC",
"id": "http://xbmc.org/jsonrpc/ServiceDescription.json",
"methods": {
"Addons.ExecuteAddon": {
"description": "Executes the given addon with the given parameters (if possible)",
"params": [
{
"name": "addonid",
"required": true,
"type": "string"
},
{
"default": "",
"name": "params",
"type": [
{
"additionalProperties": {
"default": "",
"type": "string"
},
"type": "object"
},
{
"items": {
"type": "string"
},
"type": "array"
},
{
"description": "URL path (must start with / or ?",
"type": "string"
}
]
},
{
"default": false,
"name": "wait",
"type": "boolean"
}
],
"returns": {
"type": "string"
},
"type": "method"
}
},
"notifications": {
"Application.OnVolumeChanged": {
"description": "The volume of the application has changed.",
"params": [
{
"name": "sender",
"required": true,
"type": "string"
},
{
"name": "data",
"properties": {
"muted": {
"required": true,
"type": "boolean"
},
"volume": {
"maximum": 100,
"minimum": 0,
"required": true,
"type": "integer"
}
},
"required": true,
"type": "object"
}
],
"returns": null,
"type": "notification"
}
},
"types": {
"Addon.Content": {
"default": "unknown",
"enums": [
"unknown",
"video",
"audio",
"image",
"executable"
],
"id": "Addon.Content",
"type": "string"
}
},
"version": "6.14.3"
}
</code></pre>
<p>I must admin that my knowledge of JSON is very terse, maybe it is just a simple fault of mine. But can anyone help me how I can generate Java objects from such a JSON Schema?</p>
| 3 | 1,406 |
Using Ghost4j with MaxProcessCount on a tomcat causes jna error
|
<p>I'm trying to develop a web-service (based on jersey) which is converting a pdf document into jpeg images.
I choosed GhostScript because I have good experiences with it and it's results (especially with embedet fonts). So I searched a way to use GhostScript with Java and found Ghost4j.</p>
<p>So I put all the Ghost4j jars into my applications lib folder (also the jna.jar). In my first tests I encountered a problem with executing the task more than once, because jna throws an error when it's launched more than one time.
So I put the jna.jar into the tomcat lib folder. That worked a littlebit better, but it only executed one task at a time. If I started another one at the same time, nothing happened. I just didn't seem to execute the other task.</p>
<p>So I tried <code>setMaxProcessCount(2);</code> to allow my application to execute more than one task at a time. Here is my code:</p>
<pre><code>private static void generateImages(String inputFile, String outputPath) throws IOException, RendererException, org.ghost4j.document.DocumentException {
PDFDocument document = new PDFDocument();
document.load(new File(inputFile));
SimpleRenderer renderer = new SimpleRenderer();
renderer.setMaxProcessCount(2);
renderer.setResolution(150);
renderer.setAntialiasing(4);
System.setProperty("jna.library.path", "C:\\Program Files\\gs\\gs9.09\\bin\\");
List<Image> images = renderer.render(document);
for (int i = 0; i < images.size(); i++) {
ImageIO.write((RenderedImage) images.get(i), "jpeg", new File(outputPath + File.separatorChar + (i + 1) + ".jpeg"));
}
}
</code></pre>
<p>But if I'm trying to execute my task, Ghost4j throws this error:</p>
<pre><code>org.ghost4j.renderer.RendererException: java.lang.Exception: java.lang.NoClassDefFoundError: com/sun/jna/Structure
at org.ghost4j.renderer.AbstractRemoteRenderer.render(AbstractRemoteRenderer.java:133)
at PdfResource.ConversionTask.generateImages(ConversionTask.java:218)
at PdfResource.ConversionTask.exec(ConversionTask.java:58)
at PdfResource.Task.run(Task.java:86)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.Exception: java.lang.NoClassDefFoundError: com/sun/jna/Structure
at gnu.cajo.invoke.Remote.invoke(Remote.java:594)
at gnu.cajo.invoke.Remote.invoke(Remote.java:722)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:273)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:251)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:160)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at com.sun.proxy.$Proxy165.invoke(Unknown Source)
at gnu.cajo.invoke.Remote.invoke(Remote.java:565)
at org.ghost4j.renderer.AbstractRemoteRenderer.render(AbstractRemoteRenderer.java:126)
... 4 more
Caused by: java.lang.NoClassDefFoundError: com/sun/jna/Structure
at org.ghost4j.renderer.SimpleRenderer.run(SimpleRenderer.java:68)
at org.ghost4j.renderer.AbstractRemoteRenderer.remoteRender(AbstractRemoteRenderer.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at gnu.cajo.invoke.Remote.invoke(Remote.java:582)
at gnu.cajo.invoke.Remote.invoke(Remote.java:722)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
... 1 more
Caused by: java.lang.ClassNotFoundException: com.sun.jna.Structure
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 23 more
</code></pre>
<p>I guess that it has something todo with the additional JVM that Ghost4j is launching and it doesn't seem to use the same classpath that tomcat uses, but I'm not really a java expert and have no idea how to solve this problem.</p>
| 3 | 2,371 |
My custom JMeter listener cannot work in Linux
|
<p>I want to save the information about sampleResult into MySQL. So I write my own listener named Performance Logger. And it can work well on my Windows. But when I move the same JMeter Script into Linux, it failed. Here are some code about my custom listener.</p>
<pre><code>LoggerVisualizer.class
public class LoggerVisualizer extends AbstractVisualizer {
private PerformanceResultCollector collector;
public LoggerVisualizer() {
super();
initConfiguration();
}
private void initConfiguration() {
// some code
}
@Override
public void clearData() {
//some codes
}
public String getStaticLabel() {
return "Performance Logger";
}
public String getLabelResource(){
return "Performance Logger";
}
@Override
public void add(SampleResult sampleResult) {
}
public TestElement createTestElement() {
if (collector == null) {
collector = new PerformanceResultCollector();
}
modifyTestElement(collector);
return collector;
}
}
</code></pre>
<p>PerformanceResultCollector.class</p>
<pre><code>public class PerformanceResultCollector extends ResultCollector implements Serializable {
CustomCollector collector;
public PerformanceResultCollector() {
log.info("construct performance collector")
collector = new CustomCollector();
}
@Override
public void sampleOccurred(SampleEvent e) {
collector.addSample(e.getResult());
}
public void cleanUp(){
CustomCollector.cleanUp();
}
}
</code></pre>
<p>On my Windows server, I add the listener and it works well. I can see the data in the MySQL server. But when I move the script into the Linux and run it with command</p>
<pre><code> nohup ./jmeter -n -t /opt/tests/test.jmx -l /opt/log/perf_result.csv -Jjmeter.save.saveservice.output_format=csv -Jjmeter.save.saveservice.hostname=true -Jjmeter.save.saveservice.print_field_names=false -Jjmeter.save.saveservice.url=true -Jjmeter.save.saveservice.thread_counts=true -Jjmeter.save.saveservice.timestamp_format="yyyy-MM-dd HH:mm:ss" > /opt/log/jmeter_script_run.out 2> /opt/log/jmeter_script_run.err < /dev/null
</code></pre>
<p>And I get the error in jmeter.log like:</p>
<pre><code>2015/08/08 04:36:28 INFO - com.test.jmeter.logger.PerformanceResultCollector: construct performance collector
2015/08/08 04:36:28 ERROR - jmeter.save.SaveService: Conversion error com.thoughtworks.xstream.converters.ConversionException: java.lang.NullPointerException : java.lang.NullPointerException
---- Debugging information ----
message : java.lang.NullPointerException
cause-exception : java.lang.RuntimeException
cause-message : java.lang.NullPointerException
class : com.test.jmeter.logger.PerformanceResultCollector
required-type : com.test.jmeter.logger.PerformanceResultCollector
converter-type : org.apache.jmeter.save.converters.TestElementConverter
path : /jmeterTestPlan/hashTree/hashTree/hashTree/com.test.jmeter.logger.PerformanceResultCollector
line number : 379
class[1] : org.apache.jorphan.collections.ListedHashTree
converter-type[1] : org.apache.jmeter.save.converters.HashTreeConverter
------------------------------- : java.lang.NullPointerException : java.lang.NullPointerException
---- Debugging information ----
message : java.lang.NullPointerException
cause-exception : java.lang.RuntimeException
cause-message : java.lang.NullPointerException
class : com.test.jmeter.logger.PerformanceResultCollector
required-type : com.test.jmeter.logger.PerformanceResultCollector
converter-type : org.apache.jmeter.save.converters.TestElementConverter
path : /jmeterTestPlan/hashTree/hashTree/hashTree/com.test.jmeter.logger.PerformanceResultCollector
line number : 379
class[1] : org.apache.jorphan.collections.ListedHashTree
converter-type[1] : org.apache.jmeter.save.converters.HashTreeConverter
</code></pre>
<p>In the log, I find that it has alreay come into the construct function of PerformanceResultCollector. But why it throw the NulPointerException. I confirm the lib of jmeter on Linux is same as on Windows. Can anyone tell me what's wrong with my listener? Many thanks</p>
<blockquote>
<p></p>
</blockquote>
<p>After I have modified my code many times, I finally know how to resolve it, even through I don't know the reason. In the PerformanceResultCollector.class, if I construct the lazy CustomCollector, it works.</p>
<pre><code>public class PerformanceResultCollector extends ResultCollector implements Serializable {
CustomCollector collector;
public PerformanceResultCollector() {
log.info("construct performance collector")
}
@Override
public void sampleOccurred(SampleEvent e) {
if (null == collector) {
collector = new CustomCollector();
}
collector.addSample(e.getResult());
}
public void cleanUp(){
CustomCollector.cleanUp();
}
}
</code></pre>
<p>Maybe the JMeter parses the jmx script in different ways for non-gui and gui mode. </p>
| 3 | 1,673 |
Twitter reply-to-mentions bot programmed in Python works once and then crashes with error 400: what is the problem?
|
<p>I´ve been building a bot and it works exactly as intended, but only for one Tweet. Then, it waits 60 seconds, and, if it doesn´t find a new Tweet to reply to (since it´s configured to reply to the most recent Tweet), it throws an error (it´s 400 as in "400: Bad Authentication Data", but I think the issue is not that, since the bot posts on Twitter once without any issues. However, I do think it´s possibly some kind of Bad Request error).
Whenever it crashes, I can just run in my command "python (botname).py" and it works once if there is now a new Tweet, but then, it crashes again.
I want the bot to run properly by itself, so I would really appreciate some help!
This is the code in my file:</p>
<pre><code>
#!/usr/bin/env python
# tweepy-bots/bots/autoreply.py
import tweepy
import logging
from config import create_api
import time
import re
from googlesearch import search
import sys
import io
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def check_mentions(api, since_id):
logger.info("Collecting info")
new_since_id = since_id
for tweet in tweepy.Cursor(api.mentions_timeline,
since_id=since_id).items():
new_since_id = max(tweet.id, new_since_id)
if tweet.in_reply_to_status_id is not None:
in_reply_to_status_id = tweet.id
status_id = tweet.in_reply_to_status_id
tweet_u = api.get_status(status_id,tweet_mode='extended')
logger.info(f"Answering to {tweet.user.name}")
# remove words between 1 and 3
shortword = re.compile(r'\W*\b\w{1,3}\b')
keywords_search = str(shortword.sub('', tweet_u.full_text))
print(keywords_search)
if keywords_search is not None:
mystring = search(keywords_search, num_results=500)
else:
mystring = search("error", num_results=1)
print(mystring)
output_info=[]
for word in mystring:
if "harvard" in word or "cornell" in word or "researchgate" in word or "yale" in word or "rutgers" in word or "caltech" in word or "upenn" in word or "princeton" in word or "columbia" in word or "journal" in word or "mit" in word or "stanford" in word or "gov" in word or "pubmed" in word or "theguardian" in word or "aaas" in word or "bbc" in word or "rice" in word or "ams" in word or "sciencemag" in word or "research" in word or "article" in word or "publication" in word or "nationalgeographic" in word or "ngenes" in word:
output_info.append(word)
infostringa = ' '.join(output_info)
if output_info:
output_info4 = output_info[:5]
infostring = ' '.join(output_info4)
print(infostring)
status = "Hi there! This may be what you're looking for " + infostring
len(status) <= 280
api.update_status(status, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)
else:
status = "Sorry, I cannot help you with that :(. You might want to try again with a distinctly sourced Tweet"
api.update_status(status, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)
print(status)
return new_since_id
return check_mentions
def main():
api = create_api()
since_id = 1 #the last mention you have.
while True:
since_id = check_mentions(api, since_id)
logger.info("Waiting...")
time.sleep(60)
main()
</code></pre>
<p>My config module:</p>
<pre><code># tweepy-bots/bots/config.py
import tweepy
import logging
import os
logger = logging.getLogger()
def create_api():
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
try:
api.verify_credentials()
except Exception as e:
logger.error("Error creating API", exc_info=True)
raise e
logger.info("API created")
return api
</code></pre>
<p>The error raised:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring32.py", line 92, in <module>
main()
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring32.py", line 87, in main
since_id = check_mentions(api, since_id)
File "C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring32.py", line 26, in check_mentions
for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items():
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\cursor.py", line 51, in __next__
return self.next()
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\cursor.py", line 243, in next
self.current_page = self.page_iterator.next()
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\cursor.py", line 132, in next
data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kwargs)
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py", line 253, in _call
return method.execute()
File "C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py", line 234, in execute
raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: Twitter error response: status code = 400
</code></pre>
<p>Thank you really much!</p>
| 3 | 2,801 |
Form rendering for many to many relation in symfony 4 does not work
|
<p>I have many to many relation between two entities Recipient and Recipient Group. I am trying to setup a form for Recipient where I must be able to add multiple Recipient Group to Recipient. But when I try to run the rendered form, I get the following error even though addXXX and removeXXX methods exist in both the classes.</p>
<pre><code>Could not determine access type for property "recipientGroups" in class
"App\Entity\Recipient": The property "recipientGroups" in class "App\Entity\Recipient" can
be defined with the methods "addRecipientGroup()", "removeRecipientGroup()" but the new
value must be an array or an instance of \Traversable, "App\Entity\RecipientGroup" given.
</code></pre>
<p>Entity/Recipient</p>
<pre><code>**
*
@ORM\Entity(repositoryClass="App\Repository\RecipientRepository")
*/
class Recipient
{
...
/**
* @ORM\ManyToMany(targetEntity="App\Entity\RecipientGroup", inversedBy="recipients")
*/
private $recipientGroups;
public function __construct()
{
$this->recipientGroups = new ArrayCollection();
}
/**
* @return Collection|RecipientGroup[]
*/
public function getRecipientGroups(): Collection
{
return $this->recipientGroups;
}
public function addRecipientGroup(RecipientGroup $recipientGroup): self
{
if (!$this->recipientGroups->contains($recipientGroup)) {
$this->recipientGroups[] = $recipientGroup;
$recipientGroup->addRecipient($this);
}
return $this;
}
public function removeRecipientGroup(RecipientGroup $recipientGroup): self
{
if ($this->recipientGroups->contains($recipientGroup)) {
$this->recipientGroups->removeElement($recipientGroup);
$recipientGroup->removeRecipient($this);
}
return $this;
}
public function getCreatedAt(): DateTime
{
return $this->createdAt;
}
public function setCreatedAt(DateTime $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): DateTime
{
return $this->updatedAt;
}
public function setUpdatedAt(DateTime $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
}
</code></pre>
<p>Entity/RecipientGroup:</p>
<pre><code>/**
* @ORM\Entity(repositoryClass="App\Repository\RecipientGroupRepository")
*/
class RecipientGroup
{
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Recipient", mappedBy="recipientGroups")
*/
private $recipients;
public function __construct()
{
$this->recipients = new ArrayCollection();
}
* @return Collection|Recipient[]
*/
public function getRecipients(): Collection
{
return $this->recipients;
}
public function addRecipient(Recipient $recipient): self
{
if (!$this->recipients->contains($recipient)) {
$this->recipients[] = $recipient;
$recipient->addRecipientGroup($this);
}
return $this;
}
public function removeRecipient(Recipient $recipient): self
{
if ($this->recipients->contains($recipient)) {
$this->recipients->removeElement($recipient);
$recipient->removeRecipientGroup($this);
}
return $this;
}
}
</code></pre>
<p>form/RecipientType</p>
<pre><code>class RecipientType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('fullName')
->add('email')
->add('recipientGroups', CollectionType::class, [
'entry_type' => RecipientGroupBlockType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'help' => '<a data-collection="add" class="btn btn-info btn-sm" href="#">Add Recipient Group</a>',
'help_html' => true,
'by_reference' => false,
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Recipient::class,
]);
}
</code></pre>
<p>}</p>
<p>form/RecipientGroupBlockType:</p>
<pre><code><?php
namespace App\Form;
use App\Entity\Recipient;
use App\Entity\RecipientGroup;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RecipientGroupBlockType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('recipientGroups', EntityType::class,[
'class' => RecipientGroup::class,
'choice_label' => 'title',
'placeholder' => 'Select an option'
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Recipient::class,
]);
}
}
</code></pre>
| 3 | 2,264 |
Issue with reading and writing a name
|
<p>I am just learning js and have the following issue that I cannot seem to resolve. The object of the exercise is to read in the name when the button is clicked and then display a message that says "hello "</p>
<p>All of the functions are contained within the mainC div.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Sentence Diagrammer</title>
<link rel="stylesheet" href="./css/main.css">
</head>
<body>
<h1>Welcome to the Sentence Diagrammer!</h1>
<h2>You can practice your diagramming skills here.</h2>
<div id="container">
<div id="mainL">
<h1>Left Conatainer</h1>
</div>
<div id="mainC">
<h1>This is the center</h1>
<p>Please tell us your name</p>
<p>I am <input id="theName" name="aName" type="text" /></p>
<button onclick="validName()">Click</button>
<p id="demo"></p>
<input id="slide" type="range" min="1" max="10" step="1" onchange="displayPrelimQ(this.value)" />
<span id="slideValue">1</span>
<script type="text/javascript">
function validName() {
var text1 = "hello";
var text2 = document.getElementById("theName").innerHTML;
document.getElementById("demo").innerHTML = text1 + text2;
}
</script>
<script type="text/javascript">
function displayPrelimQ(val) {
document.getElementById("slideValue").innerHTML = val;
}
</script>
</div>
<div id="mainR">
<h1>right container</h1>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| 3 | 1,155 |
Requiring a package is causing an error
|
<p>Each time I am bundling scripts, I have following error:</p>
<pre><code>ERROR in ./resources/assets/scripts/main.js
Module not found: Error: Can't resolve 'datatables.net-colreorder-bs4' in '/home/vagrant/sites/laravel/resources/assets/scripts'
@ ./resources/assets/scripts/main.js 12:23-63
</code></pre>
<p>My webpack config js:</p>
<pre><code>var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './resources/assets/scripts/main.js',
output: {
path: path.resolve(__dirname, './public/js'),
filename: 'mainBundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env']
}
}
]
},
stats: {
colors: true
},
node: {
fs: 'empty'
},
devtool: 'source-map'
};
</code></pre>
<p>And my main js file looks like this (no other modules are causing any problems).</p>
<pre><code>var jszip = require('jszip');
var pdfmake = require('pdfmake');
var netBs4 = require('datatables.net-bs4')();
var netButtonsBs4 = require('datatables.net-buttons-bs4')();
var buttonsHtml5 = require('datatables.net-buttons/js/buttons.html5.js')();
var buttonsPrint = require('datatables.net-buttons/js/buttons.print.js')();
var netColreorderBs4 = require('datatables.net-colreorder-bs4')();
var netReponsiveBs4 = require('datatables.net-responsive-bs4')();
</code></pre>
<p>I checked the path and it is ok, I also changed the path to absolute but it did not have any effect.</p>
<p>package json: </p>
<pre><code>"dependencies": {
"add": "^2.0.6",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"chart.js": "^2.7.1",
"datatables.net-bs4": "^1.10.16",
"datatables.net-buttons-bs4": "^1.5.1",
"datatables.net-colreorder-bs4": "^1.4.1",
"datatables.net-responsive-bs4": "^2.2.1",
"gulp-changed": "^3.2.0",
"gulp-debug": "^3.2.0",
"jquery": "^3.2.1",
"jquery-ui": "^1.12.1",
"jszip": "^3.1.5",
</code></pre>
<p>This question is still not resolved, for some reason 'datatables.net-colreorder-bs4' will not be found when using npm... I decided to load it as a ready to use bundle instead of webpacking it...</p>
| 3 | 1,115 |
Draw/erase button in java
|
<p>I am struggling to find a way to implement a way that whenever you click a draw button it will decide whether you are drawing or erasing.</p>
<pre><code> private void drawButtonActionPerformed (java.awt.event.ActionEvent evt) {
solveButton.setEnabled(true);
slider.setEnabled(true);
captureButton.setEnabled(true);
}
</code></pre>
<p>My code at the moment lets automatically decides whether to draw or erase based on whether there is an obstacle where you are clicking</p>
<pre><code> private class MouseHandler implements MouseListener, MouseMotionListener {
int cur_row, cur_col, cur_val;
@Override
public void mousePressed(MouseEvent evt) {
int row = (evt.getY() - 10) / squareSize;
int col = (evt.getX() - 10) / squareSize;
if (row >= 0 && row < rows && col >= 0 && col < columns) {
cur_row = row;
cur_col = col;
cur_val = grid[row][col];
if (cur_val == EMPTY) {
grid[row][col] = OBST;
}
if (cur_val == OBST) {
grid[row][col] = EMPTY;
}
repaint();
}
}
@Override
public void mouseDragged(MouseEvent evt) {
int row = (evt.getY() - 10) / squareSize;
int col = (evt.getX() - 10) / squareSize;
if (row >= 0 && row < rows && col >= 0 && col < columns) {
if ((row * columns + col != cur_row * columns + cur_col) && (cur_val == STARTNODE || cur_val == ENDNODE)) {
int new_val = grid[row][col];
if (new_val == EMPTY) {
grid[row][col] = cur_val;
if (cur_val == STARTNODE) {
startnodeStart.row = row;
startnodeStart.col = col;
} else {
endnodePos.row = row;
endnodePos.col = col;
}
grid[cur_row][cur_col] = new_val;
cur_row = row;
cur_col = col;
if (cur_val == STARTNODE) {
startnodeStart.row = cur_row;
startnodeStart.col = cur_col;
} else {
endnodePos.row = cur_row;
endnodePos.col = cur_col;
}
cur_val = grid[row][col];
}
} else if (grid[row][col] != STARTNODE && grid[row][col] != ENDNODE) {
grid[row][col] = OBST;
}
}
repaint();
}
@Override
public void mouseReleased(MouseEvent evt) {
}
@Override
public void mouseEntered(MouseEvent evt) {
}
@Override
public void mouseExited(MouseEvent evt) {
}
@Override
public void mouseMoved(MouseEvent evt) {
}
@Override
public void mouseClicked(MouseEvent evt) {
}
}
</code></pre>
<p>Pls help me thanks.</p>
| 3 | 1,875 |
Adjusting Datepicker
|
<p>I have small knowledge of JS, but I was assigned a task to add some functionality to page. I need to add a datepicker in <code>birthDate</code> field, but once I add datepicker function to page my, validation(Jquery validation) stop working.
Here is code:</p>
<pre><code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page session="false"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site- demos.css" />
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<title>Parent Registration</title>
</head>
<body>
<!-- Everything inside should be the body -->
<tiles:insertDefinition name="defaultTemplate">
<tiles:putAttribute name="body">
....some code.........
<div class="form-group" >
<label for="birthDate" class="col-sm-3 control-label">Birthday</label>
<div class="col-sm-6">
<form:input type="text" class="form-control float_left" id="birthDate" name="birthDate" path="birthDate" placeholder="MM/DD/YYYY" required="true" />
</div>
</div>
...........some code...........
<script src="/resources/js/jquery.validate.min.js"></script>
<script src="/resources/js/validation.js"></script>
<script>
jQuery.validator.addMethod(
"dateUS",
function(value, element) {
var check = false;
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if( re.test(value)){
var adata = value.split('/');
var mm = parseInt(adata[0],10);
var dd = parseInt(adata[1],10);
var yyyy = parseInt(adata[2],10);
var xdata = new Date(yyyy,mm-1,dd);
var currentTime = new Date();
var year = currentTime.getFullYear();
if ( ( xdata.getFullYear() == yyyy) && ( xdata.getFullYear() <= year ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == dd ) )
check = true;
else
check = false;
} else
check = false;
return this.optional(element) || check;
},
"Please enter a date in the format MM/DD/YYYY"
);
jQuery.validator.addMethod("parentName", function(value, element) {
return this.optional( element ) || /^(?=.*[a-zA-Z])([a-zA-Z.'-\s]+)$/.test( value );
}, 'The name should contain at least one alphabet character, space, dot, hyphen, apostrophe.');
$(document).ready(function(){
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
firstName: {
required: true,
parentName: true
},
middleName: {
parentName: true
},
lastName: {
required: true,
parentName: true
},
noOfChildren: {
required: true,
digits: true
},
birthDate: {
required: true,
dateUS: true
},
email: {
required: true,
email:true
},
confirmemail: {
required: true,
equalTo: "#email"
},
confirmpassword: {
required: true,
equalTo: "#password"
}
},
errorPlacement: function (label, element) {
if(element.is("input:checkbox")) {
element.parent("label").after( label );
} else if(element.is("input:radio")){
element.parent("label" ).parent("div:first").after( label );
}
else {
label.insertAfter( element );
}
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#birthDate" ).datepicker();
});
</script>
</tiles:putAttribute>
</tiles:insertDefinition>
</body>
</html>
</code></pre>
| 3 | 2,676 |
C# Windows Phone 8.1 GetOutputStreamAsync(...) blocking after first use
|
<p>i'm currently trying to create a very basic test app which should:</p>
<p>1) Broadcast "sometext" on port "1234"<br>
2) Wait a second for answers<br>
3) Return all answers </p>
<p>While the solution posted below works fine for the first time, every subsequent call blocks forever at:<br>
<i>stream = await socket.GetOutputStreamAsync(...) </i></p>
<p>Till now i tried every possible way of cleaning up (since thats where i suppose the failure), even wrapping everything in <i>using(...)</i> statements.</p>
<p>The problem occurs with the emulator as well as a hardware device using Windows Phone 8.1</p>
<hr>
<p>Thanks in advance!</p>
<hr>
<p>The code to start the "discovery":</p>
<pre class="lang-cs prettyprint-override"><code>private void Button_Click(object sender, RoutedEventArgs e)
{
PluginUDP pudp = new PluginUDP();
var task = pudp.scan("asf");
task.Wait();
foreach (string s in task.Result)
output.Text += s + "\r\n";
}
</code></pre>
<hr>
<p>The code for the "discovery" itself:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using namespace whatever
{
public class PluginUDP
{
private static readonly HostName BroadcastAddress = new HostName("255.255.255.255");
private static readonly string BroadcastPort = "1234";
private static readonly byte[] data = Encoding.UTF8.GetBytes("00wlan-ping00");
ConcurrentBag<string> receivers;
public async System.Threading.Tasks.Task<string[]> scan(string options)
{
receivers = new ConcurrentBag<string>();
receivers.Add("ok");
DatagramSocket socket = null;
IOutputStream stream = null;
DataWriter writer = null;
try
{
socket = new DatagramSocket();
socket.MessageReceived += MessageReceived;
await socket.BindServiceNameAsync("");
stream = await socket.GetOutputStreamAsync(BroadcastAddress, BroadcastPort);
writer = new DataWriter(stream);
writer.WriteBytes(data);
await writer.StoreAsync();
Task.Delay(1000).Wait();
}
catch (Exception exception)
{
receivers.Add(exception.Message);
}
finally
{
if (writer != null)
{
writer.DetachStream();
writer.Dispose();
}
if(stream != null)
stream.Dispose();
if(socket != null)
socket.Dispose();
}
return receivers.ToArray(); ;
}
private async void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
{
try
{
var result = args.GetDataStream();
var resultStream = result.AsStreamForRead(1024);
using (var reader = new StreamReader(resultStream))
{
var text = await reader.ReadToEndAsync();
if (text.Contains("pong"))
{
receivers.Add(args.RemoteAddress.ToString());
}
}
}
catch (Exception exception)
{
receivers.Add("ERRCV");
}
}
}
}
</code></pre>
| 3 | 1,780 |
EOFError when open https
|
<p>I've been trying to use facebook graph api, though ruby raise EOFError when open api url (https://graph.facebook.com/.....)
I'm using Ruby 1.8.6 and Rails 2.2.2.
The code is as follows:</p>
<pre><code>require 'uri'
require 'https'
access_token = open("https://graph.facebook.com/oauth/access_token?client_id=app_id&client_secret=app_secret&grant_type=client_credentials"){|f|
f.read
}
</code></pre>
<p>Got following error:</p>
<pre><code>end of file reached
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:133:in `sysread'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:133:in `rbuf_fill'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/timeout.rb:62:in `timeout'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/timeout.rb:93:in `timeout'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:132:in `rbuf_fill'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:126:in `readline'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:2022:in `read_status_line'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:2011:in `read_new'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:1050:in `request'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:248:in `open_http'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:543:in `start'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:242:in `open_http'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:616:in `buffer_open'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:164:in `open_loop'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:162:in `catch'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:162:in `open_loop'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:132:in `open_uri'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:518:in `open'
/Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:30:in `open'
app/models/news_release.rb:75:in `post_to_facebook_wall'
</code></pre>
<p>I thoroughly googled and searched about this error and tried such as httpparty, mechanism, fb_graph, and koala.
However those raise same efoerror.
It seems that there is a bug with ruby-1.8.6 or open-uri, but I don't want to upgrade ruby.</p>
<p>Any ideas?
Thanks in advance.</p>
| 3 | 1,190 |
audio and seekbar in android
|
<p>i created audio activity with seekbar, it was played but i have problem when seekbar in progress there is cutting each 1 second in sound because i used (Thread.sleep).</p>
<p>i check another solution in Internet, all codes i checked were use same concept.</p>
<p>this is my code</p>
<pre><code>public class PlaySounds extends Activity implements Runnable {
SeekBar seeksounds;
MediaPlayer mp;
Handler handler = new Handler();
int id;
public boolean isFileExists(String fileName) {
try {
File myFile = new File(fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
return true;
} catch (Exception e) {
return false;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playsounds);
seeksounds = (SeekBar) findViewById(R.id.seeksounds);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
String path = Environment.getExternalStorageDirectory().toString() + "/dowload/splash.mp3";
if (isFileExists(path)) {
mp = new MediaPlayer();
try {
mp.setDataSource(path);
mp.prepare();
mp.start();
int maxD = mp.getDuration();
int currentD = mp.getCurrentPosition();
seeksounds.setMax(maxD);
seeksounds.setProgress(currentD);
new Thread(this).start();
seeksounds.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar arg0, int progress,
boolean arg2) {
mp.seekTo(progress);
seeksounds.setProgress(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mp.release();
}
@Override
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
seeksounds.setProgress(currentPosition);
} catch (Exception e) {
return;
}
}
}
</code></pre>
<p>}</p>
| 3 | 1,415 |
Splitting header and implementation causes significant slow-down
|
<p>When I split the header and implementation in c++, I found that significant slow-down occurs in some situation compared to the header-only one. The minumum working example is like below. In the case below, <code>get_sum</code> function is implemented in the header file and <code>get_sum2</code>, which is exactly the same implementation as <code>get_sum</code>, is implemented in <code>impl.cpp</code>. The result shows that time duration to execute is 0.001 [msec] for <code>get_sum</code> and 1066.84 [msec] for <code>get_sum2</code> (see <code>main.cpp</code>), though both have the same implementation. Could anyone explain why this happens?</p>
<p>The following codes can be found <a href="https://github.com/HiroIshida/snippets/tree/master/cpp/perf_impl_split" rel="nofollow noreferrer">here</a>.</p>
<p>The header file <code>header.h</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include<vector>
#include<iostream>
using namespace std;
class Tester
{
public:
Tester(int n){
table_.resize(n);
for(int i=0; i<n; i++){
table_[i].resize(n);
}
}
bool get_sum(){
double s = 0;
for(auto& subtable : table_){
for(double e : subtable){
s += e;
}
}
return s;
}
bool get_sum2(); // definition is in impl.cpp
private:
vector<vector<double>> table_;
};
</code></pre>
<p>The implementation file <code>impl.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>bool Tester::get_sum2(){
double s = 0;
for(auto& subtable : table_){
for(double e : subtable){
s += e;
}
}
return s;
}
</code></pre>
<p>The main file for benchmarking <code>main.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include "header.h"
int main(){
int size = 30000;
auto tester = Tester(size);
std::cout << "Finish constructing the tester" << std::endl;
{
clock_t start = clock();
tester.get_sum();
clock_t end = clock();
std::cout << (end - start)/1000.0 << " [msec]" << std::endl;
}
{
clock_t start = clock();
tester.get_sum2();
clock_t end = clock();
std::cout << (end - start)/1000.0 << " [msec]" << std::endl;
}
}
</code></pre>
<p>The output of execution of <code>main.cpp</code> is</p>
<pre><code>Finish constructing the tester
0.001 [msec]
1054.71 [msec]
</code></pre>
<p>cmake script used <code>CmakeLists.txt</code> (note that build with release mode)</p>
<pre><code>cmake_minimum_required(VERSION 3.4 FATAL_ERROR)
set(CMAKE_BUILD_TYPE Release)
add_executable(main main.cpp impl.cpp)
</code></pre>
| 3 | 1,094 |
How to boost documents matching one of the query_string
|
<p>Elasticsearch newbie here. I'm trying to lookup documents that has <code>foo</code> in its name but want to prioritize that ones having <code>bar</code> as well i.e. those with <code>bar</code> will be at the top of the list. The result doesn't have the ones with bar at the top. <code>boost</code> here doesn't seem to have any effect, likely I'm not understanding how boost works here. Appreciate any help here.</p>
<pre><code>query: {
bool: {
should: [
{
query_string: {
query: `name:foo*bar*`,
boost: 5
}
},
{
query_string: {
query: `name:*foo*`,
}
}
]
}
}
</code></pre>
<p>Sample document structure:</p>
<pre><code>{
"name": "foos, one two three",
"type": "car",
"age": 10
}
{
"name": "foos, one two bar three",
"type": "train",
"age": 30
}
</code></pre>
<p>Index mapping</p>
<pre><code>{
"detail": {
"mappings": {
"properties": {
"category": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"servings": {
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
}
</code></pre>
| 3 | 1,692 |
Partial specialization of members
|
<p>Trying to specialize member methods.<br>
Reading this previous question: <a href="https://stackoverflow.com/q/6972368/14065">std::enable_if to conditionally compile a member function</a><br>
I can quite understand what I am doing wrong.</p>
<pre><code>#include <string>
#include <iostream>
#include <type_traits>
template<typename T>
class Traits
{
};
struct Printer
{
template<typename T>
typename std::enable_if<!std::is_function<decltype(Traits<T>::converter)>::value, void>::type
operator()(T const& object)
{
std::cout << object;
}
template<typename T>
typename std::enable_if<std::is_function<decltype(Traits<T>::converter)>::value, void>::type
operator()(T const& object)
{
std::cout << Traits<T>::converter(object);
}
};
template<>
class Traits<std::string>
{
public:
static std::size_t converter(std::string const& object)
{
return object.size();
}
};
int main()
{
using namespace std::string_literals;
Printer p;
p(5);
p("This is a C-string");
p("This is a C++String"s); // This compiles.
}
</code></pre>
<p>Compilation Gives:</p>
<pre><code>> g++ -std=c++1z X.cpp
X.cpp:42:5: error: no matching function for call to object of type 'Printer'
p(5);
^
X.cpp:14:5: note: candidate template ignored: substitution failure [with T = int]: no member named 'converter' in 'Traits<int>'
operator()(T const& object)
^
X.cpp:20:5: note: candidate template ignored: substitution failure [with T = int]: no member named 'converter' in 'Traits<int>'
operator()(T const& object)
^
</code></pre>
<p>They both seem to fail because they can't see the method <code>converter</code>. But I am trying to use SFINE and <code>std::enable_if</code> to recognize that this function does not exist and thus only instantiate one of the methods.</p>
<p>The same error is generated for each of the types:</p>
<pre><code>X.cpp:43:5: error: no matching function for call to object of type 'Printer'
p("This is a C-string");
^
X.cpp:14:5: note: candidate template ignored: substitution failure [with T = char [19]]: no member named 'converter' in 'Traits<char [19]>'
operator()(T const& object)
^
X.cpp:20:5: note: candidate template ignored: substitution failure [with T = char [19]]: no member named 'converter' in 'Traits<char [19]>'
operator()(T const& object)
^
</code></pre>
<p>Note: It compiles for the <code>std::string</code> version.</p>
| 3 | 1,056 |
Trying to set different styles on two items from JSON
|
<p>I try to build a news app that shows on the MainPage an overview of news items.
The first 3 items need to be rendered different as the rest, using a FlatList.</p>
<ul>
<li>First item is a 100% background image with some text on it (did this with: if index === 0))</li>
<li>The second and third item needs to be background images with titles in a row (so next to each other)</li>
<li>The rests is a list with image, title, and date (underneath each other)</li>
</ul>
<p>I tried everything but item 2 and 3 is not working.</p>
<p>Tried with this little basic test:</p>
<pre><code>import React, { Component } from "react";
import { View, StyleSheet, Text, FlatList } from "react-native";
export default class Screen1 extends Component {
state = {
data: [
{
text: "one"
},
{
item1: {
text: "two"
},
item2: {
text: "three"
}
},
{
item1: {
text: "four"
},
item2: {
text: "five"
}
},
{
item1: {
text: "six"
}
}
]
};
renderItem = ({ item, index }) => {
if (index === 0) {
return (
<View style={styles.bigSquare}>
<Text> {item.text} </Text>{" "}
</View>
);
} else if (index > 0 || index <= 3) {
return (
<View
style={{
flexDirection: "row"
}}
>
{" "}
{item.item2 && (
<View
style={[
styles.smallSquare,
{
backgroundColor: "red"
}
]}
>
<Text> {item.item2.text} </Text> <Text> {item.item2.text} </Text>{" "}
</View>
)}{" "}
</View>
);
}
};
keyExtractor = (item, index) => `${index}`;
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>{" "}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
bigSquare: {
flexDirection: "column",
height: 220,
width: "100%",
margin: 10,
backgroundColor: "yellow",
justifyContent: "center",
alignItems: "center"
},
smallSquare: {
height: 100,
width: 100,
margin: 10,
backgroundColor: "green",
justifyContent: "center",
alignItems: "center"
}
});
</code></pre>
<p>Can someone point me in the right direction?</p>
<p>Example:</p>
<p><a href="https://i.stack.imgur.com/RgSXO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RgSXO.jpg" alt="Example of what I need "></a></p>
| 3 | 1,441 |
How to remove parent row and its items in array : jquery
|
<p><strong>Summary:</strong></p>
<p>I am creating a web page which shows results of user selections. First user select items from the given panel and clicks on add button. This creates a table row of selected items of the user(Just like adding items to the cart). User can remove items in the list when remove button is clicked. i am using parents('tr').remove()</p>
<p><strong>Issue:</strong></p>
<p>When the user clicks remove button, the row is getting deleted but the selection items a still in my array "benefits_array".</p>
<p>Here is jquery code:</p>
<pre><code>.on('click','.add-benefits-items', function(e) {
var target = $(this).siblings('.panel-body');
var tree_benefits_text = target.find('#tree-dropdown option:selected').text();
var display_text = target.find('#benefits-display-dropdown option:selected').text();
var unit_text = target.find('benefitsunit.active').text();
var dataset_text = target.find('benefitsDataset.active').text();
var checkboxes = target.find('input[type="checkbox"]');
benefits_array.push(
{
Tree_Benefits : tree_benefits_text,
Display : display_text,
Unit : unit_text,
Dataset: dataset_text,
});
$('.table-benefits').find('tbody')
.each(function(){
var map_elements = '<td style = "text-align:center">';
if (display_text == 'Map') {
map_elements += '<button data-target="#map_btn_benefits_id" type="button" class="map_btn_benefits btn btn-info active" data-toggle="modal">Map</button>';
map_elements += '<div id="map_btn_benefits_id" class="modal fade" role="dialog">';
map_elements += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Landscape Map</h4></div>';
map_elements += '<div class="modal-body"><div id="map_id_benefits" style="width: 500px; height: 380px; margin: 0; padding: 0;"></div></div>';
map_elements += '<div class="modal-footer"><button type="button" class="save-exit-benefits btn btn-primary" data-dismiss="modal">Save changes and Close</button>';
map_elements += '</div></div></div></div>';
map_elements += '</td>';
}
else {
map_elements += display_text+'</td>';
}
$(this).append(
'<tr>'+
'<td style="text-align:center"><a class="remove-row-benefits text-danger"><i class="fa fa-times"></i></a></td>'+
'<td style="text-align:center">'+tree_benefits_text+'</td>'+
map_elements+
'<td style="text-align:center">'+unit_text+'</td>'+
'<td style="text-align:center">'+dataset_text+'</td>'+
'</tr>')
});
})
.on('click', '.remove-row-benefits', function(){
$(this)
.parents('tr').remove();
})
</code></pre>
<p>I am passing "benefits_array" to other template using django views.py. For this question i believe you do not need code for it. What is the logic i am missing here. </p>
| 3 | 1,461 |
Bootstrap <select> element only gets 1 value
|
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(()=>{
$(".userChoice").on("click",()=>{
var selectedItem = $(".userChoice").val();
//console.log(selectedItem)
if(selectedItem = "monthly"){
console.log(selectedItem);
}
else if(selectedItem = "weekly"){
console.log(selectedItem);
}
else if(selectedItem = "daily"){
console.log(selectedItem);
}
})
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DASHBOARD</title>
<!--Lib css-->
<!--bootstrap-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!--fontawesome-->
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!--jquery-->
<script src="https://code.jquery.com/jquery-3.5.0.js"
integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script>
<!--own css-->
<style>
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";
body {
font-family: 'Poppins', sans-serif;
background: #fafafa;
}
p {
font-family: 'Poppins', sans-serif;
font-size: 1.1em;
font-weight: 300;
line-height: 1.7em;
color: #999;
}
a,
a:hover,
a:focus {
color: inherit;
text-decoration: none;
transition: all 0.3s;
}
.navbar {
padding: 15px 10px;
background: #fff;
border: none;
border-radius: 0;
margin-bottom: 40px;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}
.navbar-btn {
box-shadow: none;
outline: none !important;
border: none;
}
/* ---------------------------------------------------
SIDEBAR STYLE
----------------------------------------------------- */
.wrapper {
display: flex;
width: 100%;
align-items: stretch;
}
#sidebar {
min-width: 250px;
max-width: 250px;
background: rgb(60, 95, 238);
color: #fff;
transition: all 0.3s;
}
#sidebar.active {
margin-left: -250px;
}
#sidebar .sidebar-header {
padding: 20px;
background: rgb(90, 121, 243);
}
#sidebar ul.components {
padding: 20px 0;
border-bottom: 1px solid #47748b;
}
#sidebar ul p {
color: #fff;
padding: 10px;
}
#sidebar ul li a {
padding: 10px;
font-size: 1.1em;
display: block;
}
#sidebar ul li a:hover {
color: #7386D5;
background: #fff;
}
#sidebar ul li.active>a,
a[aria-expanded="true"] {
color: #fff;
background: #6d7fcc;
}
a[data-toggle="collapse"] {
position: relative;
}
.dropdown-toggle::after {
display: block;
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
}
ul ul a {
font-size: 0.9em !important;
padding-left: 30px !important;
background: #6d7fcc;
}
ul.CTAs {
padding: 20px;
}
ul.CTAs a {
text-align: center;
font-size: 0.9em !important;
display: block;
border-radius: 5px;
margin-bottom: 5px;
}
a.download {
background: #fff;
color: #7386D5;
}
a.article,
a.article:hover {
background: #6d7fcc !important;
color: #fff !important;
}
/* ---------------------------------------------------
CONTENT STYLE
----------------------------------------------------- */
#content {
width: 100%;
padding: 20px;
min-height: 100vh;
transition: all 0.3s;
}
/* ---------------------------------------------------
MEDIAQUERIES
----------------------------------------------------- */
@media (max-width: 768px) {
#sidebar {
margin-left: -250px;
}
#sidebar.active {
margin-left: 0;
}
#sidebarCollapse span {
display: none;
}
}
/* ---------------------------------------------------
CHART STYLE
-----------------------------------------------------
/* LINE CHART STYLE */
.axis--x path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<!--lib js-->
<!--bootstrap-->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<!--fontawesome js-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>
<!--d3(chart) js-->
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<div class="wrapper">
<!-- Sidebar -->
<nav id="sidebar">
<ul class="list-unstyled components">
<li class="active">
<a href="/">DASHBOARD</a>
</li>
</ul>
<!--End of nav.sidebar-->
</nav>
<!--Page content-->
<div id="content">
<!-- navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<button type="button" id="sidebarCollapse" class="btn btn-info">
<i class="fas fa-align-justify"></i>
</button>
</div>
</nav>
<div class="container-fluid content-header">
<form class="form-inline">
<div class="form-row">
<div class="form-group">
<select id="" class="form-control userChoice col-md-16">
<option value="monthly">Monthly</option>
<option value="weekly">Weekly</option>
<option value="daily">Daily</option>
</select>
</div>
</div>
</form>
</div>
<!--End of div.row-->
</div>
<!--End of div.wrapper-->
<script src="js/script3.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I have this ` element but the problem is that it only gets one value. Please see on the console:
<a href="https://i.stack.imgur.com/x6SGx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x6SGx.png" alt="enter image description here"></a></p>
<p>I've tried getting the value of my dropdown/select element with the help of jquery/javascript
using the code below:</p>
<pre><code> $(document).ready(()=>{
$(".userChoice").on("click",()=>{
var selectedItem = $(".userChoice").val();
//console.log(selectedItem)
if(selectedItem = "monthly"){
console.log(selectedItem);
}
else if(selectedItem = "weekly"){
console.log(selectedItem);
}
else if(selectedItem = "daily"){
console.log(selectedItem);
}
})
});
</code></pre>
<p>But it only outputs monthly. Can someone please help me with these?
The code snippet is below:</p>
| 3 | 4,942 |
Web dev - setup firebase firestore question
|
<p>i asked here few questions before and i did always got help so here i am again,
im kinda new to HTML,CSS,JS and i just wrote some html- css -js code for single webpage and i need to add some data that i can manage (data base) i searched online and found firestore and good solution for me (if u recommand on other ways to use live-data on ur site ill be happy to hear)
anyway i opened firestore database and set everything in firebase website went to my project followed this instructions:
<a href="https://firebase.google.com/docs/firestore/quickstart#web-version-9" rel="nofollow noreferrer">https://firebase.google.com/docs/firestore/quickstart#web-version-9</a>
and
<a href="https://firebase.google.com/docs/web/setup" rel="nofollow noreferrer">https://firebase.google.com/docs/web/setup</a>
and few videos online
i tried all methods in these websites and youtube and still i cant make this work i even tried to load my website on XAMPP (maybe its not related to my problem but i cant think of any more solutions) please help me figure it out and try to explain the details as much as u can so it will really clear this for me.</p>
<p>this what ive done now:
1.my project is in htdoc folder inside XAMPP
2.i run Apache module in XAMPP in port 8080
3.i use localhost:8080/Website/Main.html in google chrome to reach the website
4.used npm install firebase in visual studio code console
these are my files:
Index.html</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Calander </title>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-storage.js"></script>
<link rel="stylesheet" href="Calander.css">
</head>
<body">
<div class="calander">
</div>
<script type="module" src="firebase.js"></script>
<script src="Calander.js"></script>
</body>
</html>
</code></pre>
<p>firebase.js</p>
<pre><code>import { initializeApp } from ".//node_modules/@firebase/app";
import { getFirestore } from ".//node_modules/@firebase/firestore";
const firebaseApp = initializeApp({
apiKey: "******************",
authDomain: "******************",
projectId: "******************",
storageBucket: "******************",
messagingSenderId: "******************",
appId: "******************",
measurementId: "******************"
});
const db = getFirestore();
import { collection, addDoc } from ".//node_modules/@firebase/firestore";
try {
const docRef = await addDoc(collection(db, "users"), {
first: "Ada",
last: "Lovelace",
born: 1815
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
</code></pre>
| 3 | 1,416 |
Inner join 3 table
|
<p>I have 6 table in my database <img src="https://i.stack.imgur.com/EzxmW.jpg" alt="booking_system">. And now I would like to inner join car_space, transaction and sport_facilities. However, I got a problem. </p>
<p>When I use these two sql command respectively, these command also can be run and I can get the result I want.</p>
<pre><code>-- car_space INNER JOIN transaction
SELECT * FROM car_space INNER JOIN transaction ON car_space.carSpaceId = transaction.carSpaceId ORDER BY transactionId;
-- sport_facilities INNER JOIN transaction
SELECT * FROM sport_facilities INNER JOIN transaction ON sport_facilities.sportFacilitiesId = transaction.sportFacilitiesId ORDER BY transactionId;
</code></pre>
<p>And then, I combine them into one command.</p>
<pre><code>-- Combine But Not Work
SELECT * FROM transaction
INNER JOIN car_space ON transaction.carSpaceId = car_space.carSpaceId
INNER JOIN sport_facilities ON transaction.sportFacilitiesId = sport_facilities.sportFacilitiesId
ORDER BY transactionId;
</code></pre>
<p>Although this can be run, there are no result or records was shown.</p>
<p>I want to do is the database can be found the record in which table (car_space / sport_facilities) when I typed a transactionId.
For example:
I type <code>WHERE transactionId = 1</code>
Database can be searched this is from sport_facilities table rather that car_space.</p>
<p>Thank you. Here is some code for reference.</p>
<pre><code> -- Create a database
CREATE DATABASE booking_system;
-- Use This database
USE booking_system;
-- Create smartcart table
CREATE TABLE card(
cardId CHAR(8) NOT NULL,
PRIMARY KEY (cardId)
);
-- Insert some recond to card table
INSERT INTO card VALUES
('4332A0D5'),
('637ED500'),
('B3895A02'),
('E32F3702')
;
-- Create user table
CREATE TABLE user(
userId INT(5) NOT NULL AUTO_INCREMENT,
cardNo CHAR(8) NOT NULL,
firstName VARCHAR(255) NOT NULL,
lastName VARCHAR(255) NOT NULL,
sex CHAR(1) NOT NULL,
dob DATE NOT NULL,
hkid CHAR(8) NOT NULL,
email VARCHAR(255) NOT NULL,
telNo INT(8) NOT NULL,
PRIMARY KEY (userId),
FOREIGN KEY (cardNo) REFERENCES card (cardId) ON DELETE CASCADE,
UNIQUE (hkid)
);
-- Alter user table
ALTER TABLE user AUTO_INCREMENT = 16001;
-- Insert some recond to user table
INSERT INTO user VALUES
('','4332A0D5','Andy','Ding','M','1962-04-20','K5216117','mkding@yahoo.com','98626229'),
('','637ED500','Emma','Dai','F','1972-06-15','D5060339','emmadai@yahoo.com.hk','62937453'),
('','B3895A02','Brinsley','Au','F','1984-02-24','P8172327','da224@live.hk','91961624'),
('','E32F3702','Eric','Fong','M','1990-04-15','Y1129323','ericfong0415@gmail.com','98428731')
;
-- Create car space price table
CREATE TABLE car_space_price(
spaceNo INT(2) NOT NULL AUTO_INCREMENT,
price INT(2) NOT NULL,
carSpaceDescription VARCHAR(16),
CHECK (carSpaceDescription IN ('motorcycles','small vehicles','medium vehicles','large vehicles')),
PRIMARY KEY (spaceNo)
);
-- Insert some recond to car space price table
INSERT INTO car_space_price VALUES
('','10','motorcycles'), -- 1
('','10','motorcycles'), -- 2
('','10','motorcycles'), -- 3
('','10','motorcycles'), -- 4
('','10','motorcycles'), -- 5
('','20','small vehicles'), -- 6
('','20','small vehicles'), -- 7
('','20','small vehicles'), -- 8
('','20','small vehicles'), -- 9
('','20','small vehicles'), -- 10
('','40','medium vehicles'), -- 11
('','40','medium vehicles'), -- 12
('','40','medium vehicles'), -- 13
('','80','large vehicles'), -- 14
('','80','large vehicles') -- 15
;
-- Create car space table
CREATE TABLE car_space(
carSpaceId INT(5) NOT NULL AUTO_INCREMENT,
spaceNo INT(2) NOT NULL,
cardNo VARCHAR(8) NOT NULL,
inTime DATETIME,
outTime DATETIME,
PRIMARY KEY (carSpaceId),
FOREIGN KEY (spaceNo) REFERENCES car_space_price (spaceNo) ON DELETE CASCADE,
FOREIGN KEY (cardNo) REFERENCES card (cardId) ON DELETE CASCADE
);
-- Insert some recond to car space table
INSERT INTO car_space VALUES
('','2','E32F3702','2015-02-23 14:24:18','2015-02-23 17:01:43'), -- 1 --16004
('','6','B3895A02','2016-02-24 11:56:43','2016-02-25 09:21:08'), -- 2 --16003
('','2','E32F3702','2016-02-24 16:42:34','2016-02-24 21:02:45'), -- 3 --16004
('','2','E32F3702','2016-02-25 14:25:32','2016-02-25 17:03:54'), -- 4 --16004
('','6','B3895A02','2016-02-25 17:12:11','2016-02-25 20:58:18'), -- 5 --16003
('','13','637ED500','2016-02-25 19:17:03','2016-02-27 18:05:28'), -- 6 --16002
('','6','B3895A02','2016-02-25 21:14:03','2016-02-25 23:53:28'), -- 7 --16003
('','6','B3895A02','2016-02-26 08:46:23','2016-02-26 17:21:08'), -- 8 --16003
('','2','E32F3702','2016-02-26 14:15:45','2016-02-26 21:01:15'), -- 9 --16004
('','6','B3895A02','2016-02-27 09:42:13','2016-02-27 15:48:45'), -- 10 --16003
('','2','E32F3702','2016-02-27 13:25:45','2016-02-27 15:15:45'), -- 11 --16004
('','6','B3895A02','2016-02-28 10:57:16','2016-02-28 14:41:25'), -- 12 --16003
('','2','E32F3702','2016-02-28 11:47:32','2016-02-28 13:43:15'), -- 13 --16004
('','13','637ED500','2016-02-28 13:04:43','2016-03-02 22:39:46'), -- 14 --16002
('','2','E32F3702','2016-02-28 14:42:34','2016-02-28 21:47:45'), -- 15 --16004
('','6','B3895A02','2016-02-29 08:50:42','2016-02-29 14:28:42'), -- 16 --16003
('','2','E32F3702','2016-02-29 12:12:35','2016-02-29 16:45:28'), -- 17 --16004
('','6','B3895A02','2016-03-01 11:26:43','2016-03-01 14:56:26'), -- 18 --16003
('','6','B3895A02','2016-03-03 13:45:26','2016-03-03 17:54:18') -- 19 --16003
;
-- Create sport facilities price table
CREATE TABLE sport_facilities_price(
sportNo INT(2) NOT NULL AUTO_INCREMENT,
sportType VARCHAR(10) NOT NULL,
price INT(2) NOT NULL,
sportDescription VARCHAR(20),
PRIMARY KEY (sportNo)
);
-- Insert some recond to sport facilities price table
INSERT INTO sport_facilities_price VALUES
('','snooker','15','Snooker Room 1'), -- 1
('','snooker','15','Snooker Room 2'), -- 2
('','snooker','15','Snooker Room 3'), -- 3
('','snooker','15','Snooker Room 4'), -- 4
('','table_tennis','15','Table Tennis Room 1'), -- 5
('','table_tennis','15','Table Tennis Room 2'), -- 6
('','table_tennis','15','Table Tennis Room 3'), -- 7
('','table_tennis','15','Table Tennis Room 4'), -- 8
('','tennis','30','Tennis Vanue 1'), -- 9
('','tennis','30','Tennis Vanue 2'), -- 10
('','badminton','30','Badminton Vanue 1'), -- 11
('','badminton','30','Badminton Vanue 2'), -- 12
('','basketball','60','Hall') -- 13
;
-- Create sport facilities table
CREATE TABLE sport_facilities(
sportFacilitiesId INT(5) NOT NULL AUTO_INCREMENT,
sportNo INT(2) NOT NULL,
cardNo VARCHAR(8) NOT NULL,
bookDate DATE NOT NULL,
startTime TIME NOT NULL,
endTime TIME NOT NULL,
PRIMARY KEY (sportFacilitiesId),
FOREIGN KEY (sportNo) REFERENCES sport_facilities_price (sportNo) ON DELETE CASCADE,
FOREIGN KEY (cardNo) REFERENCES card (cardId) ON DELETE CASCADE
);
-- Insert some recond to sport facilities table
INSERT INTO sport_facilities VALUES
('','1','E32F3702','2015-02-23','12:00:00','14:00:00'), -- 1 --16004
('','5','B3895A02','2016-02-23','14:00:00','15:00:00'), -- 2 --16003
('','8','637ED500','2016-02-23','17:00:00','21:00:00'), -- 3 --16002
('','2','E32F3702','2016-02-24','09:00:00','11:00:00'), -- 4 --16004
('','5','4332A0D5','2016-02-24','13:00:00','14:00:00'), -- 5 --16001
('','7','637ED500','2016-02-24','15:00:00','17:00:00'), -- 6 --16002
('','8','B3895A02','2016-02-24','16:00:00','18:00:00'), -- 7 --16003
('','10','4332A0D5','2016-02-25','09:00:00','10:00:00'), -- 8 --16001
('','12','B3895A02','2016-02-25','13:00:00','14:00:00'), -- 9 --16003
('','6','637ED500','2016-02-25','21:00:00','22:00:00'), -- 10 --16002
('','4','637ED500','2016-02-26','11:00:00','13:00:00'), -- 11 --16002
('','8','4332A0D5','2016-02-26','22:00:00','23:00:00'), -- 12 --16001
('','13','B3895A02','2016-02-27','09:00:00','14:00:00'), -- 13 --16003
('','4','637ED500','2016-02-28','12:00:00','14:00:00'), -- 14 --16002
('','3','B3895A02','2016-02-28','14:00:00','15:00:00'), -- 15 --16003
('','4','E32F3702','2016-02-28','17:00:00','19:00:00'), -- 16 --16004
('','5','B3895A02','2016-02-28','21:00:00','22:00:00'), -- 17 --16003
('','2','4332A0D5','2016-02-28','21:00:00','23:00:00'), -- 18 --16001
('','10','E32F3702','2016-02-28','19:00:00','20:00:00'), -- 19 --16004
('','11','B3895A02','2016-02-29','11:00:00','13::00:00'), -- 20 --16003
('','8','E32F3702','2016-02-29','12:00:00','14:00:00'), -- 21 --16004
('','4','4332A0D5','2016-02-29','15:00:00','18:00:00'), -- 22 --16001
('','6','E32F3702','2016-03-01','09:00:00','11:00:00'), -- 23 --16004
('','5','637ED500','2016-03-01','12:00:00','15:00:00'), -- 24 --16002
('','3','B3895A02','2016-03-02','09:00:00','11:00:00'), -- 25 --16003
('','7','4332A0D5','2016-03-02','12:00:00','13:00:00'), -- 26 --16001
('','4','637ED500','2016-03-02','15:00:00','17:00:00'), -- 27 --16002
('','1','E32F3702','2016-03-02','19:00:00','22:00:00'), -- 28 --16004
('','12','4332A0D5','2016-03-03','11:00:00','13:00:00'), -- 29 --16001
('','9','E32F3702','2016-03-03','15:00:00','16:00:00'), -- 30 --16004
('','10','B3895A02','2016-03-03','09:00:00','11:00:00'), -- 31 --16003
('','4','637ED500','2016-03-04','11:00:00','12:00:00'), -- 32 --16002
('','8','E32F3702','2016-03-04','14:00:00','16:00:00'), -- 33 --16004
('','6','B3895A02','2016-03-05','19:00:00','21:00:00'), -- 34 --16003
('','13','E32F3702','2016-03-05','11:00:00','12:00:00'), -- 35 --16004
('','8','637ED500','2016-03-05','14:00:00','15:00:00'), -- 36 --16002
('','4','4332A0D5','2016-03-05','16:00:00','18:00:00'), -- 37 --16001
('','5','E32F3702','2016-03-06','13:00:00','15:00:00'), -- 38 --16004
('','9','B3895A02','2016-03-06','17:00:00','18:00:00'), -- 39 --16003
('','11','4332A0D5','2016-03-07','20:00:00','21::00:00'), -- 40 --16001
('','5','B3895A02','2016-03-07','22:00:00','23:00:00') -- 41 --16003
;
-- Create transaction table
CREATE TABLE transaction(
transactionId INT(5) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
userId INT(5) NOT NULL,
carSpaceId INT(5),
sportFacilitiesId INT(5),
transactionDate DATE NOT NULL,
PRIMARY KEY (transactionId),
FOREIGN KEY (userId) REFERENCES user (userId) ON DELETE CASCADE,
FOREIGN KEy (carSpaceId) REFERENCES car_space (carSpaceId) ON DELETE CASCADE,
FOREIGN KEY (sportFacilitiesId) REFERENCES sport_facilities (sportFacilitiesId) ON DELETE CASCADE
);
-- Insert some recond to transaction table
INSERT INTO transaction VALUES
('','16004',NULL,'1','2015-02-23'), -- 1 -- Sport Facilities
('','16003',NULL,'5','2015-02-23'), -- 2 -- Sport Facilities
('','16004','2',NULL,'2015-02-23'), -- 3 -- Car Space
('','16002',NULL,'8','2015-02-23'), -- 4 -- Sport Facilities
('','16004',NULL,'2','2016-02-24'), -- 5 -- Sport Facilities
('','16003','6',NULL,'2016-02-24'), -- 6 -- Car Space
('','16001',NULL,'5','2016-02-24'), -- 7 -- Sport Facilities
('','16002',NULL,'7','2016-02-24'), -- 8 -- Sport Facilities
('','16003',NULL,'8','2016-02-24'), -- 9 -- Sport Facilities
('','16004','2',NULL,'2016-02-24'), -- 10 -- Car Space
('','16001',NULL,'10','2016-02-25'), -- 11 -- Sport Facilities
('','16003',NULL,'12','2016-02-25'), -- 12 -- Sport Facilities
('','16004','2',NULL,'2016-02-25'), -- 13 -- Car Space
('','16003','6',NULL,'2016-02-25'), -- 14 -- Car Space
('','16002','13',NULL,'2016-02-25'), -- 15 -- Car Space
('','16002',NULL,'6','2016-02-25'), -- 16 -- Sport Facilities
('','16003','6',NULL,'2016-02-25'), -- 17 -- Car Space
('','16003','6',NULL,'2016-02-26'), -- 18 -- Car Space
('','16002',NULL,'4','2016-02-26'), -- 19 -- Sport Facilities
('','16004','2',NULL,'2016-02-26'), -- 20 -- Car Space
('','16001',NULL,'8','2016-02-26'), -- 21 -- Sport Facilities
('','16003',NULL,'13','2016-02-27'), -- 22 -- Sport Facilities
('','16003','6',NULL,'2016-02-27'), -- 23 -- Car Space
('','16004','2',NULL,'2016-02-27'), -- 24 -- Car Space
('','16003','6',NULL,'2016-02-28'), -- 25 -- Car Space
('','16004','2',NULL,'2016-02-28'), -- 26 -- Car Space
('','16002',NULL,'4','2016-02-28'), -- 27 -- Sport Facilities
('','16002','13',NULL,'2016-02-28'), -- 28 -- Car Space
('','16003',NULL,'3','2016-02-28'), -- 29 -- Sport Facilities
('','16004','2',NULL,'2016-02-28'), -- 30 -- Car Space
('','16004',NULL,'4','2016-02-28'), -- 31 -- Sport Facilities
('','16003',NULL,'5','2016-02-28'), -- 32 -- Sport Facilities
('','16001',NULL,'2','2016-02-28'), -- 33 -- Sport Facilities
('','16004',NULL,'10','2016-02-28'), -- 34 -- Sport Facilities
('','16003','6',NULL,'2016-02-29'), -- 35 -- Car Space
('','16003',NULL,'11','2016-02-29'), -- 36 -- Sport Facilities
('','16004',NULL,'8','2016-02-29'), -- 37 -- Sport Facilities
('','16004','2',NULL,'2016-02-29'), -- 38 -- Car Space
('','16001',NULL,'4','2016-02-29'), -- 39 -- Sport Facilities
('','16004',NULL,'6','2016-03-01'), -- 40 -- Sport Facilities
('','16003','6',NULL,'2016-03-01'), -- 41 -- Car Space
('','16002',NULL,'5','2016-03-01'), -- 42 -- Sport Facilities
('','16003',NULL,'3','2016-03-02'), -- 43 -- Sport Facilities
('','16001',NULL,'7','2016-03-02'), -- 44 -- Sport Facilities
('','16002',NULL,'4','2016-03-02'), -- 45 -- Sport Facilities
('','16004',NULL,'1','2016-03-02'), -- 46 -- Sport Facilities
('','16001',NULL,'12','2016-03-03'), -- 47 -- Sport Facilities
('','16003','6',NULL,'2016-03-03'), -- 48 -- Car Space
('','16004',NULL,'9','2016-03-03'), -- 49 -- Sport Facilities
('','16003',NULL,'10','2016-03-03'), -- 50 -- Sport Facilities
('','16002',NULL,'4','2016-03-04'), -- 51 -- Sport Facilities
('','16004',NULL,'8','2016-03-04'), -- 52 -- Sport Facilities
('','16003',NULL,'6','2016-03-05'), -- 53 -- Sport Facilities
('','16004',NULL,'13','2016-03-05'), -- 54 -- Sport Facilities
('','16002',NULL,'8','2016-03-05'), -- 55 -- Sport Facilities
('','16001',NULL,'4','2016-03-05'), -- 56 -- Sport Facilities
('','16004',NULL,'5','2016-03-06'), -- 57 -- Sport Facilities
('','16003',NULL,'9','2016-03-06'), -- 58 -- Sport Facilities
('','16001',NULL,'11','2016-03-07'), -- 59 -- Sport Facilities
('','16003',NULL,'5','2016-03-07') -- 60 -- Sport Facilities
;
</code></pre>
| 3 | 7,261 |
How to have type transfer of ChartJS configuration from a react component prop?
|
<p>I made a <code>ChartJS</code> component that is a simple react wrapper to correctly setup and destroy ChartJS instances with some default options:</p>
<pre class="lang-js prettyprint-override"><code>import React, {
useEffect,
useState,
VFC,
} from 'react';
import {
ArcElement,
BarController,
BarElement,
CategoryScale,
Chart,
ChartConfiguration,
DoughnutController,
LinearScale,
} from 'chart.js';
Chart.register(
ArcElement,
BarElement,
BarController,
DoughnutController,
CategoryScale,
LinearScale,
);
export interface ChartJSProps {
config: ChartConfiguration;
}
export const ChartJS: VFC<ChartJSProps> = ({
config,
}) => {
const [id, setId] = useState<string>();
useEffect(() => {
setId(`chart-${Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)}`);
}, []);
useEffect(() => {
if (!id) {
return;
}
// @see https://stackoverflow.com/a/58877962/1731473
const canvas: HTMLCanvasElement = document.getElementById(id) as HTMLCanvasElement;
const ctx = canvas.getContext('2d');
let chart: Chart;
if (ctx !== null) {
const { options } = config;
chart = new Chart(ctx, {
...config,
options: {
responsive: true,
maintainAspectRatio: false,
...options,
elements: {
...options?.elements,
line: {
fill: false,
...options?.elements?.line,
},
},
plugins: {
...options?.plugins,
legend: {
display: false,
...options?.plugins?.legend,
},
tooltip: {
mode: 'nearest',
intersect: false,
...options?.plugins?.tooltip,
},
},
},
});
}
return () => {
if (chart) {
// @see https://www.chartjs.org/docs/latest/developers/api.html#destroy
chart.destroy();
}
};
}, [id]);
return (
<canvas id={id} />
);
};
export default null;
</code></pre>
<p>This wrapper is fully working, however, Typescript is yelling about type specific configuration.</p>
<p>Here is a <code>GaugeChart</code> component using the ChartJS <code>doughnut</code> type as an example:</p>
<pre class="lang-js prettyprint-override"><code>import React, {
VFC,
} from 'react';
import { ChartJS } from './ChartJS';
export interface GaugeChartProps {
value: number;
max?: number;
}
export const GaugeChart: VFC<GaugeChartProps> = ({
value,
max = 100,
}) => {
const percent = value / max;
return (
<ChartJS config={{
type: 'doughnut',
data: {
datasets: [
{
backgroundColor: [
'rgb(255, 99, 132)',
'#ccc',
],
// eslint-disable-next-line id-blacklist
data: [
percent * 100,
100 - (percent * 100),
],
},
],
},
options: {
rotation: 270, // start angle in degrees
circumference: 180, // sweep angle in degrees
},
}}
/>
);
};
export default null;
</code></pre>
<p>The <code>npx tsc</code> command give me this:</p>
<pre><code>src/components/chart/GaugeChart.tsx:36:9 - error TS2322: Type '{ rotation: number; circumference: number; }' is not assignable to type '_DeepPartialObject<CoreChartOptions<keyof ChartTypeRegistry> & ElementChartOptions<keyof ChartTypeRegistry> & PluginChartOptions<...> & DatasetChartOptions<...> & ScaleChartOptions<...>>'.
Object literal may only specify known properties, and 'rotation' does not exist in type '_DeepPartialObject<CoreChartOptions<keyof ChartTypeRegistry> & ElementChartOptions<keyof ChartTypeRegistry> & PluginChartOptions<...> & DatasetChartOptions<...> & ScaleChartOptions<...>>'.
36 rotation: 270, // start angle in degrees
~~~~~~~~~~~~~
node_modules/chart.js/types/index.esm.d.ts:3493:3
3493 options?: ChartOptions<TType>;
~~~~~~~
The expected type comes from property 'options' which is declared here on type 'ChartConfiguration<keyof ChartTypeRegistry, (number | ScatterDataPoint | BubbleDataPoint | null)[], unknown>'
</code></pre>
<p>Typescript Version:</p>
<pre><code>❯ npx tsc -v
Version 4.2.2
</code></pre>
<p>As you can see, the <code>rotation</code> option is not recognized.</p>
<p>Of course, I could resolve it by declaring a well typed constant:</p>
<pre class="lang-js prettyprint-override"><code>import React, {
VFC,
} from 'react';
import { ChartConfiguration } from 'chart.js';
import { ChartJS } from './ChartJS';
export const GaugeChart: VFC<GaugeChartProps> = ({
value,
max = 100,
}) => {
const percent = value / max;
const config: ChartConfiguration<'doughnut'> = {
type: 'doughnut',
data: {
datasets: [
{
backgroundColor: [
'rgb(255, 99, 132)',
'#ccc',
],
// eslint-disable-next-line id-blacklist
data: [
percent * 100,
100 - (percent * 100),
],
},
],
},
options: {
rotation: 270, // start angle in degrees
circumference: 180, // sweep angle in degrees
},
};
return <ChartJS config={config} />;
};
</code></pre>
<p>But it means I have to rely directly to the <code>chart.js</code> vendor, it looks not ideal.</p>
<p>Also, the <code>type</code> configuration value should infer to the <code>options</code> defintion, as it is done with a simple <code>new Chart</code> call with direct configuration.</p>
<p>How can I have the same behavior with <code>type</code> value inference on my component wrapper <code>config</code> prop?</p>
| 3 | 2,521 |
How can we add multiple color for multiple jquery ui datepicker?
|
<p>I have a project in laravel. On one page I have several jQuery ui datepicker see the image below. When page loads I need to get some date from database and mark some color on calendar, based on data. At-present I can mark color only on one datepicker. How can I mark color on multiple datepicker?<a href="https://i.stack.imgur.com/g7CFx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g7CFx.jpg" alt="enter image description here"></a></p>
<p><strong>CalendarController.php</strong></p>
<pre><code>return view('searchResult',['greenDates' => $available_dates, 'orangeDates' => $orangeDates, 'redDates' => $not_available_dates]);
</code></pre>
<p><strong>searchResult.blade.php</strong></p>
<pre><code>@foreach($cabinSearchResult as $result)
<div class="form-group row calendar" data-id="{{ $result->_id }}">
<div class="col-sm-4">
<input type="text" class="form-control dateFrom" id="dateFrom_{{ $result->_id }}" name="dateFrom" placeholder="Arrival" readonly>
</div>
<div class="col-sm-4">
<input type="text" class="form-control dateTo" id="dateTo_{{ $result->_id }}" name="dateTo" placeholder="Departure" readonly>
</div>
</div>
@endforeach
@push('scripts')
var greenDates = {!! json_encode($greenDates) !!};
var orangeDates = {!! json_encode($orangeDates) !!};
var redDates = {!! json_encode($redDates) !!};
var start_date = '';
$(".dateFrom").datepicker({
showAnim: "drop",
dateFormat: "dd.mm.y",
changeMonth: true,
changeYear: true,
minDate: '+1d',
yearRange: "0:+2"
});
$("body").on('mousedown', ".dateFrom", function() {
var dataId = $(this).parent().parent().data("id");
var $this = $(this);
var returnResult = [];
$this.datepicker("option", "beforeShowDay", function(date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
if( greenDates.indexOf(string) >=0 ) {
returnResult = [true, "greenDates", "Available"];
}
if( orangeDates.indexOf(string) >=0 ) {
returnResult = [true, "orangeDates", "Few are available"];
}
if( redDates.indexOf(string) >=0 ) {
returnResult = [true, "redDates", "Not available"];
}
return returnResult;
});
$this.datepicker("show");
});
@endpush
</code></pre>
| 3 | 1,104 |
Button not working when sidenav is out
|
<p>I'm working on a login page on my site button for some reason the submit button isn't clickable when the sidenav is out (I'm using the materialize framework).</p>
<p>I have modified my sidenav a bit so that the overlay is removed when it is out and it doesn't close when clicked outside it.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.button-collapse').sideNav({
menuWidth: 260,
edge: 'left',
closeOnClick: true
}
);
//Unbind sidenav click to close
$(function(){
$(".drag-target").unbind('click');
$("#sidenav-overlay").unbind('click');
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,body {
height: 100%;
background-color:
}
header, main, footer, header{
padding-left: 0 auto;
}
@media only screen and (max-width : 992px) {
header, main, footer {
padding-left: 0;
}
}
.rotate90 {
-ms-transform: rotate(-90deg);
-webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
}
.text1 {
color: #212121;
}
.text2 {
color: #757575;
}
nav.top-nav {
background-color: #303F9F;
}
.title-text {
font-family: Roboto;
font-weight: bold;
}
a.bold, .bold {
font-family: Roboto;
font-weight: bold;
}
a.light, .light {
font-family: Roboto;
font-weight: normal;
}
#sidenav-overlay {
display: none;
}
</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<header>
<nav class="top-nav">
<div class="container">
<a href="#" data-activates="slide-out" class="button-collapse show-on-large"><i class="material-icons">menu</i></a>
<div class="navbar-wrapper">
<a href="/index.html" class="brand-logo center">Icy Fire</a>
</div>
</div>
</nav>
<ul id="slide-out" class="side-nav">
<h4 class="title-text center-align">Navigation</h4>
<div class="divider"></div>
<li><a href="/user/account.php" class="waves-effect waves-teal bold">Account</a></li>
<li class="no-padding">
<ul class="collapsible collapsible-accordion">
<li>
<a class="collapsible-header waves-effect waves-teal bold">Pages<i class="material-icons">arrow_drop_down</i></a>
<div class="collapsible-body">
<a href="/index.html" class="active waves-effect light">Index</a>
</div>
</li>
</ul>
</ul>
</header>
<main>
<div class="container">
<div class="row">
<div class="col s12">
<h2 class="indigo-text">Login</h2>
<div class="divider"></div>
<form class="col s12" action="login.php" method="POST">
<div class="input-field">
<input id="username" type="text" class="validate" name="username" required>
<label for="username">Username</label>
</div>
<div class="input-field">
<input id="password" type="password" class="validate" name="password" required>
<label for="password">Password</label>
</div>
<div class="input-field">
<input type="checkbox" id="indeterminate-checkbox" name="remember" value="on" />
<label for="indeterminate-checkbox">Remember me</label>
</div>
<button class="btn waves-effect waves-light blue right" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
<h5 class="indigo-text"><?php getMsg(); ?></h5>
</div>
</div>
</div>
</main>
<footer>
</footer>
</body></code></pre>
</div>
</div>
</p>
<p>Here it is on my website: <a href="https://icy-fire.com/user/login.php" rel="nofollow">link</a></p>
| 3 | 2,994 |
Spawning enemies in four different positions with a fixed trajectory in android game
|
<p>This is my first android game, I appreciate all the help. I want to define 4 spawning zones starting from out of the screen (left, right, up and down). Enemies coming from this areas have a fixed trajectory to the center, when this enemies come into the screen the player can move them to a specific corner, but if it lets go of it a new trajectory has to be calculated so it keeps moving to the center.</p>
<p>I am having trouble thinking on how to define this 4 areas, there is also 4 types enemies (they are the same, but they have a different color), should I place this 4 enemies on an arrayList ?. If I know how to define this 4 spawning areas which randomly decides where to spawn I then don't exactly know how to define the fixed trajectory to the center. Also, need to lower the speed to a more adecuate one. (Sorry if this seems like a lot am asking)</p>
<p>Current code looks like this (I am using AndEngine library):</p>
<pre><code>public class gameEscene extends baseScene {
// Regions for images
private ITextureRegion BackgroundRegion;
private ITextureRegion Corner;
private ITextureRegion Center;
private ITextureRegion Marco;
// Sprites
private Sprite spriteBackground;
private Sprite spriteCorner;
private Sprite spriteCenter;
private Sprite spriteMarco;
// Enemies
private ArrayList<Enemies> listEnemies;
private ITextureRegion regionEnemy;
// Time to generate enemies
private float timeEnemies = 0; // Counter
private float TIME_LIMIT = 2.5f; // Every 2.5s it creates
@Override
public void loadResources() {
BackgroundRegion = loadImage("black.jpg");
Corner = loadImage("Corner_T.png");
Center = loadImage("Center.png");
Marco = loadImage("m.png");
regionEnemy = loadimage("ship.png");
}
private void createEnemies() {
for (int x = 700; x <= 1200; x += 100) {
for (int y = 100; y <= 700; y += 100) {
Sprite ship = loadSprite(x, y, regionEnemy);
attachChild(ship);
Enemies enemy = new Enemies(ship);
listEnemies.add(enemy);
}
}
}
@Override
public void createScene() {
listEnemies = new ArrayList<>();
spriteBackground = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, BackgroundRegion);
spriteCorner = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, Corner);
spriteCenter = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, Center);
spriteMarco = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, Marco);
attachChild(spriteBackground);
attachChild(spriteCorner);
attachChild(spriteCenter);
attachChild(spriteMarco);
createEnemies();
}
@Override
public void onBackKeyPressed() {
// Regresar al menú principal
admScenes.createMenuScenes();
admScenes.setScene(SceneType.MENU_SCENE);
admScene.liberateGameScene();
}
@Override
public sceneType getSceneType() {
return sceneType.GAME_SCENE;
}
@Override
public void liberateScene() {
this.detachSelf();
this.dispose();
}
@Override
public void liberateResources() {
BackgroundRegion.getTexture().unload();
Corner.getTexture().unload();
Center.getTexture().unload();
Marco.getTexture().unload();
regionEnemy.getTexture().unload();
BackgroundRegion = null;
Corner = null;
Center = null;
Marco = null;
regionEnemy = null;
}
@Override
protected void onManagedUpdate(float pSecondsElapsed) {
super.onManagedUpdate(pSecondsElapsed);
timeEnemies += pSecondsElapsed; // Acumulates time
if (timeEnemies>TIME_LIMIT) { // Time has completed
tiemeEnemies = 0;
Sprite spriteEnemy = loadSprite(GameControl.CAMARA_WIDTH+regionEnemy.getWidth(),
(float)(Math.random()*GameControl.CAMARA_HEIGHT-regionEnemy.getHeight()) +
regionEnemy.getHeight(),regionEnemy);
Enemies newEnemy = new Enemies(spriteEnemies);
//newEnemies.mover(0,10);
listEnemies.add(newEnemy); // Adds it to the scene
attachChild(newEnemy.getSpriteEnemy()); // Adds it to the list
}
// Updates every enemy and sees if any has gotten out of the screen
for (int i=listEnemies.size()-1; i>=0; i--) {
Enemies enemy = listEnemies.get(i);
enemy.mover(-10, 0);
if (enemy.getSpriteEnemy().getX()<-enemy.getSpriteEnemy().getWidth()) {
detachChild(enemy.getSpriteEnemy()); // Deletes it from the scene
listEnemies.remove(enemy); // eliminates it from the list
}
// Checks the collision of enemy with another sprite
if (spriteCenter.collidesWith(enemy.getSpriteEnemy())) {
detachChild(enemy.getSpriteEnemy());
//enemies.remove(enemy);
}
}
}
}
</code></pre>
<p><code>Enemies</code> class looks like this:</p>
<pre><code>public class Enemies {
private Sprite sprite;
public Enemies(Sprite sprite) {
this.sprite = sprite;
}
public Sprite getSpriteEnemy() {
return sprite;
}
public void setSprite(Sprite sprite) {
this.sprite = sprite;
}
public void mover(int dx, int dy) {
sprite.setPosition( sprite.getX()+dx, sprite.getY()+dy );
}
}
</code></pre>
<p>Thanks in advance for the help.</p>
| 3 | 2,454 |
Getting error while using pip installation
|
<p>I am trying to install <a href="https://github.com/gunthercox/ChatterBot" rel="nofollow noreferrer">Chatterbot</a> using pip but getting following error.</p>
<blockquote>
<p>Command "python setup.py egg_info" failed with error code 1 in
/private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/</p>
</blockquote>
<p>Full log is as below</p>
<pre><code>➜ Documents pip install ./ChatterBot
Processing ./ChatterBot
Collecting chatterbot-corpus<1.1,>=1.0 (from ChatterBot==0.7.3)
Using cached chatterbot_corpus-1.0.0-py2.py3-none-any.whl
Collecting jsondatabase<1.0.0,>=0.1.7 (from ChatterBot==0.7.3)
Using cached jsondatabase-0.1.7-py2.py3-none-any.whl
Collecting nltk<4.0,>=3.2 (from ChatterBot==0.7.3)
Using cached nltk-3.2.4.tar.gz
Collecting pymongo<4.0,>=3.3 (from ChatterBot==0.7.3)
Using cached pymongo-3.4.0-cp27-cp27m-macosx_10_12_intel.whl
Collecting python-dateutil<2.7,>=2.6 (from ChatterBot==0.7.3)
Using cached python_dateutil-2.6.1-py2.py3-none-any.whl
Collecting python-twitter<4.0,>=3.0 (from ChatterBot==0.7.3)
Using cached python_twitter-3.3-py2-none-any.whl
Collecting sqlalchemy<1.2,>=1.1 (from ChatterBot==0.7.3)
Using cached SQLAlchemy-1.1.11.tar.gz
Collecting ruamel.yaml<=0.15 (from chatterbot-corpus<1.1,>=1.0->ChatterBot==0.7.3)
Using cached ruamel.yaml-0.15.0.tar.gz
Complete output from command python setup.py egg_info:
/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:8: warning: explicitly assigning value of variable of type 'yaml_parser_t' (aka 'struct yaml_parser_s') to itself [-Wself-assign]
parser = parser; /* prevent warning */
~~~~~~ ^ ~~~~~~
/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:10: warning: variable 'parser' is uninitialized when used here [-Wuninitialized]
parser = parser; /* prevent warning */
^~~~~~
/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:5:1: note: variable 'parser' is declared here
yaml_parser_t parser;
^
2 warnings generated.
/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:8: warning: explicitly assigning value of variable of type 'yaml_parser_t' (aka 'struct yaml_parser_s') to itself [-Wself-assign]
parser = parser; /* prevent warning */
~~~~~~ ^ ~~~~~~
/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:6:10: warning: variable 'parser' is uninitialized when used here [-Wuninitialized]
parser = parser; /* prevent warning */
^~~~~~
/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/tmp_ruamel_H5mSkZ/test_ruamel_yaml.c:5:1: note: variable 'parser' is declared here
yaml_parser_t parser;
^
2 warnings generated.
sys.argv ['-c', 'egg_info', '--egg-base', 'pip-egg-info']
test compiling test_ruamel_yaml
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/setup.py", line 858, in <module>
main()
File "/private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/setup.py", line 847, in main
setup(**kw)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 111, in setup
_setup_distribution = dist = klass(attrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/dist.py", line 272, in __init__
_Distribution.__init__(self,attrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 287, in __init__
self.finalize_options()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/dist.py", line 326, in finalize_options
ep.require(installer=self.fetch_build_egg)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2385, in require
reqs = self.dist.requires(self.extras)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2617, in requires
dm = self._dep_map
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2606, in _dep_map
if invalid_marker(marker):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1424, in is_invalid_marker
cls.evaluate_marker(text)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1549, in _markerlib_evaluate
env = cls._translate_metadata2(_markerlib.default_environment())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1537, in _translate_metadata2
for key, value in env
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 1536, in <genexpr>
(key.replace('.', '_'), value)
ValueError: too many values to unpack
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/nw/vxggqrcx463g3f3zxp71dc5r0000gn/T/pip-build-8wG6yW/ruamel.yaml/
</code></pre>
<p>My pip installation is already at latest version. I even tried re-installing it as suggested on other websites but couldn't make it working yet. Any help is appreciated.</p>
| 3 | 2,440 |
How to resolve "System.UnauthorizedAccessException: Authorization for Microsoft App ID xxx failed with status code Unauthorized"
|
<p>I've created a simple bot using the .net framework. Messages are received but when replying, the application throw the exception below</p>
<pre><code>System.AggregateException: One or more errors occurred. ---> System.UnauthorizedAccessException: Authorization for Microsoft App ID xxx failed with status code Unauthorized and reason phrase 'Unauthorized' ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Bot.Connector.BotState.<GetConversationDataWithHttpMessagesAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.BotStateExtensions.<GetConversationDataAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.ConnectorStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<LoadFromInnerAndCache>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadData>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogTaskManagerBotDataLoader.<LoadAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()
--- End of inner exception stack trace ---
---> (Inner Exception #0) System.UnauthorizedAccessException: Authorization for Microsoft App ID 9d88e9f7-289e-45d2-8215-8f539955335d failed with status code Unauthorized and reason phrase 'Unauthorized' ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.Bot.Connector.JwtTokenRefresher.<SendAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Bot.Connector.BotState.<GetConversationDataWithHttpMessagesAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.BotStateExtensions.<GetConversationDataAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.ConnectorStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<LoadFromInnerAndCache>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.CachingBotDataStore.<Microsoft-Bot-Builder-Dialogs-Internals-IBotDataStore<Microsoft-Bot-Connector-BotData>-LoadAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadData>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.BotDataBase`1.<LoadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.DialogTaskManagerBotDataLoader.<LoadAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.SerializeByConversation.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUser.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Builder.Dialogs.Conversation.<SendAsync>d__6.MoveNext()<---
</code></pre>
<p>Code</p>
<pre><code>open System
open System.Text
open Hopac
open Hopac.Hopac
open Microsoft.Bot.Connector
open Suave
open Suave.Successful
open Suave.Filters
open Suave.Operators
open Microsoft.Bot.Builder.Dialogs
open Newtonsoft.Json
open System.Threading.Tasks
open Microsoft.Bot.Builder.Dialogs.Internals
type RootDialog () =
let rec onMessageReceived (context: IDialogContext) (result: IAwaitable<obj>) =
job {
//let! activity = result
do! context.PostAsync ("Sweet") |> Job.awaitUnitTask
context.Wait (ResumeAfter onMessageReceived) }
|> startAsTask |> unbox
interface IDialog<obj> with
member x.StartAsync (context: IDialogContext) =
context.Wait (ResumeAfter (onMessageReceived))
Task.CompletedTask
let getActivity request =
let body = request.rawForm |> Encoding.UTF8.GetString
let activity = JsonConvert.DeserializeObject<Activity> (body)
activity
let handleSystemMessage (activity: Activity) =
match activity.Type with
| ActivityTypes.DeleteUserData
| _ -> ()
let post (activity: Activity) ctx =
job {
match activity.Type with
| ActivityTypes.Message ->
do! Conversation.SendAsync (activity, fun () -> RootDialog() :> _) |> Job.awaitUnitTask
| _ -> handleSystemMessage activity
return! OK "Got it" ctx }
let part =
choose [
POST >=> path "/bot/messages" >=> request (getActivity >> (fun a b -> post a b |> Job.toAsync)) ]
</code></pre>
<p>PS:</p>
<p>I followed the tutorial <a href="https://docs.microsoft.com/en-us/bot-framework/troubleshoot-authentication-problems" rel="nofollow noreferrer">here</a> and it fails at step 3. Everything works fine when security is disabled.</p>
<p>Checking with fiddler shows that multiple requests are made to <code>login.microsoftonline.com</code> and all such requests are successful so I don't think it is the credentials. What could be the problem?</p>
| 3 | 4,745 |
Writing geotiff is grayscale instead of color python-gdal
|
<p>I am trying to upscale an geotiff, using deep learning network. I read in a color geo-tiff using gdal and process each band separately and write that band back into the new geo-tiff driver. The code snippet that does this is given below.</p>
<pre><code> # Remove the scale the image and create separate image for each Band
bands = tiffimg.shape[-1]
#Create TIFF File driver similar to input
driver = gdal.GetDriverByName("GTiff")
outdata = driver.Create(f'{save_dir}/{imgname}.{fileExtension}', tiffDS.RasterXSize*2, tiffDS.RasterYSize*2, bands, gdal.GDT_UInt16)
outpng = np.ones((tiffimg.shape[0]*2,tiffimg.shape[1]*2,tiffimg.shape[2]),dtype=tiffimg.dtype)
for band in range(bands):
singleBand = tiffimg[:,:,band]
bandMaxValue = np.ndarray.max(singleBand)
print(f'Band {band+1} min and max values before processing:{np.ndarray.min(singleBand)} \t {np.ndarray.max(singleBand)}')
scaledBand = (singleBand).astype(np.float32)/bandMaxValue
img_lq = np.stack((scaledBand,)*3,axis=-1)
resizedImg = getSRImage(args, img_lq, imgname) # gets the upscaled band
resizedImg = (resizedImg[:,:,1]*bandMaxValue).round().astype(tiffimg.dtype)
print(f'Band {band+1} min and max values After processing:{np.ndarray.min(resizedImg)} \t {np.ndarray.max(resizedImg)}')
outdata.GetRasterBand(band+1).WriteArray(resizedImg)
outdata.GetRasterBand(band+1).SetNoDataValue(100000)##if you want these values transparent
outpng[band] = resizedImg
outdata.SetGeoTransform(tiffDS.GetGeoTransform())##sets same geotransform as input
outdata.SetProjection(tiffDS.GetProjection())##sets same projection as input
outdata.SetMetadata(tiffDS.GetMetadata())
outdata.FlushCache() ##saves to disk!!
cv2.imwrite(f'{save_dir}/backup/{imgname}.png', outpng[:,:,0:3])
</code></pre>
<p>But as the title suggest the resulting image has all the same characteristics as the parent image (the data type and the number of bands) but when viewing it, the saved image is a gray scale image and not a color image. Not sure where I am going wrong.</p>
<p>Any help is greatly appreciated.</p>
<p>Update 1:
The output of exiftool for the original image is</p>
<pre><code>ExifTool Version Number : 12.44
File Name : sample.tif
Directory : .
File Size : 6.6 MB
File Modification Date/Time : 2022:08:31 19:23:36-06:00
File Access Date/Time : 2022:08:31 21:51:47-06:00
File Inode Change Date/Time : 2022:08:31 19:23:36-06:00
File Permissions : -rw-r--r--
File Type : TIFF
File Type Extension : tif
MIME Type : image/tiff
Exif Byte Order : Little-endian (Intel, II)
Subfile Type : Full-resolution image
Image Width : 2076
Image Height : 1053
Bits Per Sample : 8 8 8
Compression : Uncompressed
Photometric Interpretation : RGB
Strip Offsets : (Binary data 8254 bytes, use -b option to extract)
Orientation : Horizontal (normal)
Samples Per Pixel : 3
Rows Per Strip : 1
Strip Byte Counts : (Binary data 5264 bytes, use -b option to extract)
X Resolution : 72
Y Resolution : 72
Planar Configuration : Chunky
Resolution Unit : inches
Software : Adobe Photoshop CS6 (Windows)
Modify Date : 2022:06:15 14:25:22
XMP Toolkit : Adobe XMP Core 5.3-c011 66.145661, 2012/02/06-14:56:27
Create Date : 2022:06:15 14:13:45+08:00
Metadata Date : 2022:06:15 14:25:22+08:00
Format : image/tiff
Color Mode : RGB
Instance ID : xmp.iid:EF964DEF73ECEC11B05DA55541B9A9AE
Document ID : xmp.did:EE964DEF73ECEC11B05DA55541B9A9AE
Original Document ID : xmp.did:EE964DEF73ECEC11B05DA55541B9A9AE
History Action : created, saved
History Instance ID : xmp.iid:EE964DEF73ECEC11B05DA55541B9A9AE, xmp.iid:EF964DEF73ECEC11B05DA55541B9A9AE
History When : 2022:06:15 14:13:45+08:00, 2022:06:15 14:25:22+08:00
History Software Agent : Adobe Photoshop CS6 (Windows), Adobe Photoshop CS6 (Windows)
History Changed : /
Pixel Scale : 1 1 0
Model Tie Point : 0 0 0 7671 3249 0
IPTC Digest : 00000000000000000000000000000000
Displayed Units X : inches
Displayed Units Y : inches
Print Style : Centered
Print Position : 0 0
Print Scale : 1
Global Angle : 30
Global Altitude : 30
URL List :
Slices Group Name :
Num Slices : 1
Pixel Aspect Ratio : 1
Photoshop Thumbnail : (Binary data 10449 bytes, use -b option to extract)
Has Real Merged Data : Yes
Writer Name : Adobe Photoshop
Reader Name : Adobe Photoshop CS6
Color Space : Uncalibrated
Exif Image Width : 2076
Exif Image Height : 1053
Geo Tiff Version : 1.1.0
GT Model Type : Geographic
GT Raster Type : Pixel Is Area
Geographic Type : WGS 84
Geog Citation : WGS 84
Geog Angular Unit Size : 4.84813681109536e-06
Geog Semi Major Axis : 6378137
Geog Inv Flattening : 298.257223563
Image Size : 2076x1053
Megapixels : 2.2
</code></pre>
<p>while the up-scaled one is</p>
<pre><code>ExifTool Version Number : 12.44
File Name : sample_upscaled.TIF
Directory : .
File Size : 52 MB
File Modification Date/Time : 2022:09:01 12:12:57-06:00
File Access Date/Time : 2022:09:01 12:12:59-06:00
File Inode Change Date/Time : 2022:09:01 12:12:57-06:00
File Permissions : -rw-r--r--
File Type : TIFF
File Type Extension : tif
MIME Type : image/tiff
Exif Byte Order : Little-endian (Intel, II)
Image Width : 4152
Image Height : 2106
Bits Per Sample : 16 16 16
Compression : Uncompressed
Photometric Interpretation : BlackIsZero
Strip Offsets : (Binary data 18508 bytes, use -b option to extract)
Samples Per Pixel : 3
Rows Per Strip : 1
Strip Byte Counts : (Binary data 12635 bytes, use -b option to extract)
Planar Configuration : Chunky
Extra Samples : Unknown (0 0)
Sample Format : Unsigned; Unsigned; Unsigned
GDAL No Data : 100000
Image Size : 4152x2106
Megapixels : 8.7
</code></pre>
<p>Solution Update:</p>
<p>As suggested in the comments, the "Photometric interpretation" was the problem. Added "Photometric interpretation=RGB" while creating the driver. which solved the issue.</p>
<pre><code>driver = gdal.GetDriverByName("GTiff")
options = ['PHOTOMETRIC=RGB', 'PROFILE=GeoTIFF']
outdata = driver.Create(f'{save_dir}/{imgname}.{fileExtension}', tiffDS.RasterXSize*2, tiffDS.RasterYSize*2, bands, gdal.GDT_UInt16, options=options)
</code></pre>
| 3 | 3,861 |
Add new sheet in Excel from windows application c#
|
<p>Hi i want to add new sheet and populate data from data-table into excel from windows application c#.If If the excel is already existing i have to create a new sheet for the same excel and get data from db using datatable and save. while adding new sheet i get typemismatch error
<a href="https://imgur.com/6zlSub9" rel="nofollow noreferrer">https://imgur.com/6zlSub9</a>
Please help. Code attached.</p>
<pre><code>SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand("select * from tblBrand", con);
con.Open();
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
System.Data.DataTable dt = new System.Data.DataTable();
DataSet ds = new DataSet("New_data");
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
sda.Fill(dt);
ds.Tables.Add(dt);
string folder = Directory.GetParent(Directory.GetCurrentDirectory()).FullName + "\\OutPut\\";
using (XLWorkbook wb = new XLWorkbook())
{
if(System.IO.File.Exists(folder + "sample.xlsx"))
{
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.DisplayAlerts = false;
app.DefaultSaveFormat = XlFileFormat.xlOpenXMLWorkbook;
Excel.Workbook xwb = app.Workbooks.Open(folder + "sample.xlsx", 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets sheet = xwb.Worksheets;
var xlNewSheet = (Excel.Worksheet)sheet.Add(sheet[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "newsheet";
// xlNewSheet.Cells[0, 0] = xwb.Worksheets.Add(ds);
//xlNewSheet = xwb.Worksheets.Add(dt);
xlNewSheet = (Excel.Worksheet)xwb.Worksheets.Add(dt);
xlNewSheet = (Excel.Worksheet)xwb.Worksheets.get_Item(1);
xlNewSheet.Select();
xwb.Save();
xwb.Close();
releaseObject(xlNewSheet);
releaseObject(sheet);
releaseObject(xwb);
releaseObject(app);
}
else
{
wb.Worksheets.Add(dt, "Brands");
wb.SaveAs(folder + "sample.xlsx");
}
}
con.Close();
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
</code></pre>
| 3 | 1,876 |
SwiftUI: NavigationLink weird behaviour
|
<p>I'm trying to build a store in order to navigate in a SwifUI flow.
The idea is that every screen should observe the state and push into the next one using a NavigationLink.</p>
<p>It seems to work for pushing one view, but a soon as I push several views into the stack, it starts behaving oddly: the view pops itself.</p>
<p>Luckily I was able to reproduce it in a separate project. When I move from 2 to 3, the third screen appears but the NavigationView resets to it's original state (<code>ContentView</code>):</p>
<pre><code>import SwiftUI
@main
struct NavigationTestApp: App {
var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}.navigationViewStyle(StackNavigationViewStyle())
}
}
}
class Store: ObservableObject{
@Published var state: StoreState
struct StoreState {
var flowState: FlowState = .none
}
enum FlowState {
case none, one, two, three
}
enum Action {
case moveTo1, moveTo2, moveTo3
}
init(state: StoreState) {
self.state = state
}
func send(_ action: Action) {
switch action {
case .moveTo1:
state.flowState = .one
case .moveTo2:
state.flowState = .two
case .moveTo3:
state.flowState = .three
}
}
}
struct ContentView: View {
@ObservedObject var store = Store(state: .init())
var body: some View {
VStack {
Button(action: {
store.send(.moveTo1)
}, label: {
Text("moveTo1")
})
NavigationLink(
destination: ContentView1().environmentObject(store),
isActive: Binding(
get: { store.state.flowState == .one },
set: { _ in
}
),
label: {}
)
}
}
}
struct ContentView1: View {
@EnvironmentObject var store: Store
var body: some View {
VStack {
Button(action: {
store.send(.moveTo2)
}, label: {
Text("moveTo2")
})
NavigationLink(
destination: ContentView2().environmentObject(store),
isActive: Binding(
get: { store.state.flowState == .two },
set: { _ in
}
),
label: {}
)
}
}
}
struct ContentView2: View {
@EnvironmentObject var store: Store
var body: some View {
VStack {
Button(action: {
store.send(.moveTo3)
}, label: {
Text("moveTo3")
})
NavigationLink(
destination: ContentView3().environmentObject(store),
isActive: Binding(
get: { store.state.flowState == .three },
set: { _ in
}
),
label: {}
)
}
}
}
struct ContentView3: View {
@EnvironmentObject var store: Store
var body: some View {
Text("Hello, world!")
.padding()
}
}
</code></pre>
<p>What am I missing?</p>
| 3 | 1,804 |
Jquery data json not showing in Html [Laravel]
|
<p>I want to get json data, But when the row in html code it's now showing anything
<strong>Html Code</strong></p>
<pre><code> <thead>
<tr>
<th>No</th>
<th>Waktu</th>
</tr>
</thead>
<tbody id="bodyData">
</tbody>
</table>
<script>
$(document).ready(function() {
var url = "{{URL('userData')}}";
$.ajax({
url: "mulai/getUserData",
type: "GET",
data:{
_token:'{{csrf_token()}}'
},
cache: false,
dataType: 'json',
success: function(dataResult){
console.log(dataResult);
var resultData = dataResult.data;
var bodyData = '';
var i=1;
$.each(resultData,function(row){
bodyData+="<tr>"
bodyData+="<td>"+ i++ +"</td>"
"<td>"+row.waktu+"</td>"
;
bodyData+="</tr>";
})
$("#bodyData").append(bodyData);
}
});
});
</script>
</code></pre>
<p><strong>Result Data with URL Method GET mulai/getUserData</strong></p>
<pre><code>{"data":[{"id":4,"namakelas":"Percobaan","waktu":"1","created_at":"2020-08-27T03:52:36.000000Z","updated_at":"2020-08-27T03:52:36.000000Z"}]}
</code></pre>
<p>But when row in html code it's now showing anything</p>
| 3 | 1,095 |
ReportServer database deadlock on dbo.DataSource table
|
<p>I get several deadlocks a day on the DataSource table with the stored procedures dbo.AddDataSource and dbo.GetDataSources. They are page level locks. Any ideas on how to alleviate the situation?</p>
<p>XML Deadlock Graph:</p>
<pre><code><deadlock> <victim-list>
<victimProcess id="process1d1df6548c8" /> </victim-list> <process-list>
<process id="process1d1df6548c8" taskpriority="0" logused="0" waitresource="PAGE: 5:1:11004 " waittime="2057" ownerId="7905394629" transactionname="SELECT" lasttranstarted="2019-01-03T09:58:26.103" XDES="0x1c61d053a40" lockMode="S" schedulerid="6" kpid="5472" status="suspended" spid="311" sbid="0" ecid="0" priority="0" trancount="0" lastbatchstarted="2019-01-03T09:58:26.103" lastbatchcompleted="2019-01-03T09:58:26.103" lastattention="1900-01-01T00:00:00.103" clientapp="Report Server" hostname="FMS-SQL2016" hostpid="14792" loginname="NT SERVICE\ReportServer" isolationlevel="read committed (2)" xactid="7905394629" currentdb="5" currentdbname="ReportServer" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
<executionStack>
<frame procname="ReportServer.dbo.GetDataSources" line="8" stmtstart="200" stmtend="2868" sqlhandle="0x03000500394a6d31fe340400eea8000001000000000000000000000000000000000000000000000000000000">
*password------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- </frame>
</executionStack>
<inputbuf> Proc [Database Id = 5 Object Id = 829246009] </inputbuf>
</process>
<process id="process1c87b3a28c8" taskpriority="0" logused="1012" waitresource="PAGE: 5:1:245381 " waittime="2059" ownerId="7905394609" transactionname="user_transaction" lasttranstarted="2019-01-03T09:58:26.100" XDES="0x1cc631e4ee0" lockMode="IX" schedulerid="2" kpid="12924" status="suspended" spid="316" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2019-01-03T09:58:26.107" lastbatchcompleted="2019-01-03T09:58:26.107" lastattention="1900-01-01T00:00:00.107" clientapp="Report Server" hostname="FMS-SQL2016" hostpid="14792" loginname="NT SERVICE\ReportServer" isolationlevel="read committed (2)" xactid="7905394609" currentdb="5" currentdbname="ReportServer" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
<executionStack>
<frame procname="ReportServer.dbo.AddDataSource" line="56" stmtstart="3944" stmtend="5074" sqlhandle="0x0300050000267930fc340400eea8000001000000000000000000000000000000000000000000000000000000">
*password---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- </frame>
</executionStack>
<inputbuf> Proc [Database Id = 5 Object Id = 813245952] </inputbuf>
</process> </process-list> <resource-list>
<pagelock fileid="1" pageid="11004" dbid="5" subresource="FULL" objectname="ReportServer.dbo.DataSource" id="lock1c4ef2b1700" mode="IX" associatedObjectId="72057594043301888">
<owner-list>
<owner id="process1c87b3a28c8" mode="IX" />
</owner-list>
<waiter-list>
<waiter id="process1d1df6548c8" mode="S" requestType="wait" />
</waiter-list>
</pagelock>
<pagelock fileid="1" pageid="245381" dbid="5" subresource="FULL" objectname="ReportServer.dbo.DataSource" id="lock1c4fcf6f780" mode="S" associatedObjectId="72057594043301888">
<owner-list>
<owner id="process1d1df6548c8" mode="S" />
</owner-list>
<waiter-list>
<waiter id="process1c87b3a28c8" mode="IX" requestType="wait" />
</waiter-list>
</pagelock> </resource-list> </deadlock>`
</code></pre>
| 3 | 1,600 |
AWS AMI Cleanup w/Ansible iterate through results array
|
<p>I have a previous task that creates weekly backups, labeling them with the server name followed by a date/time tag. The goal of this job is to go in behind it and clean up the old AMI backups, leaving only the last 3. The <code>ec2_ami_find</code> task works fine, but it could also return empty results for some servers and I'd like the deregister task to handle that.</p>
<p>The error I'm getting is pretty generic:</p>
<blockquote>
<p>fatal: [127.0.0.1]: FAILED! => {
"failed": true,
"msg": "The conditional check 'item.ec2_ami_find.exists' failed. The error was: error while evaluating conditional
(item.ec2_ami_find.exists): 'dict object' has no attribute
'ec2_ami_find'\n\nThe error appears to have been in
'/root/ansible/ec2-backups-purge/roles/first_acct/tasks/main.yml': line 25,
column 3, but may\nbe elsewhere in the file depending on the exact
syntax problem.\n\nThe offending line appears to be:\n\n\n- name:
Deregister old backups\n ^ here\n"</p>
</blockquote>
<p>The playbook task reads as follows:</p>
<pre><code>---
- name: Find old backups
tags: always
ec2_ami_find:
owner: self
aws_access_key: "{{ access_key }}"
aws_secret_key: "{{ secret_key }}"
region: "{{ aws_region }}"
ami_tags:
Name: "{{ item }}-weekly-*"
sort: name
sort_order: descending
sort_start: 3
with_items:
- server-01
- server-02
- server-win-01
- downloads
register: stale_amis
- name: Deregister old backups
tags: always
ec2_ami:
aws_access_key: "{{ access_key }}"
aws_secret_key: "{{ secret_key }}"
region: "{{ aws_region }}"
image_id: "{{ item.ami_id }}"
delete_snapshot: True
state: absent
with_items:
- "{{ stale_amis.results }}"
</code></pre>
<p>Snippet of one of the results returns:</p>
<pre><code>"results": [
{
"ami_id": "ami-zzzzzzz",
"architecture": "x86_64",
"block_device_mapping": {
"/dev/xvda": {
"delete_on_termination": true,
"encrypted": false,
"size": 200,
"snapshot_id": "snap-xxxxxxxxxxxxx",
"volume_type": "gp2"
}
},
"creationDate": "2017-08-01T15:26:11.000Z",
"description": "Weekly backup via Ansible",
"hypervisor": "xen",
"is_public": false,
"location": "111111111111/server-01.example.com-20170801152611Z",
"name": "server-01.example.com-20170801152611Z",
"owner_id": "111111111111",
"platform": null,
"root_device_name": "/dev/xvda",
"root_device_type": "ebs",
"state": "available",
"tags": {
"Name": "server-01-weekly-20170801152611Z",
"Type": "weekly"
},
"virtualization_type": "hvm"
},
</code></pre>
| 3 | 1,255 |
Query the database in foreach results
|
<p>I'm trying to build a webpage with simple status posts. I've created foreach loop to query the database and load all the posts:</p>
<pre><code> <?php
$user_id = Check::isLoggedIn();
$dbstories = DB::query('SELECT * FROM stories WHERE user_id=:user_id ORDER BY story_time DESC', array(':user_id'=>$user_id));
$post_story = "";
foreach($dbstories as $story) {
?>
<div>
<article>
<div>
<a href="profile.php">
<?php
// to pull user first name
$user_first = DB::query('SELECT user_first FROM users WHERE user_id=:user_id', array(':user_id'=>$user_id))[0]['user_first'];
echo $user_first;
?>
</a>
<div>
<time>
<?php
// to pull post datetime
$post_time = $story['story_time'];
echo '<time class="timeago" datetime="' . $post_time . '"></time>';
?>
</time>
</div>
</div>
</div>
<?php
// to pull post contents
$post_story = $story['story_body'];
if (strlen($post_story) <= 25) {
echo '<h3>' . $post_story . '</h3>';
} else {
echo '<p>' . $post_story . '</p>';
}
?>
<div>
<div>
<a href="#">
<svg class="thunder-icon"><use xlink:href="icons/icons.svg#thunder-icon"></use></svg>
<span>
<?php
// to pull number of likes
$post_likes = $story['story_likes'];
echo $post_likes;
?>
</span>
</a>
<!-- the same for comments and shares number goes here -->
</div>
</div>
<div>
<!-- This form over here should pull the story_id which is the post ID from the database like the other queries up there and post it next to the url then that will allow me to use it in isset($_GET['story_id']) and trigger a query to increment likes -->
<form action="stories.php?post_id=<?php $post_id = $story['story_id']; echo $post_id; ?>" method="post" id="like_story">
<a href="#" class="btn btn-control" id="post_like">
<svg class="like-post-icon"><use xlink:href="icons/icons.svg#thunder-icon"></use></svg>
</a>
</form>
<!-- the same for comment and share goes here -->
</div>
</article>
</div>
<?php
}
?>
</code></pre>
<p>*Please read the comments within the code</p>
<p>Everything works fine but, I still cant get each post's ID linked to the like button (like_story). It only access the most recent post's ID.</p>
<p>Any workaround to reference the post ID (story_id)?</p>
| 3 | 1,535 |
Firefox html5 validation anomaly with dynamic select options
|
<p>Here is a simple html5 form with two select controls. Changing the selection in the first select generates a new list of options for the second select. Both have the "required" attribute, and an initially selected blank option. The odd bit is that I get a red validation outline around the second select control, without submitting the form. No tool-tip with an error message, just the outline.</p>
<pre><code><!DOCTYPE html>
<BODY>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
function select_update(srcCtrlId, DstCtrlId)
{
//alert(srcCtrlId+','+DstCtrlId+','+url);
sel1 = document.getElementById(srcCtrlId);
srcValue = sel1.value;
sel2 = document.getElementById(DstCtrlId);
while(sel2.options.length > 0) {
sel2.remove(0);
}
if (srcValue == '')
{
var oOption = new Option( '(no matches)', '', true, true );
sel2.add(oOption);
}
else
{
var oOption = new Option( '-- Select2 --', '', true, true );
sel2.add(oOption);
for(i=1; i<=5; ++i)
{
v = srcValue * 10 + i;
s = 'Select2, Option'+v;
var oOption = new Option( s, v, false, false );
sel2.add(oOption);
}
}
}
function jsValidatePage1()
{
alert('onSubmit');
return false;
return true;
}
</script>
<form onSubmit="return jsValidatePage1();">
<select name="select1" id="select1" size="1" onChange="select_update('select1','select2');" required>
<option value="" selected="selected">-- Select1 --</option>
<option value="1">Select1, Option1</option>
<option value="2">Select1, Option2</option>
<option value="3">Select1, Option3</option>
<option value="4">Select1, Option4</option>
<option value="5">Select1, Option5</option>
</select>
<br><br>
<select name="select2" id="select2" size="1" required>
<option value="" selected="selected">-- Select2 --</option>
<option value='' DISABLED>(empty)</option>
</select>
<br><br>
<select name="select3" id="select3" size="1" required>
<option value="" selected="selected">-- Select3 --</option>
<option value="1">Select3, Option1</option>
<option value="2">Select3, Option2</option>
<option value="3">Select3, Option3</option>
<option value="4">Select3, Option4</option>
<option value="5">Select3, Option5</option>
</select>
<br><br>
<input type="text" name="dummy" value="" required="">
<br><br>
<input type="submit">
</form>
</html>
</code></pre>
<p>fiddle here: <a href="https://jsfiddle.net/afg57g0u/1/" rel="nofollow">https://jsfiddle.net/afg57g0u/1/</a></p>
<p>Run the code, and then select any option in the first select control.
The second lights up red immediately, but the other required controls do not, so it's not validating the whole form, just the second select control (sort-of). </p>
<p>This happens in Firefox 36.0.4. This does not happen on IE 11.0.17, Opera 28.0, Chrome 41.0.2272.101, or Safari 5.1.7 (duh). (on Win8 box)</p>
<p>I can find no other mention online of a similar problem. I have tried numerous approaches to disable or work-around this problem, but no luck.
Does anyone have any ideas? Is this a Firefox bug?</p>
| 3 | 1,454 |
Displaying the last object of nested relationship
|
<p>i'm having trouble with returning data from many to many relationship between two models. i wan't to show all <code>Currency? objects with their newest</code>Ticker<code>object related to that currency based on the</code>created_at` field. i'm wondering how i can create such an output in json?</p>
<p><strong>desired output</strong></p>
<pre><code>[
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"img": "/media/static/img/currencies/bitcoin_uzSOQkH.png",
"tickers":
{
"rank": 1,
"price_dkk": "111239.222648",
"market_cap_dkk": 1861795518438,
"percent_change_1h": "0.03",
"percent_change_24h": "2.44",
"percent_change_7d": "46.80",
"created_at": "2017-12-12T20:11:49.995851Z"
}
}
]
</code></pre>
<p><strong>view</strong></p>
<pre><code>class CurrencyGetView(ProtectedResourceView):
def get(self, request):
currencies = CurrencySerializer(Currency.objects.all(), many=True)
return JsonResponse(currencies.data, safe=False)
</code></pre>
<p><strong>serializers</strong></p>
<pre><code>class TickerSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Ticker
fields = ('rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d', 'created_at', )
class CurrencySerializer(serializers.HyperlinkedModelSerializer):
tickers = TickerSerializer(many=True)
class Meta:
model = Currency
fields = ('id', 'name','symbol', 'img', 'tickers',)
</code></pre>
<p><strong>models</strong></p>
<pre><code>class Ticker(models.Model):
rank = models.IntegerField()
price_dkk = models.DecimalField(max_digits=20, decimal_places=6)
market_cap_dkk = models.BigIntegerField()
percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2)
percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2)
percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = _('Ticker')
def __str__(self):
return self.id
class Currency(models.Model):
symbol = models.CharField(max_length=4, default='BTC', unique=True)
name = models.CharField(max_length=20, default='Bitcoin', unique=True)
img = models.ImageField(upload_to = 'static/img/currencies', blank=True)
is_active = models.BooleanField(default=False)
tickers = models.ManyToManyField(Ticker)
class Meta:
verbose_name_plural = 'currencies'
def __str__(self):
return self.name
</code></pre>
| 3 | 1,158 |
Agile Web Development with Rails 5.1 Playground - Ch 15 Password Trouble
|
<p>I can't figure out something in Agile Web Development with Rails, Chapter 15 - Playgrounds question 1.
It asks <strong>Modify the user update function to require and validate the current
password before allowing a user’s password to be changed.</strong></p>
<p>I really can't understand how I can get the <em>has_secure_password</em> helper method to allow me to also seek the current password, if there is one, and see if it equals a hash before allowing a change of the password to be made.</p>
<p>I'm reading along with the book and when it gets to these Playgrounds, I feel like chewing glass alot of the time.</p>
<p>My _form partial looks like this:</p>
<pre><code><h2>Enter User Details</h2>
<div class="field">
<%= form.label :name, 'Name:' %>
<%= form.text_field :name, id: :user_name, size: 40 %>
</div>
<% if user.password_digest %>
<%= form.label :password_digest, 'Current Password' %>
<%= form.password_field :password_digest, id: :password_digest, size: 40 %>
<% end %>
<div class="field">
<%= form.label :password, 'Password' %>
<%= form.password_field :password, id: :user_password, size: 40 %>
</div>
<div class="field">
<%= form.label :password_confirmation, 'Confirm:' %>
<%= form.password_field :password_confirmation,
id: :user_password_confirmation,
size: 40 %>
</div>
<div class="actions">
<%= form.submit %>
</div>
</code></pre>
<p>I check whether the user at present has a password_digest property in the the instance-variable to see whether I display the form chunk that is all decked out with password_digest symbols.</p>
<p>In my user_controller's <strong>update</strong> function, looks like this</p>
<pre><code>def update
puts "update running"
puts @user
puts @user.name
puts @user.password
puts @user.password_confirmation
respond_to do |format|
if @user.update(update_params)
# format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.html { redirect_to users_url, notice: "User #{@user.name} was successfully updated." }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
</code></pre>
<p>You'll notice the use of 'update_params'...I made another private method at the bottom of the file that differs from the standard 'user_params', I thought by substituting that into the mix I could get the whole thing to work.</p>
<p>To be honest, I'm so incredibly lost. If someone could please guide me on how to do this, I would be really grateful. I've googled and stackflow searched all over and I feel like in the search to find water to douse fire, I can only find flammable liquids, each one more reactive to heat than the last.</p>
<p>Is there a repository out there that has all these extra 'Playgrounds' things done, so I can take a look at them and see what's going on?</p>
| 3 | 1,127 |
Cannot download any plugins with PhpStorm - "Read Timed Out"
|
<p>I cannot download any plugins via PhpStorm. When I select a plugin and click <strong>install</strong>, I get the following error:</p>
<p><a href="https://i.stack.imgur.com/GRaKv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GRaKv.jpg" alt="enter image description here"></a></p>
<p>Here is what happened in idea.log:</p>
<pre><code> 2017-11-11 17:14:39,589 [ 499601] WARN - Settings.impl.PluginDownloader - Cannot download 'https://plugins.jetbrains.com/pluginManager/?action=download&id=net.rentalhost.idea.laravelInsight&build=PS-172.4155.41&uuid=ab043267-0a5e-4706-a6f2-491a1a1b9b78': Read timed out
java.io.IOException: Cannot download 'https://plugins.jetbrains.com/pluginManager/?action=download&id=net.rentalhost.idea.laravelInsight&build=PS-172.4155.41&uuid=ab043267-0a5e-4706-a6f2-491a1a1b9b78': Read timed out
at com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:362)
at com.intellij.openapi.updateSettings.impl.PluginDownloader$1.process(PluginDownloader.java:245)
at com.intellij.openapi.updateSettings.impl.PluginDownloader$1.process(PluginDownloader.java:242)
at com.intellij.util.io.HttpRequests.lambda$doProcess$0(HttpRequests.java:414)
at com.intellij.util.net.ssl.CertificateManager.runWithUntrustedCertificateStrategy(CertificateManager.java:349)
at com.intellij.util.io.HttpRequests.doProcess(HttpRequests.java:414)
at com.intellij.util.io.HttpRequests.process(HttpRequests.java:394)
at com.intellij.util.io.HttpRequests.access$100(HttpRequests.java:60)
at com.intellij.util.io.HttpRequests$RequestBuilderImpl.connect(HttpRequests.java:262)
at com.intellij.openapi.updateSettings.impl.PluginDownloader.a(PluginDownloader.java:242)
at com.intellij.openapi.updateSettings.impl.PluginDownloader.prepareToInstall(PluginDownloader.java:142)
at com.intellij.ide.plugins.PluginInstaller.a(PluginInstaller.java:243)
at com.intellij.ide.plugins.PluginInstaller.a(PluginInstaller.java:131)
at com.intellij.ide.plugins.PluginInstaller.prepareToInstall(PluginInstaller.java:70)
at com.intellij.ide.plugins.PluginManagerMain$5.run(PluginManagerMain.java:432)
at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:718)
at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:170)
at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:548)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:493)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:94)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:157)
at com.intellij.openapi.progress.impl.ProgressManagerImpl$2.run(ProgressManagerImpl.java:165)
at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:342)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:940)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1569)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at com.intellij.util.io.HttpRequests.openConnection(HttpRequests.java:505)
at com.intellij.util.io.HttpRequests.access$300(HttpRequests.java:60)
at com.intellij.util.io.HttpRequests$RequestImpl.getConnection(HttpRequests.java:288)
at com.intellij.util.io.HttpRequests$RequestImpl.getInputStream(HttpRequests.java:297)
at com.intellij.util.io.HttpRequests$RequestImpl.saveToFile(HttpRequests.java:358)
... 27 more
</code></pre>
<p>I have already tried adding <code>-Djava.net.preferIPv4Stack=true</code> to VMOptions, this did not work, same for IPv6.</p>
<p>I have also already tried running <code>netsh advfirewall set global StatefulFTP disable</code> in the elevated PowerShell, but also nothing happened.</p>
| 3 | 2,012 |
Getting a 403 when calling Azure Resource Rate API using certificate auth
|
<p>I am trying to create a console app that can call the <a href="https://msdn.microsoft.com/en-us/library/azure/mt219004" rel="nofollow noreferrer">Azure Resource Rate API</a> using certificate authentication. For this, I used the following branch <a href="https://github.com/HarvestingClouds/billing-dotnet-ratecard-api" rel="nofollow noreferrer">GitHub link</a>.</p>
<p>I am getting a 403 error. I've added an Web App to my Azure AD. In the manifest, I've copied the key credentials from the certificate I've signed using the following PowerShell commands;</p>
<pre><code>$cert=New-SelfSignedCertificate -Subject "CN=RateCardCert"
-CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature
$bin = $cert.RawData $base64Value = [System.Convert]::ToBase64String($bin)
$bin = $cert.GetCertHash()
$base64Thumbprint = [System.Convert]::ToBase64String($bin)
$keyid = [System.Guid]::NewGuid().ToString()
$jsonObj = @ customKeyIdentifier=$base64Thumbprint;keyId=$keyid;type="AsymmetricX509Cert";usage="Verify";value=$base64Value}
$keyCredentials=ConvertTo-Json @($jsonObj) | Out-File "keyCredentials.txt"
</code></pre>
<p>In de console app, I use the following function to get the token;</p>
<pre><code>public static string GetOAuthTokenFromAAD_ByCertificate(string TenanatID, string ClientID, string CertificateName)
{
//Creating the Authentication Context
var authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", TenanatID));
//Console.WriteLine("new authContext made");
//Creating the certificate object. This will be used to authenticate
X509Certificate2 cert = null;
//Console.WriteLine("empty 'cert' made, null");
//The Certificate should be already installed in personal store of the current user under
//the context of which the application is running.
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
//Trying to open and fetch the certificate
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates;
var certs = certCollection.Find(X509FindType.FindBySubjectName, CertificateName, false);
//Checking if certificate found
if (certs == null || certs.Count <= 0)
{
//Throwing error if certificate not found
throw new Exception("Certificate " + CertificateName + " not found.");
}
cert = certs[0];
}
finally
{
//Closing the certificate store
store.Close();
}
//Creating Client Assertion Certificate object
var certCred = new ClientAssertionCertificate(ClientID, cert);
//Fetching the actual token for authentication of every request from Azure using the certificate
var token = authContext.AcquireToken("https://management.core.windows.net/", certCred);
//Optional steps if you need more than just a token from Azure AD
//var creds = new TokenCloudCredentials(subscriptionId, token.AccessToken);
//var client = new ResourceManagementClient(creds);
//Returning the token
return token.AccessToken;
}
</code></pre>
<p>This is the part of the code that makes the URL and puts in the request (the xxxx part is replaced by the ClientID of the webapp that I've registered in Azure AD);</p>
<pre><code>//Get the AAD User token to get authorized to make the call to the Usage API
string token = GetOAuthTokenFromAAD_ByCertificate("<MyTenantName.onmicrosoft.com", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "RateCardCert");
// Build up the HttpWebRequest
string requestURL = String.Format("{0}/{1}/{2}/{3}",
ConfigurationManager.AppSettings["ARMBillingServiceURL"],
"subscriptions",
ConfigurationManager.AppSettings["SubscriptionID"],
"providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq 'MS-AZR-0044P' and Currency eq 'EUR' and Locale eq 'nl-NL' and RegionInfo eq 'NL'");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
// Add the OAuth Authorization header, and Content Type header
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
request.ContentType = "application/json";
// Call the RateCard API, dump the output to the console window
try
{
// Call the REST endpoint
Console.WriteLine("Calling RateCard service...");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(String.Format("RateCard service response status: {0}", response.StatusDescription));
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
var rateCardResponse = readStream.ReadToEnd();
Console.WriteLine("RateCard stream received. Press ENTER to continue with raw output.");
Console.ReadLine();
Console.WriteLine(rateCardResponse);
Console.WriteLine("Raw output complete. Press ENTER to continue with JSON output.");
Console.ReadLine();
// Convert the Stream to a strongly typed RateCardPayload object.
// You can also walk through this object to manipulate the individuals member objects.
RateCardPayload payload = JsonConvert.DeserializeObject<RateCardPayload>(rateCardResponse);
Console.WriteLine(rateCardResponse.ToString());
response.Close();
readStream.Close();
Console.WriteLine("JSON output complete. Press ENTER to close.");
Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine(String.Format("{0} \n\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
Console.ReadLine();
}
</code></pre>
<p>I just don't know what I have to do anymore, what am I missing here??</p>
<p>Full return of the console is:</p>
<blockquote>
<p>Calling RateCard Service...
The remote server returned an error: (403) Forbidden.</p>
</blockquote>
| 3 | 2,412 |
Difficulties with dependencies in maven
|
<p>i'm really new to creating projects in java with maven and so i've stumbled on quite a error for something really basic. I've created a maven project with the following pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.kthmaven</groupId>
<artifactId>KTHMaven</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>edu.princeton.cs.introcs</groupId>
<artifactId>algs4-package</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>edu.princeton.cs.introcs</groupId>
<artifactId>stdlib-package</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>sics-release</id>
<name>SICS Release Repository</name>
<url>http://kompics.sics.se/maven/repository</url>
</repository>
</repositories>
</project>
</code></pre>
<p>Now when I try to compile the following code</p>
<pre><code>package com.mycompany.kthmaven;
public class NewClass {
public static void main(String[] args) {
Stopwatch stopwatch = new Stopwatch();
long counter = 0;
for (int i=0; i<1000000; i++) {
counter += i;
}
StdOut.println("Körtiden var: " + stopwatch.elapsedTime());
}
}
</code></pre>
<p>I get a error telling me it doesnt recognize the symbols Stopwatch and StdOut which do exist in the dependencies I assigned for the project. Maven also succeeds in downloading the jars so im not sure where the problem is.</p>
<p>Heres a picture how the project looks like in netbeans (sorry cant upload images yet)</p>
<p><a href="http://i.gyazo.com/d9aa109c9bc34238f3548f7548dfb234.png" rel="nofollow">http://i.gyazo.com/d9aa109c9bc34238f3548f7548dfb234.png</a></p>
| 3 | 1,347 |
How to render JS to a content generated with JS?
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml">Executing <script> elements inserted with .innerHTML</a> </p>
</blockquote>
<p>I have a problem, when generating content with Java Script, an embedded script does not function. How can one code this correctly?</p>
<p>Here is a working example:
class datepicker works correctly for a static html code, but does not work for those lines that are added on runtime with the add new line button. Plesae note, that reloading the page is not an option for me as the real problem is more complicated.</p>
<p>Thanks for your help.</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( ".datepicker" ).datepicker({
yearRange: "-100:+0",
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd'
});
});
</script>
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<br/>This is a correct date picker:
<input type="text" class="datepicker" id="dp1" />
<script>
var lines=0;
function addNew()
{
lines++;
var newElement = document.createElement("span");
newElement.innerHTML = 'Name:<input type="text" id="qchildrenname'+window.lines+'" /> Birth date:<input type="text" class="datepicker" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(newElement);
}
function save()
{
var answer='';
for (var ii=1;ii<=window.lines;ii++)
{
if (document.getElementById('qchildrenname'+ii.toString()).value.toString()!=''){
answer+=document.getElementById('qchildrenname'+ii.toString()).value.toString()+','+document.getElementById('qchildrenage'+ii.toString()).value.toString()+';';
}
}
document.getElementById("qchildren").value=answer;
}
</script>
</body>
</html>
</code></pre>
| 3 | 1,064 |
How to send values form javascript to php
|
<p>I created two files, one is an html and the other is a php file. I have created an array in java script. In java script, I create a dynamic table, and get values from the HTML file and pass into the array. Also I created an on click event. Whenever the button is clicked from the html page, I want to send a java script value or array from java script to php page.<br>
When retrieving values in php, the values are not displayed.
Please guide me. Bellow is my code.</p>
<pre><code>var t = 0;
var counter = 0;
var Arr1 = [];
var Arr2 = [];
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.name = "tables[]";
table.setAttribute('id', 'tables'+counter);
table.setAttribute('align', 'center');
var row = document.getElementById('txt_rows').value;
var col = document.getElementById('txt_column').value;
var j;
// creating all cells
for(j = 0; j < row; j++) {
// creates a <tr> element
var mycurrent_row = document.createElement("tr");
for(var i = 0; i < col; i++) {
// creates a <td> element
var mycurrent_cell = document.createElement("td");
//appends img tag to table data node
//mycurrent_cell.appendChild(imgTag)
var div1 = document.createElement('div');
div1.style.width = "200px";
div1.style.height = "20px";
div1.style.align = "center";
div1.setAttribute('id', "tables"+counter+""+j+""+i);
//mycurrent_cell.appendChild(currenttext);
mycurrent_cell.appendChild(div1);
// appends the cell <td> into the row <tr>
mycurrent_row.appendChild(mycurrent_cell);
}
table.appendChild(mycurrent_row);
}
// appends <tbody> into <table>
// appends <table> into <body>
myTableDiv.appendChild(table);
// sets the border attribute of mytable to 2;
var arr1 = new Array();
var arr2 = new Array();
var table1 = document.getElementById('tables'+counter);
var cells1 = table1.getElementsByTagName('div');
//var bbb = document.getElementById('cell_id');
for (var ii=0,len=cells1.length; ii<len; ii++){
cells1[ii].onclick = function(){
//console.log(this.innerHTML);
/* if you know it's going to be numeric:
console.log(parseInt(this.innerHTML),10);
*/
//var xyz = this.innerHTML;
var str1 = this.id;
var len1 = str1.length;
var len2 = counter.toString().length;
var cell_Id=str1.slice(6+len2,len1);
var _ele = document.getElementById(this.id);
var btnOk = document.getElementById('btn_Ok');
btnOk.onclick = function(){
var newText;
var newLabel;
//document.getElementById("txt_name").style.fontSize = size
//var getPropery = document.getElementById("getProperties");
if(_ele.innerHTML == '')
{
var getName = document.getElementById("txt_name").value;
var element = document.getElementById("sel_element").value;
var selectFont = document.getElementById("fontChanger").value;
var selectFontValue = document.getElementById("font").value;
var selectColor = document.getElementById("txt_color").value;
var alpha_num = document.getElementById("char").value;
var text_form = document.getElementById("txt_from").value;
var text_to = document.getElementById("txt_to").value;
if(selectColor == '#008000')
{
var para = document.getElementById("txt_parameters");
if(para.value == '')
{
para.value = getName;
}
else
{
var paraTable = document.getElementById("assingInstrument");
var newtr = document.createElement("tr");
var cell1 = document.createElement('td');
var cell2 = document.createElement('td');
var cell3 = document.createElement('td');
var cell4 = document.createElement('td');
var newText1 = document.createElement('input');
newText1.type = "text";
newText1.name = "txt_invItemId[]";
newText1.value = getName;
newText1.className = "input";
var newText2 = document.createElement('select');
newText2.name = "sel_invType[]";
newText2.style.width = 160 +"px";
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
newText2.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.php?getInstrumentName",true);
xmlhttp.send();
cell2.appendChild(newText1);
cell4.appendChild(newText2);
newtr.appendChild(cell1);
newtr.appendChild(cell2);
newtr.appendChild(cell3);
newtr.appendChild(cell4);
paraTable.appendChild(newtr);
}
}
if(element == "label")
{
newLabel = document.createElement('label');
newLabel.innerHTML = getName;
newLabel.style.fontSize = selectFont;
if (selectFontValue == "Bold Italic")
{
newLabel.style.font = "italic bold 12px arial,serif";
}
else if (selectFontValue == "Regular")
{
newLabel.style.font = "12px arial,serif";
}
else if (selectFontValue == "Bold")
{
newLabel.style.font = "bold 12px arial,serif";
}
else
{
newLabel.style.font = "italic 12px arial,serif";
}
newLabel.style.color = selectColor;
_ele.appendChild(newLabel);
if(_ele.innerHTML != '')
{
arr1.push(table.id);
arr1.push(cell_Id);
arr1.push(getName);
arr1.push(element);
arr1.push(selectFont);
arr1.push(selectFontValue);
arr1.push(alpha_num);
arr1.push(text_form);
arr1.push(text_to);
arr1.push(selectColor);
}
}
else if(element == "text")
{
var newText = document.createElement('input');
newText.type = "text";
newText.name = getName;
newText.style.fontSize = selectFont;
if (selectFontValue == "Bold Italic")
{
newText.style.font = "italic bold 12px arial,serif";
}
else if (selectFontValue == "Regular")
{
newText.style.font = "12px arial,serif";
}
else if (selectFontValue == "Bold")
{
newText.style.font = "bold 12px arial,serif";
}
else
{
newText.style.font = "italic 12px arial,serif";
}
newText.style.color = selectColor;
_ele.appendChild(newText);
arr1.push(table.id);
arr1.push(cell_Id);
arr1.push(getName);
arr1.push(element);
arr1.push(selectFont);
arr1.push(selectFontValue);
arr1.push(alpha_num);
arr1.push(text_form);
arr1.push(text_to);
arr1.push(selectColor);
}
}
//alert(arr2);
// Creates all lines:
// Creates an empty line
Arr1.push([]);
Arr2.push([]);
// Adds cols to the empty line:
Arr1[t].push(new Array(10));
//Arr2[t].push(new Array(1));
for(var jjj=0; jjj < 10; jjj++){
// Initializes:
Arr1[t][jjj] = arr1[jjj];
}
for(var lll=0; lll < 1; lll++){
// Initializes:
Arr2[t][lll] = arr2[lll];
}
arr1.splice(0, arr1.length);
//arr2.splice(0, arr2.length);
t++;
}
}
}counter++;
var btnhh = document.getElementById('btn_add');
btnhh.onclick = function(){
//alert(Arr2);
window.location.href = 'index.php?btn_saveTct='+Arr1+'&column='+col+'&Array_color='+Arr2;
//"<?php $abcd='Sandip'; ?>";
}
}
</code></pre>
| 3 | 9,035 |
Cannot close a running event loop
|
<p>What is the way to close the discord.py bot loop once tasks are done?</p>
<p>Added:</p>
<pre><code>nest_asyncio.apply()
</code></pre>
<p>Tried:</p>
<pre><code>bot.logout(), bot.close(), bot.cancel()
</code></pre>
<p>Code:</p>
<pre><code>async def helper(bot, discord_user_feed):
nest_asyncio.apply()
await bot.wait_until_ready()
# await asyncio.sleep(10)
for each_id, events_list in discord_user_feed.items():
discord_user = await bot.fetch_user(int(each_id))
for each_one in events_list:
msg_sent = True
while msg_sent:
await discord_user.send(each_one)
msg_sent = False
await bot.close()
return 'discord messages sent'
async def discord_headlines(request):
nest_asyncio.apply()
discord_user_feed = await get_details()
bot = commands.Bot(command_prefix='!')
bot.loop.create_task(helper(bot, discord_user_feed))
message = bot.run('my_token')
return HttpResponse(message)
</code></pre>
<p>I can be able to send messages to discord users using id and discord bot. But, even after, django view api is continuously running and getting the error. It needs to return a response message - discord messages sent.</p>
<p>Error:</p>
<pre><code>Exception in callback <TaskWakeupMethWrapper object at 0x000001C852D2DA38>(<Future finis...SWdZVtXT7E']}>)
handle: <Handle <TaskWakeupMethWrapper object at 0x000001C852D2DA38>(<Future finis...SWdZVtXT7E']}>)>
Traceback (most recent call last):
File "E:\sd\envs\port\lib\asyncio\events.py", line 145, in _run
self._callback(*self._args)
KeyError: <_WindowsSelectorEventLoop running=True closed=False debug=False>
Internal Server Error: /api/v0/discord_headlines/
Traceback (most recent call last):
File "E:\sd\envs\port\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "E:\sd\envs\port\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\sd\envs\port\lib\site-packages\asgiref\sync.py", line 139, in __call__
return call_result.result()
File "E:\sd\envs\port\lib\concurrent\futures\_base.py", line 425, in result
return self.__get_result()
File "E:\sd\envs\port\lib\concurrent\futures\_base.py", line 384, in __get_result
raise self._exception
File "E:\sd\envs\port\lib\site-packages\asgiref\sync.py", line 204, in main_wrap
result = await self.awaitable(*args, **kwargs)
File "E:\back-end\port_api\views\discord_integration.py", line 110, in discord_headlines
message = bot.run('my_token')
File "E:\sd\envs\port\lib\site-packages\discord\client.py", line 719, in run
_cleanup_loop(loop)
File "E:\sd\envs\port\lib\site-packages\discord\client.py", line 95, in _cleanup_loop
loop.close()
File "E:\sd\envs\port\lib\asyncio\selector_events.py", line 107, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
[13/Jun/2021 01:07:34] "GET /api/v0/discord_headlines/ HTTP/1.1" 500 109010
</code></pre>
<p>These are the versions:</p>
<pre><code>Python 3.6.4, Django 3.1, discord.py 1.7.3, Asyncio, Anaconda-4.9.2, Windows-10
</code></pre>
| 3 | 1,400 |
R shiny: slickROutput disappears when switching tabpanel()
|
<p>I am making a <code>Shiny</code> app with <code>tabPanels</code> embedded in a <code>navbarPage</code>.
In each <code>tabPanel</code>, I generate a serie of image. When switching from one panel to the other one, the image loaded in one of them disappear.</p>
<p>I have to "refresh" manually the page to see it again. The problem seems similar than the one posted <a href="https://stackoverflow.com/questions/51380071/keep-plots-and-input-values-when-switching-between-tabs">here</a> but I cannot really subset my <code>tabPanels</code>, even though I gave <code>$id</code> and <code>value</code> to them.</p>
<p>Here is a reproducible example:</p>
<pre><code>library(shiny)
library(shinythemes)
library(slickR)
## ui ----
# Image list
imgs <- list(
stackoverflow =
"https://upload.wikimedia.org/wikipedia/fr/9/95/Stack_Overflow_website_logo.png",
stackexchange =
"https://upload.wikimedia.org/wikipedia/commons/6/6f/Stack_Exchange_Logo.png"
)
ui <- navbarPage(title = div(
HTML('<span style="font-size:180%;color:white;font-weight:bold;"> Navbarpage</span></a>'),
tags$style(style = 'position:absolute; right:42px;'),
tags$style(HTML("#panel1{font-size: 25px}")),
tags$style(HTML("#panel2{font-size: 25px}")),
tags$style(HTML("#panel_about{font-size: 25px}"))
),
theme = shinytheme("flatly"),
windowTitle = "Navbarpage",
id = "navbar",
## First tabpanel ----
tabPanel(h1(id = "panel1", "Panel 1"), value = 1, fluid = TRUE,
fluidRow(column(4,
selectInput("img_list", "Image list",
choices = imgs,
selected = imgs[1])),
column(8,
slickROutput("plot_panel1"))),
),
tabPanel(h1(id = "panel2", "Panel 2"), value = 2, fluid = TRUE,
fluidRow(column(4,
selectInput("img_list", "Image list",
choices = imgs,
selected = imgs[1])),
column(8,
slickROutput("plot_panel2"))),
)
) # closes navbarpage
## server ----
server <- function(input, output, session){
observe({
output$plot_panel1 <- renderSlickR({
slick1 <- slick_list(slick_div(
input$img_list,
css = htmltools::css(width = "100%", margin.left = "auto",
margin.right = "auto"),
type = "img", links = NULL))
slickR(slick1)
})
})
observe({
output$plot_panel2 <- renderSlickR({
slick2 <- slick_list(slick_div(
input$img_list,
css = htmltools::css(width = "100%", margin.left = "auto",
margin.right = "auto"),
type = "img", links = NULL))
slickR(slick2)
})
})
}
shinyApp(ui, server)
</code></pre>
<p>And what it produces:
<a href="https://i.stack.imgur.com/SpBQH.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SpBQH.gif" alt="enter image description here" /></a></p>
| 3 | 1,751 |
Html5 - Overlapping of footer over the main content
|
<p>I have this html file:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width = device-width">
<meta name="description" content="Some training on web design">
<meta name="keywords" content="web, design">
<meta name="author" content="Houssem badri">
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>
<title>My Web design | Welcome</title>
</head>
<body>
<header>
<div class="branding">
<h1>Some title</h1>
</div>
<nav>
<ul>
<li><a href="#">Contact us</a></li>
<li><a href="#">About us</a></li>
<li><a href="#">Services</a></li>
<li><a class="current" href="#">Home</a></li>
</ul>
</nav>
</header>
<div class="left-col">
<section>
<article>
<h1>My first article</h1>
<p>Some Text</p>
</article>
<article>
<h1>My Second article</h1>
<p>Some Text</p>
</article>
</section>
</div>
<div class="mid-col">
<section>
<h1> Main section title </h1>
<p>Some Text</p>
</section>
</div>
<aside role="complementary">
<h1>Aside title</h1>
<p> Some text </p>
</aside>
<footer>
<h4>Copyright&copy <a href="#">blabla.com</a></h4>
</footer>
</body>
</html>
</code></pre>
<p>And this css styling file:</p>
<pre><code>/* Global */
body{
background: #E1F9A8;
font-family: "Arial";
font-size: 16px;
width: 80%;
margin: auto;
overflow: hidden;
padding-bottom:60px;
}
ul{
margin:0;
padding:0;
}
/* Header */
header{
border: 1px solid;
border-radius: 10px;
background-color: #D0D8BE;
min-height: 75px;
padding-top:30px;
margin-top: 20px;
}
header nav{
margin-top:10px;
}
header li{
float: right;
padding: 0 10px 10px 0;
display: inline;
}
header a {
text-decoration: none;
text-transform: uppercase;
color: #226B90;
font-weight: bold;
}
header .branding{
float: left;
margin: 0 0 35px 10px;
/* Some design */
text-shadow: 1px 1px 2px orange;
}
header .branding h1{
margin:0;
}
header .current, header a:hover{
color: #C48B19;
text-shadow: 1px 1px 2px orange;
}
/* Left side */
.left-col {
width: 26%;
float: left;
border: 1px solid;
border-radius: 10px;
overflow: hidden;
margin-top: 10px;
background-color: #FAF8F3;
margin-right: 12px;
}
.left-col h1{
padding-left: 10px;
}
.left-col p{
padding-left: 10px;
}
.left-col i{
padding-left: 10px;
}
.left-col .read-more{
color: #C48B19;
text-shadow: 1px 1px 2px orange;
float: right;
text-decoration: none;
}
/* Right side */
aside{
width: 25%;
float: left;
border: 1px solid;
border-radius: 10px;
overflow: hidden;
margin-top: 10px;
background-color: #FAF8F3;
}
aside h1{
padding-left: 10px;
}
aside form{
padding: 0 10px 10px 10px;
}
/* Main section */
.mid-col{
width: 46%;
border: 1px solid;
border-radius: 10px;
overflow: hidden;
margin-top: 10px;
background-color: #FAF8F3;
float: left;
margin-right: 12px;
}
.mid-col h1, .mid-col h2, .mid-col img, .mid-col p{
padding-left: 10px;
}
.mid-col img{
width: 96%;
}
/* footer */
footer{
border: 1px solid;
border-radius: 10px;
background-color: #D0D8BE;
padding:20px;
margin:20px 0 0 20px;
}
</code></pre>
<p>When I see the output, I get this overlapping. I didn't catch how to fix it. I think I have bad restructured my html 5 page.</p>
<p><a href="https://i.stack.imgur.com/WrPJV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WrPJV.png" alt="enter image description here"></a></p>
| 3 | 2,317 |
WPF elements are in visual tree, but not animated?
|
<p>I'm trying to figure out how to generate animations procedurally. I create a Line, create four animations, and associate the line's endpoints to the animations. I add the animations to a storyboard, then I run the storyboard.</p>
<p>The panel itself is visible (I could change the background orange, and that change shows up), but not its children. The heck am I doing wrong? </p>
<p>Code behind:</p>
<pre><code>using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
namespace MyProject.Animations
{
public class MyAnimation : Panel
{
private DoubleAnimation[] lineAnimation;
private Line line;
private Storyboard storyboard;
public MyAnimation()
{
storyboard = new Storyboard();
line = new Line();
line.StrokeThickness = 4;
line.Stroke = Brushes.Black;
this.Children.Add(line);
lineAnimation = new DoubleAnimation[4];
for (int i = 0; i < 4; i++)
{
lineAnimation[i] = new DoubleAnimation();
lineAnimation[i].Duration = new Duration(TimeSpan.FromSeconds(5));
lineAnimation[i].AutoReverse = true;
lineAnimation[i].RepeatBehavior = RepeatBehavior.Forever;
lineAnimation[i].From = 10 * i;
lineAnimation[i].To = 100 * i;
storyboard.Children.Add(lineAnimation[i]);
}
Storyboard.SetTarget(lineAnimation[0], line);
Storyboard.SetTargetProperty(lineAnimation[0], new PropertyPath("X1"));
Storyboard.SetTarget(lineAnimation[1], line);
Storyboard.SetTargetProperty(lineAnimation[1], new PropertyPath("Y1"));
Storyboard.SetTarget(lineAnimation[2], line);
Storyboard.SetTargetProperty(lineAnimation[2], new PropertyPath("X2"));
Storyboard.SetTarget(lineAnimation[3], line);
Storyboard.SetTargetProperty(lineAnimation[3], new PropertyPath("Y2"));
storyboard.Begin();
}
}
}
</code></pre>
<p>XAML:</p>
<pre><code><Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sdk="http://schemas.microsoft.com/netfx/2009/xaml/presentation/sdk"
xmlns:local="clr-namespace:MyProject"
xmlns:a="clr-namespace:Myproject.Animations"
Title="MyProject">
<Grid>
<a:MyAnimation>
</Grid>
</Window>
</code></pre>
<p>Inspecting the application with Snoop, I see my lines in the visual tree. But they're not being drawn. (Note, this is the debug window for the actual application, not the representative code sample I've transcribed.)</p>
<p><img src="https://i.stack.imgur.com/ez9mE.png" alt=""></p>
| 3 | 1,242 |
React: override internal components with custom component
|
<p>I have a modal that is completely self contained. The modal is opened via going to the modal route and all the functionality to close the modal from button or outside clicks is within the modal component. Basically the modal is not controlled by any parent passing state. I was given a task of making the modals button customizable, meaning passing in a new button component, so we can add the modal to our lib instead of copy pasting the code in projects. Lol this seemed simple enough, and maybe it is and I am just overthinking this.</p>
<p>I cant paste the actual code but I can use a contrived example. This is a very simplified version of the modal, keeping in mind it opens via route so there's really no state and setState in the actual code. Also here is a <a href="https://jsfiddle.net/aaronbalthaser/af5p2kvj/73/" rel="nofollow noreferrer">fiddle</a></p>
<pre><code>const ModalHeader = ({ onClose }) => {
return (
<div className="modal__header">
<button
className="modal__close-btn"
data-testid="modal-close-button"
onClick={onClose}
/>
</div>
);
};
const Modal = ({ children }) => {
const [state, setState] = React.useState(true);
const handleCloseOutsideClick = () => {
setState(false);
};
const handleCloseButtonClick = () => {
setState(false);
};
const renderModal = () => {
return (
<div className="modal-overlay" onClick={handleCloseOutsideClick}>
<div className="modal">
<ModalHeader onClose={handleCloseButtonClick} />
{children}
</div>
</div>
);
};
return state ? renderModal() : null;
};
const App = () => {
return (
<Modal>
<div>Modal Children</div>
</Modal>
);
};
ReactDOM.render(<App />, document.querySelector('#app'));
</code></pre>
<p>I tried a few things, initially I attempted to find a way to pass in a new header component containing a button. Then as I got into the code I realized what I was doing would lose the self contained functionality of the modal. My approach was along the lines of below but obviously the onClick would be an issue since invoking the close functionality is internal.</p>
<p>So I tried using cloneElement to add props within the component if the custom header was detected:</p>
<pre><code>// inside modal component
React.useEffect(() => {
React.Children.map(children, (child: React.ReactElement) => {
if (child && child.type === ModalHeader) {
setHederFound(true);
}
});
}, []);
// inside modal render:
<div className={modalClasses} onClick={stopPropagation}>
{!headerFound ? (
<ModalDefaultHeader onClose={handleCloseButtonClick} />
) : (
React.Children.map(children, (child: React.ReactElement) => {
if (child && child.type === ModalHeader) {
return React.cloneElement(child, {
onClose: handleCloseButtonClick,
});
}
})
)}
{children}
</div>;
</code></pre>
<p>Obviously that did not work because there's no onClick in the custom button. Anyways I am thinking that I am over complicating this. I just need a way to pass in a custom button while leaving the functionality internal to the modal. Any assistance would be appreciated.</p>
<p>Thanks in advance.</p>
| 3 | 1,238 |
Passing DateTime variable to controller causing an error
|
<p>I am building a small prediction feature into my application. Running into an issue which I cannot seem to understand. I am calculating some basic results and returning a Dictionary containing the 2 results. Thought this would be a good way to get back both results from one function instead of calling two. I have found some proposed solutions for this error such as converting the DateTime to a string but this did not work for me either. Would appreciate any insight into the cause of the error. Thanks in advance.</p>
<h2>Error</h2>
<pre><code>Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
---> System.Text.Json.JsonReaderException: '<' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
at System.Text.Json.Utf8JsonReader.Read()
at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[Dictionary`2](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[Dictionary`2](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& state, JsonConverter converterBase)
at System.Text.Json.JsonSerializer.<ReadAsync>d__20`1[[System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__3`1[[System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__9`1[[System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
at WebApp.Client.Pages.Prediction.Predict.InitPrediction() in C:\Users\source\repos\WebApp\WebApp\Client\Pages\Prediction\Predict.razor:line 48
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)
</code></pre>
<p>This error only started to occur when I started passing a DateTime variable when making the Get request</p>
<h2>Razor page: problematic</h2>
<pre><code>[CascadingParameter]
private DateTime selectedDate { get; set; } = new DateTime();
private Dictionary<string, int> predictedInfo = new Dictionary<string, int>();
private async Task InitPrediction()
{
predictedInfo = await http.GetFromJsonAsync<Dictionary<string, int>>($"Prediction/{selectedDate}");
Navigation.NavigateTo("/prediction");
}
</code></pre>
<h2>Controller: problematic</h2>
<pre><code>[HttpGet("{date}")]
public async Task<ActionResult<Dictionary<string, int>>> GetProjects(DateTime date)
{
int total_projects_per_company = 0;
int users_per_project_sum = 0;
Dictionary<string, int> d = new Dictionary<string, int>();
// calculation code...
d.Add("users", users_per_project_sum);
d.Add("projects", total_projects_per_company);
return d;
}
</code></pre>
<p>The problem does not occur when <strong>I do not pass the DateTime</strong> and I am not sure what the correlation between this is.</p>
<h2>Razor page: Not causing a problem</h2>
<pre><code>[CascadingParameter]
private DateTime selectedDate { get; set; } = new DateTime();
private Dictionary<string, int> predictedInfo = new Dictionary<string, int>();
private async Task InitPrediction()
{
predictedInfo = await http.GetFromJsonAsync<Dictionary<string, int>>("Prediction");
Navigation.NavigateTo("/prediction");
}
</code></pre>
<h2>Controller: Not causing a problem</h2>
<pre><code>[HttpGet]
public async Task<ActionResult<Dictionary<string, int>>> GetProjects()
{
int total_projects_per_company = 0;
int users_per_project_sum = 0;
Dictionary<string, int> d = new Dictionary<string, int>();
// calculation code...
d.Add("users", users_per_project_sum);
d.Add("projects", total_projects_per_company);
return d;
}
</code></pre>
| 3 | 2,474 |
notifyDataSetChanged() not updating RecyclerView Adapter
|
<p>I am working on a very simple implementation of a RecyclerView that displays data stored in a ViewModel. I am still very new to Android development and am trying to learn the fundamentals. In this situation, all the data to be stored in the ViewModel is stored in a simple list, later on I want to use Room to do this but right now I am struggling to get things working. Currently adding an item to the list only adds that item to the private member (_mainList) of the ViewModel, the public member (mainList) is unchanged, and this is the member passed into the adapter constructor call.</p>
<p>ViewModel:</p>
<pre><code>class ListViewModel : ViewModel() {
private val _mainList = mutableListOf<String>()
val mainList = _mainList.toList()
fun addMainListItem(item: String) {
_mainList.add(item)
}
}
</code></pre>
<p>Adapter:</p>
<pre><code>class MainAdapter(private var list: List<String>) :
RecyclerView.Adapter<MainAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.list_item_text.text = list[position]
}
override fun getItemCount(): Int {
return list.size
}
}
</code></pre>
<p>Fragment that displays the list:</p>
<pre><code>class MainListFragment : Fragment() {
private val viewModel: ListViewModel by activityViewModels()
private var _binding: FragmentMainListBinding? = null
private val binding get() = _binding!!
lateinit var adapter: MainAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainListBinding.inflate(inflater, container, false)
val root: View = binding.root
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Add click listener to floating action button
binding.fabMain.setOnClickListener {
addListItem()
}
adapter = MainAdapter(viewModel.mainList)
main_list_view.adapter = adapter
main_list_view.layoutManager = LinearLayoutManager(requireContext())
}
private fun addListItem() {
val input = EditText(activity)
input.setHint("Enter the name of your new list item")
input.inputType = InputType.TYPE_CLASS_TEXT
activity?.let {
val builder = AlertDialog.Builder(activity)
builder.apply {
setTitle("Add List Item")
setView(input)
setPositiveButton(
"Add"
) { dialog, id ->
val newItem = input.text.toString()
viewModel.addMainListItem(newItem)
adapter.notifyDataSetChanged()
}
setNegativeButton("Cancel"
) { dialog, id ->
dialog.cancel()
}
}
builder.create()
builder.show()
}
}
}
</code></pre>
| 3 | 1,408 |
SQL Grouping columns by row
|
<p>Struggling with the SQL query to convert the data I have into the required format. I have an event log for machines and would like to associate the start and stop time and event outcome in the same row.
I am unable to use LAG due to the version of SQLServer. Any help appreciated.</p>
<p>current dataset:</p>
<pre><code>+----------+----------+------------+------------------------------+---------------------+
| MACHINE | EVENT_ID | EVENT_CODE | DATE_TIME | EVENT_DESCRIPTOR |
+----------+----------+------------+------------------------------+---------------------+
| 1 | 1 | 1 | 2020-08-06 14:59:26 | SCAN : START : z1 : |
| 1 | 2 | 6 | 2020-08-06 15:00:18 | SCAN : END : z1 : |
| 1 | 3 | 1 | 2020-08-06 15:00:45 | SCAN : START : z1 : |
| 1 | 4 | 5 | 2020-08-06 15:01:54 | SCAN : ABORT : z1 : |
| 2 | 5 | 1 | 2020-08-06 15:02:15 | SCAN : START : z1 : |
| 2 | 6 | 6 | 2020-08-06 15:05:07 | SCAN : END : z1 : |
| 1 | 7 | 1 | 2020-08-06 15:05:13 | NEST : START : z1 : |
| 1 | 8 | 6 | 2020-08-06 15:05:22 | NEST : END : z1 : |
| 1 | 9 | 1 | 2020-08-06 15:07:17 | CUT : START : z1 : |
| 1 | 10 | 6 | 2020-08-06 15:10:40 | CUT : END : z1 : |
+----------+----------+------------+------------------------------+---------------------+
</code></pre>
<p>The outcome I am trying to achieve:</p>
<pre><code>+----------+------------------------------+------------------------------+----------+
| Machine | SCAN:START:Z1 _TIME | SCAN:STOP_OR_ABORT:Z1 _TIME | OUTCOME |
+----------+------------------------------+------------------------------+----------+
| 1 | Thu Aug 06 14:59:26 BST 2020 | 2020-08-06 15:00:18 | END |
| 1 | Thu Aug 06 15:00:45 BST 2020 | 2020-08-06 15:01:54 | ABORT |
| 1 | Thu Aug 06 15:02:15 BST 2020 | 2020-08-06 15:05:07 | END |
+----------+------------------------------+------------------------------+----------+
</code></pre>
| 3 | 1,050 |
How do I create a function that will return a value in a dictionary for each row within a data sheet using Python?
|
<p>I need to create a new column in my table for a state region that populates a region for every row of data (each having a state). How do I write a function to call upon a dictionary for each row item?</p>
<p>I have about 30,000 row items, and I believe a loop would take too long. I am certain there is some way to do this with dictionaries. I've tried using different methods to call this but cannot seem to get it to populate the correct data.</p>
<pre><code>states = {
'AK': 'Alaska',
'AL': 'Alabama',
'AR': 'Arkansas',
'AZ': 'Arizona',
'CA': 'California',
'CO': 'Colorado',
'CT': 'Connecticut',
'DC': 'District of Columbia',
'DE': 'Delaware',
'FL': 'Florida',
'GA': 'Georgia',
'HI': 'Hawaii',
'IA': 'Iowa',
'ID': 'Idaho',
'IL': 'Illinois',
'IN': 'Indiana',
'KS': 'Kansas',
'KY': 'Kentucky',
'LA': 'Louisiana',
'MA': 'Massachusetts',
'MD': 'Maryland',
'ME': 'Maine',
'MI': 'Michigan',
'MN': 'Minnesota',
'MO': 'Missouri',
'MS': 'Mississippi',
'MT': 'Montana',
'NC': 'North Carolina',
'ND': 'North Dakota',
'NE': 'Nebraska',
'NH': 'New Hampshire',
'NJ': 'New Jersey',
'NM': 'New Mexico',
'NV': 'Nevada',
'NY': 'New York',
'OH': 'Ohio',
'OK': 'Oklahoma',
'OR': 'Oregon',
'PA': 'Pennsylvania',
'RI': 'Rhode Island',
'SC': 'South Carolina',
'SD': 'South Dakota',
'TN': 'Tennessee',
'TX': 'Texas',
'UT': 'Utah',
'VA': 'Virginia',
'VT': 'Vermont',
'WA': 'Washington',
'WI': 'Wisconsin',
'WV': 'West Virginia',
'WY': 'Wyoming'
}
state_abbrev = {v: k for k, v in states.items()}
state_code = {
'AK': '10','AL': '4', 'AR': '9', 'AR': '6', 'CA': '9', 'CO': '8', 'CT': '1', 'DC': '3', 'DE': '3', 'FL': '4',
'GA': '4', 'HI': '9', 'IA': '7', 'ID': '10', 'IL': '5', 'IN': '5', 'KS': '7', 'KY': '4', 'LA': '6',
'MA': '1', 'MD': '3', 'ME': '1', 'MI': '5', 'MN': '5','MO': '7', 'MS': '4', 'MT': '8', 'NC': '4',
'ND': '8', 'NE': '7', 'NH': '1', 'NJ': '2', 'NM': '6','NV': '9', 'NY': '2', 'OH': '5', 'OK': '6',
'OR': '10', 'PA': '3', 'PR': '2', 'RI': '1', 'SC': '4', 'SD': '8', 'TN': '4', 'TX': '6', 'UT': '8',
'VA': '3', 'VI': '2', 'VT': '1', 'WA': '10', 'WI': '5', 'WV': '3', 'WY': '8', 'PI': '9'
}
state_region = {v: k for k, v in state_code.items()}
</code></pre>
<p>def get_region():
return [state_region[i] for i in fulldf['state']]</p>
<p>fulldf["Region"] = get_region()
fulldf.tail()</p>
<p>Returns key error 'MA', expected to return a new column named "Region" that populates the region for each "state" listed.</p>
<pre><code>KeyError Traceback (most recent call last)
<ipython-input-338-6afc1e48556a> in <module>
33 return [state_region[i] for i in fulldf['state']]
34
---> 35 fulldf["Region"] = get_region()
36 fulldf.tail()
37
<ipython-input-338-6afc1e48556a> in get_region()
31
32 def get_region():
---> 33 return [state_region[i] for i in fulldf['state']]
34
35 fulldf["Region"] = get_region()
<ipython-input-338-6afc1e48556a> in <listcomp>(.0)
31
32 def get_region():
---> 33 return [state_region[i] for i in fulldf['state']]
34
35 fulldf["Region"] = get_region()
KeyError: 'MA'
</code></pre>
| 3 | 1,708 |
Binding column width programmatically in UWP?
|
<p>I am trying to create columns that can be resized by the user during runtime just like in excel. However, I am creating fields dynamically and don't know how to bind the programmatically created column's width to the width of my column created in xaml.</p>
<p>Question: How can I bind column width programmatically rather than in the XAML?</p>
<p>cs:</p>
<pre><code>public sealed partial class WepPage : Page
{
static int i = 0;
Grid grid;
public WepPage()
{
this.InitializeComponent();
}
private void AddWepButton_Click(object sender, RoutedEventArgs e)
{
addWepStack();
}
private void addWepStack()
{
grid = new Grid();
grid.Name = ("ItemGrid" + i.ToString());
WepStackPanel.Children.Add(grid);
//create columns
ColumnDefinition col0 = new ColumnDefinition();
ColumnDefinition col1 = new ColumnDefinition();
ColumnDefinition col2 = new ColumnDefinition();
ColumnDefinition col3 = new ColumnDefinition();
ColumnDefinition col4 = new ColumnDefinition();
ColumnDefinition col5 = new ColumnDefinition();
// Set the width of each column
//HERE IS WHERE I WANT TO BIND THE COLUMN WIDTH TO THE WIDTH OF THE HEADERS
//SO THE USERS CAN CHANGE THE COLUMN WIDTH WHILE THE APPLICATION IS RUNNING.
// Add columns to grid
grid.ColumnDefinitions.Add(col0);
grid.ColumnDefinitions.Add(col1);
grid.ColumnDefinitions.Add(col2);
grid.ColumnDefinitions.Add(col3);
grid.ColumnDefinitions.Add(col4);
grid.ColumnDefinitions.Add(col5);
i++;
}
}
</code></pre>
<p>XAML:</p>
<pre><code><Page NavigationCacheMode="Required"
x:Class="WASP.WepPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WASP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="PoleDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" x:Name="WepNumColumn" x:DefaultBindMode="OneWay"/>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- HERE IS WHERE I ADDED GRID SPLITTERS SO THE USERS CAN EDIT COLUMN WIDTH
THIS IS WHAT I WANT THE WIDTH OF THE OTHER COLUMNS BOUND TO-->
<controls:GridSplitter Grid.Column="1">
<controls:GridSplitter.RenderTransform>
<TranslateTransform X="-8" />
</controls:GridSplitter.RenderTransform>
</controls:GridSplitter>
<controls:GridSplitter Grid.Column="3">
<controls:GridSplitter.RenderTransform>
<TranslateTransform X="-8" />
</controls:GridSplitter.RenderTransform>
</controls:GridSplitter>
<controls:GridSplitter Grid.Column="5">
<controls:GridSplitter.RenderTransform>
<TranslateTransform X="-8" />
</controls:GridSplitter.RenderTransform>
</controls:GridSplitter>
<controls:GridSplitter Grid.Column="7">
<controls:GridSplitter.RenderTransform>
<TranslateTransform X="-8" />
</controls:GridSplitter.RenderTransform>
</controls:GridSplitter>
<Button x:Name="addWepButton"
Content="+"
FontSize="30"
Grid.Column="10"
Grid.Row="0"
Click="AddWepButton_Click" />
<TextBlock Text="WEP #"
Grid.Column="0"
Grid.Row="0"
Style="{StaticResource WepTextBlock}"/>
<TextBlock Text="Type"
Grid.Column="2"
Grid.Row="0"
Style="{StaticResource WepTextBlock}"/>
<TextBlock Text="Distance"
Grid.Column="4"
Grid.Row="0"
Style="{StaticResource WepTextBlock}"/>
<TextBlock Text="Direction"
Grid.Column="6"
Grid.Row="0"
Style="{StaticResource WepTextBlock}"/>
<TextBlock Text="Flip"
Grid.Column="8"
Grid.Row="0"
Style="{StaticResource WepTextBlock}"/>
<ScrollViewer Grid.Row="1" Grid.ColumnSpan="20">
<StackPanel x:Name="WepStackPanel">
</StackPanel>
</ScrollViewer>
</Grid>
</Page>
</code></pre>
| 3 | 3,336 |
Valgrind invalid read and segmentation fault with QApplication
|
<p>I'm stuck with run-time errors in my Qt application. This is part of my Valgrind output. There is more before it but it is a lot to post.</p>
<pre><code>==13659== Invalid read of size 8
==13659== at 0x75E4085: QCoreApplication::arguments() (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x1B4E0114: ??? (in /usr/local/Qt/5.2.1/gcc_64/plugins/platforms/libqxcb.so)
==13659== by 0x1B4E10E8: ??? (in /usr/local/Qt/5.2.1/gcc_64/plugins/platforms/libqxcb.so)
==13659== by 0x1B9C0D2E: _SmcProcessMessage (in /usr/lib/x86_64-linux-gnu/libSM.so.6.0.1)
==13659== by 0x1BBD48A5: IceProcessMessages (in /usr/lib/x86_64-linux-gnu/libICE.so.6.3.0)
==13659== by 0x76096B0: QMetaObject::activate(QObject*, int, int, void**) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x767B1FD: QSocketNotifier::activated(int, QSocketNotifier::QPrivateSignal) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x7616840: QSocketNotifier::event(QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x65D20F3: QApplicationPrivate::notify_helper(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Widgets.so.5.2.1)
==13659== by 0x65D56AD: QApplication::notify(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Widgets.so.5.2.1)
==13659== by 0x75E0733: QCoreApplication::notifyInternal(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x7630A55: ??? (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== Address 0x178ddfb0 is 0 bytes after a block of size 16 alloc'd
==13659== at 0x4C28147: operator new[](unsigned long) (vg_replace_malloc.c:348)
==13659== by 0x4FAD41: GUIApp::init() (GUIApp.cpp:73)
==13659== by 0x423009: main (main.cpp:121)
==13659==
==13659== Invalid read of size 1
==13659== at 0x4C294E2: strlen (mc_replace_strmem.c:390)
==13659== by 0x75E409B: QCoreApplication::arguments() (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x1B4E0114: ??? (in /usr/local/Qt/5.2.1/gcc_64/plugins/platforms/libqxcb.so)
==13659== by 0x1B4E10E8: ??? (in /usr/local/Qt/5.2.1/gcc_64/plugins/platforms/libqxcb.so)
==13659== by 0x1B9C0D2E: _SmcProcessMessage (in /usr/lib/x86_64-linux-gnu/libSM.so.6.0.1)
==13659== by 0x1BBD48A5: IceProcessMessages (in /usr/lib/x86_64-linux-gnu/libICE.so.6.3.0)
==13659== by 0x76096B0: QMetaObject::activate(QObject*, int, int, void**) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x767B1FD: QSocketNotifier::activated(int, QSocketNotifier::QPrivateSignal) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x7616840: QSocketNotifier::event(QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x65D20F3: QApplicationPrivate::notify_helper(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Widgets.so.5.2.1)
==13659== by 0x65D56AD: QApplication::notify(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Widgets.so.5.2.1)
==13659== by 0x75E0733: QCoreApplication::notifyInternal(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== Address 0x50 is not stack'd, malloc'd or (recently) free'd
==13659==
==13659==
==13659== Process terminating with default action of signal 11 (SIGSEGV)
==13659== Access not within mapped region at address 0x50
==13659== at 0x4C294E2: strlen (mc_replace_strmem.c:390)
==13659== by 0x75E409B: QCoreApplication::arguments() (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x1B4E0114: ??? (in /usr/local/Qt/5.2.1/gcc_64/plugins/platforms/libqxcb.so)
==13659== by 0x1B4E10E8: ??? (in /usr/local/Qt/5.2.1/gcc_64/plugins/platforms/libqxcb.so)
==13659== by 0x1B9C0D2E: _SmcProcessMessage (in /usr/lib/x86_64-linux-gnu/libSM.so.6.0.1)
==13659== by 0x1BBD48A5: IceProcessMessages (in /usr/lib/x86_64-linux-gnu/libICE.so.6.3.0)
==13659== by 0x76096B0: QMetaObject::activate(QObject*, int, int, void**) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x767B1FD: QSocketNotifier::activated(int, QSocketNotifier::QPrivateSignal) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x7616840: QSocketNotifier::event(QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== by 0x65D20F3: QApplicationPrivate::notify_helper(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Widgets.so.5.2.1)
==13659== by 0x65D56AD: QApplication::notify(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Widgets.so.5.2.1)
==13659== by 0x75E0733: QCoreApplication::notifyInternal(QObject*, QEvent*) (in /usr/local/Qt/5.2.1/gcc_64/lib/libQt5Core.so.5.2.1)
==13659== If you believe this happened as a result of a stack
==13659== overflow in your program's main thread (unlikely but
==13659== possible), you can try to increase the size of the
==13659== main thread stack using the --main-stacksize= flag.
==13659== The main thread stack size used in this run was 8388608.
</code></pre>
<p>I am <code>porting code Qt3 to Qt5 and from 32-bit to 64-bit.</code> Line 73 in my code below is <code>test = new char*[2];</code>. </p>
<p>My program seems to crash with segmentation fault on the <code>showFullScreen()</code> call.</p>
<p>Could the use of the variable <code>test</code> be the cause of the Valgrind output and of the program crash? Is the form of argc and argv on 64-bit Linux the same as 32-bit?</p>
<pre><code>void GUIApp::init()
{
QApplication::setStyle("motif");
int nbrparams=1;
test = new char*[2];
test[0] = new char[100];
test[1] = new char[100];
printf(" Test : %d\n", (int)sizeof test ); // Test : 8
printf(" *Test : %d\n", (int)sizeof *test ); // *Test : 8
printf("**Test : %d\n", (int)sizeof **test ); // **Test : 1
strcpy(test[0], "gv_GUI");
go_app = new QApplication( nbrparams,test );
translator = new QTranslator( 0 );
// load translation file, make sure that this symbolic link points to the desired translation file
if (translator->load("tt2_go.qm")) {
go_app->installTranslator( translator );
}
gaw = new GO_QT_Application_Widget( GO_GUI_MODE, mytalkbackptr, NULL, "QTApp");
gaw->init();
gaw->startup();
gaw->move(0,0);
gaw->setFixedSize(3200,1200);
gaw->showFullScreen();
init_done = true;
}
</code></pre>
| 3 | 3,076 |
Android: Detect single fragment viewpager with Tab
|
<p>I have a problem with android a <code>ViewPager</code> setup with <code>FragmentPagerAdapter</code> and <code>TabLayout</code> </p>
<p><code>TabLayout</code> works fine. But, the code in all tabs run simultaneously. I want the code in the currently selected tab to run</p>
<p>This is my activity</p>
<pre><code>package francesco.prisco.siamostudenti.ui;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import francesco.prisco.siamostudenti.R;
import francesco.prisco.siamostudenti.ui.fragments.CalendarFragment;
import francesco.prisco.siamostudenti.ui.fragments.ChatFragment;
import francesco.prisco.siamostudenti.ui.fragments.EmailFragment;
import francesco.prisco.siamostudenti.ui.fragments.HomeFragment;
import francesco.prisco.siamostudenti.ui.fragments.ProfiloFragment;
public class HomeTabActivity extends AppCompatActivity {
// private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_tab);
// toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
int[] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_calendar,
R.drawable.ic_chat,
R.drawable.ic_email,
R.drawable.ic_profile
};
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new HomeFragment(), "HOME");
adapter.addFrag(new CalendarFragment(), "CALENDAR");
adapter.addFrag(new ChatFragment(), "CHAT");
adapter.addFrag(new EmailFragment(), "EMAIL");
adapter.addFrag(new ProfiloFragment(), "PROFILO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return null;
}
}
}
</code></pre>
<p>And this is code of a fragment</p>
<pre><code>package francesco.prisco.siamostudenti.ui.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import francesco.prisco.siamostudenti.R;
import francesco.prisco.siamostudenti.ui.HomeTabActivity;
public class ProfiloFragment extends Fragment {
public ProfiloFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profilo, container, false);
return rootView;
}
}
</code></pre>
<p>Help me please</p>
| 3 | 1,919 |
Getting the check changed event for a dynamically created Radio Group within a ListView
|
<p>We are working on a project where there is a questionnaire with dynamically created radio groups with radio buttons.At the bottom of the listview we have placed a button and we need the selected values from the radio buttons on clicking the button.<strong>The issue is how to get the selected Radio button values.Also i wanted to know in which class i can get the values in the main activity or in the Base Adapter class?</strong></p>
<p>We have done the following:</p>
<p>The main activity:</p>
<pre><code>submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(m=0;m<question_list_array.size();m++)
{
View view= question_list.getChildAt(m);
RadioGroup radioGroup= (RadioGroup) view.findViewById(R.id.single_radiogroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for(int n=0;n<group.getChildCount();n++)
{
RadioButton rb= (RadioButton) group.getChildAt(n);
if (rb.getId() == checkedId) {
String result= rb.getText()+"";
Toast.makeText(MainActivity.this,result, Toast.LENGTH_LONG).show();
// do something with text
return;
}
}
}
});
}
}
});
</code></pre>
<p>But i am getting NPE at the following line:</p>
<pre><code>RadioGroup radioGroup= (RadioGroup) view.findViewById(R.id.single_radiogroup);
</code></pre>
<p>The adapter class:</p>
<pre><code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
String question_type = question_list_array.get(position).getQuestion_type();
option_list = question_list_array.get(position).option_list;
number_of_options = option_list.size();
v_single=convertView;
if (v_single == null) {
v_single = inflater.inflate(R.layout.single_choice_layout, null);
sh = new SingleHolder();
sh.single_question_name = (TextView) v_single.findViewById(R.id.single_question_name);
sh.single_radiogroup = (RadioGroup) v_single.findViewById(R.id.single_radiogroup);
v_single.setTag(sh);
}
else
{
sh = (SingleHolder) v_single.getTag();
}
sh.single_radiogroup.clearCheck();
sh.single_radiogroup.removeAllViews();
sh.single_question_name.setText(question_list_array.get(position).getQuestion_name());
for (int j = 0; j < number_of_options; j++)
{
RadioButton rb = new RadioButton(context);
rb.setText(option_list.get(j).getOption_name());
sh.single_radiogroup.addView(rb);
}
v_final=v_single;
return v_final;
}
</code></pre>
<p>We dont have any issues with the Adapter as such.Please reply at the earliest.</p>
| 3 | 1,795 |
HTMLEditorExtender inside a repeater - buttons not rendering correctly
|
<p>I have a <code>HTMLEditorExtender</code> inside a repeater:</p>
<pre><code><asp:Repeater ID="rptEditItem" runat="server">
<HeaderTemplate>
<table border="0" style="width: 100%" class="DefaultText">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<div class="containerClass">
<asp:TextBox ID="txtEdit" runat="server" TextMode="MultiLine" Text='<%# Eval("DisplayText") %>' Height="300px" Width="600px"></asp:TextBox>
<asp:HtmlEditorExtender ID="HtmlEditorExtender1" DisplaySourceTab="true" TargetControlID="txtEdit" EnableSanitization="false" runat="server" >
</asp:HtmlEditorExtender>
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</code></pre>
<p>However the buttons are rendeing without the icons. How can I resolve this?</p>
<p><img src="https://i.stack.imgur.com/f3UMv.png" alt="HTMLExtender Example"></p>
<p><strong>Edit</strong></p>
<p>I was able to work around this issue by placing another <code>HtmlEditorExtender</code> and <code>TextBox</code> outside the repeater and hide it with jquery.</p>
<pre><code><div id="hideme">
<asp:TextBox ID="txtEdit2" runat="server" TextMode="MultiLine" Height="0px" Width="0px"></asp:TextBox>
<asp:HtmlEditorExtender ID="HtmlEditorExtender1" DisplaySourceTab="false" TargetControlID="txtEdit2" EnableSanitization="false" runat="server">
</asp:HtmlEditorExtender>
</div>
</code></pre>
<p>Jquery:</p>
<pre><code><script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
function pageLoad() {
hideFalseEditor();
}
function hideFalseEditor(sender, args) {
$(document).ready(function () {
$('#hideme').hide();
});
}
</script>
</code></pre>
<p>This seems a bit odd, but works. Perhaps a better solution?</p>
| 3 | 1,078 |
key error value 0 on modelformset when queryset is empty
|
<p>i want to create multiple instances of a model using a modelformset.
but when the queryset is empty and the parameter <code>extra</code> is greater than 0 it raises this error:</p>
<pre><code> Environment:
Request Method: GET
Request URL: http://localhost:8000/alta_socies/proces_alta_projecte_autoocupat/adreces/
Django Version: 1.7.7
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.formtools',
'inici',
'alta_socies',
'empreses',
'socies')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Template error:
In template /home/usergci/gestioci/alta_socies/templates/alta_socies/proces_alta_autoocupat.html, error at line 59
0
49 : <div class="row">
50 : <div class="medium-12 columns content">
51 : <div class="row">
52 : <div class="medium-12 columns">
53 : <div class="group">
54 : <h2>{{ projecte.pas }}</h2>
55 : {% block explicacio_pas %}{% endblock %}
56 : </div>
57 : <form method="post" action="">{% csrf_token %}
58 : {{ wizard.management_form }}
59 : {% if wizard.form.forms %}
60 : {{ wizard.form.management_form }}
61 : {% for form in wizard.form.forms %}
62 : {% block step_factory_form %}
63 : {% endblock %}
64 : {% endfor %}
65 : {% else %}
66 : {% block step_single_form %}
67 : {% endblock %}
68 : {% endif %}
69 : <input class="small radius button" type="submit" name="save_only" value="Guardar y salir"/>
Traceback:
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
137. response = response.render()
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/response.py" in render
103. self.content = self.rendered_content
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content
80. content = template.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
148. return self._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
126. return compiled_parent._render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _render
142. return self.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
402. return strip_spaces_between_tags(self.nodelist.render(context).strip())
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
65. result = block.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
65. result = block.nodelist.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in render
844. bit = self.render_node(node, context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/debug.py" in render_node
80. return node.render(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
305. match = condition.eval(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/defaulttags.py" in eval
898. return self.value.resolve(context, ignore_failures=True)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in resolve
596. obj = self.var.resolve(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in resolve
734. value = self._resolve_lookup(context)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/template/base.py" in _resolve_lookup
770. current = getattr(current, bit)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/utils/functional.py" in __get__
55. res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/forms/formsets.py" in forms
141. forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "/home/usergci/.virtualenvs/heteroceras/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
591. kwargs['initial'] = self.initial_extra[i - self.initial_form_count()]
Exception Type: KeyError at /alta_socies/proces_alta_projecte_autoocupat/adreces/
Exception Value: 0
</code></pre>
<p>the offending lines as far as i debugged are:</p>
<pre><code> AdrecesFormSet = modelformset_factory(AdrecaProjecteAutoocupat,
form=FormulariAdrecaProjecteAutoocupat,
can_delete=True)
</code></pre>
<p>any hint?</p>
| 3 | 4,021 |
How to pan and zoom svg file in shiny app
|
<p>I have the shiny app below in which I want to pan and zoom the .svg.</p>
<pre><code>library(shiny)
library(DiagrammeR)
library(tidyverse)
# probably don't need all of these:
library(DiagrammeRsvg)
library(svglite)
library(svgPanZoom)
library(rsvg)
library(V8)# only for svg export but also does not work
library(xml2)
ui <- fluidPage(
grVizOutput("grr",width = "100%",height = "90vh")
)
server <- function(input, output) {
reactives <- reactiveValues()
observe({
reactives$graph <- render_graph(create_graph() %>%
add_n_nodes(n = 2) %>%
add_edge(
from = 1,
to = 2,
edge_data = edge_data(
value = 4.3)))
})
output$grr <-
renderGrViz(reactives$graph
)
}
# Run the application
shinyApp(ui = ui, server = server)
</code></pre>
<p>I tried with the <code>svgPanZoom</code> package but could make it work. How does this work? Or an alternative option?</p>
<pre><code>ui <- fluidPage(
svgPanZoomOutput("grr")
)
server <- function(input, output) {
reactives <- reactiveValues()
observe({
reactives$graph <- render_graph(create_graph() %>%
add_n_nodes(n = 2) %>%
add_edge(
from = 1,
to = 2,
edge_data = edge_data(
value = 4.3)))
})
output$grr <-
renderSvgPanZoom({
svgPanZoom(reactives$graph)
})
}
# Run the application
shinyApp(ui = ui, server = server)
</code></pre>
| 3 | 1,088 |
Processing touches on moving/ animating UiViews
|
<p>I currently have the problem that touches are not always identified correctly,
My goal is to have 3 gestures,The 3 gestures are</p>
<ol>
<li>A user can tap on a view and the tap gets recognised,</li>
<li>A user can double tap on a view and the double tap is recognised,</li>
<li>A user can move their finger on the screen and if a view is below it
a tab is recognised.</li>
</ol>
<p>However I have multiple views all animating constantly and they may overlap,
Currently I sort views by size and have the smallest views on top of larger views.
And I typically get an issue that UIViews are not recognised when tapping on them. In particular double taps, swiping seems to work fine most of the time however the whole experience is very inconsistent.</p>
<p>The current code I'm using to solve the problem is:</p>
<pre><code> class FinderrBoxView: UIView {
private var lastBox: String?
private var throttleDelay = 0.01
private var processQueue = DispatchQueue(label: "com.finderr.FinderrBoxView")
public var predictedObjects: [FinderrItem] = [] {
didSet {
predictedObjects.forEach { self.checkIfBoxIntersectCentre(prediction: $0) }
drawBoxs(with: FinderrBoxView.sortBoxByeSize(predictedObjects))
setNeedsDisplay()
}
}
func drawBoxs(with predictions: [FinderrItem]) {
var newBoxes = Set(predictions)
var views = subviews.compactMap { $0 as? BoxView }
views = views.filter { view in
guard let closest = newBoxes.sorted(by: { x, y in
let xd = FinderrBoxView.distanceBetweenBoxes(view.frame, x.box)
let yd = FinderrBoxView.distanceBetweenBoxes(view.frame, y.box)
return xd < yd
}).first else { return false }
if FinderrBoxView.updateOrCreateNewBox(view.frame, closest.box)
{
newBoxes.remove(closest)
UIView.animate(withDuration: self.throttleDelay, delay: 0, options: .curveLinear, animations: {
view.frame = closest.box
}, completion: nil)
return false
} else {
return true
}
}
views.forEach { $0.removeFromSuperview() }
newBoxes.forEach { self.createLabelAndBox(prediction: $0) }
accessibilityElements = subviews
}
func update(with predictions: [FinderrItem]) {
var newBoxes = Set(predictions)
var viewsToRemove = [UIView]()
for view in subviews {
var shouldRemoveView = true
for box in predictions {
if FinderrBoxView.updateOrCreateNewBox(view.frame, box.box)
{
UIView.animate(withDuration: throttleDelay, delay: 0, options: .curveLinear, animations: {
view.frame = box.box
}, completion: nil)
shouldRemoveView = false
newBoxes.remove(box)
}
}
if shouldRemoveView {
viewsToRemove.append(view)
}
}
viewsToRemove.forEach { $0.removeFromSuperview() }
for prediction in newBoxes {
createLabelAndBox(prediction: prediction)
}
accessibilityElements = subviews
}
func checkIfBoxIntersectCentre(prediction: FinderrItem) {
let centreX = center.x
let centreY = center.y
let maxX = prediction.box.maxX
let minX = prediction.box.midX
let maxY = prediction.box.maxY
let minY = prediction.box.minY
if centreX >= minX, centreX <= maxX, centreY >= minY, centreY <= maxY {
// NotificationCenter.default.post(name: .centreIntersectsWithBox, object: prediction.name)
}
}
func removeAllSubviews() {
UIView.animate(withDuration: throttleDelay, delay: 0, options: .curveLinear) {
for i in self.subviews {
i.frame = CGRect(x: i.frame.midX, y: i.frame.midY, width: 0, height: 0)
}
} completion: { _ in
self.subviews.forEach { $0.removeFromSuperview() }
}
}
static func getDistanceFromCloseBbox(touchAt p1: CGPoint, items: [FinderrItem]) -> Float {
var boxCenters = [Float]()
for i in items {
let distance = Float(sqrt(pow(i.box.midX - p1.x, 2) + pow(i.box.midY - p1.y, 2)))
boxCenters.append(distance)
}
boxCenters = boxCenters.sorted { $0 < $1 }
return boxCenters.first ?? 0.0
}
static func sortBoxByeSize(_ items: [FinderrItem]) -> [FinderrItem] {
return items.sorted { i, j -> Bool in
let iC = sqrt(pow(i.box.height, 2) + pow(i.box.width, 2))
let jC = sqrt(pow(j.box.height, 2) + pow(j.box.width, 2))
return iC > jC
}
}
static func updateOrCreateNewBox(_ box1: CGRect, _ box2: CGRect) -> Bool {
let distance = sqrt(pow(box1.midX - box2.midX, 2) + pow(box1.midY - box2.midY, 2))
print(distance)
return distance < 50
}
static func distanceBetweenBoxes(_ box1: CGRect, _ box2: CGRect) -> Float {
return Float(sqrt(pow(box1.midX - box2.midX, 2) + pow(box1.midY - box2.midY, 2)))
}
func createLabelAndBox(prediction: FinderrItem) {
let bgRect = prediction.box
let boxView = BoxView(frame: bgRect ,itemName: "box")
addSubview(boxView)
}
@objc func handleTap(_ sender: UITapGestureRecognizer) {
// handling code
// NotificationCenter.default.post(name: .didDoubleTapOnObject, object: itemName)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
processTouches(touches, with: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
processTouches(touches, with: event)
}
func processTouches(_ touches: Set<UITouch>, with event: UIEvent?) {
if UIAccessibility.isVoiceOverRunning { return }
if predictedObjects.count == 0 { return }
if let touch = touches.first {
let hitView = hitTest(touch.location(in: self), with: event)
if hitView?.accessibilityLabel == lastBox { return }
lastBox = hitView?.accessibilityLabel
guard let boxView = hitView as? BoxView else {
return
}
UIView.animate(withDuration: 0.1, delay: 0, options: .curveLinear) {
boxView.backgroundColor = UIColor.yellow.withAlphaComponent(0.5)
} completion: { _ in
UIView.animate(withDuration: 0.1, delay: 0, options: .curveLinear, animations: {
boxView.backgroundColor = UIColor.clear
}, completion: nil)
}
}
}
}
class BoxView: UIView {
let id = UUID()
var itemName: String
init(frame: CGRect, itemName: String) {
self.itemName = itemName
super.init(frame: frame)
if !UIAccessibility.isVoiceOverRunning {
let singleDoubleTapRecognizer = SingleDoubleTapGestureRecognizer(
target: self,
singleAction: #selector(handleDoubleTapGesture),
doubleAction: #selector(handleDoubleTapGesture)
)
addGestureRecognizer(singleDoubleTapRecognizer)
}
}
@objc func navigateAction() -> Bool {
// NotificationCenter.default.post(name: .didDoubleTapOnObject, object: itemName)
return true
}
required init?(coder aDecoder: NSCoder) {
itemName = "error aDecoder"
super.init(coder: aDecoder)
}
@objc func handleDoubleTapGesture(_: UITapGestureRecognizer) {
// handling code
// NotificationCenter.default.post(name: .didDoubleTapOnObject, object: itemName)
}
}
public class SingleDoubleTapGestureRecognizer: UITapGestureRecognizer {
var targetDelegate: SingleDoubleTapGestureRecognizerDelegate
public var timeout: TimeInterval = 0.5 {
didSet {
targetDelegate.timeout = timeout
}
}
public init(target: AnyObject, singleAction: Selector, doubleAction: Selector) {
targetDelegate = SingleDoubleTapGestureRecognizerDelegate(target: target, singleAction: singleAction, doubleAction: doubleAction)
super.init(target: targetDelegate, action: #selector(targetDelegate.recognizerAction(recognizer:)))
}
}
class SingleDoubleTapGestureRecognizerDelegate: NSObject {
weak var target: AnyObject?
var singleAction: Selector
var doubleAction: Selector
var timeout: TimeInterval = 0.5
var tapCount = 0
var workItem: DispatchWorkItem?
init(target: AnyObject, singleAction: Selector, doubleAction: Selector) {
self.target = target
self.singleAction = singleAction
self.doubleAction = doubleAction
}
@objc func recognizerAction(recognizer: UITapGestureRecognizer) {
tapCount += 1
if tapCount == 1 {
workItem = DispatchWorkItem { [weak self] in
guard let weakSelf = self else { return }
weakSelf.target?.performSelector(onMainThread: weakSelf.singleAction, with: recognizer, waitUntilDone: false)
weakSelf.tapCount = 0
}
DispatchQueue.main.asyncAfter(
deadline: .now() + timeout,
execute: workItem!
)
} else {
workItem?.cancel()
DispatchQueue.main.async { [weak self] in
guard let weakSelf = self else { return }
weakSelf.target?.performSelector(onMainThread: weakSelf.doubleAction, with: recognizer, waitUntilDone: false)
weakSelf.tapCount = 0
}
}
}
}
class FinderrItem: Equatable, Hashable {
var box: CGRect
init(
box: CGRect)
{
self.box = box
}
func hash(into hasher: inout Hasher) {
hasher.combine(Float(box.origin.x))
hasher.combine(Float(box.origin.y))
hasher.combine(Float(box.width))
hasher.combine(Float(box.height))
hasher.combine(Float(box.minX))
hasher.combine(Float(box.maxY))
}
static func == (lhs: FinderrItem, rhs: FinderrItem) -> Bool {
return lhs.box == rhs.box
}
}
</code></pre>
| 3 | 6,844 |
How to add a word per minute calculator to a website using Javascript, html, or css?
|
<p>Iv'e been trying to complete a typing test website for some time and am stuck on how to add a word per minute counter. I have tried multiple ways but none of them work. What I want it do do is give the words per minute after the user types a prompt correctly.
Code is below:</p>
<p>HTML:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<h1>
<span id="word-1">man</span> <span id="word-2">become</span> <span id="word-3">as</span>
<span id="word-4">and</span> <span id="word-5">through</span> <span id="word-6">find</span> <span id="word-7">would</span> <span id="word-8">here</span> <span id="word-9">and</span> <span id="word-10">before</span>
</h1>
<input type="text" id="boch">
</div>
<div id="typing-area">
<button id="bocho" onclick="document.getElementById('boch').value = ''">Enter</button>
</html>
<script src="main.js"></script>
</code></pre>
<p>JavaScript:</p>
<pre><code>var input = document.getElementById("boch");
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("bocho").click();
}
});
var element = document.querySelector("#boch");
element.onkeyup = function () {
var value = element.value;
if (value.includes("man")) {
document.getElementById('word-1').style.backgroundColor = 'green';
} else {
document.getElementById('word-1').style.backgroundColor = 'transparent';
}
if (value.includes("man become")) {
document.getElementById('word-2').style.backgroundColor = 'green';
} else {
document.getElementById('word-2').style.backgroundColor = 'transparent';
}
if (value.includes("man become as")) {
document.getElementById('word-3').style.backgroundColor = 'green';
} else {
document.getElementById('word-3').style.backgroundColor = 'transparent';
}
if (value.includes("man become as and")) {
document.getElementById('word-4').style.backgroundColor = 'green';
} else {
document.getElementById('word-4').style.backgroundColor = 'transparent';
}
if (value.includes("man become as and through")) {
document.getElementById('word-5').style.backgroundColor = 'green';
} else {
document.getElementById('word-5').style.backgroundColor = 'transparent';
}
if (value.includes("man become as and through find")) {
document.getElementById('word-6').style.backgroundColor = 'green';
} else {
document.getElementById('word-6').style.backgroundColor = 'transparent';
}
if (value.includes("man become as and through find would")) {
document.getElementById('word-7').style.backgroundColor = 'green';
} else {
document.getElementById('word-7').style.backgroundColor = 'transparent';
}
if (value.includes("man become as and through find would here")) {
document.getElementById('word-8').style.backgroundColor = 'green';
} else {
document.getElementById('word-8').style.backgroundColor = 'transparent';
}
if (value.includes("man become as and through find would here and")) {
document.getElementById('word-9').style.backgroundColor = 'green';
} else {
document.getElementById('word-9').style.backgroundColor = 'transparent';
}
if (value.includes("man become as and through find would here and before")) {
document.getElementById('word-10').style.backgroundColor = 'green';
} else {
document.getElementById('word-10').style.backgroundColor = 'transparent';
}
}
let tagArr = document.getElementsByTagName("input");
for (let i = 0; i < tagArr.length; i++) {
tagArr[i].autocomplete = 'off';
}
</code></pre>
<p>Thank you for the help!</p>
<p>Irfan</p>
| 3 | 1,770 |
When using Google's Cloud Speech and sending Speech Contexts the returned transcriptions are not returning expected results
|
<p>Ref see: <a href="https://issuetracker.google.com/u/1/issues/128352542" rel="nofollow noreferrer">https://issuetracker.google.com/u/1/issues/128352542</a></p>
<p>We are having an issue where certain words added in the user's speech context are not being returned or prioritized. </p>
<p>When using phrase hints, the API will generally correctly transcribe the phrases or words supplied when uttered, however some words will not be transcribed no matter how you add them in phrase hints.</p>
<p>Config sent inside StreamingRecognitionConfig:</p>
<pre><code>{
"config":{
"encoding":"LINEAR16",
"sampleRateHertz":8000,
"languageCode":"en-US",
"enableWordTimeOffsets":true,
"enableAutomaticPunctuation":false,
"model":"default",
"useEnhanced":true,
"speechContexts":[
{
"phrases":[
"Bill Uhma",
"Uhma",
"I got coffee with Bill Uhma"
]
}
]
}
}
</code></pre>
<p>Result when trying to say "I got coffee with Bill Uhma":</p>
<pre><code>{
"results":{
"alternatives":[
{
"confidence":0.8440007,
"transcript":"I got coffee with Bill Uma",
"words":[
{
"confidence":0.847875,
"word":"I"
},
{
"confidence":0.9265712,
"word":"got"
},
{
"confidence":0.98762906,
"word":"coffee"
},
{
"confidence":0.98762906,
"word":"with"
},
{
"confidence":0.9239746,
"word":"Bill"
},
{
"confidence":0.23432566,
"word":"Uma"
}
]
},
{
"confidence":0.94561315,
"transcript":"I got coffee with Bill Luma"
},
{
"confidence":0.911253,
"transcript":"I got coffee with Bill Guma"
},
{
"confidence":0.91219664,
"transcript":"I got coffee with Bill Houma"
},
{
"confidence":0.94028026,
"transcript":"I got coffee with Bill looma"
},
{
"confidence":0.9403957,
"transcript":"I got coffee with Bill bouma"
},
{
"confidence":0.9403957,
"transcript":"I got coffee with Bill goomah"
},
{
"confidence":0.9403957,
"transcript":"I got coffee with Bill Wilma"
},
{
"confidence":0.938467,
"transcript":"I got coffee with Bill Boomer"
},
{
"confidence":0.9403957,
"transcript":"I got coffee with Bill buma"
},
{
"confidence":0.9403957,
"transcript":"I got coffee with Bill Ooma"
},
{
"confidence":0.9403957,
"transcript":"I got coffee with Bill Gooma"
}
],
"confidence":0.8440007,
"is_final":true,
"transcription":"I got coffee with Bill Uma"
}
}
</code></pre>
<p>The <strong>received</strong> transcription is "I got coffee with Bill Uma".</p>
<p>The <strong>expected</strong> transcription is "I got coffee with Bill Uhma".</p>
<p>As seen in the result, the provided hints do not appear in any of the 12 alternatives received.</p>
<p>Separating the phrase hints and only sending one of them has no effect on the result.</p>
| 3 | 1,977 |
Problem in debugging templates. Build fails specifically for Linux GCC 7, GCC 6, GCC 5, GCC 4.9 error: template argument 1 is invalid
|
<p>My Travis is only failing for Linux GCC 7, GCC 6, GCC 5, GCC 4.9 with error</p>
<pre><code>libs/astronomy/test/coordinate/equatorial_coord.cpp:22:57: error: template argument 1 is invalid
RightAscension<double, quantity<bud::plane_angle>>
^
libs/astronomy/test/coordinate/equatorial_coord.cpp:23:39: error: template argument 2 is invalid
ra(25.0 * bud::degrees);
</code></pre>
<p><strong>Here is equatorial_cord.cpp</strong></p>
<pre><code>#define BOOST_TEST_MODULE equatorial_coord_test
#include <iostream>
#include <boost/units/io.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/angle/degrees.hpp>
#include <boost/units/systems/si/plane_angle.hpp>
#include <boost/astronomy/coordinate/coord_sys/equatorial_coord.hpp>
#include <boost/test/unit_test.hpp>
using namespace boost::astronomy::coordinate;
using namespace boost::units;
using namespace boost::units::si;
namespace bud = boost::units::degree;
namespace bu = boost::units;
BOOST_AUTO_TEST_SUITE(angle)
BOOST_AUTO_TEST_CASE(right_ascension) {
//Create object of Right Ascension
RightAscension<double, quantity<bud::plane_angle>>
ra(25.0 * bud::degrees);
//Check value
BOOST_CHECK_CLOSE(ra.get_angle().value(), 25.0, 0.001);
//Quantity stored as expected?
BOOST_TEST((std::is_same<decltype(ra.get_angle()), quantity<bud::plane_angle>>::value));
}
BOOST_AUTO_TEST_SUITE_END()
</code></pre>
<p><strong>which includes and uses Equatorial_coord.hpp</strong></p>
<pre><code>#include <iostream>
#include <boost/units/io.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/units/systems/angle/degrees.hpp>
#include <boost/units/systems/si/plane_angle.hpp>
#include <boost/astronomy/coordinate/coord_sys/coord_sys.hpp>
namespace boost {
namespace astronomy {
namespace coordinate {
namespace bu = boost::units;
namespace bg = boost::geometry;
namespace bud = boost::units::degree;
//Right Ascension
template
<
typename CoordinateType = double,
typename RightAscensionQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>
>
struct RightAscension {
private:
RightAscensionQuantity ra;
public:
RightAscension(){
ra = 0.0 * bu::si::radian;
};
RightAscension(RightAscensionQuantity const& _ra) : ra(_ra) {}
RightAscensionQuantity get_angle() const{
return static_cast<RightAscensionQuantity>(ra);
}
void print() {
std::cout << "Right Ascension: " << ra;
}
};
...
</code></pre>
<p>It builds perfectly on my machine and I have tried some variation of code but I cannot understand what am I missing that builds are failing specifically for Linux GCC 7, GCC 6, GCC 5, GCC 4.9.</p>
<p>In this project, I have made many headers in a similar fashion but never faced such an issue. I will be grateful for any suggestions.</p>
<p><a href="https://dev.azure.com/lpranam/lpranam/_build/results?buildId=392&view=logs&j=d5b3eaca-5133-5bed-7ece-a6421a4fcca5&t=9b0787b9-d206-5213-01a9-f3ff4bf8b6d6" rel="nofollow noreferrer">https://dev.azure.com/lpranam/lpranam/_build/results?buildId=392&view=logs&j=d5b3eaca-5133-5bed-7ece-a6421a4fcca5&t=9b0787b9-d206-5213-01a9-f3ff4bf8b6d6</a></p>
| 3 | 1,831 |
We can't do account linking using iOS's Google assistant app
|
<p>I want to realize account linking to Google account with Google Home.
On realizing this, our app's flow of account linking follow to
<a href="https://stackoverflow.com/questions/50931590/google-home-authorization-code-and-authentication-with-google-account/50932537#50932537">this page</a>.<br></p>
<p>It page shows this.</p>
<blockquote>
<ol start="6">
<li>...so we send back a message saying they need to visit our website to authorize us to access their Google services. We may require them to switch to a mobile device to do this part and even include a link to the login page.</li>
</ol>
</blockquote>
<p>At this part, we use <a href="https://developers.google.com/assistant/conversational/df-asdk/rich-responses" rel="nofollow noreferrer">GoogleHome's rich response</a> to send authentication link to user's mobile device.<br>
For example,</p>
<pre><code> payload: {
google: {
expectUserResponse: true,
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: "textToSpeech"
}
},
{
basicCard: {
title: "Title",
formattedText: "formattedText",
buttons: [
{
title: "ButtonTitle",
openUrlAction: {
url: "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https//www.googleapis.com/auth/calendar.readonly&response_type=code&client_id=xxx.apps.googleusercontent.com&redirect_uri=https//project.com"
}
}
],
}
}
]
}
}
}
</code></pre>
<p>We can do account linking using Android OS, but iOS can't do that due to 403 error.
We've investigated <a href="https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html" rel="nofollow noreferrer">the cause</a>, it needs to use a specific browser to see google authentication page.</p>
<p><strong>How can I do account linking to avoid such problem?<br>
Or could you tell me another way to do account linking to Google account.</strong></p>
<p>Please excuse my poor English. Thank you.</p>
| 3 | 1,357 |
Regex Date and Time Delimitter and Sort
|
<p>My logs are getting stored in multiple Sun based unix servers.</p>
<p>So logs of Req1 might be in server1, Req2 and Req3 might be in server2 and then Req4 could be in server1 again. There is no proper sequence as it is stored based on what load balancer decides.</p>
<p>We use grep to get the data from all the servers. But problem is they are not sorted based on the time. What I want is to get the log file from all the servers as below but sort it based on the date and time.</p>
<p><strong>Edit</strong>
Here is example for the question.</p>
<pre><code>for (( i=1; i<=24; i++ )) do
echo 'server1' $logfile $i
grep abd12453 /var/logs/$i.log
echo 'server2' $logfile $i
ssh server2 "grep 'abd12453' /var/logs/$i.log"
done
</code></pre>
<p>where abd12453 is the user based on which the log will be extracted.</p>
<p>The above commands combines logs of all files of both server and print it. like below.</p>
<pre><code>server1 logfile1.log
06/13/2020 13:26:11.142 abd12453 server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log
server2 logfile1.log
06/13/2020 13:25:23.250 abd12453 server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log
server1 logfile2.log
06/13/2020 13:15:35.142 abd12453 server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2.
server2 logfile2.log
06/13/2020 13:14:42.156 abd12453 server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log
</code></pre>
<p>The above logs are all single lines along with username.</p>
<p>I need to sort the log data above based on date and time.</p>
<p>Required output should be</p>
<pre><code> server2 logfile2.log
06/13/2020 13:14:42.156 abd12453 server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log
server1 logfile2.log
06/13/2020 13:15:35.142 abd12453 server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2. server 1 log data2.
server2 logfile1.log
06/13/2020 13:25:23.250 abd12453 server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log data1. server 2 log
server1 logfile1.log
06/13/2020 13:26:11.142 abd12453 server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log data1. server 1 log
</code></pre>
| 3 | 1,135 |
What kind of CSS positioning can I use that isn't going to have (many) side effects?
|
<p>I'm currently building a website and and I can't find a CSS positioning method that works, meaning any CSS positioning element that doesn't make other HTML elements behave weirdly. Is there any CSS positioning methods that would position an HTML element precisely, accurately and not cause (many) issues with other elements? So far <code>float</code> and <code>position: absolute;</code> don't work well. Thanks!</p>
<p>Since apparently what I'm asking is unclear, I'm asking "What kind of positioning can I use that doesn't have any (or few) side effects?"</p>
<hr>
<p>Here's the Code I'm working on:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
display: inline-block;
}
ul {
display: inline-block;
margin: 0px;
padding: 0px;
}
#main_nav, logo {
display: inline-block;
padding: 0px;
margin: 0px;
}
nav li a:link {
font-weight: bold;
display: inline-block;
text-decoration: none;
font-family: times;
font-size: 24px;
list-style: none;
padding: 5px;
border: 2px solid black;
border-radius: 5px;
color: black;
}
nav li a:visited {
color: rgba(0,0,0,0.7);
}
nav li a:hover {
background-color: rgba(0,0,0,0.6);
color: white;
}
nav li a:active {
color: black;
border-color: black;
}
nav {
width: 1000px;
height: 130px;
background-color: rgba(255,255,255,0.7);
padding: 10px;
margin: 0px auto;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
}
input[type=search] {
font-size: 16px;
}
#searchbox {
position: absolute;
right: 0px;
top: 0px;
}
#searchbox_div {
position: relative;
display: inline-block;
padding: 0;
width: 100%;
}
#logo {
display: inline-block;
width: 200px;
font-family: arial;
margin: 0px;
padding: 0px;
font-size: 26px;
}
#logo_jeff, #logo_arries, #logo_website {
margin: 0px;
}
#logo_jeff {
letter-spacing: 35.5px;
}
#logo_arries {
letter-spacing: 11px;
}
#logo_website {
letter-spacing: 4px;
}
body {
background-image: url("../pictures/jeff_skiing.jpg");
background-color: red;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
min-height: 500px;
margin: 0px;
padding: 0px;
}
aside {
position: absolute;
right: 0px;
background-color: rgba(255,255,255,0.9);
width: 170px;
height: 600px;
margin: 0;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
padding: 10px;
}
#main_content {
width: 1000px;
min-height: 600px;
display: block;
background-color: rgba(255,255,255,0.7);
margin: 0 auto;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
position: relative; top: 0px;
padding: 10px;
}
#here_you_can_learn {
font-size: 47px;
color: gray;
margin: 0 auto;
margin-bottom: 10px;
text-align: center;
}
#welcome {
text-align: center;
color: rgb(0, 0, 110);
font-size: 100px;
margin: 0;
padding: 10px 10px 20px 10px;
}
#down_arrow {
height: 50px;
margin: auto;
display: block;
padding: 10px;
}
#most_frequent {
width: 600px;
vertical-align: top;
display: inline-block;
background-color: rgba(0,0,0,0.1);
border-radius: 3px;
}
#m_f_heading {
font-size: 30px;
margin: 10px;
padding: 5px;
text-align: center;
background-color: rgba(0,0,0,0.2);
border-radius: 5px;
}
#m_f_show_more {
font-size: 20px;
margin: 10px;
padding: 5px;
text-align: center;
background-color: rgba(0,0,0,0.2);
border-radius: 5px;
}
#recent_activity {
width: 375px;
display: inline-block;
background-color: rgba(0,0,0,0.1);
border-radius: 3px;
}
#r_a_heading {
font-size: 30px;
margin: 10px;
padding: 5px;
text-align: center;
background-color: rgba(0,0,0,0.2);
border-radius: 5px;
}
#r_a_body {
font-size: 15px;
margin: 10px;
padding: 5px;
text-align: center;
background-color: rgba(0,0,0,0.2);
border-radius: 5px;
}
#r_a_show_more {
font-size: 20px;
margin: 10px;
padding: 5px;
text-align: center;
background-color: rgba(0,0,0,0.2);
border-radius: 5px;
}
#r_a_show_more_link:visited {
color: black;
}
#r_a_show_more_link:hover {
color: gray;
background-color: rgba(0,0,0,0.9);
}
#r_a_show_more_link:active {
color: black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
<title>Home | Jeff's Website</title>
<link href="styles/main_navigation.css" type="text/css" rel="stylesheet" />
<link href="styles/body.css" type="text/css" rel="stylesheet" />
<link href="styles/main_content.css" type="text/css" rel="stylesheet" />
</head>
<body>
<!--Main Nav-->
<header>
<nav>
<div id="searchbox_div">
<form action="" id="searchbox">
<input id="search_input" type="search" name="searchmysite" placeholder="Search my Site!">
<input type="submit" value="Search!">
</form>
</div>
<div id="logo">
<h1 id="logo_jeff">JEFF</h1>
<h1 id="logo_arries">ARRIES</h1>
<h1 id="logo_website">WEBSITE</h1>
</div>
<div id="main_nav">
<ul>
<li><a href="">Home</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Trips</a></li>
<li><a href="">Politics</a></li>
<li><a href="">Pictures</a></li>
<li><a href="">Videos</a></li>
<li><a href="">Computer</a></li>
<li><a href="">Misc</a></li>
</ul>
</div>
</nav>
</header>
<!--Welcome to jeff's website-->
<div>
<h2 id="welcome">Welcome to my Website!</h1>
<a href="#here_you_can_learn">
<img src="pictures/down_arrow.png" id="down_arrow"/>
</a>
</div>
<!--right side nav-->
<aside>
<p>this is aside</p>
</aside>
<!--Main Content-->
<div id="main_content">
<h2 id="here_you_can_learn">Here you can learn about me and my adventures!</h2>
<!--Most Frequently visited pages: on left side of page-->
<div id="most_frequent">
<p id="m_f_heading">Most frequently visted pages!</p>
<a href=""><p id="m_f_show_more">Show More</p></a>
</div>
<!--Recent Activity: on the right side of page-->
<div id="recent_activity">
<p id="r_a_heading">Recent Activity</p>
<p id="r_a_body">test</p>
<a href="" id="r_a_show_more_link"><p id="r_a_show_more">Show More</p></a>
</div>
</div>
</body></code></pre>
</div>
</div>
</p>
| 3 | 3,047 |
PHP simple XML parser not returning data
|
<p><strong>I cannot display data from an XML file using the simple PHP parser. How do I fix it?</strong></p>
<p>I cannot find the problem to this simple task and I am completely stuck. I am following a w3schools.com tutorial and the code won't display the data. I am using an apache web server on my raspberry pi.</p>
<p>PHP:</p>
<pre><code><html>
<head>
<style>
code {
font-family: ;
} div {
margin-top: 5px;
margin-bottom: 5px;
margin-left: 5px;
margin-right: 5px;
background-color: rgb(177,177,177);
height: 200px;
width: 300px;
}
</style>
</head>
<body>
<center><h1>Hello BISD! This is a perfectly fine webpage!</h1></center>
<p>TXT File:</p>
<div>
<?php
$file=fopen("placeholder.txt","r");
while(!feof($file)) {
echo fgets($file).'<br>';
}
fclose($file);
?>
</div>
<p>XML File:</p>
<div>
<?php
$XMLFile = simplexml_load_file("test.xml");
if ($XMLFile === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
foreach($XMLFile->message() as $data) {
echo $data->subject;
echo $data->recipient;
echo $data->sender;
}
}
?>
</div>
</body>
</html>
</code></pre>
<p>XML:</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<message>
<subject>Test XML File</subject>
<sender>Harry</sender>
<recipient>The Internet</recipient>
<content>Hello world!</content>
</message>
<message>
<subject>Regarding XML</subject>
<sender>Harry</sender>
<recipient>The Internet</recipient>
<content>XML is awesome!</content>
</message>
</code></pre>
<p>The page loads the txt file and displays it fine.</p>
| 3 | 1,292 |
C#, ASP.NET MVC: Multiple image upload and uploaded images all remain the same problem
|
<p>I'm trying to upload multiple images, I managed to upload as many images as I wanted. My only problem is that all the images I chose duplicate by copying the first one. I could not find the error in my codes.</p>
<p>My <code>UploadImage</code> method:</p>
<pre><code>public static string UploadImage(string serverPath, IEnumerable<HttpPostedFileBase> files)
{
Guid uniqueName = Guid.NewGuid();
serverPath = serverPath.Replace("~", string.Empty);
string filePath;
foreach (HttpPostedFileBase item in files)
{
if (files != null && item.ContentLength > 0)
{
string extension = Path.GetExtension(item.FileName);
string fileName = $"{uniqueName}{extension}";
if (extension.ToLower() == ".jpeg" || extension.ToLower() == ".gif" || extension.ToLower() == ".png" || extension.ToLower() == ".jpg")
{
if (File.Exists(HttpContext.Current.Server.MapPath(serverPath + fileName)))
{
return "Already exists from same file";
}
else
{
filePath = Path.Combine(HttpContext.Current.Server.MapPath(serverPath),fileName);
item.SaveAs(filePath);
return serverPath+fileName;
}
}
else
{
return "Not the selected picture.";
}
}
else
{
return "No File Selected";
}
}
return "";
}
</code></pre>
<p>This is the <code>ImageController</code>:</p>
<pre><code>[HttpPost]
public ActionResult Index(TestClass model, IEnumerable<HttpPostedFileBase> files)
{
foreach (HttpPostedFileBase item in files)
{
model.ImagePath = ImageUploader.UploadImage("~/Images/", files) ;
db.TestClass.Add(model);
db.SaveChanges();
}
return View();
}
</code></pre>
<p>and the <code>ImageClass</code>:</p>
<pre><code>public class TestClass
{
public int ID { get; set; }
public string Name { get; set; }
public string ImagePath { get; set; }
}
</code></pre>
<p>and the view <code>Index.cshtml</code>:</p>
<pre><code>@using (Html.BeginForm("Index","Image",FormMethod.Post, new { enctype="multipart/form-data"}))
{
<div>
Name
</div>
<div>
@Html.TextBoxFor(x=>x.Name)
</div>
<div>
<input multiple type="file" name="files" value="Browse" />
</div>
<div>
<button class="btn btn-primary">Save</button>
</div>
}
</code></pre>
| 3 | 1,470 |
Golang REST API Deployment on AWS EKS Fails with CrashLoopBackOff
|
<p>I'm trying to deploy a simple REST API written in Golang to AWS EKS.</p>
<p>I created an EKS cluster on AWS using Terraform and applied the AWS load balancer controller Helm chart to it.</p>
<p>All resources in the cluster look like:</p>
<pre><code>NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system pod/aws-load-balancer-controller-5947f7c854-fgwk2 1/1 Running 0 75m
kube-system pod/aws-load-balancer-controller-5947f7c854-gkttb 1/1 Running 0 75m
kube-system pod/aws-node-dfc7r 1/1 Running 0 120m
kube-system pod/aws-node-hpn4z 1/1 Running 0 120m
kube-system pod/aws-node-s6mng 1/1 Running 0 120m
kube-system pod/coredns-66cb55d4f4-5l7vm 1/1 Running 0 127m
kube-system pod/coredns-66cb55d4f4-frk6p 1/1 Running 0 127m
kube-system pod/kube-proxy-6ndf5 1/1 Running 0 120m
kube-system pod/kube-proxy-s95qk 1/1 Running 0 120m
kube-system pod/kube-proxy-vdrdd 1/1 Running 0 120m
NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
default service/kubernetes ClusterIP 10.100.0.1 <none> 443/TCP 127m
kube-system service/aws-load-balancer-webhook-service ClusterIP 10.100.202.90 <none> 443/TCP 75m
kube-system service/kube-dns ClusterIP 10.100.0.10 <none> 53/UDP,53/TCP 127m
NAMESPACE NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE
kube-system daemonset.apps/aws-node 3 3 3 3 3 <none> 127m
kube-system daemonset.apps/kube-proxy 3 3 3 3 3 <none> 127m
NAMESPACE NAME READY UP-TO-DATE AVAILABLE AGE
kube-system deployment.apps/aws-load-balancer-controller 2/2 2 2 75m
kube-system deployment.apps/coredns 2/2 2 2 127m
NAMESPACE NAME DESIRED CURRENT READY AGE
kube-system replicaset.apps/aws-load-balancer-controller-5947f7c854 2 2 2 75m
kube-system replicaset.apps/coredns-66cb55d4f4 2 2 2 127m
</code></pre>
<p>I can run the application locally with Go and with Docker. But releasing this on AWS EKS always throws <code>CrashLoopBackOff</code>.</p>
<p>Running <code>kubectl describe pod PODNAME</code> shows:</p>
<pre><code>Name: go-api-55d74b9546-dkk9g
Namespace: default
Priority: 0
Node: ip-172-16-1-191.ec2.internal/172.16.1.191
Start Time: Tue, 15 Mar 2022 07:04:08 -0700
Labels: app=go-api
pod-template-hash=55d74b9546
Annotations: kubernetes.io/psp: eks.privileged
Status: Running
IP: 172.16.1.195
IPs:
IP: 172.16.1.195
Controlled By: ReplicaSet/go-api-55d74b9546
Containers:
go-api:
Container ID: docker://a4bc07b60c85fd308157d967d2d0d688d8eeccfe4c829102eb929ca82fb25595
Image: saurabhmish/golang-hello:latest
Image ID: docker-pullable://saurabhmish/golang-hello@sha256:f79a495ad17710b569136f611ae3c8191173400e2cbb9cfe416e75e2af6f7874
Port: 3000/TCP
Host Port: 0/TCP
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Error
Exit Code: 1
Started: Tue, 15 Mar 2022 07:09:50 -0700
Finished: Tue, 15 Mar 2022 07:09:50 -0700
Ready: False
Restart Count: 6
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-jt4gp (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
kube-api-access-jt4gp:
Type: Projected (a volume that contains injected data from multiple sources)
TokenExpirationSeconds: 3607
ConfigMapName: kube-root-ca.crt
ConfigMapOptional: <nil>
DownwardAPI: true
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 7m31s default-scheduler Successfully assigned default/go-api-55d74b9546-dkk9g to ip-172-16-1-191.ec2.internal
Normal Pulled 7m17s kubelet Successfully pulled image "saurabhmish/golang-hello:latest" in 12.77458991s
Normal Pulled 7m16s kubelet Successfully pulled image "saurabhmish/golang-hello:latest" in 110.127771ms
Normal Pulled 7m3s kubelet Successfully pulled image "saurabhmish/golang-hello:latest" in 109.617419ms
Normal Created 6m37s (x4 over 7m17s) kubelet Created container go-api
Normal Started 6m37s (x4 over 7m17s) kubelet Started container go-api
Normal Pulled 6m37s kubelet Successfully pulled image "saurabhmish/golang-hello:latest" in 218.952336ms
Normal Pulling 5m56s (x5 over 7m30s) kubelet Pulling image "saurabhmish/golang-hello:latest"
Normal Pulled 5m56s kubelet Successfully pulled image "saurabhmish/golang-hello:latest" in 108.105083ms
Warning BackOff 2m28s (x24 over 7m15s) kubelet Back-off restarting failed container
</code></pre>
<p>Running <code>kubectl logs PODNAME</code> and <code>kubectl logs PODNAME -c go-api</code> shows <code>standard_init_linux.go:228: exec user process caused: exec format error</code></p>
<p>Manifests:</p>
<p><code>go-deploy.yaml</code> ( This is the <a href="https://hub.docker.com/repository/docker/saurabhmish/golang-hello" rel="nofollow noreferrer">Docker Hub Image</a> with documentation )</p>
<pre><code>---
apiVersion: apps/v1
kind: Deployment
metadata:
name: go-api
labels:
app: go-api
spec:
replicas: 2
selector:
matchLabels:
app: go-api
strategy: {}
template:
metadata:
labels:
app: go-api
spec:
containers:
- name: go-api
image: saurabhmish/golang-hello:latest
ports:
- containerPort: 3000
resources: {}
</code></pre>
<p><code>go-service.yaml</code></p>
<pre><code>---
kind: Service
apiVersion: v1
metadata:
name: go-api
spec:
selector:
app: go-api
type: NodePort
ports:
- protocol: TCP
port: 80
targetPort: 3000
</code></pre>
<p>How can I fix this error ?</p>
| 3 | 4,106 |
Canvas returns blank image
|
<p>I have simply a button 'Create screenshot' and live stream 'rtsp-relay'. When that button is cliked it should take a snapshot or screenshot and show that under image, my problem is it shows blank image, i have tried to do this in two ways and both of them show blank image (live stream works fine).</p>
<p>code works fine with a simple drawing on a canvas:
<a href="https://codesandbox.io/s/copy-canvas-c5l8et-c5l8et?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/copy-canvas-c5l8et-c5l8et?file=/src/App.js</a></p>
<p>but when there is live video playing, it shows blank image when 'Create screenshot' button is clicked.</p>
<p>Any idea why ?</p>
<p>two ways i have tried:</p>
<p>1:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { loadPlayer } from 'rtsp-relay/browser';
const StreamVideo = () => {
const canvasRef = useRef(null);
const createScreenshot = () =>
new Promise((resolve) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.drawImage(canvasRef.current, 0, 0);
canvas.toBlob((blob) => {
const src = URL.createObjectURL(blob);
console.log('src', src);
const image = new Image();
image.onload = () => resolve(image);
image.src = src;
});
});
const handleButtonClick = () => {
createScreenshot().then((image) => {
document.body.append(image);
});
};
useEffect(() => {
if (!canvasRef.current) throw new Error('Ref is null');
loadPlayer({
url: 'ws://localho.../api/stream',
canvas: canvasRef.current,
});
}, []);
return (
<div style={{ border: '5px solid red' }}>
<canvas ref={canvasRef} style={{ width: '100%', height: '100%' }} />
<button onClick={handleButtonClick}>Create screenshot</button>
</div>
);
};
export default StreamVideo;</code></pre>
</div>
</div>
</p>
<p>2:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { loadPlayer } from 'rtsp-relay/browser';
const StreamVideo = () => {
const canvasRef = useRef(null);
const createScreenshot = () =>
new Promise((resolve) => {
canvasRef.current.toBlob((blob) => {
const src = URL.createObjectURL(blob);
const image = new Image();
image.onload = () => resolve(image);
image.src = src;
});
});
const handleButtonClick = () => {
createScreenshot().then((image) => {
document.body.append(image);
});
};
useEffect(() => {
if (!canvasRef.current) throw new Error('Ref is null');
loadPlayer({
url: 'ws://localh.../api/stream',
canvas: canvasRef.current,
});
}, []);
return (
<div style={{ border: '5px solid red' }}>
<canvas ref={canvasRef} style={{ width: '100%', height: '100%' }} />
<button onClick={handleButtonClick}>Create screenshot</button>
</div>
);
};
export default StreamVideo;</code></pre>
</div>
</div>
</p>
<p>image:</p>
<p><a href="https://i.stack.imgur.com/kWqo3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kWqo3.png" alt="enter image description here" /></a></p>
| 3 | 1,464 |
passing values to bootstrap modal
|
<p>I am trying to pass values to my <code>modal</code> in html using <code>JQUERY</code>.</p>
<p>I have this:</p>
<pre><code><a class="dropdown-item" href="javascript:void(0);" data-toggle="modal" data-target="#clientStatus" data-clientCurrentStatus="inactive">Change Client Status</a>
<script>
$(function() {
$('#clientStatus').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var clientCurrentStatus = button.data('clientCurrentStatus'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('#clientCurrentStatus').val(clientCurrentStatus);
});
});
</script>
</code></pre>
<p>and what I am trying to do is inside <code>data-clientCurrentStatus</code> i am passing the value. and then inside my <code>modal</code> I have this:</p>
<pre><code><div class="modal fade" id="clientStatus" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabelLogout"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabelLogout">Update Client Status</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<p>Current Status:</p>
<input type="text" name="clientCurrentStatus" id="clientCurrentStatus">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-primary" data-dismiss="modal">Cancel</button>
<a href="/logout" class="btn btn-primary">Logout</a>
</div>
</div>
</div>
</div>
</code></pre>
<p>so as you can see, the <code>id</code> matches, and everything matches. I am not sure why it isn't working. I am importing the <code>jquery</code> tag like this:</p>
<pre><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</code></pre>
<p>but nothing is working. how can i fix this?</p>
| 3 | 1,421 |
create , publish vuejs component on npm using vue/cli version 4 and use it in typescript based class style vuejs project
|
<p>i am learning vuejs and i am using latest versions of it like vue/cli version 4.x.x and now i want to perform a task which is like:</p>
<ol>
<li><p>I need to create a simple header using vue/cli version 4.x.x which will take an array inside headers variable as a
props.</p>
</li>
<li><p>Now, i want to publish it over npm.</p>
</li>
<li><p>Next i will be creating another vue project which will be using typescript and as a class based style and use my npm package create in 2nd step in this project.</p>
</li>
</ol>
<p>i have followed several articles to complete this approach. link of which is mentioned below
<a href="https://stackoverflow.com/questions/47754244/how-to-create-and-publish-a-vuejs-component-on-npm">How to create and publish a Vuejs component on NPM</a></p>
<p>Another article is this: <a href="https://dev.to/amroessam/publish-your-first-npm-package-vue-263h" rel="nofollow noreferrer">https://dev.to/amroessam/publish-your-first-npm-package-vue-263h</a></p>
<p>Last article is this: <a href="https://v2.vuejs.org/v2/cookbook/packaging-sfc-for-npm.html" rel="nofollow noreferrer">https://v2.vuejs.org/v2/cookbook/packaging-sfc-for-npm.html</a></p>
<p>Even though i am able to create header and publish it over npm but i am unable to use that npm package at all it gives the error.</p>
<blockquote>
<p>This dependency was not found:</p>
</blockquote>
<ul>
<li>header-bell-app in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/UserComponent/UserComponent.vue?vue&type=script&lang=js&</li>
</ul>
<p>To install it, you can run: npm install --save header-bell-app</p>
<p>i created my header package with the name header-bell-app and installed it as well but still it was giving me error when i was trying to import it somewhere.</p>
<p>Below is the code and screenshot<a href="https://i.stack.imgur.com/dATAq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dATAq.png" alt="in this image i have the structure of code" /></a> of my header-bell npm package:</p>
<pre><code> entry.js
import component from "./headerComponent.vue";
function install(Vue) {
if (install.installed) return;
install.installed = true;
Vue.component("header-component", component);
}
const plugin = {
install
};
let GlobalVue = null;
if (typeof window !== "undefined") {
GlobalVue = window.Vue;
} else if (typeof global !== "undefined") {
GlobalVue = global.vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
component.install = install;
export default component;
HeaderComponent.vue
<template>
<div>
<div class="header">
<div class="header-right">
<a v-for="header in headers" v-bind:key="header.id" v-bind:href="header.url">{{header.name}}</a>
</div>
</div>
</div>
</template>
<script>
export default {
name: "HeaderComponent",
props: {
headers: []
},
mounted() {}
};
</script>
<style scoped>
/* Style the header with a grey background and some padding */
.header {
overflow: hidden;
background-color: #f1f1f1;
padding: 20px 10px;
}
/* Style the header links */
.header a {
float: left;
color: black;
text-align: center;
padding: 12px;
text-decoration: none;
font-size: 18px;
line-height: 25px;
border-radius: 4px;
}
/* Style the logo link (notice that we set the same value of line-height and font-size to prevent the header to increase when the font gets bigger */
.header a.logo {
font-size: 25px;
font-weight: bold;
}
/* Change the background color on mouse-over */
.header a:hover {
background-color: #ddd;
color: black;
}
/* Style the active/current link*/
.header a.active {
background-color: dodgerblue;
color: white;
}
/* Float the link section to the right */
.header-right {
float: right;
}
/* Add media queries for responsiveness - when the screen is 500px wide or less, stack the links on top of each other */
@media screen and (max-width: 500px) {
.header a {
float: none;
display: block;
text-align: left;
}
.header-right {
float: none;
}
}
</style>
rollup.config.js
import vue from "rollup-plugin-vue";
import buble from "rollup-plugin-buble";
import commonjs from "rollup-plugin-commonjs";
export default {
input: 'src/entry.js', // Path relative to package.json
output: {
name: 'HeaderComponent',
exports: 'named',
},
plugins: [
commonjs(),
vue({
css: true, // Dynamically inject css as a <style> tag
compileTemplate: true, // Explicitly convert template to render function
}),
buble(), // Transpile to ES5
],
};
package.json
{
"name": "header-bell",
"version": "0.1.2",
"main": "dist/headercomponent.umd.js",
"module": "dist/headercomponent.esm.js",
"unpkg": "dist/headercomponent.min.js",
"browser": {
"./sfc": "src/HeaderComponent.vue"
},
"files": [
"dist/*",
"src/*",
"attributes.json",
"tags.json"
],
"vetur": {
"tags": "tags.json",
"attributes": "attributes.json"
},
"scripts": {
"build": "npm run build:unpkg & npm run build:es & npm run build:umd",
"build:umd": "cross-env NODE_ENV=production rollup --config build/rollup.config.js --format umd --file dist/headercomponent.umd.js",
"build:es": "cross-env NODE_ENV=production rollup --config build/rollup.config.js --format es --file dist/headercomponent.esm.js",
"build:unpkg": "cross-env NODE_ENV=production rollup --config build/rollup.config.js --format iife --file dist/headercomponent.min.js"
},
"devDependencies": {
"cross-env": "^5.2.0",
"minimist": "^1.2.0",
"rollup": "^1.14.4",
"rollup-plugin-buble": "^0.19.6",
"rollup-plugin-commonjs": "^9.3.4",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-uglify-es": "0.0.1",
"rollup-plugin-vue": "^4.7.2",
"vue": "^2.6.10",
"vue-template-compiler": "^2.6.10"
}
}
</code></pre>
<p>And i am using above package in my another project like below after installing header-bell</p>
<p><a href="https://i.stack.imgur.com/FgfFm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FgfFm.png" alt="enter image description here" /></a></p>
<p>Now its giving me an error that</p>
<blockquote>
<p>Could not find a declaration file for module 'header-bell'. 'd:/Alok/Work/References/interceptor-boilerplate/node_modules/header-bell/dist/headercomponent.umd.js' implicitly has an 'any' type.
Try <code>npm install @types/header-bell</code> if it exists or add a new declaration (.d.ts) file containing `declare module 'header-bell';</p>
</blockquote>
<p>and error in console while using HeaderComponent is in below image</p>
<p><a href="https://i.stack.imgur.com/NIVgJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NIVgJ.png" alt="enter image description here" /></a></p>
<p>I hope this will be enough evidence to correct my things. i will thankful if you can provide me with the best solution for this.</p>
| 3 | 3,160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.